domainhunter.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. #!/usr/bin/env python
  2. ## Title: domainhunter.py
  3. ## Author: @joevest and @andrewchiles
  4. ## Description: Checks expired domains, reputation/categorization, and Archive.org history to determine
  5. ## good candidates for phishing and C2 domain names
  6. # If the expected response format from a provider changes, use the traceback module to get a full stack trace without removing try/catch blocks
  7. #import traceback
  8. #traceback.print_exc()
  9. import time
  10. import random
  11. import argparse
  12. import json
  13. import base64
  14. import os
  15. import sys
  16. from urllib.parse import urlparse
  17. import getpass
  18. # Bluecoat XSRF
  19. from hashlib import sha256
  20. __version__ = "20221024"
  21. ## Functions
  22. def doSleep(timing):
  23. """Add nmap like random sleep interval for multiple requests"""
  24. if timing == 0:
  25. time.sleep(random.randrange(90,120))
  26. elif timing == 1:
  27. time.sleep(random.randrange(60,90))
  28. elif timing == 2:
  29. time.sleep(random.randrange(30,60))
  30. elif timing == 3:
  31. time.sleep(random.randrange(10,20))
  32. elif timing == 4:
  33. time.sleep(random.randrange(5,10))
  34. # There's no elif timing == 5 here because we don't want to sleep for -t 5
  35. def checkUmbrella(domain):
  36. """Umbrella Domain reputation service"""
  37. try:
  38. url = 'https://investigate.api.umbrella.com/domains/categorization/?showLabels'
  39. postData = [domain]
  40. headers = {
  41. 'User-Agent':useragent,
  42. 'Content-Type':'application/json; charset=UTF-8',
  43. 'Authorization': 'Bearer {}'.format(umbrella_apikey)
  44. }
  45. print('[*] Umbrella: {}'.format(domain))
  46. response = s.post(url,headers=headers,json=postData,verify=False,proxies=proxies)
  47. responseJSON = json.loads(response.text)
  48. if len(responseJSON[domain]['content_categories']) > 0:
  49. return responseJSON[domain]['content_categories'][0]
  50. else:
  51. return 'Uncategorized'
  52. except Exception as e:
  53. print('[-] Error retrieving Umbrella reputation! {0}'.format(e))
  54. return "error"
  55. def checkBluecoat(domain):
  56. """Symantec Sitereview Domain Reputation"""
  57. try:
  58. headers = {
  59. 'User-Agent':useragent,
  60. 'Referer':'http://sitereview.bluecoat.com/'}
  61. # Establish our session information
  62. response = s.get("https://sitereview.bluecoat.com/",headers=headers,verify=False,proxies=proxies)
  63. response = s.head("https://sitereview.bluecoat.com/resource/captcha-request",headers=headers,verify=False,proxies=proxies)
  64. # Pull the XSRF Token from the cookie jar
  65. session_cookies = s.cookies.get_dict()
  66. if "XSRF-TOKEN" in session_cookies:
  67. token = session_cookies["XSRF-TOKEN"]
  68. else:
  69. raise NameError("No XSRF-TOKEN found in the cookie jar")
  70. # Perform SiteReview lookup
  71. # BlueCoat Added base64 encoded phrases selected at random and sha256 hashing of the JSESSIONID
  72. phrases = [
  73. 'UGxlYXNlIGRvbid0IGZvcmNlIHVzIHRvIHRha2UgbWVhc3VyZXMgdGhhdCB3aWxsIG1ha2UgaXQgbW9yZSBkaWZmaWN1bHQgZm9yIGxlZ2l0aW1hdGUgdXNlcnMgdG8gbGV2ZXJhZ2UgdGhpcyBzZXJ2aWNlLg==',
  74. 'SWYgeW91IGNhbiByZWFkIHRoaXMsIHlvdSBhcmUgbGlrZWx5IGFib3V0IHRvIGRvIHNvbWV0aGluZyB0aGF0IGlzIGFnYWluc3Qgb3VyIFRlcm1zIG9mIFNlcnZpY2U=',
  75. 'RXZlbiBpZiB5b3UgYXJlIG5vdCBwYXJ0IG9mIGEgY29tbWVyY2lhbCBvcmdhbml6YXRpb24sIHNjcmlwdGluZyBhZ2FpbnN0IFNpdGUgUmV2aWV3IGlzIHN0aWxsIGFnYWluc3QgdGhlIFRlcm1zIG9mIFNlcnZpY2U=',
  76. 'U2NyaXB0aW5nIGFnYWluc3QgU2l0ZSBSZXZpZXcgaXMgYWdhaW5zdCB0aGUgU2l0ZSBSZXZpZXcgVGVybXMgb2YgU2VydmljZQ=='
  77. ]
  78. # New Bluecoat XSRF Code added May 2022 thanks to @froyo75
  79. xsrf_token_parts = token.split('-')
  80. xsrf_random_part = random.choice(xsrf_token_parts)
  81. key_data = xsrf_random_part + ': ' + token
  82. # Key used as part of POST data
  83. key = sha256(key_data.encode('utf-8')).hexdigest()
  84. random_phrase = base64.b64decode(random.choice(phrases)).decode('utf-8')
  85. phrase_data = xsrf_random_part + ': ' + random_phrase
  86. # Phrase used as part of POST data
  87. phrase = sha256(phrase_data.encode('utf-8')).hexdigest()
  88. postData = {
  89. 'url':domain,
  90. 'captcha':'',
  91. 'key':key,
  92. 'phrase':phrase, # Pick a random base64 phrase from the list
  93. 'source':'new-lookup'}
  94. headers = {'User-Agent':useragent,
  95. 'Accept':'application/json, text/plain, */*',
  96. 'Accept-Language':'en_US',
  97. 'Content-Type':'application/json; charset=UTF-8',
  98. 'X-XSRF-TOKEN':token,
  99. 'Referer':'http://sitereview.bluecoat.com/'}
  100. print('[*] BlueCoat: {}'.format(domain))
  101. response = s.post('https://sitereview.bluecoat.com/resource/lookup',headers=headers,json=postData,verify=False,proxies=proxies)
  102. # Check for any HTTP errors
  103. if response.status_code != 200:
  104. a = "HTTP Error ({}-{}) - Is your IP blocked?".format(response.status_code,response.reason)
  105. else:
  106. responseJSON = json.loads(response.text)
  107. if 'errorType' in responseJSON:
  108. a = responseJSON['errorType']
  109. else:
  110. a = responseJSON['categorization'][0]['name']
  111. # Print notice if CAPTCHAs are blocking accurate results and attempt to solve if --ocr
  112. if a == 'captcha':
  113. if ocr:
  114. # This request is also performed by a browser, but is not needed for our purposes
  115. #captcharequestURL = 'https://sitereview.bluecoat.com/resource/captcha-request'
  116. print('[*] Received CAPTCHA challenge!')
  117. captcha = solveCaptcha('https://sitereview.bluecoat.com/resource/captcha.jpg',s)
  118. if captcha:
  119. b64captcha = base64.urlsafe_b64encode(captcha.encode('utf-8')).decode('utf-8')
  120. # Send CAPTCHA solution via GET since inclusion with the domain categorization request doesn't work anymore
  121. captchasolutionURL = 'https://sitereview.bluecoat.com/resource/captcha-request/{0}'.format(b64captcha)
  122. print('[*] Submiting CAPTCHA at {0}'.format(captchasolutionURL))
  123. response = s.get(url=captchasolutionURL,headers=headers,verify=False,proxies=proxies)
  124. # Try the categorization request again
  125. response = s.post(url,headers=headers,json=postData,verify=False,proxies=proxies)
  126. responseJSON = json.loads(response.text)
  127. if 'errorType' in responseJSON:
  128. a = responseJSON['errorType']
  129. else:
  130. a = responseJSON['categorization'][0]['name']
  131. else:
  132. print('[-] Error: Failed to solve BlueCoat CAPTCHA with OCR! Manually solve at "https://sitereview.bluecoat.com/sitereview.jsp"')
  133. else:
  134. print('[-] Error: BlueCoat CAPTCHA received. Try --ocr flag or manually solve a CAPTCHA at "https://sitereview.bluecoat.com/sitereview.jsp"')
  135. return a
  136. except Exception as e:
  137. print('[-] Error retrieving Bluecoat reputation! {0}'.format(e))
  138. return "error"
  139. def checkIBMXForce(domain):
  140. """IBM XForce Domain Reputation"""
  141. try:
  142. url = 'https://exchange.xforce.ibmcloud.com/url/{}'.format(domain)
  143. headers = {'User-Agent':useragent,
  144. 'Accept':'application/json, text/plain, */*',
  145. 'x-ui':'XFE',
  146. 'Origin':url,
  147. 'Referer':url}
  148. print('[*] IBM xForce: {}'.format(domain))
  149. url = 'https://api.xforce.ibmcloud.com/url/{}'.format(domain)
  150. response = s.get(url,headers=headers,verify=False,proxies=proxies)
  151. responseJSON = json.loads(response.text)
  152. if 'error' in responseJSON:
  153. a = responseJSON['error']
  154. elif not responseJSON['result']['cats']:
  155. a = 'Uncategorized'
  156. ## TO-DO - Add noticed when "intrusion" category is returned. This is indication of rate limit / brute-force protection hit on the endpoint
  157. else:
  158. categories = ''
  159. # Parse all dictionary keys and append to single string to get Category names
  160. for key in responseJSON['result']['cats']:
  161. categories += '{0}, '.format(str(key))
  162. a = '{0}(Score: {1})'.format(categories,str(responseJSON['result']['score']))
  163. return a
  164. except Exception as e:
  165. print('[-] Error retrieving IBM-Xforce reputation! {0}'.format(e))
  166. return "error"
  167. def checkTalos(domain):
  168. """Cisco Talos Domain Reputation"""
  169. url = 'https://www.talosintelligence.com/sb_api/query_lookup?query=%2Fapi%2Fv2%2Fdetails%2Fdomain%2F&query_entry={0}&offset=0&order=ip+asc'.format(domain)
  170. headers = {'User-Agent':useragent,
  171. 'Referer':url}
  172. print('[*] Cisco Talos: {}'.format(domain))
  173. try:
  174. response = s.get(url,headers=headers,verify=False,proxies=proxies)
  175. responseJSON = json.loads(response.text)
  176. if 'error' in responseJSON:
  177. a = str(responseJSON['error'])
  178. if a == "Unfortunately, we can't find any results for your search.":
  179. a = 'Uncategorized'
  180. elif responseJSON['category'] is None:
  181. a = 'Uncategorized'
  182. else:
  183. a = '{0} (Score: {1})'.format(str(responseJSON['category']['description']), str(responseJSON['web_score_name']))
  184. return a
  185. except Exception as e:
  186. print('[-] Error retrieving Talos reputation! {0}'.format(e))
  187. return "error"
  188. def checkMcAfeeWG(domain):
  189. """McAfee Web Gateway Domain Reputation"""
  190. try:
  191. print('[*] McAfee Web Gateway (Cloud): {}'.format(domain))
  192. # HTTP Session container, used to manage cookies, session tokens and other session information
  193. s = requests.Session()
  194. headers = {
  195. 'User-Agent':useragent,
  196. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  197. 'Accept-Language': 'en-US,en;q=0.5',
  198. 'Accept-Encoding': 'gzip, deflate',
  199. 'Referer':'https://sitelookup.mcafee.com/'
  200. }
  201. # Establish our session information
  202. response = s.get("https://sitelookup.mcafee.com",headers=headers,verify=False,proxies=proxies)
  203. # Pull the hidden attributes from the response
  204. soup = BeautifulSoup(response.text,"html.parser")
  205. hidden_tags = soup.find_all("input", {"type": "hidden"})
  206. for tag in hidden_tags:
  207. if tag['name'] == 'sid':
  208. sid = tag['value']
  209. elif tag['name'] == 'e':
  210. e = tag['value']
  211. elif tag['name'] == 'c':
  212. c = tag['value']
  213. elif tag['name'] == 'p':
  214. p = tag['value']
  215. # Retrieve the categorization infos
  216. multipart_form_data = {
  217. 'sid': (None, sid),
  218. 'e': (None, e),
  219. 'c': (None, c),
  220. 'p': (None, p),
  221. 'action': (None, 'checksingle'),
  222. 'product': (None, '14-ts'),
  223. 'url': (None, domain)
  224. }
  225. response = s.post('https://sitelookup.mcafee.com/en/feedback/url',headers=headers,files=multipart_form_data,verify=False,proxies=proxies)
  226. if response.status_code == 200:
  227. soup = BeautifulSoup(response.text,"html.parser")
  228. for table in soup.findAll("table", {"class": ["result-table"]}):
  229. datas = table.find_all('td')
  230. if "not valid" in datas[2].text:
  231. a = 'Uncategorized'
  232. else:
  233. status = datas[2].text
  234. category = (datas[3].text[1:]).strip().replace('-',' -')
  235. web_reputation = datas[4].text
  236. a = '{0}, Status: {1}, Web Reputation: {2}'.format(category,status,web_reputation)
  237. return a
  238. else:
  239. raise Exception
  240. except Exception as e:
  241. print('[-] Error retrieving McAfee Web Gateway Domain Reputation!')
  242. return "error"
  243. def downloadMalwareDomains(malwaredomainsURL):
  244. """Downloads a current list of known malicious domains"""
  245. url = malwaredomainsURL
  246. response = s.get(url=url,headers=headers,verify=False,proxies=proxies)
  247. responseText = response.text
  248. if response.status_code == 200:
  249. return responseText
  250. else:
  251. print("[-] Error reaching:{} Status: {}").format(url, response.status_code)
  252. def checkDomain(domain):
  253. """Executes various domain reputation checks included in the project"""
  254. print('[*] Fetching domain reputation for: {}'.format(domain))
  255. if domain in maldomainsList:
  256. print("[!] {}: Identified as known malware domain (malwaredomains.com)".format(domain))
  257. bluecoat = checkBluecoat(domain)
  258. print("[+] {}: {}".format(domain, bluecoat))
  259. ibmxforce = checkIBMXForce(domain)
  260. print("[+] {}: {}".format(domain, ibmxforce))
  261. ciscotalos = checkTalos(domain)
  262. print("[+] {}: {}".format(domain, ciscotalos))
  263. umbrella = "not available"
  264. if len(umbrella_apikey):
  265. umbrella = checkUmbrella(domain)
  266. print("[+] {}: {}".format(domain, umbrella))
  267. mcafeewg = checkMcAfeeWG(domain)
  268. print("[+] {}: {}".format(domain, mcafeewg))
  269. print("")
  270. results = [domain,bluecoat,ibmxforce,ciscotalos,umbrella,mcafeewg]
  271. return results
  272. def solveCaptcha(url,session):
  273. """Downloads CAPTCHA image and saves to current directory for OCR with tesseract
  274. Returns CAPTCHA string or False if error ocurred
  275. """
  276. jpeg = 'captcha.jpg'
  277. try:
  278. response = session.get(url=url,headers=headers,verify=False, stream=True,proxies=proxies)
  279. if response.status_code == 200:
  280. with open(jpeg, 'wb') as f:
  281. response.raw.decode_content = True
  282. shutil.copyfileobj(response.raw, f)
  283. else:
  284. print('[-] Error downloading CAPTCHA file!')
  285. return False
  286. # Perform basic OCR without additional image enhancement
  287. text = pytesseract.image_to_string(Image.open(jpeg))
  288. text = text.replace(" ", "")
  289. # Remove CAPTCHA file
  290. try:
  291. os.remove(jpeg)
  292. except OSError:
  293. pass
  294. return text
  295. except Exception as e:
  296. print("[-] Error solving CAPTCHA - {0}".format(e))
  297. return False
  298. def drawTable(header,data):
  299. """Generates a text based table for printing to the console"""
  300. data.insert(0,header)
  301. t = Texttable(max_width=maxwidth)
  302. t.add_rows(data)
  303. t.header(header)
  304. return(t.draw())
  305. def loginExpiredDomains():
  306. """Login to the ExpiredDomains site with supplied credentials"""
  307. data = "login=%s&password=%s&redirect_2_url=/" % (username, password)
  308. headers["Content-Type"] = "application/x-www-form-urlencoded"
  309. r = s.post(expireddomainHost + "/login/", headers=headers, data=data, proxies=proxies, verify=False, allow_redirects=False)
  310. cookies = s.cookies.get_dict()
  311. if "location" in r.headers:
  312. if "/login/" in r.headers["location"]:
  313. print("[!] Login failed")
  314. sys.exit()
  315. if "ExpiredDomainssessid" in cookies:
  316. print("[+] Login successful. ExpiredDomainssessid: %s" % (cookies["ExpiredDomainssessid"]))
  317. else:
  318. print("[!] Login failed")
  319. sys.exit()
  320. def getIndex(cells, index):
  321. if cells[index].find("a") == None:
  322. return cells[index].text.strip()
  323. return cells[index].find("a").text.strip()
  324. ## MAIN
  325. if __name__ == "__main__":
  326. parser = argparse.ArgumentParser(
  327. description='Finds expired domains, domain categorization, and Archive.org history to determine good candidates for C2 and phishing domains',
  328. epilog = '''
  329. Examples:
  330. ./domainhunter.py -k apples -c --ocr -t5
  331. ./domainhunter.py --check --ocr -t3
  332. ./domainhunter.py --single mydomain.com
  333. ./domainhunter.py --keyword tech --check --ocr --timing 5 --alexa
  334. ./domaihunter.py --filename inputlist.txt --ocr --timing 5''',
  335. formatter_class=argparse.RawDescriptionHelpFormatter)
  336. parser.add_argument('-a','--alexa', help='Filter results to Alexa listings', required=False, default=0, action='store_const', const=1)
  337. parser.add_argument('-k','--keyword', help='Keyword used to refine search results', required=False, default=False, type=str, dest='keyword')
  338. parser.add_argument('-c','--check', help='Perform domain reputation checks', required=False, default=False, action='store_true', dest='check')
  339. parser.add_argument('-f','--filename', help='Specify input file of line delimited domain names to check', required=False, default=False, type=str, dest='filename')
  340. parser.add_argument('--ocr', help='Perform OCR on CAPTCHAs when challenged', required=False, default=False, action='store_true')
  341. parser.add_argument('-r','--maxresults', help='Number of results to return when querying latest expired/deleted domains', required=False, default=100, type=int, dest='maxresults')
  342. parser.add_argument('-s','--single', help='Performs detailed reputation checks against a single domain name/IP.', required=False, default=False, dest='single')
  343. parser.add_argument('-t','--timing', help='Modifies request timing to avoid CAPTCHAs. Slowest(0) = 90-120 seconds, Default(3) = 10-20 seconds, Fastest(5) = no delay', required=False, default=3, type=int, choices=range(0,6), dest='timing')
  344. parser.add_argument('-w','--maxwidth', help='Width of text table', required=False, default=400, type=int, dest='maxwidth')
  345. parser.add_argument('-V','--version', action='version',version='%(prog)s {version}'.format(version=__version__))
  346. parser.add_argument("-P", "--proxy", required=False, default=None, help="proxy. ex https://127.0.0.1:8080")
  347. parser.add_argument("-u", "--username", required=False, default=None, type=str, help="username for expireddomains.net")
  348. parser.add_argument("-p", "--password", required=False, default=None, type=str, help="password for expireddomains.net")
  349. parser.add_argument("-o", "--output", required=False, default=None, type=str, help="output file path")
  350. parser.add_argument('-ks','--keyword-start', help='Keyword starts with used to refine search results', required=False, default="", type=str, dest='keyword_start')
  351. parser.add_argument('-ke','--keyword-end', help='Keyword ends with used to refine search results', required=False, default="", type=str, dest='keyword_end')
  352. parser.add_argument('-um','--umbrella-apikey', help='API Key for umbrella (paid)', required=False, default="", type=str, dest='umbrella_apikey')
  353. parser.add_argument('-q','--quiet', help='Surpress initial ASCII art and header', required=False, default=False, action='store_true', dest='quiet')
  354. args = parser.parse_args()
  355. # Load dependent modules
  356. try:
  357. import requests
  358. from bs4 import BeautifulSoup
  359. from texttable import Texttable
  360. except Exception as e:
  361. print("Expired Domains Reputation Check")
  362. print("[-] Missing basic dependencies: {}".format(str(e)))
  363. print("[*] Install required dependencies by running `pip3 install -r requirements.txt`")
  364. quit(0)
  365. # Load OCR related modules if --ocr flag is set since these can be difficult to get working
  366. if args.ocr:
  367. try:
  368. import pytesseract
  369. from PIL import Image
  370. import shutil
  371. except Exception as e:
  372. print("Expired Domains Reputation Check")
  373. print("[-] Missing OCR dependencies: {}".format(str(e)))
  374. print("[*] Install required Python dependencies by running: pip3 install -r requirements.txt")
  375. print("[*] Ubuntu\Debian - Install tesseract by running: apt-get install tesseract-ocr python3-imaging")
  376. print("[*] macOS - Install tesseract with homebrew by running: brew install tesseract")
  377. quit(0)
  378. ## Variables
  379. username = args.username
  380. password = args.password
  381. proxy = args.proxy
  382. alexa = args.alexa
  383. keyword = args.keyword
  384. check = args.check
  385. filename = args.filename
  386. maxresults = args.maxresults
  387. single = args.single
  388. timing = args.timing
  389. maxwidth = args.maxwidth
  390. ocr = args.ocr
  391. output = args.output
  392. keyword_start = args.keyword_start
  393. keyword_end = args.keyword_end
  394. umbrella_apikey = args.umbrella_apikey
  395. malwaredomainsURL = 'https://gitlab.com/gerowen/old-malware-domains-ad-list/-/raw/master/malwaredomainslist.txt'
  396. expireddomainsqueryURL = 'https://www.expireddomains.net/domain-name-search'
  397. expireddomainHost = "https://member.expireddomains.net"
  398. timestamp = time.strftime("%Y%m%d_%H%M%S")
  399. useragent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'
  400. headers = {'User-Agent':useragent}
  401. proxies = {}
  402. requests.packages.urllib3.disable_warnings()
  403. # HTTP Session container, used to manage cookies, session tokens and other session information
  404. s = requests.Session()
  405. if(args.proxy != None):
  406. proxy_parts = urlparse(args.proxy)
  407. proxies["http"] = "http://%s" % (proxy_parts.netloc)
  408. proxies["https"] = "https://%s" % (proxy_parts.netloc)
  409. s.proxies = proxies
  410. title = '''
  411. ____ ___ __ __ _ ___ _ _ _ _ _ _ _ _ _____ _____ ____
  412. | _ \ / _ \| \/ | / \ |_ _| \ | | | | | | | | | \ | |_ _| ____| _ \
  413. | | | | | | | |\/| | / _ \ | || \| | | |_| | | | | \| | | | | _| | |_) |
  414. | |_| | |_| | | | |/ ___ \ | || |\ | | _ | |_| | |\ | | | | |___| _ <
  415. |____/ \___/|_| |_/_/ \_\___|_| \_| |_| |_|\___/|_| \_| |_| |_____|_| \_\ '''
  416. # Print header
  417. if not (args.quiet):
  418. print(title)
  419. print('''\nExpired Domains Reputation Checker
  420. Authors: @joevest and @andrewchiles\n
  421. DISCLAIMER: This is for educational purposes only!
  422. It is designed to promote education and the improvement of computer/cyber security.
  423. The authors or employers are not liable for any illegal act or misuse performed by any user of this tool.
  424. If you plan to use this content for illegal purpose, don't. Have a nice day :)\n''')
  425. # Download known malware domains
  426. # print('[*] Downloading malware domain list from {}\n'.format(malwaredomainsURL))
  427. maldomains = downloadMalwareDomains(malwaredomainsURL)
  428. maldomainsList = maldomains.split("\n")
  429. # Retrieve reputation for a single choosen domain (Quick Mode)
  430. if single:
  431. checkDomain(single)
  432. exit(0)
  433. # Perform detailed domain reputation checks against input file, print table, and quit. This does not generate an HTML report
  434. if filename:
  435. # Initialize our list with an empty row for the header
  436. data = []
  437. try:
  438. with open(filename, 'r') as domainsList:
  439. for line in domainsList.read().splitlines():
  440. data.append(checkDomain(line))
  441. doSleep(timing)
  442. # Print results table
  443. header = ['Domain', 'BlueCoat', 'IBM X-Force', 'Cisco Talos', 'Umbrella', 'McAfee Web Gateway (Cloud)']
  444. print(drawTable(header,data))
  445. except KeyboardInterrupt:
  446. print('Caught keyboard interrupt. Exiting!')
  447. exit(0)
  448. except Exception as e:
  449. print('[-] Error: {}'.format(e))
  450. exit(1)
  451. exit(0)
  452. # Lists for our ExpiredDomains results
  453. domain_list = []
  454. data = []
  455. # Generate list of URLs to query for expired/deleted domains
  456. urls = []
  457. if username == None or username == "":
  458. print('[-] Error: ExpiredDomains.net requires a username! Use the --username parameter')
  459. exit(1)
  460. if args.password == None or args.password == "":
  461. password = getpass.getpass("expireddomains.net Password: ")
  462. loginExpiredDomains()
  463. m = 200
  464. if maxresults < m:
  465. m = maxresults
  466. for i in range (0,(maxresults),m):
  467. k=""
  468. if keyword:
  469. k=keyword
  470. urls.append('{}/domains/combinedexpired/?fwhois=22&fadult=1&start={}&ftlds[]=2&ftlds[]=3&ftlds[]=4&flimit={}&fdomain={}&fdomainstart={}&fdomainend={}&falexa={}'.format(expireddomainHost,i,m,k,keyword_start,keyword_end,alexa))
  471. max_reached = False
  472. for url in urls:
  473. print("[*] {}".format(url))
  474. domainrequest = s.get(url,headers=headers,verify=False,proxies=proxies)
  475. domains = domainrequest.text
  476. # Turn the HTML into a Beautiful Soup object
  477. soup = BeautifulSoup(domains, 'html.parser')
  478. try:
  479. table = soup.find_all("table", class_="base1")
  480. tbody = table[0].select("tbody tr")
  481. for row in tbody:
  482. # Alternative way to extract domain name
  483. # domain = row.find('td').find('a').text
  484. cells = row.findAll("td")
  485. if len(cells) == 1:
  486. max_reached = True
  487. break # exit if max rows reached
  488. if len(cells) >= 1:
  489. c0 = getIndex(cells, 0).lower() # domain
  490. c1 = getIndex(cells, 3) # bl
  491. c2 = getIndex(cells, 4) # domainpop
  492. c3 = getIndex(cells, 5) # birth
  493. c4 = getIndex(cells, 7) # Archive.org entries
  494. c5 = getIndex(cells, 8) # Alexa
  495. c6 = getIndex(cells, 10) # Dmoz.org
  496. c7 = getIndex(cells, 12) # status com
  497. c8 = getIndex(cells, 13) # status net
  498. c9 = getIndex(cells, 14) # status org
  499. c10 = getIndex(cells, 17) # status de
  500. c11 = getIndex(cells, 11) # TLDs
  501. c12 = getIndex(cells, 19) # RDT
  502. c13 = "" # List
  503. c14 = getIndex(cells, 22) # Status
  504. c15 = "" # links
  505. # create available TLD list
  506. available = ''
  507. if c7 == "available":
  508. available += ".com "
  509. if c8 == "available":
  510. available += ".net "
  511. if c9 == "available":
  512. available += ".org "
  513. if c10 == "available":
  514. available += ".de "
  515. # Only grab status for keyword searches since it doesn't exist otherwise
  516. status = ""
  517. if keyword:
  518. status = c14
  519. if keyword:
  520. # Only add Expired, not Pending, Backorder, etc
  521. # "expired" isn't returned any more, I changed it to "available"
  522. if c14 == "available": # I'm not sure about this, seems like "expired" isn't an option anymore. expireddomains.net might not support this any more.
  523. # Append parsed domain data to list if it matches our criteria (.com|.net|.org and not a known malware domain)
  524. if (c0.lower().endswith(".com") or c0.lower().endswith(".net") or c0.lower().endswith(".org")) and (c0 not in maldomainsList):
  525. domain_list.append([c0,c3,c4,available,status])
  526. # Non-keyword search table format is slightly different
  527. else:
  528. # Append original parsed domain data to list if it matches our criteria (.com|.net|.org and not a known malware domain)
  529. if (c0.lower().endswith(".com") or c0.lower().endswith(".net") or c0.lower().endswith(".org")) and (c0 not in maldomainsList):
  530. domain_list.append([c0,c3,c4,available,status])
  531. if max_reached:
  532. print("[*] All records returned")
  533. break
  534. except Exception as e:
  535. print("[!] Error: ", e)
  536. pass
  537. # Add additional sleep on requests to ExpiredDomains.net to avoid errors
  538. time.sleep(5)
  539. # Check for valid list results before continuing
  540. if len(domain_list) == 0:
  541. print("[-] No domain results found or none are currently available for purchase!")
  542. exit(0)
  543. else:
  544. domain_list_unique = []
  545. [domain_list_unique.append(item) for item in domain_list if item not in domain_list_unique]
  546. # Print number of domains to perform reputation checks against
  547. if check:
  548. print("\n[*] Performing reputation checks for {} domains".format(len(domain_list_unique)))
  549. print("")
  550. for domain_entry in domain_list_unique:
  551. domain = domain_entry[0]
  552. birthdate = domain_entry[1]
  553. archiveentries = domain_entry[2]
  554. availabletlds = domain_entry[3]
  555. status = domain_entry[4]
  556. bluecoat = '-'
  557. ibmxforce = '-'
  558. ciscotalos = '-'
  559. umbrella = '-'
  560. # Perform domain reputation checks
  561. if check:
  562. unwantedResults = ['Uncategorized','error','Not found.','Spam','Spam URLs','Pornography','badurl','Suspicious','Malicious Sources/Malnets','captcha','Phishing','Placeholders']
  563. bluecoat = checkBluecoat(domain)
  564. if bluecoat not in unwantedResults:
  565. print("[+] Bluecoat - {}: {}".format(domain, bluecoat))
  566. ibmxforce = checkIBMXForce(domain)
  567. if ibmxforce not in unwantedResults:
  568. print("[+] IBM XForce - {}: {}".format(domain, ibmxforce))
  569. ciscotalos = checkTalos(domain)
  570. if ciscotalos not in unwantedResults:
  571. print("[+] Cisco Talos {}: {}".format(domain, ciscotalos))
  572. if len(umbrella_apikey):
  573. umbrella = checkUmbrella(domain)
  574. if umbrella not in unwantedResults:
  575. print("[+] Umbrella {}: {}".format(domain, umbrella))
  576. mcafeewg = checkMcAfeeWG(domain)
  577. if mcafeewg not in unwantedResults:
  578. print("[+] McAfee Web Gateway (Cloud) {}: {}".format(domain, mcafeewg))
  579. print("")
  580. # Sleep to avoid captchas
  581. doSleep(timing)
  582. # Append entry to new list with reputation if at least one service reports reputation
  583. if not (\
  584. (bluecoat in ('Uncategorized','badurl','Suspicious','Malicious Sources/Malnets','captcha','Phishing','Placeholders','Spam','error')) \
  585. and (ibmxforce in ('Not found.','error')) \
  586. and (ciscotalos in ('Uncategorized','error')) \
  587. and (umbrella in ('Uncategorized','None')) \
  588. and (mcafeewg in ('Uncategorized','error'))):
  589. data.append([domain,birthdate,archiveentries,availabletlds,status,bluecoat,ibmxforce,ciscotalos,umbrella,mcafeewg])
  590. # Sort domain list by column 2 (Birth Year)
  591. sortedDomains = sorted(data, key=lambda x: x[1], reverse=True)
  592. if check:
  593. if len(sortedDomains) == 0:
  594. print("[-] No domains discovered with a desireable categorization!")
  595. exit(0)
  596. else:
  597. print("[*] {} of {} domains discovered with a potentially desireable categorization!".format(len(sortedDomains),len(domain_list)))
  598. # Build HTML Table
  599. html = ''
  600. htmlHeader = '<html><head><title>Expired Domain List</title></head>'
  601. htmlBody = '<body><p>The following available domains report was generated at {}</p>'.format(timestamp)
  602. htmlTableHeader = '''
  603. <table border="1" align="center">
  604. <th>Domain</th>
  605. <th>Birth</th>
  606. <th>Entries</th>
  607. <th>TLDs Available</th>
  608. <th>Status</th>
  609. <th>BlueCoat</th>
  610. <th>IBM X-Force</th>
  611. <th>Cisco Talos</th>
  612. <th>Umbrella</th>
  613. <th>WatchGuard</th>
  614. <th>Namecheap</th>
  615. <th>Archive.org</th>
  616. '''
  617. htmlTableBody = ''
  618. htmlTableFooter = '</table>'
  619. htmlFooter = '</body></html>'
  620. # Build HTML table contents
  621. for i in sortedDomains:
  622. htmlTableBody += '<tr>'
  623. htmlTableBody += '<td>{}</td>'.format(i[0]) # Domain
  624. htmlTableBody += '<td>{}</td>'.format(i[1]) # Birth
  625. htmlTableBody += '<td>{}</td>'.format(i[2]) # Entries
  626. htmlTableBody += '<td>{}</td>'.format(i[3]) # TLDs
  627. htmlTableBody += '<td>{}</td>'.format(i[4]) # Status
  628. htmlTableBody += '<td><a href="https://sitereview.bluecoat.com/" target="_blank">{}</a></td>'.format(i[5]) # Bluecoat
  629. htmlTableBody += '<td><a href="https://exchange.xforce.ibmcloud.com/url/{}" target="_blank">{}</a></td>'.format(i[0],i[6]) # IBM x-Force Categorization
  630. htmlTableBody += '<td><a href="https://www.talosintelligence.com/reputation_center/lookup?search={}" target="_blank">{}</a></td>'.format(i[0],i[7]) # Cisco Talos
  631. htmlTableBody += '<td>{}</td>'.format(i[8]) # Cisco Umbrella
  632. htmlTableBody += '<td><a href="https://sitelookup.mcafee.com/en/feedback/url?action=checksingle&url=http%3A%2F%2F{}&product=14-ts" target="_blank">{}</a></td>'.format(i[0],i[9]) # McAfee Web Gateway (Cloud)
  633. htmlTableBody += '<td><a href="http://www.borderware.com/domain_lookup.php?ip={}" target="_blank">WatchGuard</a></td>'.format(i[0]) # Borderware WatchGuard
  634. htmlTableBody += '<td><a href="https://www.namecheap.com/domains/registration/results.aspx?domain={}" target="_blank">Namecheap</a></td>'.format(i[0]) # Namecheap
  635. htmlTableBody += '<td><a href="http://web.archive.org/web/*/{}" target="_blank">Archive.org</a></td>'.format(i[0]) # Archive.org
  636. htmlTableBody += '</tr>'
  637. html = htmlHeader + htmlBody + htmlTableHeader + htmlTableBody + htmlTableFooter + htmlFooter
  638. logfilename = "{}_domainreport.html".format(timestamp)
  639. if output != None:
  640. logfilename = output
  641. log = open(logfilename,'w')
  642. log.write(html)
  643. log.close
  644. print("\n[*] Search complete")
  645. print("[*] Log written to {}\n".format(logfilename))
  646. # Print Text Table
  647. header = ['Domain', 'Birth', '#', 'TLDs', 'Status', 'BlueCoat', 'IBM', 'Cisco Talos', 'Umbrella']
  648. print(drawTable(header,sortedDomains))