domainhunter.py 30 KB

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