Incredibly fast crawler designed for OSINT.
x100 faster with logic changes, temporarily removed ninja
Somdev Sangwane2bd7c758c98
diff --git a/photon.py b/photon.pyindex b1864e2..bc9c271 100644--- a/photon.py+++ b/photon.py@@ -10,8 +10,9 @@ import randomimport urllib3import argparseimport threading+import lxml.htmlfrom re import search, findall-from requests import get, post+from requests import get, post, Timeouttry:from urllib.parse import urlparse # for python3except ImportError:@@ -46,7 +47,7 @@ print ('''%s ____ __ __/_/ /_/ /_/\____/\__/\____/_/ /_/ %s\n''' %(red, white, red, white, red, white, red, white, red, white, red, white, red, end))-urllib3.disable_warnings() # Disable SSL related warnings+urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Disable SSL related warnings# Processing command line argumentsparser = argparse.ArgumentParser()@@ -61,7 +62,6 @@ parser.add_argument('-t', '--threads', help='number of threads', dest='threads',parser.add_argument('-d', '--delay', help='delay between requests', dest='delay', type=int)# Switchesparser.add_argument('--dns', help='dump dns data', dest='dns', action='store_true')-parser.add_argument('--ninja', help='ninja mode', dest='ninja', action='store_true')parser.add_argument('--update', help='update photon', dest='update', action='store_true')parser.add_argument('--only-urls', help='only extract urls', dest='only_urls', action='store_true')args = parser.parse_args()@@ -109,16 +109,14 @@ else: # if the user hasn't supplied a urlquit()delay = 0 # Delay between requests+timeout = 6 # HTTP request timeoutcook = None # Cookie-ninja = False # Ninja mode togglecrawl_level = 2 # Crawling levelthread_count = 2 # Number of threadsonly_urls = False # only urls mode is off by defaultif args.cook:cook = args.cook-if args.ninja:- ninja = Trueif args.only_urls:only_urls = Trueif args.delay:@@ -141,6 +139,9 @@ fuzzable = set() # urls that have get params in them e.g. example.com/page.php?iendpoints = set() # urls found from javascript filesprocessed = set() # urls that have been crawled+everything = []+bad_scripts = set() # bad javascript files+seeds = []if args.seeds: # if the user has supplied custom seedsseeds = args.seeds@@ -173,95 +174,48 @@ user_agents = ['Mozilla/5.0 (X11; Linux i686; rv:60.0) Gecko/20100101 Firefox/60def requester(url):processed.add(url) # mark the url as crawledtime.sleep(delay) # pause/sleep the program for specified time+ headers = {+ 'Host' : name, # ummm this is the hostname?+ 'User-Agent' : random.choice(user_agents), # selecting a random user-agent+ 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',+ 'Accept-Language' : 'en-US,en;q=0.5',+ 'Accept-Encoding' : 'gzip',+ 'DNT' : '1',+ 'Connection' : 'close'}+ # make request and return responsetry:- def normal(url):- headers = {- 'Host' : name, # ummm this is the hostname?- 'User-Agent' : random.choice(user_agents), # selecting a random user-agent- 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',- 'Accept-Language' : 'en-US,en;q=0.5',- 'Accept-Encoding' : 'gzip',- 'DNT' : '1',- 'Connection' : 'close'}- # make request and return response- return get(url, cookies=cook, headers=headers, verify=False)-- # pixlr.com API- def pixlr(url):- if url == main_url:- url = main_url + '/' # because pixlr throws error if http://example.com is used- # make request and return response- return get('https://pixlr.com/proxy/?url=' + url, headers={'Accept-Encoding' : 'gzip'}, verify=False)-- # codebeautify.org API- def code_beautify(url):- headers = {- 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0',- 'Accept' : 'text/plain, */*; q=0.01',- 'Accept-Encoding' : 'gzip',- 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',- 'Origin' : 'https://codebeautify.org',- 'Connection' : 'close'- }- # make request and return response- return post('https://codebeautify.com/URLService', headers=headers, data='path=' + url, verify=False)-- # www.photopea.com API- def photopea(url):- # make request and return response- return get('https://www.photopea.com/mirror.php?url=' + url, verify=False)-- if ninja: # if the ninja mode is enabled- # select a random request function i.e. random API- response = random.choice([photopea, normal, pixlr, code_beautify])(url)-- #check if link is not broken- if response.status_code == '404':- failed.add(url) # add it to the failed list- return response.text # return response body--+ response = get(url, cookies=cook, headers=headers, verify=False, timeout=timeout, stream=True)+ if 'text/html' in response.headers['content-type']:+ return response.textelse:- response = normal(url)-- #check if link is not broken- if response.status_code == '404':- failed.add(url) # add it to the failed list- return response.text # return response body-- except: # if photon fails to connect to the url- failed.add(url) # add it to the failed list+ response.close()+ return 'dummy'+ except Timeout:+ return 'dummy'##### This function extracts links from robots.txt and sitemap.xml####def zap(url):- try:- response = requester(url + '/robots.txt') # makes request to robots.txt- if '<body' not in response: # making sure robots.txt isn't some fancy 404 page- matches = findall(r'Allow: (.*)|Disallow: (.*)', response) # If you know it, you know it+ response = get(url + '/robots.txt').text # makes request to robots.txt+ if '<body' not in response: # making sure robots.txt isn't some fancy 404 page+ matches = findall(r'Allow: (.*)|Disallow: (.*)', response) # If you know it, you know it+ if matches:for match in matches: # iterating over the matches, match is a tuple here- match = match[0] + match[1] # one item in match will always be empty so will combine both items+ match = ''.join(match) # one item in match will always be empty so will combine both itemsif '/*/' not in match: # if the url doesn't use a wildcardurl = main_url + matchstorage.add(url) # add the url to storage list for crawlingrobots.add(url) # add the url to robots list- if '=' in url: # self-explanatory- fuzzable.add(url) # add url to the fuzzable urls list- if len(matches) > 0: # if there are more than 0 matches- print ('%s URLs retrieved from robots.txt: %s' % (good, len(robots)))-- response = requester(url + '/sitemap.xml') # makes request to sitemap.xml-- if '<body' not in response: # making sure robots.txt isn't some fancy 404 page- matches = findall(r'<loc>[^<]*</loc>', response) # regex for extracting urls- if matches: # if there are any matches- print ('%s URLs retrieved from sitemap.xml: %s' % (good, len(matches)))- for match in matches:- storage.add(match.split('<loc>')[1][:-6]) #cleaning up the url & adding it to the storage list for crawling- except:- pass+ print ('%s URLs retrieved from robots.txt: %s' % (good, len(robots)))+ response = get(url + '/sitemap.xml').text # makes request to sitemap.xml+ if '<body' not in response: # making sure robots.txt isn't some fancy 404 page+ matches = findall(r'<loc>[^<]*</loc>', response) # regex for extracting urls+ if matches: # if there are any matches+ print ('%s URLs retrieved from sitemap.xml: %s' % (good, len(matches)))+ for match in matches:+ storage.add(match.split('<loc>')[1][:-6]) #cleaning up the url & adding it to the storage list for crawling##### This functions checks whether a url should be crawled or not@@ -269,18 +223,13 @@ def zap(url):def is_link(url):# file extension that don't need to be crawled and are files- bad = ['xml', 'png', 'bmp', 'jpg', 'jpeg', 'pdf', 'css', 'ico', 'js', 'svg', 'json']conclusion = False # whether the the url should be crawled or notif url not in processed: # if the url hasn't been crawled already- if '.' in url[-5:]: # url[-5:] = last 5 chars of url- extension = url[-5:].split('.')[-1] # finding the extension of webpage- if extension not in bad: # if the extension isn't "bad"- conclusion = True # url can be crawled- else:- files.add(main_url + url) # its a file- else: # it has no extension+ if not ('.xml' or '.png' or '.bmp' or '.jpg' or '.jpeg' or '.pdf' or '.css' or '.ico' or '.js' or '.svg' or '.json') in url:return True # url can be crawled+ else:+ files.add(url)return conclusion # return the conclusion :D####@@ -301,33 +250,21 @@ def regxy(pattern, response):####def intel_extractor(response):- try:- matches = findall(r'''([\w\.-]+s[\w\.-]+\.amazonaws\.com)|(github\.com/[\w\.-/]+)|- (facebook\.com/.*?)[\'" ]|(youtube\.com/.*?)[\'" ]|(linkedin\.com/.*?)[\'" ]|- (twitter\.com/.*?)[\'" ]|([\w\.-]+@[\w\.-]+\.[\.\w]+)''', response)+ matches = findall(r'''([\w\.-]+s[\w\.-]+\.amazonaws\.com)|(github\.com/[\w\.-/]+)|+ (facebook\.com/.*?)[\'" ]|(youtube\.com/.*?)[\'" ]|(linkedin\.com/.*?)[\'" ]|+ (twitter\.com/.*?)[\'" ]|([\w\.-]+@[\w\.-]+\.[\.\w]+)''', response)+ if matches:for match in matches: # iterate over the matches- for x in match: # iterate over the match because it's a tuple- if x != '': # if the value isn't empty- intel.add(x) # add it to intel list- except:- pass+ intel.add(match) # add it to intel list##### This function extracts js files from the response body####def js_extractor(response):- try:- matches = findall(r'src=[\'"](.*?\.js)["\']', response) # extract .js files- for match in matches: # iterate over the matches- if match.startswith(main_url):- scripts.add(match)- elif match.startswith('/') and not match.startswith('//'):- scripts.add(main_url + match)- elif not match.startswith('http') and not match.startswith('//'):- scripts.add(main_url + '/' + match)- except:- pass+ matches = findall(r'src=[\'"](.*?\.js)["\']', response) # extract .js files+ for match in matches: # iterate over the matches+ bad_scripts.add(match)##### This function extracts stuff from the response body@@ -335,52 +272,36 @@ def js_extractor(response):def extractor(url):response = requester(url) # make request to the url- try:- matches = findall(r'href=[\'"](.*?)["\']', response) # find all the linkx- for link in matches: # iterate over the matches- link = link.split('#')[0] # remove everything after a "#" to deal with in-page anchors- if is_link(link): # checks if the urls should be crawled- if link.startswith(main_url): # self-explanatory+ root = lxml.html.fromstring(response) # find all the links+ for link in root.xpath('//a/@href'): # iterate over the matches+ link = link.split('#')[0] # remove everything after a "#" to deal with in-page anchors+ if is_link(link): # checks if the urls should be crawled+ if link.startswith('http'): # self-explanatory+ if link.startswith(main_url):storage.add(link)- if '=' in link:- fuzzable.add(link)- if link.startswith('http') or link.startswith('//'):- if not link.startswith(main_url):- external.add(link)- elif link.startswith('javascript') or link.startswith('{{'):- pass # we aren't fucking with javascript- elif link.startswith('/') and not link.startswith('//'):- storage.add(main_url + link)- if '=' in link:- fuzzable.add(link)- elif not link.startswith('http') and not link.startswith('//'):- storage.add(main_url + '/' + link)- if '=' in link:- fuzzable.add(link)-- if not only_urls:- intel_extractor(response)- js_extractor(response)- if args.regex and not supress_regex:- regxy(args.regex, response)-- except: # if something bad happens- failed.add(url)+ else:+ external.add(link)+ elif link.startswith('/') and not link.startswith('//'):+ storage.add(main_url + link)+ elif not link.startswith('http') and not link.startswith('//'):+ storage.add(main_url + '/' + link)+ if not only_urls:+ intel_extractor(response)+ js_extractor(response)+ if args.regex and not supress_regex:+ regxy(args.regex, response)##### This function extracts endpoints from JavaScript Code####def jscanner(url):- try:- response = requester(url) # make request to the url- matches = findall(r'[\'"](/.*?)[\'"]|[\'"](http.*?)[\'"]', response) # extract urls/endpoints- for match in matches: # iterate over the matches, match is a tuple- match = match[0] + match[1] # combining the items because one of them is always empty- if not search(r'[}{><"\']', match) and not match == '/': # making sure it's not some js code- endpoints.add(match) # add it to the endpoints list- except:- failed.add(url)+ response = requester(url) # make request to the url+ matches = findall(r'[\'"](/.*?)[\'"]|[\'"](http.*?)[\'"]', response) # extract urls/endpoints+ for match in matches: # iterate over the matches, match is a tuple+ match = match[0] + match[1] # combining the items because one of them is always empty+ if not search(r'[}{><"\']', match) and not match == '/': # making sure it's not some js code+ endpoints.add(match) # add it to the endpoints list##### This function starts multiple threads for a function@@ -439,6 +360,13 @@ for level in range(crawl_level):breakif not only_urls:+ for match in bad_scripts:+ if match.startswith(main_url):+ scripts.add(match)+ elif match.startswith('/') and not match.startswith('//'):+ scripts.add(main_url + match)+ elif not match.startswith('http') and not match.startswith('//'):+ scripts.add(main_url + '/' + match)# Step 3. Scan the JavaScript files for enpointsprint ('%s Crawling %i JavaScript files' % (run, len(scripts)))flash(jscanner, scripts)@@ -463,6 +391,10 @@ os.mkdir(name) # create a new directoryif args.dns:dnsdumpster(name, colors)+for url in storage:+ if '=' in url:+ fuzzable.add(url)+if len(storage) > 0:with open('%s/links.txt' % name, 'w+') as f:for x in storage:@@ -475,8 +407,10 @@ if len(files) > 0:if len(intel) > 0:with open('%s/intel.txt' % name, 'w+') as f:- for x in intel:- f.write(str(x.encode('utf-8')) + '\n')+ for match in intel:+ for x in match: # iterate over the match because it's a tuple+ if x != '': # if the value isn't empty+ f.write(str(x.encode('utf-8')) + '\n')if len(robots) > 0:with open('%s/robots.txt' % name, 'w+') as f:@@ -528,8 +462,8 @@ len(intel), good, len(files), good, len(endpoints), good, len(fuzzable), good,len(custom), good, len(scripts), good, len(external),(('%s-%s' % (red, end)) * 50)))-print ('%s Total time taken: %i:%i' % (info, minutes, seconds))-print ('%s Average request time: %s' % (info, str(time_per_request)[:4]))+print ('%s Total time taken: %i minutes %i seconds' % (info, minutes, seconds))+print ('%s Average request time: %s seconds' % (info, str(time_per_request)[:4]))if args.export:# exporter(directory, format, *sets)