domainhunter.py 33 KB

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