domainhunter.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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 checkMXToolbox(domain):
  189. """ Checks the MXToolbox service for Google SafeBrowsing and PhishTank information. Currently broken"""
  190. url = 'https://mxtoolbox.com/Public/Tools/BrandReputation.aspx'
  191. headers = {'User-Agent':useragent,
  192. 'Origin':url,
  193. 'Referer':url}
  194. print('[*] Google SafeBrowsing and PhishTank: {}'.format(domain))
  195. try:
  196. response = s.get(url=url, headers=headers,proxies=proxies,verify=False)
  197. soup = BeautifulSoup(response.content,'lxml')
  198. viewstate = soup.select('input[name=__VIEWSTATE]')[0]['value']
  199. viewstategenerator = soup.select('input[name=__VIEWSTATEGENERATOR]')[0]['value']
  200. eventvalidation = soup.select('input[name=__EVENTVALIDATION]')[0]['value']
  201. data = {
  202. "__EVENTTARGET": "",
  203. "__EVENTARGUMENT": "",
  204. "__VIEWSTATE": viewstate,
  205. "__VIEWSTATEGENERATOR": viewstategenerator,
  206. "__EVENTVALIDATION": eventvalidation,
  207. "ctl00$ContentPlaceHolder1$brandReputationUrl": domain,
  208. "ctl00$ContentPlaceHolder1$brandReputationDoLookup": "Brand Reputation Lookup",
  209. "ctl00$ucSignIn$hfRegCode": 'missing',
  210. "ctl00$ucSignIn$hfRedirectSignUp": '/Public/Tools/BrandReputation.aspx',
  211. "ctl00$ucSignIn$hfRedirectLogin": '',
  212. "ctl00$ucSignIn$txtEmailAddress": '',
  213. "ctl00$ucSignIn$cbNewAccount": 'cbNewAccount',
  214. "ctl00$ucSignIn$txtFullName": '',
  215. "ctl00$ucSignIn$txtModalNewPassword": '',
  216. "ctl00$ucSignIn$txtPhone": '',
  217. "ctl00$ucSignIn$txtCompanyName": '',
  218. "ctl00$ucSignIn$drpTitle": '',
  219. "ctl00$ucSignIn$txtTitleName": '',
  220. "ctl00$ucSignIn$txtModalPassword": ''
  221. }
  222. response = s.post(url=url, headers=headers, data=data,proxies=proxies,verify=False)
  223. soup = BeautifulSoup(response.content,'lxml')
  224. a = ''
  225. if soup.select('div[id=ctl00_ContentPlaceHolder1_noIssuesFound]'):
  226. a = 'No issues found'
  227. return a
  228. else:
  229. if soup.select('div[id=ctl00_ContentPlaceHolder1_googleSafeBrowsingIssuesFound]'):
  230. a = 'Google SafeBrowsing Issues Found. '
  231. if soup.select('div[id=ctl00_ContentPlaceHolder1_phishTankIssuesFound]'):
  232. a += 'PhishTank Issues Found'
  233. return a
  234. except Exception as e:
  235. print('[-] Error retrieving Google SafeBrowsing and PhishTank reputation!')
  236. return "error"
  237. def downloadMalwareDomains(malwaredomainsURL):
  238. """Downloads a current list of known malicious domains"""
  239. url = malwaredomainsURL
  240. response = s.get(url=url,headers=headers,verify=False,proxies=proxies)
  241. responseText = response.text
  242. if response.status_code == 200:
  243. return responseText
  244. else:
  245. print("[-] Error reaching:{} Status: {}").format(url, response.status_code)
  246. def checkDomain(domain):
  247. """Executes various domain reputation checks included in the project"""
  248. print('[*] Fetching domain reputation for: {}'.format(domain))
  249. if domain in maldomainsList:
  250. print("[!] {}: Identified as known malware domain (malwaredomains.com)".format(domain))
  251. bluecoat = checkBluecoat(domain)
  252. print("[+] {}: {}".format(domain, bluecoat))
  253. ibmxforce = checkIBMXForce(domain)
  254. print("[+] {}: {}".format(domain, ibmxforce))
  255. ciscotalos = checkTalos(domain)
  256. print("[+] {}: {}".format(domain, ciscotalos))
  257. #This service has completely changed, removing for now
  258. #mxtoolbox = checkMXToolbox(domain)
  259. #print("[+] {}: {}".format(domain, mxtoolbox))
  260. mxtoolbox = "-"
  261. umbrella = "not available"
  262. if len(umbrella_apikey):
  263. umbrella = checkUmbrella(domain)
  264. print("[+] {}: {}".format(domain, umbrella))
  265. print("")
  266. results = [domain,bluecoat,ibmxforce,ciscotalos,umbrella,mxtoolbox]
  267. return results
  268. def solveCaptcha(url,session):
  269. """Downloads CAPTCHA image and saves to current directory for OCR with tesseract
  270. Returns CAPTCHA string or False if error occured
  271. """
  272. jpeg = 'captcha.jpg'
  273. try:
  274. response = session.get(url=url,headers=headers,verify=False, stream=True,proxies=proxies)
  275. if response.status_code == 200:
  276. with open(jpeg, 'wb') as f:
  277. response.raw.decode_content = True
  278. shutil.copyfileobj(response.raw, f)
  279. else:
  280. print('[-] Error downloading CAPTCHA file!')
  281. return False
  282. # Perform basic OCR without additional image enhancement
  283. text = pytesseract.image_to_string(Image.open(jpeg))
  284. text = text.replace(" ", "")
  285. # Remove CAPTCHA file
  286. try:
  287. os.remove(jpeg)
  288. except OSError:
  289. pass
  290. return text
  291. except Exception as e:
  292. print("[-] Error solving CAPTCHA - {0}".format(e))
  293. return False
  294. def drawTable(header,data):
  295. """Generates a text based table for printing to the console"""
  296. data.insert(0,header)
  297. t = Texttable(max_width=maxwidth)
  298. t.add_rows(data)
  299. t.header(header)
  300. return(t.draw())
  301. def loginExpiredDomains():
  302. """Login to the ExpiredDomains site with supplied credentials"""
  303. data = "login=%s&password=%s&redirect_2_url=/" % (username, password)
  304. headers["Content-Type"] = "application/x-www-form-urlencoded"
  305. r = s.post(expireddomainHost + "/login/", headers=headers, data=data, proxies=proxies, verify=False, allow_redirects=False)
  306. cookies = s.cookies.get_dict()
  307. if "location" in r.headers:
  308. if "/login/" in r.headers["location"]:
  309. print("[!] Login failed")
  310. sys.exit()
  311. if "ExpiredDomainssessid" in cookies:
  312. print("[+] Login successful. ExpiredDomainssessid: %s" % (cookies["ExpiredDomainssessid"]))
  313. else:
  314. print("[!] Login failed")
  315. sys.exit()
  316. def getIndex(cells, index):
  317. if cells[index].find("a") == None:
  318. return cells[index].text.strip()
  319. return cells[index].find("a").text.strip()
  320. ## MAIN
  321. if __name__ == "__main__":
  322. parser = argparse.ArgumentParser(
  323. description='Finds expired domains, domain categorization, and Archive.org history to determine good candidates for C2 and phishing domains',
  324. epilog = '''
  325. Examples:
  326. ./domainhunter.py -k apples -c --ocr -t5
  327. ./domainhunter.py --check --ocr -t3
  328. ./domainhunter.py --single mydomain.com
  329. ./domainhunter.py --keyword tech --check --ocr --timing 5 --alexa
  330. ./domaihunter.py --filename inputlist.txt --ocr --timing 5''',
  331. formatter_class=argparse.RawDescriptionHelpFormatter)
  332. parser.add_argument('-a','--alexa', help='Filter results to Alexa listings', required=False, default=0, action='store_const', const=1)
  333. parser.add_argument('-k','--keyword', help='Keyword used to refine search results', required=False, default=False, type=str, dest='keyword')
  334. parser.add_argument('-c','--check', help='Perform domain reputation checks', required=False, default=False, action='store_true', dest='check')
  335. parser.add_argument('-f','--filename', help='Specify input file of line delimited domain names to check', required=False, default=False, type=str, dest='filename')
  336. parser.add_argument('--ocr', help='Perform OCR on CAPTCHAs when challenged', required=False, default=False, action='store_true')
  337. 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')
  338. parser.add_argument('-s','--single', help='Performs detailed reputation checks against a single domain name/IP.', required=False, default=False, dest='single')
  339. 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')
  340. parser.add_argument('-w','--maxwidth', help='Width of text table', required=False, default=400, type=int, dest='maxwidth')
  341. parser.add_argument('-V','--version', action='version',version='%(prog)s {version}'.format(version=__version__))
  342. parser.add_argument("-P", "--proxy", required=False, default=None, help="proxy. ex https://127.0.0.1:8080")
  343. parser.add_argument("-u", "--username", required=False, default=None, type=str, help="username for expireddomains.net")
  344. parser.add_argument("-p", "--password", required=False, default=None, type=str, help="password for expireddomains.net")
  345. parser.add_argument("-o", "--output", required=False, default=None, type=str, help="output file path")
  346. parser.add_argument('-ks','--keyword-start', help='Keyword starts with used to refine search results', required=False, default="", type=str, dest='keyword_start')
  347. parser.add_argument('-ke','--keyword-end', help='Keyword ends with used to refine search results', required=False, default="", type=str, dest='keyword_end')
  348. parser.add_argument('-um','--umbrella-apikey', help='API Key for umbrella (paid)', required=False, default="", type=str, dest='umbrella_apikey')
  349. parser.add_argument('-q','--quiet', help='Surpress initial ASCII art and header', required=False, default=False, action='store_true', dest='quiet')
  350. args = parser.parse_args()
  351. # Load dependent modules
  352. try:
  353. import requests
  354. from bs4 import BeautifulSoup
  355. from texttable import Texttable
  356. except Exception as e:
  357. print("Expired Domains Reputation Check")
  358. print("[-] Missing basic dependencies: {}".format(str(e)))
  359. print("[*] Install required dependencies by running `pip3 install -r requirements.txt`")
  360. quit(0)
  361. # Load OCR related modules if --ocr flag is set since these can be difficult to get working
  362. if args.ocr:
  363. try:
  364. import pytesseract
  365. from PIL import Image
  366. import shutil
  367. except Exception as e:
  368. print("Expired Domains Reputation Check")
  369. print("[-] Missing OCR dependencies: {}".format(str(e)))
  370. print("[*] Install required Python dependencies by running: pip3 install -r requirements.txt")
  371. print("[*] Ubuntu\Debian - Install tesseract by running: apt-get install tesseract-ocr python3-imaging")
  372. print("[*] macOS - Install tesseract with homebrew by running: brew install tesseract")
  373. quit(0)
  374. ## Variables
  375. username = args.username
  376. password = args.password
  377. proxy = args.proxy
  378. alexa = args.alexa
  379. keyword = args.keyword
  380. check = args.check
  381. filename = args.filename
  382. maxresults = args.maxresults
  383. single = args.single
  384. timing = args.timing
  385. maxwidth = args.maxwidth
  386. ocr = args.ocr
  387. output = args.output
  388. keyword_start = args.keyword_start
  389. keyword_end = args.keyword_end
  390. umbrella_apikey = args.umbrella_apikey
  391. malwaredomainsURL = 'https://gitlab.com/gerowen/old-malware-domains-ad-list/-/raw/master/malwaredomainslist.txt'
  392. expireddomainsqueryURL = 'https://www.expireddomains.net/domain-name-search'
  393. expireddomainHost = "https://member.expireddomains.net"
  394. timestamp = time.strftime("%Y%m%d_%H%M%S")
  395. useragent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'
  396. headers = {'User-Agent':useragent}
  397. proxies = {}
  398. requests.packages.urllib3.disable_warnings()
  399. # HTTP Session container, used to manage cookies, session tokens and other session information
  400. s = requests.Session()
  401. if(args.proxy != None):
  402. proxy_parts = urlparse(args.proxy)
  403. proxies["http"] = "http://%s" % (proxy_parts.netloc)
  404. proxies["https"] = "https://%s" % (proxy_parts.netloc)
  405. s.proxies = proxies
  406. title = '''
  407. ____ ___ __ __ _ ___ _ _ _ _ _ _ _ _ _____ _____ ____
  408. | _ \ / _ \| \/ | / \ |_ _| \ | | | | | | | | | \ | |_ _| ____| _ \
  409. | | | | | | | |\/| | / _ \ | || \| | | |_| | | | | \| | | | | _| | |_) |
  410. | |_| | |_| | | | |/ ___ \ | || |\ | | _ | |_| | |\ | | | | |___| _ <
  411. |____/ \___/|_| |_/_/ \_\___|_| \_| |_| |_|\___/|_| \_| |_| |_____|_| \_\ '''
  412. # Print header
  413. if not (args.quiet):
  414. print(title)
  415. print('''\nExpired Domains Reputation Checker
  416. Authors: @joevest and @andrewchiles\n
  417. DISCLAIMER: This is for educational purposes only!
  418. It is designed to promote education and the improvement of computer/cyber security.
  419. The authors or employers are not liable for any illegal act or misuse performed by any user of this tool.
  420. If you plan to use this content for illegal purpose, don't. Have a nice day :)\n''')
  421. # Download known malware domains
  422. # print('[*] Downloading malware domain list from {}\n'.format(malwaredomainsURL))
  423. maldomains = downloadMalwareDomains(malwaredomainsURL)
  424. maldomainsList = maldomains.split("\n")
  425. # Retrieve reputation for a single choosen domain (Quick Mode)
  426. if single:
  427. checkDomain(single)
  428. exit(0)
  429. # Perform detailed domain reputation checks against input file, print table, and quit. This does not generate an HTML report
  430. if filename:
  431. # Initialize our list with an empty row for the header
  432. data = []
  433. try:
  434. with open(filename, 'r') as domainsList:
  435. for line in domainsList.read().splitlines():
  436. data.append(checkDomain(line))
  437. doSleep(timing)
  438. # Print results table
  439. header = ['Domain', 'BlueCoat', 'IBM X-Force', 'Cisco Talos', 'Umbrella', 'MXToolbox']
  440. print(drawTable(header,data))
  441. except KeyboardInterrupt:
  442. print('Caught keyboard interrupt. Exiting!')
  443. exit(0)
  444. except Exception as e:
  445. print('[-] Error: {}'.format(e))
  446. exit(1)
  447. exit(0)
  448. # Lists for our ExpiredDomains results
  449. domain_list = []
  450. data = []
  451. # Generate list of URLs to query for expired/deleted domains
  452. urls = []
  453. if username == None or username == "":
  454. print('[-] Error: ExpiredDomains.net requires a username! Use the --username parameter')
  455. exit(1)
  456. if args.password == None or args.password == "":
  457. password = getpass.getpass("expireddomains.net Password: ")
  458. loginExpiredDomains()
  459. m = 200
  460. if maxresults < m:
  461. m = maxresults
  462. for i in range (0,(maxresults),m):
  463. k=""
  464. if keyword:
  465. k=keyword
  466. 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))
  467. max_reached = False
  468. for url in urls:
  469. print("[*] {}".format(url))
  470. domainrequest = s.get(url,headers=headers,verify=False,proxies=proxies)
  471. domains = domainrequest.text
  472. # Turn the HTML into a Beautiful Soup object
  473. soup = BeautifulSoup(domains, 'html.parser')
  474. try:
  475. table = soup.find_all("table", class_="base1")
  476. tbody = table[0].select("tbody tr")
  477. for row in tbody:
  478. # Alternative way to extract domain name
  479. # domain = row.find('td').find('a').text
  480. cells = row.findAll("td")
  481. if len(cells) == 1:
  482. max_reached = True
  483. break # exit if max rows reached
  484. if len(cells) >= 1:
  485. c0 = getIndex(cells, 0).lower() # domain
  486. c1 = getIndex(cells, 3) # bl
  487. c2 = getIndex(cells, 4) # domainpop
  488. c3 = getIndex(cells, 5) # birth
  489. c4 = getIndex(cells, 7) # Archive.org entries
  490. c5 = getIndex(cells, 8) # Alexa
  491. c6 = getIndex(cells, 10) # Dmoz.org
  492. c7 = getIndex(cells, 12) # status com
  493. c8 = getIndex(cells, 13) # status net
  494. c9 = getIndex(cells, 14) # status org
  495. c10 = getIndex(cells, 17) # status de
  496. c11 = getIndex(cells, 11) # TLDs
  497. c12 = getIndex(cells, 19) # RDT
  498. c13 = "" # List
  499. c14 = getIndex(cells, 22) # Status
  500. c15 = "" # links
  501. # create available TLD list
  502. available = ''
  503. if c7 == "available":
  504. available += ".com "
  505. if c8 == "available":
  506. available += ".net "
  507. if c9 == "available":
  508. available += ".org "
  509. if c10 == "available":
  510. available += ".de "
  511. # Only grab status for keyword searches since it doesn't exist otherwise
  512. status = ""
  513. if keyword:
  514. status = c14
  515. if keyword:
  516. # Only add Expired, not Pending, Backorder, etc
  517. # "expired" isn't returned any more, I changed it to "available"
  518. 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.
  519. # Append parsed domain data to list if it matches our criteria (.com|.net|.org and not a known malware domain)
  520. if (c0.lower().endswith(".com") or c0.lower().endswith(".net") or c0.lower().endswith(".org")) and (c0 not in maldomainsList):
  521. domain_list.append([c0,c3,c4,available,status])
  522. # Non-keyword search table format is slightly different
  523. else:
  524. # Append original parsed domain data to list if it matches our criteria (.com|.net|.org and not a known malware domain)
  525. if (c0.lower().endswith(".com") or c0.lower().endswith(".net") or c0.lower().endswith(".org")) and (c0 not in maldomainsList):
  526. domain_list.append([c0,c3,c4,available,status])
  527. if max_reached:
  528. print("[*] All records returned")
  529. break
  530. except Exception as e:
  531. print("[!] Error: ", e)
  532. pass
  533. # Add additional sleep on requests to ExpiredDomains.net to avoid errors
  534. time.sleep(5)
  535. # Check for valid list results before continuing
  536. if len(domain_list) == 0:
  537. print("[-] No domain results found or none are currently available for purchase!")
  538. exit(0)
  539. else:
  540. domain_list_unique = []
  541. [domain_list_unique.append(item) for item in domain_list if item not in domain_list_unique]
  542. # Print number of domains to perform reputation checks against
  543. if check:
  544. print("\n[*] Performing reputation checks for {} domains".format(len(domain_list_unique)))
  545. print("")
  546. for domain_entry in domain_list_unique:
  547. domain = domain_entry[0]
  548. birthdate = domain_entry[1]
  549. archiveentries = domain_entry[2]
  550. availabletlds = domain_entry[3]
  551. status = domain_entry[4]
  552. bluecoat = '-'
  553. ibmxforce = '-'
  554. ciscotalos = '-'
  555. umbrella = '-'
  556. # Perform domain reputation checks
  557. if check:
  558. unwantedResults = ['Uncategorized','error','Not found.','Spam','Spam URLs','Pornography','badurl','Suspicious','Malicious Sources/Malnets','captcha','Phishing','Placeholders']
  559. bluecoat = checkBluecoat(domain)
  560. if bluecoat not in unwantedResults:
  561. print("[+] Bluecoat - {}: {}".format(domain, bluecoat))
  562. ibmxforce = checkIBMXForce(domain)
  563. if ibmxforce not in unwantedResults:
  564. print("[+] IBM XForce - {}: {}".format(domain, ibmxforce))
  565. ciscotalos = checkTalos(domain)
  566. if ciscotalos not in unwantedResults:
  567. print("[+] Cisco Talos {}: {}".format(domain, ciscotalos))
  568. if len(umbrella_apikey):
  569. umbrella = checkUmbrella(domain)
  570. if umbrella not in unwantedResults:
  571. print("[+] Umbrella {}: {}".format(domain, umbrella))
  572. print("")
  573. # Sleep to avoid captchas
  574. doSleep(timing)
  575. # Append entry to new list with reputation if at least one service reports reputation
  576. if not ((bluecoat in ('Uncategorized','badurl','Suspicious','Malicious Sources/Malnets','captcha','Phishing','Placeholders','Spam','error')) \
  577. and (ibmxforce in ('Not found.','error')) and (ciscotalos in ('Uncategorized','error')) and (umbrella in ('Uncategorized','None'))):
  578. data.append([domain,birthdate,archiveentries,availabletlds,status,bluecoat,ibmxforce,ciscotalos,umbrella])
  579. # Sort domain list by column 2 (Birth Year)
  580. sortedDomains = sorted(data, key=lambda x: x[1], reverse=True)
  581. if check:
  582. if len(sortedDomains) == 0:
  583. print("[-] No domains discovered with a desireable categorization!")
  584. exit(0)
  585. else:
  586. print("[*] {} of {} domains discovered with a potentially desireable categorization!".format(len(sortedDomains),len(domain_list)))
  587. # Build HTML Table
  588. html = ''
  589. htmlHeader = '<html><head><title>Expired Domain List</title></head>'
  590. htmlBody = '<body><p>The following available domains report was generated at {}</p>'.format(timestamp)
  591. htmlTableHeader = '''
  592. <table border="1" align="center">
  593. <th>Domain</th>
  594. <th>Birth</th>
  595. <th>Entries</th>
  596. <th>TLDs Available</th>
  597. <th>Status</th>
  598. <th>BlueCoat</th>
  599. <th>IBM X-Force</th>
  600. <th>Cisco Talos</th>
  601. <th>Umbrella</th>
  602. <th>WatchGuard</th>
  603. <th>Namecheap</th>
  604. <th>Archive.org</th>
  605. '''
  606. htmlTableBody = ''
  607. htmlTableFooter = '</table>'
  608. htmlFooter = '</body></html>'
  609. # Build HTML table contents
  610. for i in sortedDomains:
  611. htmlTableBody += '<tr>'
  612. htmlTableBody += '<td>{}</td>'.format(i[0]) # Domain
  613. htmlTableBody += '<td>{}</td>'.format(i[1]) # Birth
  614. htmlTableBody += '<td>{}</td>'.format(i[2]) # Entries
  615. htmlTableBody += '<td>{}</td>'.format(i[3]) # TLDs
  616. htmlTableBody += '<td>{}</td>'.format(i[4]) # Status
  617. htmlTableBody += '<td><a href="https://sitereview.bluecoat.com/" target="_blank">{}</a></td>'.format(i[5]) # Bluecoat
  618. htmlTableBody += '<td><a href="https://exchange.xforce.ibmcloud.com/url/{}" target="_blank">{}</a></td>'.format(i[0],i[6]) # IBM x-Force Categorization
  619. htmlTableBody += '<td><a href="https://www.talosintelligence.com/reputation_center/lookup?search={}" target="_blank">{}</a></td>'.format(i[0],i[7]) # Cisco Talos
  620. htmlTableBody += '<td>{}</td>'.format(i[8]) # Cisco Umbrella
  621. htmlTableBody += '<td><a href="http://www.borderware.com/domain_lookup.php?ip={}" target="_blank">WatchGuard</a></td>'.format(i[0]) # Borderware WatchGuard
  622. htmlTableBody += '<td><a href="https://www.namecheap.com/domains/registration/results.aspx?domain={}" target="_blank">Namecheap</a></td>'.format(i[0]) # Namecheap
  623. htmlTableBody += '<td><a href="http://web.archive.org/web/*/{}" target="_blank">Archive.org</a></td>'.format(i[0]) # Archive.org
  624. htmlTableBody += '</tr>'
  625. html = htmlHeader + htmlBody + htmlTableHeader + htmlTableBody + htmlTableFooter + htmlFooter
  626. logfilename = "{}_domainreport.html".format(timestamp)
  627. if output != None:
  628. logfilename = output
  629. log = open(logfilename,'w')
  630. log.write(html)
  631. log.close
  632. print("\n[*] Search complete")
  633. print("[*] Log written to {}\n".format(logfilename))
  634. # Print Text Table
  635. header = ['Domain', 'Birth', '#', 'TLDs', 'Status', 'BlueCoat', 'IBM', 'Cisco Talos', 'Umbrella']
  636. print(drawTable(header,sortedDomains))