domainhunter.py 31 KB

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