Skip to content

Incredibly fast crawler designed for OSINT.

add support for proxies plus more intels as well a multiple fixes

oXis1ebfec337df4
diff --git a/core/regex.py b/core/regex.py
new file mode 100644
index 0000000..b79f658
--- /dev/null
+++ b/core/regex.py
@@ -0,0 +1,230 @@
+import re
+
+# regex taken from https://github.com/InQuest/python-iocextract
+# Reusable end punctuation regex.
+END_PUNCTUATION = r"[\.\?>\"'\)!,}:;\u201d\u2019\uff1e\uff1c\]]*"
+
+# Reusable regex for symbols commonly used to defang.
+SEPARATOR_DEFANGS = r"[\(\)\[\]{}<>\\]"
+
+# Split URLs on some characters that may be valid, but may also be garbage.
+URL_SPLIT_STR = r"[>\"'\),};]"
+
+# Get basic url format, including a few obfuscation techniques, main anchor is the uri scheme.
+GENERIC_URL = re.compile(r"""
+ (
+ # Scheme.
+ [fhstu]\S\S?[px]s?
+ # One of these delimiters/defangs.
+ (?:
+ :\/\/|
+ :\\\\|
+ :?__
+ )
+ # Any number of defang characters.
+ (?:
+ \x20|
+ """ + SEPARATOR_DEFANGS + r"""
+ )*
+ # Domain/path characters.
+ \w
+ \S+?
+ # CISCO ESA style defangs followed by domain/path characters.
+ (?:\x20[\/\.][^\.\/\s]\S*?)*
+ )
+ """ + END_PUNCTUATION + r"""
+ (?=\s|$)
+ """, re.IGNORECASE | re.VERBOSE | re.UNICODE)
+
+# Get some obfuscated urls, main anchor is brackets around the period.
+BRACKET_URL = re.compile(r"""
+ \b
+ (
+ [\.\:\/\\\w\[\]\(\)-]+
+ (?:
+ \x20?
+ [\(\[]
+ \x20?
+ \.
+ \x20?
+ [\]\)]
+ \x20?
+ \S*?
+ )+
+ )
+ """ + END_PUNCTUATION + r"""
+ (?=\s|$)
+ """, re.VERBOSE | re.UNICODE)
+
+# Get some obfuscated urls, main anchor is backslash before a period.
+BACKSLASH_URL = re.compile(r"""
+ \b
+ (
+ [\:\/\\\w\[\]\(\)-]+
+ (?:
+ \x20?
+ \\?\.
+ \x20?
+ \S*?
+ )*?
+ (?:
+ \x20?
+ \\\.
+ \x20?
+ \S*?
+ )
+ (?:
+ \x20?
+ \\?\.
+ \x20?
+ \S*?
+ )*
+ )
+ """ + END_PUNCTUATION + r"""
+ (?=\s|$)
+ """, re.VERBOSE | re.UNICODE)
+
+# Get hex-encoded urls.
+HEXENCODED_URL = re.compile(r"""
+ (
+ [46][86]
+ (?:[57]4)?
+ [57]4[57]0
+ (?:[57]3)?
+ 3a2f2f
+ (?:2[356def]|3[0-9adf]|[46][0-9a-f]|[57][0-9af])+
+ )
+ (?:[046]0|2[0-2489a-c]|3[bce]|[57][b-e]|[8-f][0-9a-f]|0a|0d|09|[
+ \x5b-\x5d\x7b\x7d\x0a\x0d\x20
+ ]|$)
+ """, re.IGNORECASE | re.VERBOSE)
+
+# Get urlencoded urls.
+URLENCODED_URL = re.compile(r"""
+ (s?[hf]t?tps?%3A%2F%2F\w[\w%-]*?)(?:[^\w%-]|$)
+ """, re.IGNORECASE | re.VERBOSE)
+
+# Get base64-encoded urls.
+B64ENCODED_URL = re.compile(r"""
+ (
+ # b64re '([hH][tT][tT][pP][sS]|[hH][tT][tT][pP]|[fF][tT][pP])://'
+ # Modified to ignore whitespace.
+ (?:
+ [\x2b\x2f-\x39A-Za-z]\s*[\x2b\x2f-\x39A-Za-z]\s*[\x31\x35\x39BFJNRVZdhlptx]\s*[Gm]\s*[Vd]\s*[FH]\s*[A]\s*\x36\s*L\s*y\s*[\x2b\x2f\x38-\x39]\s*|
+ [\x2b\x2f-\x39A-Za-z]\s*[\x2b\x2f-\x39A-Za-z]\s*[\x31\x35\x39BFJNRVZdhlptx]\s*[Io]\s*[Vd]\s*[FH]\s*[R]\s*[Qw]\s*[O]\s*i\s*\x38\s*v\s*[\x2b\x2f-\x39A-Za-z]\s*|
+ [\x2b\x2f-\x39A-Za-z]\s*[\x2b\x2f-\x39A-Za-z]\s*[\x31\x35\x39BFJNRVZdhlptx]\s*[Io]\s*[Vd]\s*[FH]\s*[R]\s*[Qw]\s*[Uc]\s*[z]\s*o\s*v\s*L\s*[\x2b\x2f-\x39w-z]\s*|
+ [\x2b\x2f-\x39A-Za-z]\s*[\x30\x32EGUWkm]\s*[Z]\s*[\x30U]\s*[Uc]\s*[D]\s*o\s*v\s*L\s*[\x2b\x2f-\x39w-z]\s*|
+ [\x2b\x2f-\x39A-Za-z]\s*[\x30\x32EGUWkm]\s*[h]\s*[\x30U]\s*[Vd]\s*[FH]\s*[A]\s*\x36\s*L\s*y\s*[\x2b\x2f\x38-\x39]\s*|
+ [\x2b\x2f-\x39A-Za-z]\s*[\x30\x32EGUWkm]\s*[h]\s*[\x30U]\s*[Vd]\s*[FH]\s*[B]\s*[Tz]\s*[O]\s*i\s*\x38\s*v\s*[\x2b\x2f-\x39A-Za-z]\s*|
+ [RZ]\s*[ln]\s*[R]\s*[Qw]\s*[O]\s*i\s*\x38\s*v\s*[\x2b\x2f-\x39A-Za-z]\s*|
+ [Sa]\s*[FH]\s*[R]\s*[\x30U]\s*[Uc]\s*[D]\s*o\s*v\s*L\s*[\x2b\x2f-\x39w-z]\s*|
+ [Sa]\s*[FH]\s*[R]\s*[\x30U]\s*[Uc]\s*[FH]\s*[M]\s*\x36\s*L\s*y\s*[\x2b\x2f\x38-\x39]\s*
+ )
+ # Up to 260 characters (pre-encoding, reasonable URL length).
+ [A-Za-z0-9+/=\s]{1,357}
+ )
+ (?=[^A-Za-z0-9+/=\s]|$)
+ """, re.VERBOSE)
+
+# Get some valid obfuscated ip addresses.
+IPV4 = re.compile(r"""
+ (?:^|
+ (?![^\d\.])
+ )
+ (?:
+ (?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])
+ [\[\(\\]*?\.[\]\)]*?
+ ){3}
+ (?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])
+ (?:(?=[^\d\.])|$)
+ """, re.VERBOSE)
+
+# Experimental IPv6 regex, will not catch everything but should be sufficent for now.
+IPV6 = re.compile(r"""
+ \b(?:[a-f0-9]{1,4}:|:){2,7}(?:[a-f0-9]{1,4}|:)\b
+ """, re.IGNORECASE | re.VERBOSE)
+
+# Capture email addresses including common defangs.
+EMAIL = re.compile(r"""
+ (
+ [a-z0-9_.+-]+
+ [\(\[{\x20]*
+ (?:@|\Wat\W)
+ [\)\]}\x20]*
+ [a-z0-9-]+
+ (?:
+ (?:
+ (?:
+ \x20*
+ """ + SEPARATOR_DEFANGS + r"""
+ \x20*
+ )*
+ \.
+ (?:
+ \x20*
+ """ + SEPARATOR_DEFANGS + r"""
+ \x20*
+ )*
+ |
+ \W+dot\W+
+ )
+ [a-z0-9-]+?
+ )+
+ )
+ """ + END_PUNCTUATION + r"""
+ (?=\s|$)
+ """, re.IGNORECASE | re.VERBOSE | re.UNICODE)
+
+MD5 = re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{32})(?:[^a-fA-F\d]|\b)")
+SHA1 = re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{40})(?:[^a-fA-F\d]|\b)")
+SHA256 = re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{64})(?:[^a-fA-F\d]|\b)")
+SHA512 = re.compile(
+ r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{128})(?:[^a-fA-F\d]|\b)")
+
+# YARA regex.
+YARA_PARSE = re.compile(r"""
+ (?:^|\s)
+ (
+ (?:
+ \s*?import\s+?"[^\r\n]*?[\r\n]+|
+ \s*?include\s+?"[^\r\n]*?[\r\n]+|
+ \s*?//[^\r\n]*[\r\n]+|
+ \s*?/\*.*?\*/\s*?
+ )*
+ (?:
+ \s*?private\s+|
+ \s*?global\s+
+ )*
+ rule\s*?
+ \w+\s*?
+ (?:
+ :[\s\w]+
+ )?
+ \s+\{
+ .*?
+ condition\s*?:
+ .*?
+ \s*\}
+ )
+ (?:$|\s)
+ """, re.MULTILINE | re.DOTALL | re.VERBOSE)
+
+rintels = [(GENERIC_URL, "GENERIC_URL"),
+ (BRACKET_URL, "BRACKET_URL"),
+ (BACKSLASH_URL, "BACKSLASH_URL"),
+ (HEXENCODED_URL, "HEXENCODED_URL"),
+ (URLENCODED_URL, "URLENCODED_URL"),
+ (B64ENCODED_URL, "B64ENCODED_URL"),
+ (IPV4, "IPV4"),
+ (IPV6, "IPV6"),
+ (EMAIL, "EMAIL"),
+ (MD5, "MD5"),
+ (SHA1, "SHA1"),
+ (SHA256, "SHA256"),
+ (SHA512, "SHA512"),
+ (YARA_PARSE, "YARA_PARSE")]
+
+rscript = re.compile(r'<(script|SCRIPT).*(src|SRC)=([^\s>]+)')
+rhref = re.compile(r'<[aA].*(href|HREF)=([^\s>]+)')
+rendpoint = re.compile(r'[\'"](/.*?)[\'"]|[\'"](http.*?)[\'"]')
+rentropy = re.compile(r'[\w-]{16,45}')
diff --git a/core/requester.py b/core/requester.py
index 3986f34..6450933 100644
--- a/core/requester.py
+++ b/core/requester.py
@@ -17,6 +17,7 @@ def requester(
timeout=10,
host=None,
ninja=False,
+ proxies=None,
user_agents=None,
failed=None,
processed=None
@@ -51,11 +52,14 @@ def requester(
headers=final_headers,
verify=False,
timeout=timeout,
- stream=True
+ stream=True,
+ proxies=proxies
)
except TooManyRedirects:
return 'dummy'
- if 'text/html' in response.headers['content-type']:
+
+ if 'text/html' in response.headers['content-type'] or \
+ 'text/plain' in response.headers['content-type']:
if response.status_code != '404':
return response.text
else:
@@ -70,7 +74,8 @@ def requester(
"""Interact with the developer.facebook.com API."""
return requests.get(
'https://developers.facebook.com/tools/debug/echo/?q=' + url,
- verify=False
+ verify=False,
+ proxies=proxies
).text
def pixlr(url):
@@ -81,7 +86,8 @@ def requester(
return requests.get(
'https://pixlr.com/proxy/?url=' + url,
headers={'Accept-Encoding': 'gzip'},
- verify=False
+ verify=False,
+ proxies=proxies
).text
def code_beautify(url):
@@ -98,7 +104,8 @@ def requester(
'https://codebeautify.com/URLService',
headers=headers,
data='path=' + url,
- verify=False
+ verify=False,
+ proxies=proxies
).text
def photopea(url):
diff --git a/core/utils.py b/core/utils.py
index d79cf20..bef6df0 100644
--- a/core/utils.py
+++ b/core/utils.py
@@ -1,5 +1,6 @@
import math
import re
+import argparse
import tld
@@ -8,6 +9,8 @@ from core.config import VERBOSE, BAD_TYPES
try:
from urllib.parse import urlparse
+ import urllib.request
+ import urllib.error
except:
from urlparse import urlparse
@@ -71,6 +74,7 @@ def remove_regex(urls, regex):
return non_matching_urls
+
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
@@ -81,6 +85,7 @@ def writer(datasets, dataset_names, output_dir):
out_file.write(str(joined.encode('utf-8')))
out_file.write('\n')
+
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
@@ -92,26 +97,30 @@ def timer(diff, processed):
time_per_request = 0
return minutes, seconds, time_per_request
+
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
- chr(number)))/len(string.encode('utf-8'))
+ chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
+
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
+
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
+
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
@@ -127,9 +136,63 @@ def extract_headers(headers):
pass
return sorted_headers
-def top_level(url):
+
+def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
- ext = tld.get_tld(url, fix_protocol=True)
+ ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
+
+
+def UrlType(v):
+ """ Check if string is a URL """
+ if re.match(r"(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)", v):
+ # If all the checks pass, just return the string as is
+ return v
+ elif re.match(r"(http(s)?:\/\/)?(\blocalhost\b)", v):
+ return v
+ else:
+ raise argparse.ArgumentTypeError("Must be a valid url.")
+
+
+def ProxyType(v):
+ """ Match IP:PORT or DOMAIN:PORT in a losse manner """
+ if re.match(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
+ return v
+ elif re.match(r"[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}", v.split(':')[0]):
+ return v
+ else:
+ raise argparse.ArgumentTypeError(
+ "Proxy should follow IP:PORT or DOMAIN:PORT format")
+
+
+def luhn(purported):
+
+ # sum_of_digits (index * 2)
+ LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
+
+ if not isinstance(purported, str):
+ purported = str(purported)
+ try:
+ evens = sum(int(p) for p in purported[-1::-2])
+ odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
+ return (evens + odds) % 10 == 0
+ except ValueError: # Raised if an int conversion fails
+ return False
+
+
+def is_good_proxy(pip):
+ try:
+ proxy_handler = urllib.request.ProxyHandler(pip)
+ opener = urllib.request.build_opener(proxy_handler)
+ opener.addheaders = [('User-agent', 'Mozilla/5.0')]
+ urllib.request.install_opener(opener)
+ # change the URL to test here
+ req = urllib.request.Request('http://www.example.com')
+ sock = urllib.request.urlopen(req, timeout=2)
+ except urllib.error.HTTPError as e:
+ return False
+ except Exception as detail:
+ return False
+ return True
diff --git a/photon.py b/photon.py
index 4718405..a18da27 100644
--- a/photon.py
+++ b/photon.py
@@ -12,7 +12,7 @@ import warnings
import requests
-from core.colors import good, info, run, green, red, white, end
+from core.colors import good, info, run, green, red, white, end, bad
import core.config
from core.config import INTELS
from core.flash import flash
@@ -20,7 +20,19 @@ from core.mirror import mirror
from core.prompt import prompt
from core.requester import requester
from core.updater import updater
-from core.utils import top_level, extract_headers, verb, is_link, entropy, regxy, remove_regex, timer, writer
+from core.utils import (luhn,
+ UrlType,
+ ProxyType,
+ is_good_proxy,
+ top_level,
+ extract_headers,
+ verb, is_link,
+ entropy, regxy,
+ remove_regex,
+ timer,
+ writer)
+from core.regex import rintels, rendpoint, rhref, rscript, rentropy
+
from core.zap import zap
try:
@@ -42,7 +54,7 @@ print('''%s ____ __ __
/ %s__%s \/ /_ ____ / /_____ ____
/ %s/_/%s / __ \/ %s__%s \/ __/ %s__%s \/ __ \\
/ ____/ / / / %s/_/%s / /_/ %s/_/%s / / / /
- /_/ /_/ /_/\____/\__/\____/_/ /_/ %sv1.2.1%s\n''' %
+ /_/ /_/ /_/\____/\__/\____/_/ /_/ %sv2.0.0%s\n''' %
(red, white, red, white, red, white, red, white, red, white, red, white,
red, white, end))
@@ -52,7 +64,7 @@ warnings.filterwarnings('ignore')
# Processing command line arguments
parser = argparse.ArgumentParser()
# Options
-parser.add_argument('-u', '--url', help='root url', dest='root')
+parser.add_argument('-u', '--url', help='root url', dest='root', type=UrlType)
parser.add_argument('-c', '--cookie', help='cookie', dest='cook')
parser.add_argument('-r', '--regex', help='regex pattern', dest='regex')
parser.add_argument('-e', '--export', help='export format', dest='export', choices=['csv', 'json'])
@@ -74,6 +86,8 @@ parser.add_argument('--exclude', help='exclude URLs matching this regex',
dest='exclude')
parser.add_argument('--timeout', help='http request timeout', dest='timeout',
type=float)
+parser.add_argument('-p', '--proxy', help='Proxy server IP:PORT or DOMAIN:PORT', dest='proxies',
+ type=ProxyType)
# Switches
parser.add_argument('--clone', help='clone the website locally', dest='clone',
@@ -119,6 +133,15 @@ timeout = args.timeout or 6 # HTTP request timeout
cook = args.cook or None # Cookie
api = bool(args.api) # Extract high entropy strings i.e. API keys and stuff
ninja = bool(args.ninja) # Ninja mode toggle
+
+proxies = None
+if args.proxies:
+ proxies = {"http": args.proxies,
+ "https": args.proxies}
+ if not is_good_proxy(proxies):
+ print("%s Proxy doesn't seem to work" % bad)
+ exit()
+
crawl_level = args.level or 2 # Crawling level
thread_count = args.threads or 2 # Number of threads
only_urls = bool(args.only_urls) # Only URLs mode is off by default
@@ -182,17 +205,18 @@ supress_regex = False
def intel_extractor(response):
"""Extract intel from the response body."""
- matches = re.findall(r'([\w\.-]+s[\w\.-]+\.amazonaws\.com)|([\w\.-]+@[\w\.-]+\.[\.\w]+)', response)
- if matches:
- for match in matches:
- verb('Intel', match)
- bad_intel.add(match)
+ for rintel in rintels:
+ matches = rintel[0].findall(response)
+ if matches:
+ for match in matches:
+ verb('Intel', match)
+ bad_intel.add((match, rintel[1]))
def js_extractor(response):
"""Extract js files from the response body"""
# Extract .js files
- matches = re.findall(r'<(script|SCRIPT).*(src|SRC)=([^\s>]+)', response)
+ matches = rscript.findall(response)
for match in matches:
match = match[2].replace('\'', '').replace('"', '')
verb('JS file', match)
@@ -200,10 +224,10 @@ def js_extractor(response):
def extractor(url):
"""Extract details from the response body."""
- response = requester(url, main_url, delay, cook, headers, timeout, host, ninja, user_agents, failed, processed)
+ response = requester(url, main_url, delay, cook, headers, timeout, host, ninja, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
- matches = re.findall(r'<[aA].*(href|HREF)=([^\s>]+)', response)
+ matches = rhref.findall(response)
for link in matches:
# Remove everything after a "#" to deal with in-page anchors
link = link[1].replace('\'', '').replace('"', '').split('#')[0]
@@ -236,7 +260,7 @@ def extractor(url):
if args.regex and not supress_regex:
regxy(args.regex, response, supress_regex, custom)
if api:
- matches = re.findall(r'[\w-]{16,45}', response)
+ matches = rentropy.findall(response)
for match in matches:
if entropy(match) >= 4:
verb('Key', match)
@@ -245,9 +269,9 @@ def extractor(url):
def jscanner(url):
"""Extract endpoints from JavaScript code."""
- response = requester(url, main_url, delay, cook, headers, timeout, host, ninja, user_agents, failed, processed)
+ response = requester(url, main_url, delay, cook, headers, timeout, host, ninja, proxies, user_agents, failed, processed)
# Extract URLs/endpoints
- matches = re.findall(r'[\'"](/.*?)[\'"]|[\'"](http.*?)[\'"]', response)
+ matches = rendpoint.findall(response)
# Iterate over the matches, match is a tuple
for match in matches:
# Combining the items because one of them is always empty
@@ -301,10 +325,13 @@ if not only_urls:
if '=' in url:
fuzzable.add(url)
- for match in bad_intel:
- for x in match: # Because "match" is a tuple
- if x != '': # If the value isn't empty
- intel.add(x)
+ for match, intel_name in bad_intel:
+ if isinstance(match, tuple):
+ for x in match: # Because "match" is a tuple
+ if x != '': # If the value isn't empty
+ intel.add("%s:%s" % (intel_name, x))
+ else:
+ intel.add("%s:%s" % (intel_name, match))
for url in external:
try:
if top_level(url, fix_protocol=True) in INTELS:
@@ -337,14 +364,14 @@ print(('%s-%s' % (red, end)) * 50)
print('%s Total requests made: %i' % (info, len(processed)))
print('%s Total time taken: %i minutes %i seconds' % (info, minutes, seconds))
-print('%s Requests per second: %i' % (info, int(len(processed)/diff)))
+print('%s Requests per second: %i' % (info, int(len(processed) / diff)))
datasets = {
'files': list(files), 'intel': list(intel), 'robots': list(robots),
'custom': list(custom), 'failed': list(failed), 'internal': list(internal),
'scripts': list(scripts), 'external': list(external),
'fuzzable': list(fuzzable), 'endpoints': list(endpoints),
- 'keys' : list(keys)
+ 'keys': list(keys)
}
if args.dns: