| 1 |
#!/usr/bin/env python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
r''' |
| 5 |
_ _ _ _ |
| 6 |
__| |_ __ ___| |___ _(_)___| |_ |
| 7 |
/ _` | '_ \/ __| __\ \ /\ / / / __| __| |
| 8 |
| (_| | | | \__ \ |_ \ V V /| \__ \ |_ |
| 9 |
\__,_|_| |_|___/\__| \_/\_/ |_|___/\__| |
| 10 |
|
| 11 |
Generate and resolve domain variations to detect typo squatting, |
| 12 |
phishing and corporate espionage. |
| 13 |
|
| 14 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 15 |
you may not use this file except in compliance with the License. |
| 16 |
You may obtain a copy of the License at |
| 17 |
|
| 18 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 19 |
|
| 20 |
Unless required by applicable law or agreed to in writing, software |
| 21 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 22 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 23 |
See the License for the specific language governing permissions and |
| 24 |
limitations under the License. |
| 25 |
''' |
| 26 |
|
| 27 |
__author__ = 'Marcin Ulikowski' |
| 28 |
__version__ = '20250130' |
| 29 |
__email__ = '[email protected]' |
| 30 |
|
| 31 |
import re |
| 32 |
import sys |
| 33 |
import socket |
| 34 |
socket.setdefaulttimeout(12.0) |
| 35 |
import signal |
| 36 |
import time |
| 37 |
import argparse |
| 38 |
import threading |
| 39 |
import os |
| 40 |
import json |
| 41 |
import queue |
| 42 |
import urllib.request |
| 43 |
import urllib.parse |
| 44 |
import gzip |
| 45 |
from io import BytesIO |
| 46 |
from datetime import datetime |
| 47 |
|
| 48 |
def _debug(msg): |
| 49 |
if 'DEBUG' in os.environ: |
| 50 |
if isinstance(msg, Exception): |
| 51 |
print('{}:{} {}'.format(__file__, msg.__traceback__.tb_lineno, str(msg)), file=sys.stderr, flush=True) |
| 52 |
else: |
| 53 |
print(str(msg), file=sys.stderr, flush=True) |
| 54 |
|
| 55 |
try: |
| 56 |
from PIL import Image |
| 57 |
MODULE_PIL = True |
| 58 |
except ImportError as e: |
| 59 |
_debug(e) |
| 60 |
MODULE_PIL = False |
| 61 |
|
| 62 |
try: |
| 63 |
from selenium import webdriver |
| 64 |
MODULE_SELENIUM = True |
| 65 |
except ImportError as e: |
| 66 |
_debug(e) |
| 67 |
MODULE_SELENIUM = False |
| 68 |
|
| 69 |
try: |
| 70 |
from dns.resolver import Resolver, NXDOMAIN, NoNameservers |
| 71 |
import dns.rdatatype |
| 72 |
from dns.exception import DNSException |
| 73 |
MODULE_DNSPYTHON = True |
| 74 |
except ImportError as e: |
| 75 |
_debug(e) |
| 76 |
MODULE_DNSPYTHON = False |
| 77 |
|
| 78 |
GEOLITE2_MMDB = os.environ.get('GEOLITE2_MMDB' , os.path.join(os.path.dirname(__file__), 'GeoLite2-Country.mmdb')) |
| 79 |
try: |
| 80 |
import geoip2.database |
| 81 |
_ = geoip2.database.Reader(GEOLITE2_MMDB) |
| 82 |
except Exception as e: |
| 83 |
_debug(e) |
| 84 |
try: |
| 85 |
import GeoIP |
| 86 |
_ = GeoIP.new(-1) |
| 87 |
except Exception as e: |
| 88 |
_debug(e) |
| 89 |
MODULE_GEOIP = False |
| 90 |
else: |
| 91 |
MODULE_GEOIP = True |
| 92 |
class geoip: |
| 93 |
def __init__(self): |
| 94 |
self.reader = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) |
| 95 |
def country_by_addr(self, ipaddr): |
| 96 |
return self.reader.country_name_by_addr(ipaddr) |
| 97 |
else: |
| 98 |
MODULE_GEOIP = True |
| 99 |
class geoip: |
| 100 |
def __init__(self): |
| 101 |
self.reader = geoip2.database.Reader(GEOLITE2_MMDB) |
| 102 |
def country_by_addr(self, ipaddr): |
| 103 |
return self.reader.country(ipaddr).country.name |
| 104 |
|
| 105 |
try: |
| 106 |
import ssdeep |
| 107 |
MODULE_SSDEEP = True |
| 108 |
except ImportError as e: |
| 109 |
_debug(e) |
| 110 |
try: |
| 111 |
import ppdeep as ssdeep |
| 112 |
MODULE_SSDEEP = True |
| 113 |
except ImportError as e: |
| 114 |
_debug(e) |
| 115 |
MODULE_SSDEEP = False |
| 116 |
|
| 117 |
try: |
| 118 |
import tlsh |
| 119 |
MODULE_TLSH = True |
| 120 |
except ImportError as e: |
| 121 |
_debug(e) |
| 122 |
MODULE_TLSH = False |
| 123 |
|
| 124 |
try: |
| 125 |
import idna |
| 126 |
except ImportError as e: |
| 127 |
_debug(e) |
| 128 |
class idna: |
| 129 |
@staticmethod |
| 130 |
def decode(domain): |
| 131 |
return domain.encode().decode('idna') |
| 132 |
@staticmethod |
| 133 |
def encode(domain): |
| 134 |
return domain.encode('idna') |
| 135 |
|
| 136 |
|
| 137 |
VALID_FQDN_REGEX = re.compile(r'(?=^.{4,253}$)(^((?!-)[a-z0-9-]{1,63}(?<!-)\.)+[a-z0-9-]{2,63}$)', re.IGNORECASE) |
| 138 |
USER_AGENT_STRING = 'Mozilla/5.0 ({} {}-bit) dnstwist/{}'.format(sys.platform, sys.maxsize.bit_length() + 1, __version__) |
| 139 |
|
| 140 |
REQUEST_TIMEOUT_DNS = 2.5 |
| 141 |
REQUEST_RETRIES_DNS = 2 |
| 142 |
REQUEST_TIMEOUT_HTTP = 5 |
| 143 |
REQUEST_TIMEOUT_SMTP = 5 |
| 144 |
THREAD_COUNT_DEFAULT = min(32, os.cpu_count() + 4) |
| 145 |
|
| 146 |
if sys.platform != 'win32' and sys.stdout.isatty(): |
| 147 |
FG_RND = '\x1b[3{}m'.format(int(time.time())%8+1) |
| 148 |
FG_YEL = '\x1b[33m' |
| 149 |
FG_CYA = '\x1b[36m' |
| 150 |
FG_BLU = '\x1b[34m' |
| 151 |
FG_RST = '\x1b[39m' |
| 152 |
ST_BRI = '\x1b[1m' |
| 153 |
ST_CLR = '\x1b[1K' |
| 154 |
ST_RST = '\x1b[0m' |
| 155 |
else: |
| 156 |
FG_RND = FG_YEL = FG_CYA = FG_BLU = FG_RST = ST_BRI = ST_CLR = ST_RST = '' |
| 157 |
|
| 158 |
devnull = os.devnull |
| 159 |
|
| 160 |
|
| 161 |
def domain_tld(domain): |
| 162 |
try: |
| 163 |
from tld import parse_tld |
| 164 |
except ImportError: |
| 165 |
ctld = ['org', 'com', 'net', 'gov', 'edu', 'co', 'mil', 'nom', 'ac', 'info', 'biz', 'ne'] |
| 166 |
d = domain.rsplit('.', 3) |
| 167 |
if len(d) < 2: |
| 168 |
return '', d[0], '' |
| 169 |
if len(d) == 2: |
| 170 |
return '', d[0], d[1] |
| 171 |
if len(d) > 2: |
| 172 |
if d[-2] in ctld: |
| 173 |
return '.'.join(d[:-3]), d[-3], '.'.join(d[-2:]) |
| 174 |
else: |
| 175 |
return '.'.join(d[:-2]), d[-2], d[-1] |
| 176 |
else: |
| 177 |
d = parse_tld(domain, fix_protocol=True)[::-1] |
| 178 |
if d[1:] == d[:-1] and None in d: |
| 179 |
d = tuple(domain.rsplit('.', 2)) |
| 180 |
d = ('',) * (3-len(d)) + d |
| 181 |
return d |
| 182 |
|
| 183 |
|
| 184 |
class Whois(): |
| 185 |
WHOIS_IANA = 'whois.iana.org' |
| 186 |
TIMEOUT = 2.0 |
| 187 |
WHOIS_TLD = { |
| 188 |
'com': 'whois.verisign-grs.com', |
| 189 |
'net': 'whois.verisign-grs.com', |
| 190 |
'org': 'whois.pir.org', |
| 191 |
'info': 'whois.afilias.net', |
| 192 |
'pl': 'whois.dns.pl', |
| 193 |
'us': 'whois.nic.us', |
| 194 |
'co': 'whois.nic.co', |
| 195 |
'cn': 'whois.cnnic.cn', |
| 196 |
'ru': 'whois.tcinet.ru', |
| 197 |
'in': 'whois.registry.in', |
| 198 |
'eu': 'whois.eu', |
| 199 |
'uk': 'whois.nic.uk', |
| 200 |
'de': 'whois.denic.de', |
| 201 |
'nl': 'whois.domain-registry.nl', |
| 202 |
'br': 'whois.registro.br', |
| 203 |
'jp': 'whois.jprs.jp', |
| 204 |
} |
| 205 |
|
| 206 |
def __init__(self): |
| 207 |
self.whois_tld = self.WHOIS_TLD |
| 208 |
|
| 209 |
def _brute_datetime(self, s): |
| 210 |
formats = ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%d %H:%M:%S%z', '%Y-%m-%d %H:%M', '%Y.%m.%d %H:%M', |
| 211 |
'%Y.%m.%d %H:%M:%S', '%d.%m.%Y %H:%M:%S', '%a %b %d %Y', '%d-%b-%Y', '%Y-%m-%d') |
| 212 |
for f in formats: |
| 213 |
try: |
| 214 |
dt = datetime.strptime(s, f) |
| 215 |
return dt |
| 216 |
except ValueError: |
| 217 |
pass |
| 218 |
return None |
| 219 |
|
| 220 |
def _extract(self, response): |
| 221 |
fields = { |
| 222 |
'registrar': (r'[\r\n]registrar[ .]*:\s+(?:name:\s)?(?P<registrar>[^\r\n]+)', str), |
| 223 |
'creation_date': (r'[\r\n](?:created(?: on)?|creation date|registered(?: on)?)[ .]*:\s+(?P<creation_date>[^\r\n]+)', self._brute_datetime), |
| 224 |
} |
| 225 |
result = {'text': response} |
| 226 |
response_reduced = '\r\n'.join([x.strip() for x in response.splitlines() if not x.startswith('%')]) |
| 227 |
for field, (pattern, func) in fields.items(): |
| 228 |
match = re.search(pattern, response_reduced, re.IGNORECASE | re.MULTILINE) |
| 229 |
if match: |
| 230 |
result[field] = func(match.group(1)) |
| 231 |
else: |
| 232 |
result[field] = None |
| 233 |
return result |
| 234 |
|
| 235 |
def query(self, query, server=None): |
| 236 |
_, _, tld = domain_tld(query) |
| 237 |
server = server or self.whois_tld.get(tld, self.WHOIS_IANA) |
| 238 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 239 |
sock.settimeout(self.TIMEOUT) |
| 240 |
response = b'' |
| 241 |
try: |
| 242 |
sock.connect((server, 43)) |
| 243 |
sock.send(query.encode() + b'\r\n') |
| 244 |
while True: |
| 245 |
buf = sock.recv(4096) |
| 246 |
if not buf: |
| 247 |
break |
| 248 |
response += buf |
| 249 |
if server and server != self.WHOIS_IANA and tld not in self.whois_tld: |
| 250 |
self.whois_tld[tld] = server |
| 251 |
except (socket.timeout, socket.gaierror): |
| 252 |
return '' |
| 253 |
finally: |
| 254 |
sock.close() |
| 255 |
response = response.decode('utf-8', errors='ignore') |
| 256 |
refer = re.search(r'refer:\s+(?P<server>[-.a-z0-9]+)', response, re.IGNORECASE | re.MULTILINE) |
| 257 |
if refer: |
| 258 |
return self.query(query, refer.group('server')) |
| 259 |
return response |
| 260 |
|
| 261 |
def whois(self, domain, server=None): |
| 262 |
return self._extract(self.query(domain, server)) |
| 263 |
|
| 264 |
|
| 265 |
class UrlOpener(): |
| 266 |
def __init__(self, url, timeout=REQUEST_TIMEOUT_HTTP, headers={}, verify=True): |
| 267 |
http_headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9', |
| 268 |
'accept-encoding': 'gzip,identity', |
| 269 |
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8'} |
| 270 |
for h, v in headers.items(): |
| 271 |
# do not override accepted encoding - only gzip,identity is supported |
| 272 |
if h.lower() != 'accept-encoding': |
| 273 |
http_headers[h.lower()] = v |
| 274 |
if verify: |
| 275 |
ctx = urllib.request.ssl.create_default_context() |
| 276 |
else: |
| 277 |
ctx = urllib.request.ssl._create_unverified_context() |
| 278 |
request = urllib.request.Request(url, headers=http_headers) |
| 279 |
with urllib.request.urlopen(request, timeout=timeout, context=ctx) as r: |
| 280 |
self.headers = r.headers |
| 281 |
self.code = r.code |
| 282 |
self.reason = r.reason |
| 283 |
self.url = r.url |
| 284 |
self.content = r.read() |
| 285 |
if self.content[:3] == b'\x1f\x8b\x08': |
| 286 |
self.content = gzip.decompress(self.content) |
| 287 |
if 64 < len(self.content) < 1024: |
| 288 |
try: |
| 289 |
meta_url = re.search(r'<meta[^>]*?url=(https?://[\w.,?!:;/*#@$&+=[\]()%~-]*?)"', self.content.decode(), re.IGNORECASE) |
| 290 |
except Exception: |
| 291 |
pass |
| 292 |
else: |
| 293 |
if meta_url: |
| 294 |
self.__init__(meta_url.group(1), timeout=timeout, headers=http_headers, verify=verify) |
| 295 |
self.normalized_content = self._normalize() |
| 296 |
|
| 297 |
def _normalize(self): |
| 298 |
content = b' '.join(self.content.split()) |
| 299 |
mapping = dict({ |
| 300 |
b'(action|src|href)=".+"': lambda m: m.group(0).split(b'=')[0] + b'=""', |
| 301 |
b'url(.+)': b'url()', |
| 302 |
}) |
| 303 |
for pattern, repl in mapping.items(): |
| 304 |
content = re.sub(pattern, repl, content, flags=re.IGNORECASE) |
| 305 |
return content |
| 306 |
|
| 307 |
|
| 308 |
class UrlParser(): |
| 309 |
def __init__(self, url): |
| 310 |
if not url: |
| 311 |
raise TypeError('argument has to be non-empty string') |
| 312 |
u = urllib.parse.urlparse(url if '://' in url else '//' + url, scheme='http') |
| 313 |
self.scheme = u.scheme.lower() |
| 314 |
if self.scheme not in ('http', 'https'): |
| 315 |
raise ValueError('invalid scheme') from None |
| 316 |
self.domain = u.hostname.lower() |
| 317 |
try: |
| 318 |
self.domain = idna.encode(self.domain).decode() |
| 319 |
except Exception: |
| 320 |
raise ValueError('invalid domain name') from None |
| 321 |
if not self._validate_domain(self.domain): |
| 322 |
raise ValueError('invalid domain name') from None |
| 323 |
self.username = u.username |
| 324 |
self.password = u.password |
| 325 |
self.port = u.port |
| 326 |
self.path = u.path |
| 327 |
self.query = u.query |
| 328 |
self.fragment = u.fragment |
| 329 |
|
| 330 |
def _validate_domain(self, domain): |
| 331 |
if len(domain) < 1 or len(domain) > 253: |
| 332 |
return False |
| 333 |
if VALID_FQDN_REGEX.match(domain): |
| 334 |
try: |
| 335 |
_ = idna.decode(domain) |
| 336 |
except Exception: |
| 337 |
return False |
| 338 |
else: |
| 339 |
return True |
| 340 |
return False |
| 341 |
|
| 342 |
def full_uri(self, domain=None): |
| 343 |
uri = '{}://'.format(self.scheme) |
| 344 |
if self.username: |
| 345 |
uri += self.username |
| 346 |
if self.password: |
| 347 |
uri += ':{}'.format(self.password) |
| 348 |
uri += '@' |
| 349 |
uri += self.domain if not domain else domain |
| 350 |
if self.port: |
| 351 |
uri += ':{}'.format(self.port) |
| 352 |
if self.path: |
| 353 |
uri += self.path |
| 354 |
if self.query: |
| 355 |
uri += '?{}'.format(self.query) |
| 356 |
if self.fragment: |
| 357 |
uri += '#{}'.format(self.fragment) |
| 358 |
return uri |
| 359 |
|
| 360 |
|
| 361 |
class Permutation(dict): |
| 362 |
def __getattr__(self, item): |
| 363 |
if item in self: |
| 364 |
return self[item] |
| 365 |
raise AttributeError("object has no attribute '{}'".format(item)) from None |
| 366 |
|
| 367 |
__setattr__ = dict.__setitem__ |
| 368 |
|
| 369 |
def __init__(self, **kwargs): |
| 370 |
super(dict, self).__init__() |
| 371 |
self['fuzzer'] = kwargs.pop('fuzzer', '') |
| 372 |
self['domain'] = kwargs.pop('domain', '') |
| 373 |
for k, v in kwargs.items(): |
| 374 |
self[k] = v |
| 375 |
|
| 376 |
def __hash__(self): |
| 377 |
return hash(self['domain']) |
| 378 |
|
| 379 |
def __eq__(self, other): |
| 380 |
return self['domain'] == other['domain'] |
| 381 |
|
| 382 |
def __lt__(self, other): |
| 383 |
if self['fuzzer'] == other['fuzzer']: |
| 384 |
if len(self) > 2 and len(other) > 2: |
| 385 |
return self.get('dns_a', [''])[0] + self['domain'] < other.get('dns_a', [''])[0] + other['domain'] |
| 386 |
else: |
| 387 |
return self['domain'] < other['domain'] |
| 388 |
return self['fuzzer'] < other['fuzzer'] |
| 389 |
|
| 390 |
def is_registered(self): |
| 391 |
return len(self) > 2 |
| 392 |
|
| 393 |
def copy(self): |
| 394 |
return Permutation(**self) |
| 395 |
|
| 396 |
|
| 397 |
class pHash(): |
| 398 |
def __init__(self, image, hsize=8): |
| 399 |
img = Image.open(image).convert('L').resize((hsize, hsize), Image.LANCZOS) |
| 400 |
pixels = list(img.getdata()) |
| 401 |
avg = sum(pixels) / len(pixels) |
| 402 |
self.hash = ''.join('1' if p > avg else '0' for p in pixels) |
| 403 |
|
| 404 |
def __sub__(self, other): |
| 405 |
bc = len(self.hash) |
| 406 |
ham = sum(x != y for x, y in list(zip(self.hash, other.hash))) |
| 407 |
e = 2.718281828459045 |
| 408 |
sub = int((1 + e**((bc - ham) / bc) - e) * 100) |
| 409 |
return sub if sub > 0 else 0 |
| 410 |
|
| 411 |
def __repr__(self): |
| 412 |
return '{:x}'.format(int(self.hash, base=2)) |
| 413 |
|
| 414 |
def __int__(self): |
| 415 |
return int(self.hash, base=2) |
| 416 |
|
| 417 |
|
| 418 |
class HeadlessBrowser(): |
| 419 |
WEBDRIVER_TIMEOUT = 12 |
| 420 |
WEBDRIVER_ARGUMENTS = ( |
| 421 |
'--disable-dev-shm-usage', |
| 422 |
'--ignore-certificate-errors', |
| 423 |
'--headless', |
| 424 |
'--incognito', |
| 425 |
'--no-sandbox', |
| 426 |
'--disable-gpu', |
| 427 |
'--disable-extensions', |
| 428 |
'--disk-cache-size=0', |
| 429 |
'--aggressive-cache-discard', |
| 430 |
'--disable-notifications', |
| 431 |
'--disable-remote-fonts', |
| 432 |
'--disable-sync', |
| 433 |
'--window-size=1366,768', |
| 434 |
'--hide-scrollbars', |
| 435 |
'--disable-audio-output', |
| 436 |
'--dns-prefetch-disable', |
| 437 |
'--no-default-browser-check', |
| 438 |
'--disable-background-networking', |
| 439 |
'--enable-features=NetworkService,NetworkServiceInProcess', |
| 440 |
'--disable-background-timer-throttling', |
| 441 |
'--disable-backgrounding-occluded-windows', |
| 442 |
'--disable-breakpad', |
| 443 |
'--disable-client-side-phishing-detection', |
| 444 |
'--disable-component-extensions-with-background-pages', |
| 445 |
'--disable-default-apps', |
| 446 |
'--disable-features=TranslateUI', |
| 447 |
'--disable-hang-monitor', |
| 448 |
'--disable-ipc-flooding-protection', |
| 449 |
'--disable-prompt-on-repost', |
| 450 |
'--disable-renderer-backgrounding', |
| 451 |
'--force-color-profile=srgb', |
| 452 |
'--metrics-recording-only', |
| 453 |
'--no-first-run', |
| 454 |
'--password-store=basic', |
| 455 |
'--use-mock-keychain', |
| 456 |
'--disable-blink-features=AutomationControlled', |
| 457 |
) |
| 458 |
|
| 459 |
def __init__(self, useragent=None): |
| 460 |
chrome_options = webdriver.ChromeOptions() |
| 461 |
for opt in self.WEBDRIVER_ARGUMENTS: |
| 462 |
chrome_options.add_argument(opt) |
| 463 |
proxies = urllib.request.getproxies() |
| 464 |
if proxies: |
| 465 |
proxy_string = ';'.join(['{}={}'.format(scheme, url) for scheme, url in proxies.items()]) |
| 466 |
chrome_options.add_argument('--proxy-server={}'.format(proxy_string)) |
| 467 |
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation']) |
| 468 |
chrome_options.add_experimental_option('useAutomationExtension', False) |
| 469 |
self.driver = webdriver.Chrome(options=chrome_options) |
| 470 |
self.driver.set_page_load_timeout(self.WEBDRIVER_TIMEOUT) |
| 471 |
self.driver.execute_cdp_cmd('Network.setUserAgentOverride', {'userAgent': |
| 472 |
useragent or self.driver.execute_script('return navigator.userAgent').replace('Headless', '') |
| 473 |
}) |
| 474 |
self.get = self.driver.get |
| 475 |
self.screenshot = self.driver.get_screenshot_as_png |
| 476 |
|
| 477 |
def stop(self): |
| 478 |
try: |
| 479 |
self.driver.close() |
| 480 |
self.driver.quit() |
| 481 |
except Exception: |
| 482 |
pass |
| 483 |
try: |
| 484 |
pid = True |
| 485 |
while pid: |
| 486 |
pid, status = os.waitpid(-1, os.WNOHANG) |
| 487 |
except ChildProcessError: |
| 488 |
pass |
| 489 |
|
| 490 |
def __del__(self): |
| 491 |
self.stop() |
| 492 |
|
| 493 |
|
| 494 |
class Fuzzer(): |
| 495 |
glyphs_idn_by_tld = { |
| 496 |
**dict.fromkeys(['ad', 'cz', 'sk', 'uk', 'co.uk', 'nl', 'edu', 'us'], { |
| 497 |
# IDN not supported by the corresponding registry |
| 498 |
}), |
| 499 |
**dict.fromkeys(['jp', 'co.jp', 'ad.jp', 'ne.jp'], { |
| 500 |
}), |
| 501 |
**dict.fromkeys(['cn', 'com.cn', 'tw', 'com.tw', 'net.tw'], { |
| 502 |
}), |
| 503 |
**dict.fromkeys(['info'], { |
| 504 |
'a': ('á', 'ä', 'å', 'ą'), |
| 505 |
'c': ('ć', 'č'), |
| 506 |
'e': ('é', 'ė', 'ę'), |
| 507 |
'i': ('í', 'į'), |
| 508 |
'l': ('ł',), |
| 509 |
'n': ('ñ', 'ń'), |
| 510 |
'o': ('ó', 'ö', 'ø', 'ő'), |
| 511 |
's': ('ś', 'š'), |
| 512 |
'u': ('ú', 'ü', 'ū', 'ű', 'ų'), |
| 513 |
'z': ('ź', 'ż', 'ž'), |
| 514 |
'ae': ('æ',), |
| 515 |
}), |
| 516 |
**dict.fromkeys(['br', 'com.br'], { |
| 517 |
'a': ('à', 'á', 'â', 'ã'), |
| 518 |
'c': ('ç',), |
| 519 |
'e': ('é', 'ê'), |
| 520 |
'i': ('í',), |
| 521 |
'o': ('ó', 'ô', 'õ'), |
| 522 |
'u': ('ú', 'ü'), |
| 523 |
'y': ('ý', 'ÿ'), |
| 524 |
}), |
| 525 |
**dict.fromkeys(['dk'], { |
| 526 |
'a': ('ä', 'å'), |
| 527 |
'e': ('é',), |
| 528 |
'o': ('ö', 'ø'), |
| 529 |
'u': ('ü',), |
| 530 |
'ae': ('æ',), |
| 531 |
}), |
| 532 |
**dict.fromkeys(['eu', 'de', 'pl'], { |
| 533 |
'a': ('á', 'à', 'ă', 'â', 'å', 'ä', 'ã', 'ą', 'ā'), |
| 534 |
'c': ('ć', 'ĉ', 'č', 'ċ', 'ç'), |
| 535 |
'd': ('ď', 'đ'), |
| 536 |
'e': ('é', 'è', 'ĕ', 'ê', 'ě', 'ë', 'ė', 'ę', 'ē'), |
| 537 |
'g': ('ğ', 'ĝ', 'ġ', 'ģ'), |
| 538 |
'h': ('ĥ', 'ħ'), |
| 539 |
'i': ('í', 'ì', 'ĭ', 'î', 'ï', 'ĩ', 'į', 'ī'), |
| 540 |
'j': ('ĵ',), |
| 541 |
'k': ('ķ', 'ĸ'), |
| 542 |
'l': ('ĺ', 'ľ', 'ļ', 'ł'), |
| 543 |
'n': ('ń', 'ň', 'ñ', 'ņ'), |
| 544 |
'o': ('ó', 'ò', 'ŏ', 'ô', 'ö', 'ő', 'õ', 'ø', 'ō'), |
| 545 |
'r': ('ŕ', 'ř', 'ŗ'), |
| 546 |
's': ('ś', 'ŝ', 'š', 'ş'), |
| 547 |
't': ('ť', 'ţ', 'ŧ'), |
| 548 |
'u': ('ú', 'ù', 'ŭ', 'û', 'ů', 'ü', 'ű', 'ũ', 'ų', 'ū'), |
| 549 |
'w': ('ŵ',), |
| 550 |
'y': ('ý', 'ŷ', 'ÿ'), |
| 551 |
'z': ('ź', 'ž', 'ż'), |
| 552 |
'ae': ('æ',), |
| 553 |
'oe': ('œ',), |
| 554 |
}), |
| 555 |
**dict.fromkeys(['fi'], { |
| 556 |
'3': ('ʒ',), |
| 557 |
'a': ('á', 'ä', 'å', 'â'), |
| 558 |
'c': ('č',), |
| 559 |
'd': ('đ',), |
| 560 |
'g': ('ǧ', 'ǥ'), |
| 561 |
'k': ('ǩ',), |
| 562 |
'n': ('ŋ',), |
| 563 |
'o': ('õ', 'ö'), |
| 564 |
's': ('š',), |
| 565 |
't': ('ŧ',), |
| 566 |
'z': ('ž',), |
| 567 |
}), |
| 568 |
**dict.fromkeys(['no'], { |
| 569 |
'a': ('á', 'à', 'ä', 'å'), |
| 570 |
'c': ('č', 'ç'), |
| 571 |
'e': ('é', 'è', 'ê'), |
| 572 |
'i': ('ï',), |
| 573 |
'n': ('ŋ', 'ń', 'ñ'), |
| 574 |
'o': ('ó', 'ò', 'ô', 'ö', 'ø'), |
| 575 |
's': ('š',), |
| 576 |
't': ('ŧ',), |
| 577 |
'u': ('ü',), |
| 578 |
'z': ('ž',), |
| 579 |
'ae': ('æ',), |
| 580 |
}), |
| 581 |
**dict.fromkeys(['be', 'fr', 're', 'yt', 'pm', 'wf', 'tf', 'ch', 'li'], { |
| 582 |
'a': ('à', 'á', 'â', 'ã', 'ä', 'å'), |
| 583 |
'c': ('ç',), |
| 584 |
'e': ('è', 'é', 'ê', 'ë'), |
| 585 |
'i': ('ì', 'í', 'î', 'ï'), |
| 586 |
'n': ('ñ',), |
| 587 |
'o': ('ò', 'ó', 'ô', 'õ', 'ö'), |
| 588 |
'u': ('ù', 'ú', 'û', 'ü'), |
| 589 |
'y': ('ý', 'ÿ'), |
| 590 |
'ae': ('æ',), |
| 591 |
'oe': ('œ',), |
| 592 |
}), |
| 593 |
**dict.fromkeys(['ca'], { |
| 594 |
'a': ('à', 'â'), |
| 595 |
'c': ('ç',), |
| 596 |
'e': ('è', 'é', 'ê', 'ë'), |
| 597 |
'i': ('î', 'ï'), |
| 598 |
'o': ('ô',), |
| 599 |
'u': ('ù', 'û', 'ü'), |
| 600 |
'y': ('ÿ',), |
| 601 |
'ae': ('æ',), |
| 602 |
'oe': ('œ',), |
| 603 |
}), |
| 604 |
} |
| 605 |
|
| 606 |
glyphs_unicode = { |
| 607 |
'2': ('ƻ',), |
| 608 |
'3': ('ʒ',), |
| 609 |
'5': ('ƽ',), |
| 610 |
'a': ('ạ', 'ă', 'ȧ', 'ɑ', 'å', 'ą', 'â', 'ǎ', 'á', 'ə', 'ä', 'ã', 'ā', 'à'), |
| 611 |
'b': ('ḃ', 'ḅ', 'ƅ', 'ʙ', 'ḇ', 'ɓ'), |
| 612 |
'c': ('č', 'ᴄ', 'ċ', 'ç', 'ć', 'ĉ', 'ƈ'), |
| 613 |
'd': ('ď', 'ḍ', 'ḋ', 'ɖ', 'ḏ', 'ɗ', 'ḓ', 'ḑ', 'đ'), |
| 614 |
'e': ('ê', 'ẹ', 'ę', 'è', 'ḛ', 'ě', 'ɇ', 'ė', 'ĕ', 'é', 'ë', 'ē', 'ȩ'), |
| 615 |
'f': ('ḟ', 'ƒ'), |
| 616 |
'g': ('ǧ', 'ġ', 'ǵ', 'ğ', 'ɡ', 'ǥ', 'ĝ', 'ģ', 'ɢ'), |
| 617 |
'h': ('ȟ', 'ḫ', 'ḩ', 'ḣ', 'ɦ', 'ḥ', 'ḧ', 'ħ', 'ẖ', 'ⱨ', 'ĥ'), |
| 618 |
'i': ('ɩ', 'ǐ', 'í', 'ɪ', 'ỉ', 'ȋ', 'ɨ', 'ï', 'ī', 'ĩ', 'ị', 'î', 'ı', 'ĭ', 'į', 'ì'), |
| 619 |
'j': ('ǰ', 'ĵ', 'ʝ', 'ɉ'), |
| 620 |
'k': ('ĸ', 'ǩ', 'ⱪ', 'ḵ', 'ķ', 'ᴋ', 'ḳ'), |
| 621 |
'l': ('ĺ', 'ł', 'ɫ', 'ļ', 'ľ'), |
| 622 |
'm': ('ᴍ', 'ṁ', 'ḿ', 'ṃ', 'ɱ'), |
| 623 |
'n': ('ņ', 'ǹ', 'ń', 'ň', 'ṅ', 'ṉ', 'ṇ', 'ꞑ', 'ñ', 'ŋ'), |
| 624 |
'o': ('ö', 'ó', 'ȯ', 'ỏ', 'ô', 'ᴏ', 'ō', 'ò', 'ŏ', 'ơ', 'ő', 'õ', 'ọ', 'ø'), |
| 625 |
'p': ('ṗ', 'ƿ', 'ƥ', 'ṕ'), |
| 626 |
'q': ('ʠ',), |
| 627 |
'r': ('ʀ', 'ȓ', 'ɍ', 'ɾ', 'ř', 'ṛ', 'ɽ', 'ȑ', 'ṙ', 'ŗ', 'ŕ', 'ɼ', 'ṟ'), |
| 628 |
's': ('ṡ', 'ș', 'ŝ', 'ꜱ', 'ʂ', 'š', 'ś', 'ṣ', 'ş'), |
| 629 |
't': ('ť', 'ƫ', 'ţ', 'ṭ', 'ṫ', 'ț', 'ŧ'), |
| 630 |
'u': ('ᴜ', 'ų', 'ŭ', 'ū', 'ű', 'ǔ', 'ȕ', 'ư', 'ù', 'ů', 'ʉ', 'ú', 'ȗ', 'ü', 'û', 'ũ', 'ụ'), |
| 631 |
'v': ('ᶌ', 'ṿ', 'ᴠ', 'ⱴ', 'ⱱ', 'ṽ'), |
| 632 |
'w': ('ᴡ', 'ẇ', 'ẅ', 'ẃ', 'ẘ', 'ẉ', 'ⱳ', 'ŵ', 'ẁ'), |
| 633 |
'x': ('ẋ', 'ẍ'), |
| 634 |
'y': ('ŷ', 'ÿ', 'ʏ', 'ẏ', 'ɏ', 'ƴ', 'ȳ', 'ý', 'ỿ', 'ỵ'), |
| 635 |
'z': ('ž', 'ƶ', 'ẓ', 'ẕ', 'ⱬ', 'ᴢ', 'ż', 'ź', 'ʐ'), |
| 636 |
'ae': ('æ',), |
| 637 |
'oe': ('œ',), |
| 638 |
} |
| 639 |
|
| 640 |
glyphs_ascii = { |
| 641 |
'0': ('o',), |
| 642 |
'1': ('l', 'i'), |
| 643 |
'3': ('8',), |
| 644 |
'6': ('9',), |
| 645 |
'8': ('3',), |
| 646 |
'9': ('6',), |
| 647 |
'b': ('d', 'lb'), |
| 648 |
'c': ('e',), |
| 649 |
'd': ('b', 'cl', 'dl'), |
| 650 |
'e': ('c',), |
| 651 |
'g': ('q',), |
| 652 |
'h': ('lh',), |
| 653 |
'i': ('1', 'l'), |
| 654 |
'k': ('lc',), |
| 655 |
'l': ('1', 'i'), |
| 656 |
'm': ('n', 'nn', 'rn'), |
| 657 |
'n': ('m', 'r'), |
| 658 |
'o': ('0',), |
| 659 |
'q': ('g',), |
| 660 |
'u': ('v',), |
| 661 |
'v': ('u',), |
| 662 |
'w': ('vv',), |
| 663 |
'rn': ('m',), |
| 664 |
'cl': ('d',), |
| 665 |
} |
| 666 |
|
| 667 |
latin_to_cyrillic = { |
| 668 |
'a': 'а', 'b': 'ь', 'c': 'с', 'd': 'ԁ', 'e': 'е', 'g': 'ԍ', 'h': 'һ', |
| 669 |
'i': 'і', 'j': 'ј', 'k': 'к', 'l': 'ӏ', 'm': 'м', 'o': 'о', 'p': 'р', |
| 670 |
'q': 'ԛ', 's': 'ѕ', 't': 'т', 'v': 'ѵ', 'w': 'ԝ', 'x': 'х', 'y': 'у', |
| 671 |
} |
| 672 |
|
| 673 |
qwerty = { |
| 674 |
'1': '2q', '2': '3wq1', '3': '4ew2', '4': '5re3', '5': '6tr4', '6': '7yt5', '7': '8uy6', '8': '9iu7', '9': '0oi8', '0': 'po9', |
| 675 |
'q': '12wa', 'w': '3esaq2', 'e': '4rdsw3', 'r': '5tfde4', 't': '6ygfr5', 'y': '7uhgt6', 'u': '8ijhy7', 'i': '9okju8', 'o': '0plki9', 'p': 'lo0', |
| 676 |
'a': 'qwsz', 's': 'edxzaw', 'd': 'rfcxse', 'f': 'tgvcdr', 'g': 'yhbvft', 'h': 'ujnbgy', 'j': 'ikmnhu', 'k': 'olmji', 'l': 'kop', |
| 677 |
'z': 'asx', 'x': 'zsdc', 'c': 'xdfv', 'v': 'cfgb', 'b': 'vghn', 'n': 'bhjm', 'm': 'njk' |
| 678 |
} |
| 679 |
qwertz = { |
| 680 |
'1': '2q', '2': '3wq1', '3': '4ew2', '4': '5re3', '5': '6tr4', '6': '7zt5', '7': '8uz6', '8': '9iu7', '9': '0oi8', '0': 'po9', |
| 681 |
'q': '12wa', 'w': '3esaq2', 'e': '4rdsw3', 'r': '5tfde4', 't': '6zgfr5', 'z': '7uhgt6', 'u': '8ijhz7', 'i': '9okju8', 'o': '0plki9', 'p': 'lo0', |
| 682 |
'a': 'qwsy', 's': 'edxyaw', 'd': 'rfcxse', 'f': 'tgvcdr', 'g': 'zhbvft', 'h': 'ujnbgz', 'j': 'ikmnhu', 'k': 'olmji', 'l': 'kop', |
| 683 |
'y': 'asx', 'x': 'ysdc', 'c': 'xdfv', 'v': 'cfgb', 'b': 'vghn', 'n': 'bhjm', 'm': 'njk' |
| 684 |
} |
| 685 |
azerty = { |
| 686 |
'1': '2a', '2': '3za1', '3': '4ez2', '4': '5re3', '5': '6tr4', '6': '7yt5', '7': '8uy6', '8': '9iu7', '9': '0oi8', '0': 'po9', |
| 687 |
'a': '2zq1', 'z': '3esqa2', 'e': '4rdsz3', 'r': '5tfde4', 't': '6ygfr5', 'y': '7uhgt6', 'u': '8ijhy7', 'i': '9okju8', 'o': '0plki9', 'p': 'lo0m', |
| 688 |
'q': 'zswa', 's': 'edxwqz', 'd': 'rfcxse', 'f': 'tgvcdr', 'g': 'yhbvft', 'h': 'ujnbgy', 'j': 'iknhu', 'k': 'olji', 'l': 'kopm', 'm': 'lp', |
| 689 |
'w': 'sxq', 'x': 'wsdc', 'c': 'xdfv', 'v': 'cfgb', 'b': 'vghn', 'n': 'bhj' |
| 690 |
} |
| 691 |
keyboards = [qwerty, qwertz, azerty] |
| 692 |
|
| 693 |
def __init__(self, domain, dictionary=[], tld_dictionary=[]): |
| 694 |
self.subdomain, self.domain, self.tld = domain_tld(domain) |
| 695 |
self.domain = idna.decode(self.domain) |
| 696 |
self.dictionary = list(dictionary) |
| 697 |
self.tld_dictionary = list(tld_dictionary) |
| 698 |
self.domains = set() |
| 699 |
|
| 700 |
def __enter__(self): |
| 701 |
return self |
| 702 |
|
| 703 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 704 |
return |
| 705 |
|
| 706 |
def _bitsquatting(self): |
| 707 |
masks = [1, 2, 4, 8, 16, 32, 64, 128] |
| 708 |
chars = set('abcdefghijklmnopqrstuvwxyz0123456789-') |
| 709 |
for i, c in enumerate(self.domain): |
| 710 |
for mask in masks: |
| 711 |
b = chr(ord(c) ^ mask) |
| 712 |
if b in chars: |
| 713 |
yield self.domain[:i] + b + self.domain[i+1:] |
| 714 |
|
| 715 |
def _cyrillic(self): |
| 716 |
cdomain = self.domain |
| 717 |
for l, c in self.latin_to_cyrillic.items(): |
| 718 |
cdomain = cdomain.replace(l, c) |
| 719 |
for c, l in zip(cdomain, self.domain): |
| 720 |
if c == l: |
| 721 |
return [] |
| 722 |
return [cdomain] |
| 723 |
|
| 724 |
def _homoglyph(self): |
| 725 |
md = lambda a, b: {k: set(a.get(k, [])) | set(b.get(k, [])) for k in set(a.keys()) | set(b.keys())} |
| 726 |
glyphs = md(self.glyphs_ascii, self.glyphs_idn_by_tld.get(self.tld, self.glyphs_unicode)) |
| 727 |
def mix(domain): |
| 728 |
for i, c in enumerate(domain): |
| 729 |
for g in glyphs.get(c, []): |
| 730 |
yield domain[:i] + g + domain[i+1:] |
| 731 |
for i in range(len(domain)-1): |
| 732 |
win = domain[i:i+2] |
| 733 |
for c in {win[0], win[1], win}: |
| 734 |
for g in glyphs.get(c, []): |
| 735 |
yield domain[:i] + win.replace(c, g) + domain[i+2:] |
| 736 |
result1 = set(mix(self.domain)) |
| 737 |
result2 = set() |
| 738 |
for r in result1: |
| 739 |
result2.update(set(mix(r))) |
| 740 |
return result1 | result2 |
| 741 |
|
| 742 |
def _hyphenation(self): |
| 743 |
return {self.domain[:i] + '-' + self.domain[i:] for i in range(1, len(self.domain))} |
| 744 |
|
| 745 |
def _insertion(self): |
| 746 |
result = set() |
| 747 |
for i in range(0, len(self.domain)-1): |
| 748 |
prefix, orig_c, suffix = self.domain[:i], self.domain[i], self.domain[i+1:] |
| 749 |
for c in (c for keys in self.keyboards for c in keys.get(orig_c, [])): |
| 750 |
result.update({ |
| 751 |
prefix + c + orig_c + suffix, |
| 752 |
prefix + orig_c + c + suffix |
| 753 |
}) |
| 754 |
return result |
| 755 |
|
| 756 |
def _omission(self): |
| 757 |
return {self.domain[:i] + self.domain[i+1:] for i in range(len(self.domain))} |
| 758 |
|
| 759 |
def _repetition(self): |
| 760 |
return {self.domain[:i] + c + self.domain[i:] for i, c in enumerate(self.domain)} |
| 761 |
|
| 762 |
def _replacement(self): |
| 763 |
for i, c in enumerate(self.domain): |
| 764 |
pre = self.domain[:i] |
| 765 |
suf = self.domain[i+1:] |
| 766 |
for layout in self.keyboards: |
| 767 |
for r in layout.get(c, ''): |
| 768 |
yield pre + r + suf |
| 769 |
|
| 770 |
def _subdomain(self): |
| 771 |
for i in range(1, len(self.domain)-1): |
| 772 |
if self.domain[i] not in ['-', '.'] and self.domain[i-1] not in ['-', '.']: |
| 773 |
yield self.domain[:i] + '.' + self.domain[i:] |
| 774 |
|
| 775 |
def _transposition(self): |
| 776 |
return {self.domain[:i] + self.domain[i+1] + self.domain[i] + self.domain[i+2:] for i in range(len(self.domain)-1)} |
| 777 |
|
| 778 |
def _vowel_swap(self): |
| 779 |
vowels = 'aeiou' |
| 780 |
for i in range(0, len(self.domain)): |
| 781 |
for vowel in vowels: |
| 782 |
if self.domain[i] in vowels: |
| 783 |
yield self.domain[:i] + vowel + self.domain[i+1:] |
| 784 |
|
| 785 |
def _plural(self): |
| 786 |
for i in range(2, len(self.domain)-2): |
| 787 |
yield self.domain[:i+1] + ('es' if self.domain[i] in ('s', 'x', 'z') else 's') + self.domain[i+1:] |
| 788 |
|
| 789 |
|
| 790 |
def _addition(self): |
| 791 |
result = set() |
| 792 |
if '-' in self.domain: |
| 793 |
parts = self.domain.split('-') |
| 794 |
result = {'-'.join(parts[:p]) + chr(i) + '-' + '-'.join(parts[p:]) for i in (*range(48, 58), *range(97, 123)) for p in range(1, len(parts))} |
| 795 |
result.update({self.domain + chr(i) for i in (*range(48, 58), *range(97, 123))}) |
| 796 |
return result |
| 797 |
|
| 798 |
|
| 799 |
def _dictionary(self): |
| 800 |
result = set() |
| 801 |
for word in self.dictionary: |
| 802 |
if not (self.domain.startswith(word) and self.domain.endswith(word)): |
| 803 |
result.update({ |
| 804 |
self.domain + '-' + word, |
| 805 |
self.domain + word, |
| 806 |
word + '-' + self.domain, |
| 807 |
word + self.domain |
| 808 |
}) |
| 809 |
if '-' in self.domain: |
| 810 |
parts = self.domain.split('-') |
| 811 |
for word in self.dictionary: |
| 812 |
result.update({ |
| 813 |
'-'.join(parts[:-1]) + '-' + word, |
| 814 |
word + '-' + '-'.join(parts[1:]) |
| 815 |
}) |
| 816 |
return result |
| 817 |
|
| 818 |
def _tld(self): |
| 819 |
if self.tld in self.tld_dictionary: |
| 820 |
self.tld_dictionary.remove(self.tld) |
| 821 |
return set(self.tld_dictionary) |
| 822 |
|
| 823 |
def generate(self, fuzzers=[]): |
| 824 |
self.domains = set() |
| 825 |
if not fuzzers or '*original' in fuzzers: |
| 826 |
self.domains.add(Permutation(fuzzer='*original', domain='.'.join(filter(None, [self.subdomain, self.domain, self.tld])))) |
| 827 |
for f_name in fuzzers or [ |
| 828 |
'addition', 'bitsquatting', 'cyrillic', 'homoglyph', 'hyphenation', |
| 829 |
'insertion', 'omission', 'plural', 'repetition', 'replacement', |
| 830 |
'subdomain', 'transposition', 'vowel-swap', 'dictionary', |
| 831 |
]: |
| 832 |
try: |
| 833 |
f = getattr(self, '_' + f_name.replace('-', '_')) |
| 834 |
except AttributeError: |
| 835 |
pass |
| 836 |
else: |
| 837 |
for domain in f(): |
| 838 |
self.domains.add(Permutation(fuzzer=f_name, domain='.'.join(filter(None, [self.subdomain, domain, self.tld])))) |
| 839 |
if not fuzzers or 'tld-swap' in fuzzers: |
| 840 |
for tld in self._tld(): |
| 841 |
self.domains.add(Permutation(fuzzer='tld-swap', domain='.'.join(filter(None, [self.subdomain, self.domain, tld])))) |
| 842 |
if not fuzzers or 'various' in fuzzers: |
| 843 |
if '.' in self.tld: |
| 844 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain, self.tld.split('.')[-1]])))) |
| 845 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + self.tld])))) |
| 846 |
if '.' not in self.tld: |
| 847 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + self.tld, self.tld])))) |
| 848 |
if self.tld != 'com' and '.' not in self.tld: |
| 849 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + '-' + self.tld, 'com'])))) |
| 850 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + self.tld, 'com'])))) |
| 851 |
if self.subdomain: |
| 852 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain + self.domain, self.tld]))) |
| 853 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain.replace('.', '') + self.domain, self.tld]))) |
| 854 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain + '-' + self.domain, self.tld]))) |
| 855 |
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain.replace('.', '-') + '-' + self.domain, self.tld]))) |
| 856 |
def _punycode(domain): |
| 857 |
try: |
| 858 |
domain['domain'] = idna.encode(domain['domain']).decode() |
| 859 |
except Exception: |
| 860 |
domain['domain'] = '' |
| 861 |
return domain |
| 862 |
self.domains = set(map(_punycode, self.domains)) |
| 863 |
for domain in self.domains.copy(): |
| 864 |
if not VALID_FQDN_REGEX.match(domain.get('domain')): |
| 865 |
self.domains.discard(domain) |
| 866 |
|
| 867 |
def permutations(self, registered=False, unregistered=False, dns_all=False, unicode=False): |
| 868 |
if (registered and not unregistered): |
| 869 |
domains = [x.copy() for x in self.domains if x.is_registered()] |
| 870 |
elif (unregistered and not registered): |
| 871 |
domains = [x.copy() for x in self.domains if not x.is_registered()] |
| 872 |
else: |
| 873 |
domains = [x.copy() for x in self.domains] |
| 874 |
if not dns_all: |
| 875 |
def _cutdns(x): |
| 876 |
if x.is_registered(): |
| 877 |
for k in ('dns_ns', 'dns_a', 'dns_aaaa', 'dns_mx'): |
| 878 |
if k in x: |
| 879 |
x[k] = x[k][:1] |
| 880 |
return x |
| 881 |
domains = map(_cutdns, domains) |
| 882 |
if unicode: |
| 883 |
def _punydecode(x): |
| 884 |
x.domain = idna.decode(x.domain) |
| 885 |
return x |
| 886 |
domains = map(_punydecode, domains) |
| 887 |
return sorted(domains) |
| 888 |
|
| 889 |
|
| 890 |
class Scanner(threading.Thread): |
| 891 |
def __init__(self, queue): |
| 892 |
threading.Thread.__init__(self) |
| 893 |
self._stop_event = threading.Event() |
| 894 |
self.daemon = True |
| 895 |
self.id = 0 |
| 896 |
self.jobs = queue |
| 897 |
self.lsh_init = '' |
| 898 |
self.lsh_effective_url = '' |
| 899 |
self.phash_init = None |
| 900 |
self.screenshot_dir = None |
| 901 |
self.url = None |
| 902 |
self.option_extdns = False |
| 903 |
self.option_geoip = False |
| 904 |
self.option_lsh = None |
| 905 |
self.option_phash = False |
| 906 |
self.option_banners = False |
| 907 |
self.option_mxcheck = False |
| 908 |
self.nameservers = [] |
| 909 |
self.useragent = '' |
| 910 |
|
| 911 |
@staticmethod |
| 912 |
def _send_recv_tcp(host, port, data=b'', timeout=2.0, recv_bytes=1024): |
| 913 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 914 |
sock.settimeout(timeout) |
| 915 |
resp = b'' |
| 916 |
try: |
| 917 |
sock.connect((host, port)) |
| 918 |
if data: |
| 919 |
sock.send(data) |
| 920 |
resp = sock.recv(recv_bytes) |
| 921 |
except Exception as e: |
| 922 |
_debug(e) |
| 923 |
finally: |
| 924 |
sock.close() |
| 925 |
return resp.decode('utf-8', errors='ignore') |
| 926 |
|
| 927 |
def _banner_http(self, ip, vhost): |
| 928 |
response = self._send_recv_tcp(ip, 80, |
| 929 |
'HEAD / HTTP/1.1\r\nHost: {}\r\nUser-Agent: {}\r\n\r\n'.format(vhost, self.useragent).encode()) |
| 930 |
if not response: |
| 931 |
return '' |
| 932 |
headers = response.splitlines() |
| 933 |
for field in headers: |
| 934 |
if field.lower().startswith('server: '): |
| 935 |
return field[8:] |
| 936 |
return '' |
| 937 |
|
| 938 |
def _banner_smtp(self, mx): |
| 939 |
response = self._send_recv_tcp(mx, 25) |
| 940 |
if not response: |
| 941 |
return '' |
| 942 |
hello = response.splitlines()[0] |
| 943 |
if hello.startswith('220'): |
| 944 |
return hello[4:].strip() |
| 945 |
return '' |
| 946 |
|
| 947 |
def _mxcheck(self, mxhost, domain_from, domain_rcpt): |
| 948 |
r''' |
| 949 |
Detects potential email honey pots waiting for mistyped emails to arrive. |
| 950 |
Note: Some mail servers only pretend to accept incorrectly addressed |
| 951 |
emails - this technique is used to prevent "directory harvesting attack". |
| 952 |
''' |
| 953 |
try: |
| 954 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 955 |
sock.settimeout(REQUEST_TIMEOUT_SMTP) |
| 956 |
sock.connect((mxhost, 25)) |
| 957 |
except Exception: |
| 958 |
return False |
| 959 |
for cmd in [ |
| 960 |
'EHLO {}\r\n'.format(mxhost), |
| 961 |
'MAIL FROM: randombob1986@{}\r\n'.format(domain_from), |
| 962 |
'RCPT TO: randomalice1986@{}\r\n'.format(domain_rcpt), |
| 963 |
# And that's how the cookie crumbles |
| 964 |
]: |
| 965 |
try: |
| 966 |
resp = sock.recv(512) |
| 967 |
except Exception: |
| 968 |
break |
| 969 |
if not resp: |
| 970 |
break |
| 971 |
if resp[0] != 0x32: # status code != 2xx |
| 972 |
break |
| 973 |
sock.send(cmd.encode()) |
| 974 |
else: |
| 975 |
sock.close() |
| 976 |
return True |
| 977 |
sock.close() |
| 978 |
return False |
| 979 |
|
| 980 |
def stop(self): |
| 981 |
self._stop_event.set() |
| 982 |
|
| 983 |
def is_stopped(self): |
| 984 |
return self._stop_event.is_set() |
| 985 |
|
| 986 |
def run(self): |
| 987 |
if self.option_extdns: |
| 988 |
if self.nameservers: |
| 989 |
resolv = Resolver(configure=False) |
| 990 |
resolv.nameservers = self.nameservers |
| 991 |
else: |
| 992 |
resolv = Resolver() |
| 993 |
resolv.search = [] |
| 994 |
|
| 995 |
resolv.lifetime = REQUEST_TIMEOUT_DNS * REQUEST_RETRIES_DNS |
| 996 |
resolv.timeout = REQUEST_TIMEOUT_DNS |
| 997 |
EDNS_PAYLOAD = 1232 |
| 998 |
resolv.use_edns(edns=True, ednsflags=0, payload=EDNS_PAYLOAD) |
| 999 |
resolv.rotate = True |
| 1000 |
|
| 1001 |
if hasattr(resolv, 'resolve'): |
| 1002 |
resolve = resolv.resolve |
| 1003 |
else: |
| 1004 |
resolve = resolv.query |
| 1005 |
|
| 1006 |
if self.option_geoip: |
| 1007 |
geo = geoip() |
| 1008 |
|
| 1009 |
if self.option_phash: |
| 1010 |
browser = HeadlessBrowser(useragent=self.useragent) |
| 1011 |
|
| 1012 |
_answer_to_list = lambda ans: sorted([str(x).split(' ')[-1].rstrip('.') for x in ans]) |
| 1013 |
|
| 1014 |
while not self.is_stopped(): |
| 1015 |
try: |
| 1016 |
task = self.jobs.get(block=False) |
| 1017 |
except queue.Empty: |
| 1018 |
self.stop() |
| 1019 |
return |
| 1020 |
|
| 1021 |
domain = task.get('domain') |
| 1022 |
|
| 1023 |
dns_a = False |
| 1024 |
dns_aaaa = False |
| 1025 |
if self.option_extdns: |
| 1026 |
nxdomain = False |
| 1027 |
dns_ns = False |
| 1028 |
dns_mx = False |
| 1029 |
|
| 1030 |
try: |
| 1031 |
task['dns_ns'] = _answer_to_list(resolve(domain, rdtype=dns.rdatatype.NS)) |
| 1032 |
dns_ns = True |
| 1033 |
except NXDOMAIN: |
| 1034 |
nxdomain = True |
| 1035 |
except NoNameservers: |
| 1036 |
task['dns_ns'] = ['!ServFail'] |
| 1037 |
except DNSException as e: |
| 1038 |
_debug(e) |
| 1039 |
|
| 1040 |
if nxdomain is False: |
| 1041 |
try: |
| 1042 |
task['dns_a'] = _answer_to_list(resolve(domain, rdtype=dns.rdatatype.A)) |
| 1043 |
dns_a = True |
| 1044 |
except NoNameservers: |
| 1045 |
task['dns_a'] = ['!ServFail'] |
| 1046 |
except DNSException as e: |
| 1047 |
_debug(e) |
| 1048 |
|
| 1049 |
try: |
| 1050 |
task['dns_aaaa'] = _answer_to_list(resolve(domain, rdtype=dns.rdatatype.AAAA)) |
| 1051 |
dns_aaaa = True |
| 1052 |
except NoNameservers: |
| 1053 |
task['dns_aaaa'] = ['!ServFail'] |
| 1054 |
except DNSException as e: |
| 1055 |
_debug(e) |
| 1056 |
|
| 1057 |
if nxdomain is False and dns_ns is True: |
| 1058 |
try: |
| 1059 |
task['dns_mx'] = _answer_to_list(resolve(domain, rdtype=dns.rdatatype.MX)) |
| 1060 |
dns_mx = True |
| 1061 |
except NoNameservers: |
| 1062 |
task['dns_mx'] = ['!ServFail'] |
| 1063 |
except DNSException as e: |
| 1064 |
_debug(e) |
| 1065 |
else: |
| 1066 |
try: |
| 1067 |
addrinfo = socket.getaddrinfo(domain, None, proto=socket.IPPROTO_TCP) |
| 1068 |
except socket.gaierror as e: |
| 1069 |
if e.errno == -3: |
| 1070 |
task['dns_a'] = ['!ServFail'] |
| 1071 |
except Exception as e: |
| 1072 |
_debug(e) |
| 1073 |
else: |
| 1074 |
for _, _, _, _, sa in addrinfo: |
| 1075 |
ip = sa[0] |
| 1076 |
if '.' in ip: |
| 1077 |
if 'dns_a' not in task: |
| 1078 |
task['dns_a'] = set() |
| 1079 |
dns_a = True |
| 1080 |
task['dns_a'].add(ip) |
| 1081 |
if ':' in ip: |
| 1082 |
if 'dns_aaaa' not in task: |
| 1083 |
task['dns_aaaa'] = set() |
| 1084 |
dns_aaaa = True |
| 1085 |
task['dns_aaaa'].add(ip) |
| 1086 |
if 'dns_a' in task: |
| 1087 |
task['dns_a'] = list(task['dns_a']) |
| 1088 |
if 'dns_aaaa' in task: |
| 1089 |
task['dns_aaaa'] = list(task['dns_aaaa']) |
| 1090 |
|
| 1091 |
if self.option_mxcheck: |
| 1092 |
if dns_mx is True: |
| 1093 |
if domain != self.url.domain: |
| 1094 |
if self._mxcheck(task['dns_mx'][0], self.url.domain, domain): |
| 1095 |
task['mx_spy'] = True |
| 1096 |
|
| 1097 |
if self.option_geoip: |
| 1098 |
if dns_a is True: |
| 1099 |
try: |
| 1100 |
country = geo.country_by_addr(task['dns_a'][0]) |
| 1101 |
except Exception as e: |
| 1102 |
_debug(e) |
| 1103 |
pass |
| 1104 |
else: |
| 1105 |
if country: |
| 1106 |
task['geoip'] = country.split(',')[0] |
| 1107 |
|
| 1108 |
if self.option_banners: |
| 1109 |
if dns_a is True: |
| 1110 |
banner = self._banner_http(task['dns_a'][0], domain) |
| 1111 |
if banner: |
| 1112 |
task['banner_http'] = banner |
| 1113 |
if dns_mx is True: |
| 1114 |
banner = self._banner_smtp(task['dns_mx'][0]) |
| 1115 |
if banner: |
| 1116 |
task['banner_smtp'] = banner |
| 1117 |
|
| 1118 |
if self.option_phash or self.screenshot_dir: |
| 1119 |
if dns_a or dns_aaaa: |
| 1120 |
try: |
| 1121 |
browser.get(self.url.full_uri(domain)) |
| 1122 |
screenshot = browser.screenshot() |
| 1123 |
except Exception as e: |
| 1124 |
_debug(e) |
| 1125 |
else: |
| 1126 |
if self.option_phash: |
| 1127 |
phash = pHash(BytesIO(screenshot)) |
| 1128 |
task['phash'] = self.phash_init - phash |
| 1129 |
if self.screenshot_dir: |
| 1130 |
filename = os.path.join(self.screenshot_dir, '{:08x}_{}.png'.format(self.id, domain)) |
| 1131 |
try: |
| 1132 |
with open(filename, 'wb') as f: |
| 1133 |
f.write(screenshot) |
| 1134 |
except Exception as e: |
| 1135 |
_debug(e) |
| 1136 |
|
| 1137 |
if self.option_lsh: |
| 1138 |
if dns_a is True or dns_aaaa is True: |
| 1139 |
try: |
| 1140 |
r = UrlOpener(self.url.full_uri(domain), |
| 1141 |
timeout=REQUEST_TIMEOUT_HTTP, |
| 1142 |
headers={'user-agent': self.useragent}, |
| 1143 |
verify=False) |
| 1144 |
except Exception as e: |
| 1145 |
_debug(e) |
| 1146 |
else: |
| 1147 |
if r.url.split('?')[0] != self.lsh_effective_url: |
| 1148 |
if self.option_lsh == 'ssdeep': |
| 1149 |
lsh_curr = ssdeep.hash(r.normalized_content) |
| 1150 |
if lsh_curr not in (None, '3::'): |
| 1151 |
task['ssdeep'] = ssdeep.compare(self.lsh_init, lsh_curr) |
| 1152 |
elif self.option_lsh == 'tlsh': |
| 1153 |
lsh_curr = tlsh.hash(r.normalized_content) |
| 1154 |
if lsh_curr not in (None, '', 'TNULL'): |
| 1155 |
task['tlsh'] = int(100 - (min(tlsh.diff(self.lsh_init, lsh_curr), 300)/3)) |
| 1156 |
|
| 1157 |
self.jobs.task_done() |
| 1158 |
|
| 1159 |
|
| 1160 |
class Format(): |
| 1161 |
def __init__(self, domains=[]): |
| 1162 |
self.domains = domains |
| 1163 |
|
| 1164 |
def json(self, indent=4, sort_keys=True): |
| 1165 |
return json.dumps(self.domains, indent=indent, sort_keys=sort_keys) |
| 1166 |
|
| 1167 |
def csv(self): |
| 1168 |
cols = ['fuzzer', 'domain'] |
| 1169 |
for domain in self.domains: |
| 1170 |
for k in domain.keys() - cols: |
| 1171 |
cols.append(k) |
| 1172 |
cols = cols[:2] + sorted(cols[2:]) |
| 1173 |
csv = [','.join(cols)] |
| 1174 |
for domain in self.domains: |
| 1175 |
row = [] |
| 1176 |
for val in [domain.get(c, '') for c in cols]: |
| 1177 |
if isinstance(val, str): |
| 1178 |
if ',' in val: |
| 1179 |
row.append('"{}"'.format(val)) |
| 1180 |
else: |
| 1181 |
row.append(val) |
| 1182 |
elif isinstance(val, list): |
| 1183 |
row.append(';'.join(val)) |
| 1184 |
elif isinstance(val, int): |
| 1185 |
row.append(str(val)) |
| 1186 |
csv.append(','.join(row)) |
| 1187 |
return '\n'.join(csv) |
| 1188 |
|
| 1189 |
def list(self): |
| 1190 |
return '\n'.join([x.get('domain') for x in sorted(self.domains)]) |
| 1191 |
|
| 1192 |
def cli(self): |
| 1193 |
cli = [] |
| 1194 |
domains = list(self.domains) |
| 1195 |
if sys.stdout.encoding.lower() == 'utf-8': |
| 1196 |
for domain in domains: |
| 1197 |
domain.update(domain=idna.decode(domain.get('domain'))) |
| 1198 |
wfuz = max([len(x.get('fuzzer', '')) for x in domains]) + 1 |
| 1199 |
wdom = max([len(x.get('domain', '')) for x in domains]) + 1 |
| 1200 |
kv = lambda k, v: FG_YEL + k + FG_CYA + v + FG_RST if k else FG_CYA + v + FG_RST |
| 1201 |
for domain in domains: |
| 1202 |
inf = [] |
| 1203 |
if 'dns_a' in domain: |
| 1204 |
inf.append(';'.join(domain['dns_a']) + (kv('/', domain['geoip'].replace(' ', '')) if 'geoip' in domain else '')) |
| 1205 |
if 'dns_aaaa' in domain: |
| 1206 |
inf.append(';'.join(domain['dns_aaaa'])) |
| 1207 |
if 'dns_ns' in domain: |
| 1208 |
inf.append(kv('NS:', ';'.join(domain['dns_ns']))) |
| 1209 |
if 'dns_mx' in domain: |
| 1210 |
inf.append(kv('SPYING-MX:' if domain.get('mx_spy') else 'MX:', ';'.join(domain['dns_mx']))) |
| 1211 |
if 'banner_http' in domain: |
| 1212 |
inf.append(kv('HTTP:', domain['banner_http'])) |
| 1213 |
if 'banner_smtp' in domain: |
| 1214 |
inf.append(kv('SMTP:', domain['banner_smtp'])) |
| 1215 |
if 'whois_registrar' in domain: |
| 1216 |
inf.append(kv('REGISTRAR:', domain['whois_registrar'])) |
| 1217 |
if 'whois_created' in domain: |
| 1218 |
inf.append(kv('CREATED:', domain['whois_created'])) |
| 1219 |
if domain.get('ssdeep', 0) > 0: |
| 1220 |
inf.append(kv('SSDEEP:', '{}%'.format(domain['ssdeep']))) |
| 1221 |
if domain.get('tlsh', 0) > 0: |
| 1222 |
inf.append(kv('TLSH:', '{}%'.format(domain['tlsh']))) |
| 1223 |
if domain.get('phash', 0) > 0: |
| 1224 |
inf.append(kv('PHASH:', '{}%'.format(domain['phash']))) |
| 1225 |
cli.append('{}{[fuzzer]:<{}}{} {[domain]:<{}} {}'.format(FG_BLU, domain, wfuz, FG_RST, domain, wdom, ' '.join(inf or ['-']))) |
| 1226 |
return '\n'.join(cli) |
| 1227 |
|
| 1228 |
|
| 1229 |
def cleaner(func): |
| 1230 |
def wrapper(*args, **kwargs): |
| 1231 |
result = func(*args, **kwargs) |
| 1232 |
if threading.current_thread() is threading.main_thread(): |
| 1233 |
for sig in (signal.SIGINT, signal.SIGTERM): |
| 1234 |
signal.signal(sig, signal.default_int_handler) |
| 1235 |
sys.argv = sys.argv[0:1] |
| 1236 |
return result |
| 1237 |
return wrapper |
| 1238 |
|
| 1239 |
|
| 1240 |
@cleaner |
| 1241 |
def run(**kwargs): |
| 1242 |
parser = argparse.ArgumentParser( |
| 1243 |
usage='%s [OPTION]... DOMAIN' % sys.argv[0], |
| 1244 |
add_help=False, |
| 1245 |
description= |
| 1246 |
'''Domain name permutation engine for detecting homograph phishing attacks, ''' |
| 1247 |
'''typosquatting, fraud and brand impersonation.''', |
| 1248 |
formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=30) |
| 1249 |
) |
| 1250 |
|
| 1251 |
parser.add_argument('domain', help='Domain name or URL to scan') |
| 1252 |
parser.add_argument('-a', '--all', action='store_true', help='Print all DNS records instead of the first ones') |
| 1253 |
parser.add_argument('-b', '--banners', action='store_true', help='Determine HTTP and SMTP service banners') |
| 1254 |
parser.add_argument('-d', '--dictionary', type=str, metavar='FILE', help='Generate more domains using dictionary FILE') |
| 1255 |
parser.add_argument('-f', '--format', type=str, default='cli', help='Output format: cli, csv, json, list (default: cli)') |
| 1256 |
parser.add_argument('--fuzzers', type=str, metavar='LIST', help='Use only selected fuzzing algorithms (separated with commas)') |
| 1257 |
parser.add_argument('-g', '--geoip', action='store_true', help='Lookup for GeoIP location') |
| 1258 |
parser.add_argument('--lsh', type=str, metavar='LSH', nargs='?', const='ssdeep', |
| 1259 |
help='Evaluate web page similarity with LSH algorithm: ssdeep, tlsh (default: ssdeep)') |
| 1260 |
parser.add_argument('--lsh-url', metavar='URL', help='Override URL to fetch the original web page from') |
| 1261 |
parser.add_argument('-m', '--mxcheck', action='store_true', help='Check if MX host can be used to intercept emails') |
| 1262 |
parser.add_argument('-o', '--output', type=str, metavar='FILE', help='Save output to FILE') |
| 1263 |
parser.add_argument('-r', '--registered', action='store_true', help='Show only registered domain names') |
| 1264 |
parser.add_argument('-u', '--unregistered', action='store_true', help='Show only unregistered domain names') |
| 1265 |
parser.add_argument('-p', '--phash', action='store_true', help='Render web pages and evaluate visual similarity') |
| 1266 |
parser.add_argument('--phash-url', metavar='URL', help='Override URL to render the original web page from') |
| 1267 |
parser.add_argument('--screenshots', metavar='DIR', help='Save web page screenshots into DIR') |
| 1268 |
parser.add_argument('-s', '--ssdeep', action='store_true', help=argparse.SUPPRESS) |
| 1269 |
parser.add_argument('--ssdeep-url', help=argparse.SUPPRESS) |
| 1270 |
parser.add_argument('-t', '--threads', type=int, metavar='NUM', default=THREAD_COUNT_DEFAULT, |
| 1271 |
help='Start specified NUM of threads (default: %s)' % THREAD_COUNT_DEFAULT) |
| 1272 |
parser.add_argument('-w', '--whois', action='store_true', help='Lookup WHOIS database for creation date and registrar') |
| 1273 |
parser.add_argument('--tld', type=str, metavar='FILE', help='Swap TLD for the original domain from FILE') |
| 1274 |
parser.add_argument('--nameservers', type=str, metavar='LIST', help='DNS or DoH servers to query (separated with commas)') |
| 1275 |
parser.add_argument('--useragent', type=str, metavar='STRING', default=USER_AGENT_STRING, |
| 1276 |
help='Set User-Agent STRING (default: %s)' % USER_AGENT_STRING) |
| 1277 |
parser.add_argument('--version', action='version', version='dnstwist {}'.format(__version__), help=argparse.SUPPRESS) |
| 1278 |
|
| 1279 |
if kwargs: |
| 1280 |
sys.argv = [''] |
| 1281 |
for k, v in kwargs.items(): |
| 1282 |
if k in ('domain',): |
| 1283 |
sys.argv.append(v) |
| 1284 |
else: |
| 1285 |
if v is not False: |
| 1286 |
sys.argv.append('--' + k.replace('_', '-')) |
| 1287 |
if not isinstance(v, bool): |
| 1288 |
sys.argv.append(str(v)) |
| 1289 |
def _parser_error(msg): |
| 1290 |
raise Exception(msg) from None |
| 1291 |
parser.error = _parser_error |
| 1292 |
|
| 1293 |
if not sys.argv[1:] or '-h' in sys.argv or '--help' in sys.argv: |
| 1294 |
print('{}dnstwist {} by <{}>{}\n'.format(ST_BRI, __version__, __email__, ST_RST)) |
| 1295 |
parser.print_help() |
| 1296 |
return |
| 1297 |
|
| 1298 |
args = parser.parse_args() |
| 1299 |
|
| 1300 |
threads = [] |
| 1301 |
jobs = queue.Queue() |
| 1302 |
|
| 1303 |
def p_cli(text): |
| 1304 |
if args.format == 'cli' and sys.stdout.isatty(): print(text, end='', flush=True) |
| 1305 |
def p_err(text): |
| 1306 |
print(str(text), file=sys.stderr, flush=True) |
| 1307 |
|
| 1308 |
def signal_handler(signal, frame): |
| 1309 |
if threads: |
| 1310 |
print('\nstopping threads... ', file=sys.stderr, flush=True) |
| 1311 |
jobs.queue.clear() |
| 1312 |
for worker in threads: |
| 1313 |
worker.stop() |
| 1314 |
threads.clear() |
| 1315 |
sys.tracebacklimit = 0 |
| 1316 |
raise KeyboardInterrupt |
| 1317 |
|
| 1318 |
if args.registered and args.unregistered: |
| 1319 |
parser.error('arguments --registered and --unregistered are mutually exclusive') |
| 1320 |
|
| 1321 |
if args.ssdeep: |
| 1322 |
p_err('WARNING: argument --ssdeep is deprecated, use --lsh ssdeep instead') |
| 1323 |
args.lsh = 'ssdeep' |
| 1324 |
if args.ssdeep_url: |
| 1325 |
p_err('WARNING: argument --ssdeep-url is deprecated, use --lsh-url instead') |
| 1326 |
args.lsh_url = args.ssdeep_url |
| 1327 |
|
| 1328 |
if not args.lsh and args.lsh_url: |
| 1329 |
parser.error('argument --lsh-url requires --lsh') |
| 1330 |
|
| 1331 |
if args.lsh and args.lsh not in ('ssdeep', 'tlsh'): |
| 1332 |
parser.error('invalid LSH algorithm (choose ssdeep or tlsh)') |
| 1333 |
|
| 1334 |
if not args.phash: |
| 1335 |
if args.phash_url: |
| 1336 |
parser.error('argument --phash-url requires --phash') |
| 1337 |
if args.screenshots: |
| 1338 |
parser.error('argument --screenshots requires --phash') |
| 1339 |
|
| 1340 |
if not kwargs and args.format not in ('cli', 'csv', 'json', 'list'): |
| 1341 |
parser.error('invalid output format (choose from cli, csv, json, list)') |
| 1342 |
|
| 1343 |
if args.threads < 1: |
| 1344 |
parser.error('number of threads must be greater than zero') |
| 1345 |
|
| 1346 |
fuzzers = [] |
| 1347 |
if args.fuzzers: |
| 1348 |
fuzzers = [x.strip().lower() for x in set(args.fuzzers.split(','))] |
| 1349 |
if args.dictionary and 'dictionary' not in fuzzers: |
| 1350 |
parser.error('argument --dictionary cannot be used with selected fuzzing algorithms (consider enabling fuzzer: dictionary)') |
| 1351 |
if args.tld and 'tld-swap' not in fuzzers: |
| 1352 |
parser.error('argument --tld cannot be used with selected fuzzing algorithms (consider enabling fuzzer: tld-swap)') |
| 1353 |
# important: this should enable all available fuzzers |
| 1354 |
with Fuzzer('example.domain', ['foo'], ['bar']) as fuzz: |
| 1355 |
fuzz.generate() |
| 1356 |
all_fuzzers = sorted({x.get('fuzzer') for x in fuzz.permutations()}) |
| 1357 |
if not set(fuzzers).issubset(all_fuzzers): |
| 1358 |
parser.error('argument --fuzzers takes a comma-separated list with at least one of the following: {}'.format(' '.join(all_fuzzers))) |
| 1359 |
del all_fuzzers |
| 1360 |
|
| 1361 |
nameservers = [] |
| 1362 |
if args.nameservers: |
| 1363 |
if not MODULE_DNSPYTHON: |
| 1364 |
parser.error('missing DNSPython library') |
| 1365 |
nameservers = args.nameservers.split(',') |
| 1366 |
for addr in nameservers: |
| 1367 |
if re.match(r'^https://[a-z0-9.-]{4,253}/dns-query$', addr): |
| 1368 |
try: |
| 1369 |
from dns.query import https |
| 1370 |
except ImportError: |
| 1371 |
parser.error('DNS-over-HTTPS requires DNSPython 2.x or newer') |
| 1372 |
else: |
| 1373 |
del https |
| 1374 |
continue |
| 1375 |
if re.match(r'^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$', addr): |
| 1376 |
continue |
| 1377 |
parser.error('invalid nameserver: {}'.format(addr)) |
| 1378 |
|
| 1379 |
dictionary = [] |
| 1380 |
if args.dictionary: |
| 1381 |
re_subd = re.compile(r'^(?:(?:xn--)[a-z0-9-]{3,59}|[a-z0-9-]{1,63})$') |
| 1382 |
try: |
| 1383 |
with open(args.dictionary, encoding='utf-8') as f: |
| 1384 |
dictionary = [x for x in set(f.read().lower().splitlines()) if re_subd.match(x)] |
| 1385 |
except UnicodeDecodeError: |
| 1386 |
parser.error('UTF-8 decode error when reading: {}'.format(args.dictionary)) |
| 1387 |
except OSError as err: |
| 1388 |
parser.error('unable to open {} ({})'.format(args.dictionary, err.strerror.lower())) |
| 1389 |
|
| 1390 |
tld = [] |
| 1391 |
if args.tld: |
| 1392 |
re_tld = re.compile(r'^[a-z0-9-]{2,63}(?:\.[a-z0-9-]{2,63})?$') |
| 1393 |
try: |
| 1394 |
with open(args.tld, encoding='utf-8') as f: |
| 1395 |
tld = [x for x in set(f.read().lower().splitlines()) if re_tld.match(x)] |
| 1396 |
except UnicodeDecodeError: |
| 1397 |
parser.error('UTF-8 decode error when reading: {}'.format(args.tld)) |
| 1398 |
except OSError as err: |
| 1399 |
parser.error('unable to open {} ({})'.format(args.tld, err.strerror.lower())) |
| 1400 |
|
| 1401 |
if args.output: |
| 1402 |
sys._stdout = sys.stdout |
| 1403 |
try: |
| 1404 |
sys.stdout = open(args.output, 'w' if args.output == os.devnull else 'x') |
| 1405 |
except OSError as err: |
| 1406 |
parser.error('unable to open {} ({})'.format(args.output, err.strerror.lower())) |
| 1407 |
|
| 1408 |
|
| 1409 |
lsh_url = None |
| 1410 |
if args.lsh: |
| 1411 |
if args.lsh == 'ssdeep' and not MODULE_SSDEEP: |
| 1412 |
parser.error('missing ssdeep library') |
| 1413 |
if args.lsh == 'tlsh' and not MODULE_TLSH: |
| 1414 |
parser.error('missing py-tlsh library') |
| 1415 |
if args.lsh_url: |
| 1416 |
try: |
| 1417 |
lsh_url = UrlParser(args.lsh_url) |
| 1418 |
except ValueError: |
| 1419 |
parser.error('invalid domain name: ' + args.lsh_url) |
| 1420 |
|
| 1421 |
phash_url = None |
| 1422 |
if args.phash or args.screenshots: |
| 1423 |
if not MODULE_PIL: |
| 1424 |
parser.error('missing Python Imaging Library (PIL)') |
| 1425 |
if not MODULE_SELENIUM: |
| 1426 |
parser.error('missing Selenium Webdriver') |
| 1427 |
try: |
| 1428 |
_ = HeadlessBrowser() |
| 1429 |
except Exception as e: |
| 1430 |
parser.error(str(e)) |
| 1431 |
if args.screenshots: |
| 1432 |
if not os.access(args.screenshots, os.W_OK | os.X_OK): |
| 1433 |
parser.error('insufficient access permissions: %s' % args.screenshots) |
| 1434 |
if args.phash_url: |
| 1435 |
try: |
| 1436 |
phash_url = UrlParser(args.phash_url) |
| 1437 |
except ValueError: |
| 1438 |
parser.error('invalid domain name: ' + args.phash_url) |
| 1439 |
|
| 1440 |
if args.geoip: |
| 1441 |
if not MODULE_GEOIP: |
| 1442 |
parser.error('missing geoip2 library or database file (check $GEOLITE2_MMDB environment variable)') |
| 1443 |
|
| 1444 |
try: |
| 1445 |
url = UrlParser(args.domain) |
| 1446 |
except Exception: |
| 1447 |
parser.error('invalid domain name: ' + args.domain) |
| 1448 |
|
| 1449 |
if threading.current_thread() is threading.main_thread(): |
| 1450 |
for sig in (signal.SIGINT, signal.SIGTERM): |
| 1451 |
signal.signal(sig, signal_handler) |
| 1452 |
|
| 1453 |
fuzz = Fuzzer(url.domain, dictionary=dictionary, tld_dictionary=tld) |
| 1454 |
fuzz.generate(fuzzers=fuzzers) |
| 1455 |
domains = fuzz.domains |
| 1456 |
|
| 1457 |
if not domains: |
| 1458 |
parser.error('selected fuzzing algorithms do not generate any permutations for provided input domain') |
| 1459 |
|
| 1460 |
if args.format == 'list': |
| 1461 |
print(Format(domains).list()) |
| 1462 |
if hasattr(sys, '_stdout'): |
| 1463 |
sys.stdout = sys._stdout |
| 1464 |
return list(map(dict, domains)) if kwargs else None |
| 1465 |
|
| 1466 |
if not MODULE_DNSPYTHON: |
| 1467 |
p_err('WARNING: DNS features are limited due to lack of DNSPython library') |
| 1468 |
|
| 1469 |
p_cli(FG_RND + ST_BRI + |
| 1470 |
r''' _ _ _ _ |
| 1471 |
__| |_ __ ___| |___ _(_)___| |_ |
| 1472 |
/ _` | '_ \/ __| __\ \ /\ / / / __| __| |
| 1473 |
| (_| | | | \__ \ |_ \ V V /| \__ \ |_ |
| 1474 |
\__,_|_| |_|___/\__| \_/\_/ |_|___/\__| {%s} |
| 1475 |
|
| 1476 |
''' % __version__ + FG_RST + ST_RST) |
| 1477 |
|
| 1478 |
if args.lsh or args.phash: |
| 1479 |
proxies = urllib.request.getproxies() |
| 1480 |
if proxies: |
| 1481 |
p_cli('using proxy: {}\n'.format(' '.join(set(proxies.values())))) |
| 1482 |
|
| 1483 |
lsh_init = str() |
| 1484 |
lsh_effective_url = str() |
| 1485 |
if args.lsh: |
| 1486 |
request_url = lsh_url.full_uri() if lsh_url else url.full_uri() |
| 1487 |
p_cli('fetching content from: {} '.format(request_url)) |
| 1488 |
try: |
| 1489 |
r = UrlOpener(request_url, |
| 1490 |
timeout=REQUEST_TIMEOUT_HTTP, |
| 1491 |
headers={'User-Agent': args.useragent}, |
| 1492 |
verify=True) |
| 1493 |
except Exception as e: |
| 1494 |
if kwargs: |
| 1495 |
raise |
| 1496 |
p_err(e) |
| 1497 |
sys.exit(1) |
| 1498 |
else: |
| 1499 |
p_cli('> {} [{:.1f} KB]\n'.format(r.url.split('?')[0], len(r.content)/1024)) |
| 1500 |
if args.lsh == 'ssdeep': |
| 1501 |
lsh_init = ssdeep.hash(r.normalized_content) |
| 1502 |
elif args.lsh == 'tlsh': |
| 1503 |
lsh_init = tlsh.hash(r.normalized_content) |
| 1504 |
lsh_effective_url = r.url.split('?')[0] |
| 1505 |
# hash blank if content too short or insufficient entropy |
| 1506 |
if lsh_init in (None, '', 'TNULL', '3::'): |
| 1507 |
args.lsh = None |
| 1508 |
|
| 1509 |
if args.phash: |
| 1510 |
request_url = phash_url.full_uri() if phash_url else url.full_uri() |
| 1511 |
p_cli('rendering web page: {}\n'.format(request_url)) |
| 1512 |
browser = HeadlessBrowser(useragent=args.useragent) |
| 1513 |
try: |
| 1514 |
browser.get(request_url) |
| 1515 |
screenshot = browser.screenshot() |
| 1516 |
except Exception as e: |
| 1517 |
if kwargs: |
| 1518 |
raise |
| 1519 |
p_err(e) |
| 1520 |
sys.exit(1) |
| 1521 |
else: |
| 1522 |
phash = pHash(BytesIO(screenshot)) |
| 1523 |
browser.stop() |
| 1524 |
|
| 1525 |
for task in domains: |
| 1526 |
jobs.put(task) |
| 1527 |
|
| 1528 |
sid = int.from_bytes(os.urandom(4), sys.byteorder) |
| 1529 |
for _ in range(args.threads): |
| 1530 |
worker = Scanner(jobs) |
| 1531 |
worker.id = sid |
| 1532 |
worker.url = url |
| 1533 |
worker.option_extdns = MODULE_DNSPYTHON |
| 1534 |
if args.geoip: |
| 1535 |
worker.option_geoip = True |
| 1536 |
if args.banners: |
| 1537 |
worker.option_banners = True |
| 1538 |
if args.lsh and lsh_init: |
| 1539 |
worker.option_lsh = args.lsh |
| 1540 |
worker.lsh_init = lsh_init |
| 1541 |
worker.lsh_effective_url = lsh_effective_url |
| 1542 |
if args.phash: |
| 1543 |
worker.option_phash = True |
| 1544 |
worker.phash_init = phash |
| 1545 |
worker.screenshot_dir = args.screenshots |
| 1546 |
if args.mxcheck: |
| 1547 |
worker.option_mxcheck = True |
| 1548 |
if args.nameservers: |
| 1549 |
worker.nameservers = nameservers |
| 1550 |
worker.useragent = args.useragent |
| 1551 |
worker.start() |
| 1552 |
threads.append(worker) |
| 1553 |
|
| 1554 |
p_cli('started {} scanner threads\n'.format(args.threads)) |
| 1555 |
|
| 1556 |
ttime = 0 |
| 1557 |
ival = 0.2 |
| 1558 |
while True: |
| 1559 |
time.sleep(ival) |
| 1560 |
ttime += ival |
| 1561 |
dlen = len(domains) |
| 1562 |
comp = dlen - jobs.qsize() |
| 1563 |
if not comp: |
| 1564 |
continue |
| 1565 |
rate = int(comp / ttime) + 1 |
| 1566 |
eta = jobs.qsize() // rate |
| 1567 |
found = sum([1 for x in domains if x.is_registered()]) |
| 1568 |
p_cli(ST_CLR + '\rpermutations: {:.2%} of {} | found: {} | eta: {:d}m {:02d}s | speed: {:d} qps'.format(comp/dlen, |
| 1569 |
dlen, found, eta//60, eta%60, rate)) |
| 1570 |
if jobs.empty(): |
| 1571 |
break |
| 1572 |
if sum([1 for x in threads if x.is_alive()]) == 0: |
| 1573 |
break |
| 1574 |
p_cli('\n') |
| 1575 |
|
| 1576 |
for worker in threads: |
| 1577 |
worker.stop() |
| 1578 |
for worker in threads: |
| 1579 |
worker.join() |
| 1580 |
|
| 1581 |
domains = fuzz.permutations(registered=args.registered, unregistered=args.unregistered, dns_all=args.all) |
| 1582 |
|
| 1583 |
if args.whois: |
| 1584 |
total = sum([1 for x in domains if x.is_registered()]) |
| 1585 |
whois = Whois() |
| 1586 |
for i, domain in enumerate([x for x in domains if x.is_registered()]): |
| 1587 |
p_cli(ST_CLR + '\rWHOIS: {} ({:.2%})'.format(domain['domain'], (i+1)/total)) |
| 1588 |
try: |
| 1589 |
wreply = whois.whois('.'.join(domain_tld(domain['domain'])[1:])) |
| 1590 |
except Exception as e: |
| 1591 |
_debug(e) |
| 1592 |
else: |
| 1593 |
if wreply.get('creation_date'): |
| 1594 |
domain['whois_created'] = wreply.get('creation_date').strftime('%Y-%m-%d') |
| 1595 |
if wreply.get('registrar'): |
| 1596 |
domain['whois_registrar'] = wreply.get('registrar') |
| 1597 |
p_cli('\n') |
| 1598 |
|
| 1599 |
p_cli('\n') |
| 1600 |
|
| 1601 |
if domains: |
| 1602 |
if args.format == 'csv': |
| 1603 |
print(Format(domains).csv()) |
| 1604 |
elif args.format == 'json': |
| 1605 |
print(Format(domains).json()) |
| 1606 |
elif args.format == 'cli': |
| 1607 |
print(Format(domains).cli()) |
| 1608 |
|
| 1609 |
if hasattr(sys, '_stdout'): |
| 1610 |
sys.stdout = sys._stdout |
| 1611 |
|
| 1612 |
if kwargs: |
| 1613 |
return list(map(dict, domains)) |
| 1614 |
|
| 1615 |
|
| 1616 |
if __name__ == '__main__': |
| 1617 |
try: |
| 1618 |
run() |
| 1619 |
except BrokenPipeError: |
| 1620 |
pass |