-
-
Notifications
You must be signed in to change notification settings - Fork 775
/
dnstwist.py
executable file
·1618 lines (1451 loc) · 50.7 KB
/
dnstwist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r'''
_ _ _ _
__| |_ __ ___| |___ _(_)___| |_
/ _` | '_ \/ __| __\ \ /\ / / / __| __|
| (_| | | | \__ \ |_ \ V V /| \__ \ |_
\__,_|_| |_|___/\__| \_/\_/ |_|___/\__|
Generate and resolve domain variations to detect typo squatting,
phishing and corporate espionage.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__author__ = 'Marcin Ulikowski'
__version__ = '20240812'
import re
import sys
import socket
socket.setdefaulttimeout(12.0)
import signal
import time
import argparse
import threading
import os
import json
import queue
import urllib.request
import urllib.parse
import gzip
from io import BytesIO
from datetime import datetime
def _debug(msg):
if 'DEBUG' in os.environ:
if isinstance(msg, Exception):
print('{}:{} {}'.format(__file__, msg.__traceback__.tb_lineno, str(msg)), file=sys.stderr, flush=True)
else:
print(str(msg), file=sys.stderr, flush=True)
try:
from PIL import Image
MODULE_PIL = True
except ImportError as e:
_debug(e)
MODULE_PIL = False
try:
from selenium import webdriver
MODULE_SELENIUM = True
except ImportError as e:
_debug(e)
MODULE_SELENIUM = False
try:
from dns.resolver import Resolver, NXDOMAIN, NoNameservers
import dns.rdatatype
from dns.exception import DNSException
MODULE_DNSPYTHON = True
except ImportError as e:
_debug(e)
MODULE_DNSPYTHON = False
GEOLITE2_MMDB = os.environ.get('GEOLITE2_MMDB' , os.path.join(os.path.dirname(__file__), 'GeoLite2-Country.mmdb'))
try:
import geoip2.database
_ = geoip2.database.Reader(GEOLITE2_MMDB)
except Exception as e:
_debug(e)
try:
import GeoIP
_ = GeoIP.new(-1)
except Exception as e:
_debug(e)
MODULE_GEOIP = False
else:
MODULE_GEOIP = True
class geoip:
def __init__(self):
self.reader = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
def country_by_addr(self, ipaddr):
return self.reader.country_name_by_addr(ipaddr)
else:
MODULE_GEOIP = True
class geoip:
def __init__(self):
self.reader = geoip2.database.Reader(GEOLITE2_MMDB)
def country_by_addr(self, ipaddr):
return self.reader.country(ipaddr).country.name
try:
import ssdeep
MODULE_SSDEEP = True
except ImportError as e:
_debug(e)
try:
import ppdeep as ssdeep
MODULE_SSDEEP = True
except ImportError as e:
_debug(e)
MODULE_SSDEEP = False
try:
import tlsh
MODULE_TLSH = True
except ImportError as e:
_debug(e)
MODULE_TLSH = False
try:
import idna
except ImportError as e:
_debug(e)
class idna:
@staticmethod
def decode(domain):
return domain.encode().decode('idna')
@staticmethod
def encode(domain):
return domain.encode('idna')
VALID_FQDN_REGEX = re.compile(r'(?=^.{4,253}$)(^((?!-)[a-z0-9-]{1,63}(?<!-)\.)+[a-z0-9-]{2,63}$)', re.IGNORECASE)
USER_AGENT_STRING = 'Mozilla/5.0 ({} {}-bit) dnstwist/{}'.format(sys.platform, sys.maxsize.bit_length() + 1, __version__)
REQUEST_TIMEOUT_DNS = 2.5
REQUEST_RETRIES_DNS = 2
REQUEST_TIMEOUT_HTTP = 5
REQUEST_TIMEOUT_SMTP = 5
THREAD_COUNT_DEFAULT = min(32, os.cpu_count() + 4)
if sys.platform != 'win32' and sys.stdout.isatty():
FG_RND = '\x1b[3{}m'.format(int(time.time())%8+1)
FG_YEL = '\x1b[33m'
FG_CYA = '\x1b[36m'
FG_BLU = '\x1b[34m'
FG_RST = '\x1b[39m'
ST_BRI = '\x1b[1m'
ST_CLR = '\x1b[1K'
ST_RST = '\x1b[0m'
else:
FG_RND = FG_YEL = FG_CYA = FG_BLU = FG_RST = ST_BRI = ST_CLR = ST_RST = ''
devnull = os.devnull
def domain_tld(domain):
try:
from tld import parse_tld
except ImportError:
ctld = ['org', 'com', 'net', 'gov', 'edu', 'co', 'mil', 'nom', 'ac', 'info', 'biz']
d = domain.rsplit('.', 3)
if len(d) < 2:
return '', d[0], ''
if len(d) == 2:
return '', d[0], d[1]
if len(d) > 2:
if d[-2] in ctld:
return '.'.join(d[:-3]), d[-3], '.'.join(d[-2:])
else:
return '.'.join(d[:-2]), d[-2], d[-1]
else:
d = parse_tld(domain, fix_protocol=True)[::-1]
if d[1:] == d[:-1] and None in d:
d = tuple(domain.rsplit('.', 2))
d = ('',) * (3-len(d)) + d
return d
class Whois():
WHOIS_IANA = 'whois.iana.org'
TIMEOUT = 2.0
WHOIS_TLD = {
'com': 'whois.verisign-grs.com',
'net': 'whois.verisign-grs.com',
'org': 'whois.pir.org',
'info': 'whois.afilias.net',
'pl': 'whois.dns.pl',
'us': 'whois.nic.us',
'co': 'whois.nic.co',
'cn': 'whois.cnnic.cn',
'ru': 'whois.tcinet.ru',
'in': 'whois.registry.in',
'eu': 'whois.eu',
'uk': 'whois.nic.uk',
'de': 'whois.denic.de',
'nl': 'whois.domain-registry.nl',
'br': 'whois.registro.br',
'jp': 'whois.jprs.jp',
}
def __init__(self):
self.whois_tld = self.WHOIS_TLD
def _brute_datetime(self, s):
formats = ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%d %H:%M:%S%z', '%Y-%m-%d %H:%M', '%Y.%m.%d %H:%M',
'%Y.%m.%d %H:%M:%S', '%d.%m.%Y %H:%M:%S', '%a %b %d %Y', '%d-%b-%Y', '%Y-%m-%d')
for f in formats:
try:
dt = datetime.strptime(s, f)
return dt
except ValueError:
pass
return None
def _extract(self, response):
fields = {
'registrar': (r'[\r\n]registrar[ .]*:\s+(?:name:\s)?(?P<registrar>[^\r\n]+)', str),
'creation_date': (r'[\r\n](?:created(?: on)?|creation date|registered(?: on)?)[ .]*:\s+(?P<creation_date>[^\r\n]+)', self._brute_datetime),
}
result = {'text': response}
response_reduced = '\r\n'.join([x.strip() for x in response.splitlines() if not x.startswith('%')])
for field, (pattern, func) in fields.items():
match = re.search(pattern, response_reduced, re.IGNORECASE | re.MULTILINE)
if match:
result[field] = func(match.group(1))
else:
result[field] = None
return result
def query(self, query, server=None):
_, _, tld = domain_tld(query)
server = server or self.whois_tld.get(tld, self.WHOIS_IANA)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.TIMEOUT)
response = b''
try:
sock.connect((server, 43))
sock.send(query.encode() + b'\r\n')
while True:
buf = sock.recv(4096)
if not buf:
break
response += buf
if server and server != self.WHOIS_IANA and tld not in self.whois_tld:
self.whois_tld[tld] = server
except (socket.timeout, socket.gaierror):
return ''
finally:
sock.close()
response = response.decode('utf-8', errors='ignore')
refer = re.search(r'refer:\s+(?P<server>[-.a-z0-9]+)', response, re.IGNORECASE | re.MULTILINE)
if refer:
return self.query(query, refer.group('server'))
return response
def whois(self, domain, server=None):
return self._extract(self.query(domain, server))
class UrlOpener():
def __init__(self, url, timeout=REQUEST_TIMEOUT_HTTP, headers={}, verify=True):
http_headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9',
'accept-encoding': 'gzip,identity',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8'}
for h, v in headers.items():
# do not override accepted encoding - only gzip,identity is supported
if h.lower() != 'accept-encoding':
http_headers[h.lower()] = v
if verify:
ctx = urllib.request.ssl.create_default_context()
else:
ctx = urllib.request.ssl._create_unverified_context()
request = urllib.request.Request(url, headers=http_headers)
with urllib.request.urlopen(request, timeout=timeout, context=ctx) as r:
self.headers = r.headers
self.code = r.code
self.reason = r.reason
self.url = r.url
self.content = r.read()
if self.content[:3] == b'\x1f\x8b\x08':
self.content = gzip.decompress(self.content)
if 64 < len(self.content) < 1024:
try:
meta_url = re.search(r'<meta[^>]*?url=(https?://[\w.,?!:;/*#@$&+=[\]()%~-]*?)"', self.content.decode(), re.IGNORECASE)
except Exception:
pass
else:
if meta_url:
self.__init__(meta_url.group(1), timeout=timeout, headers=http_headers, verify=verify)
self.normalized_content = self._normalize()
def _normalize(self):
content = b' '.join(self.content.split())
mapping = dict({
b'(action|src|href)=".+"': lambda m: m.group(0).split(b'=')[0] + b'=""',
b'url(.+)': b'url()',
})
for pattern, repl in mapping.items():
content = re.sub(pattern, repl, content, flags=re.IGNORECASE)
return content
class UrlParser():
def __init__(self, url):
if not url:
raise TypeError('argument has to be non-empty string')
u = urllib.parse.urlparse(url if '://' in url else '//' + url, scheme='http')
self.scheme = u.scheme.lower()
if self.scheme not in ('http', 'https'):
raise ValueError('invalid scheme') from None
self.domain = u.hostname.lower()
try:
self.domain = idna.encode(self.domain).decode()
except Exception:
raise ValueError('invalid domain name') from None
if not self._validate_domain(self.domain):
raise ValueError('invalid domain name') from None
self.username = u.username
self.password = u.password
self.port = u.port
self.path = u.path
self.query = u.query
self.fragment = u.fragment
def _validate_domain(self, domain):
if len(domain) < 1 or len(domain) > 253:
return False
if VALID_FQDN_REGEX.match(domain):
try:
_ = idna.decode(domain)
except Exception:
return False
else:
return True
return False
def full_uri(self, domain=None):
uri = '{}://'.format(self.scheme)
if self.username:
uri += self.username
if self.password:
uri += ':{}'.format(self.password)
uri += '@'
uri += self.domain if not domain else domain
if self.port:
uri += ':{}'.format(self.port)
if self.path:
uri += self.path
if self.query:
uri += '?{}'.format(self.query)
if self.fragment:
uri += '#{}'.format(self.fragment)
return uri
class Permutation(dict):
def __getattr__(self, item):
if item in self:
return self[item]
raise AttributeError("object has no attribute '{}'".format(item)) from None
__setattr__ = dict.__setitem__
def __init__(self, **kwargs):
super(dict, self).__init__()
self['fuzzer'] = kwargs.pop('fuzzer', '')
self['domain'] = kwargs.pop('domain', '')
for k, v in kwargs.items():
self[k] = v
def __hash__(self):
return hash(self['domain'])
def __eq__(self, other):
return self['domain'] == other['domain']
def __lt__(self, other):
if self['fuzzer'] == other['fuzzer']:
if len(self) > 2 and len(other) > 2:
return self.get('dns_a', [''])[0] + self['domain'] < other.get('dns_a', [''])[0] + other['domain']
else:
return self['domain'] < other['domain']
return self['fuzzer'] < other['fuzzer']
def is_registered(self):
return len(self) > 2
def copy(self):
return Permutation(**self)
class pHash():
def __init__(self, image, hsize=8):
img = Image.open(image).convert('L').resize((hsize, hsize), Image.LANCZOS)
pixels = list(img.getdata())
avg = sum(pixels) / len(pixels)
self.hash = ''.join('1' if p > avg else '0' for p in pixels)
def __sub__(self, other):
bc = len(self.hash)
ham = sum(x != y for x, y in list(zip(self.hash, other.hash)))
e = 2.718281828459045
sub = int((1 + e**((bc - ham) / bc) - e) * 100)
return sub if sub > 0 else 0
def __repr__(self):
return '{:x}'.format(int(self.hash, base=2))
def __int__(self):
return int(self.hash, base=2)
class HeadlessBrowser():
WEBDRIVER_TIMEOUT = 12
WEBDRIVER_ARGUMENTS = (
'--disable-dev-shm-usage',
'--ignore-certificate-errors',
'--headless',
'--incognito',
'--no-sandbox',
'--disable-gpu',
'--disable-extensions',
'--disk-cache-size=0',
'--aggressive-cache-discard',
'--disable-notifications',
'--disable-remote-fonts',
'--disable-sync',
'--window-size=1366,768',
'--hide-scrollbars',
'--disable-audio-output',
'--dns-prefetch-disable',
'--no-default-browser-check',
'--disable-background-networking',
'--enable-features=NetworkService,NetworkServiceInProcess',
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-breakpad',
'--disable-client-side-phishing-detection',
'--disable-component-extensions-with-background-pages',
'--disable-default-apps',
'--disable-features=TranslateUI',
'--disable-hang-monitor',
'--disable-ipc-flooding-protection',
'--disable-prompt-on-repost',
'--disable-renderer-backgrounding',
'--force-color-profile=srgb',
'--metrics-recording-only',
'--no-first-run',
'--password-store=basic',
'--use-mock-keychain',
'--disable-blink-features=AutomationControlled',
)
def __init__(self, useragent=None):
chrome_options = webdriver.ChromeOptions()
for opt in self.WEBDRIVER_ARGUMENTS:
chrome_options.add_argument(opt)
proxies = urllib.request.getproxies()
if proxies:
proxy_string = ';'.join(['{}={}'.format(scheme, url) for scheme, url in proxies.items()])
chrome_options.add_argument('--proxy-server={}'.format(proxy_string))
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_experimental_option('useAutomationExtension', False)
self.driver = webdriver.Chrome(options=chrome_options)
self.driver.set_page_load_timeout(self.WEBDRIVER_TIMEOUT)
self.driver.execute_cdp_cmd('Network.setUserAgentOverride', {'userAgent':
useragent or self.driver.execute_script('return navigator.userAgent').replace('Headless', '')
})
self.get = self.driver.get
self.screenshot = self.driver.get_screenshot_as_png
def stop(self):
try:
self.driver.close()
self.driver.quit()
except Exception:
pass
try:
pid = True
while pid:
pid, status = os.waitpid(-1, os.WNOHANG)
except ChildProcessError:
pass
def __del__(self):
self.stop()
class Fuzzer():
glyphs_idn_by_tld = {
**dict.fromkeys(['ad', 'cz', 'sk', 'uk', 'co.uk', 'nl', 'edu', 'us'], {
# IDN not supported by the corresponding registry
}),
**dict.fromkeys(['jp', 'co.jp', 'ad.jp', 'ne.jp'], {
}),
**dict.fromkeys(['cn', 'com.cn', 'tw', 'com.tw', 'net.tw'], {
}),
**dict.fromkeys(['info'], {
'a': ('á', 'ä', 'å', 'ą'),
'c': ('ć', 'č'),
'e': ('é', 'ė', 'ę'),
'i': ('í', 'į'),
'l': ('ł',),
'n': ('ñ', 'ń'),
'o': ('ó', 'ö', 'ø', 'ő'),
's': ('ś', 'š'),
'u': ('ú', 'ü', 'ū', 'ű', 'ų'),
'z': ('ź', 'ż', 'ž'),
'ae': ('æ',),
}),
**dict.fromkeys(['br', 'com.br'], {
'a': ('à', 'á', 'â', 'ã'),
'c': ('ç',),
'e': ('é', 'ê'),
'i': ('í',),
'o': ('ó', 'ô', 'õ'),
'u': ('ú', 'ü'),
'y': ('ý', 'ÿ'),
}),
**dict.fromkeys(['dk'], {
'a': ('ä', 'å'),
'e': ('é',),
'o': ('ö', 'ø'),
'u': ('ü',),
'ae': ('æ',),
}),
**dict.fromkeys(['eu', 'de', 'pl'], {
'a': ('á', 'à', 'ă', 'â', 'å', 'ä', 'ã', 'ą', 'ā'),
'c': ('ć', 'ĉ', 'č', 'ċ', 'ç'),
'd': ('ď', 'đ'),
'e': ('é', 'è', 'ĕ', 'ê', 'ě', 'ë', 'ė', 'ę', 'ē'),
'g': ('ğ', 'ĝ', 'ġ', 'ģ'),
'h': ('ĥ', 'ħ'),
'i': ('í', 'ì', 'ĭ', 'î', 'ï', 'ĩ', 'į', 'ī'),
'j': ('ĵ',),
'k': ('ķ', 'ĸ'),
'l': ('ĺ', 'ľ', 'ļ', 'ł'),
'n': ('ń', 'ň', 'ñ', 'ņ'),
'o': ('ó', 'ò', 'ŏ', 'ô', 'ö', 'ő', 'õ', 'ø', 'ō'),
'r': ('ŕ', 'ř', 'ŗ'),
's': ('ś', 'ŝ', 'š', 'ş'),
't': ('ť', 'ţ', 'ŧ'),
'u': ('ú', 'ù', 'ŭ', 'û', 'ů', 'ü', 'ű', 'ũ', 'ų', 'ū'),
'w': ('ŵ',),
'y': ('ý', 'ŷ', 'ÿ'),
'z': ('ź', 'ž', 'ż'),
'ae': ('æ',),
'oe': ('œ',),
}),
**dict.fromkeys(['fi'], {
'3': ('ʒ',),
'a': ('á', 'ä', 'å', 'â'),
'c': ('č',),
'd': ('đ',),
'g': ('ǧ', 'ǥ'),
'k': ('ǩ',),
'n': ('ŋ',),
'o': ('õ', 'ö'),
's': ('š',),
't': ('ŧ',),
'z': ('ž',),
}),
**dict.fromkeys(['no'], {
'a': ('á', 'à', 'ä', 'å'),
'c': ('č', 'ç'),
'e': ('é', 'è', 'ê'),
'i': ('ï',),
'n': ('ŋ', 'ń', 'ñ'),
'o': ('ó', 'ò', 'ô', 'ö', 'ø'),
's': ('š',),
't': ('ŧ',),
'u': ('ü',),
'z': ('ž',),
'ae': ('æ',),
}),
**dict.fromkeys(['be', 'fr', 're', 'yt', 'pm', 'wf', 'tf', 'ch', 'li'], {
'a': ('à', 'á', 'â', 'ã', 'ä', 'å'),
'c': ('ç',),
'e': ('è', 'é', 'ê', 'ë'),
'i': ('ì', 'í', 'î', 'ï'),
'n': ('ñ',),
'o': ('ò', 'ó', 'ô', 'õ', 'ö'),
'u': ('ù', 'ú', 'û', 'ü'),
'y': ('ý', 'ÿ'),
'ae': ('æ',),
'oe': ('œ',),
}),
**dict.fromkeys(['ca'], {
'a': ('à', 'â'),
'c': ('ç',),
'e': ('è', 'é', 'ê', 'ë'),
'i': ('î', 'ï'),
'o': ('ô',),
'u': ('ù', 'û', 'ü'),
'y': ('ÿ',),
'ae': ('æ',),
'oe': ('œ',),
}),
}
glyphs_unicode = {
'2': ('ƻ',),
'3': ('ʒ',),
'5': ('ƽ',),
'a': ('ạ', 'ă', 'ȧ', 'ɑ', 'å', 'ą', 'â', 'ǎ', 'á', 'ə', 'ä', 'ã', 'ā', 'à'),
'b': ('ḃ', 'ḅ', 'ƅ', 'ʙ', 'ḇ', 'ɓ'),
'c': ('č', 'ᴄ', 'ċ', 'ç', 'ć', 'ĉ', 'ƈ'),
'd': ('ď', 'ḍ', 'ḋ', 'ɖ', 'ḏ', 'ɗ', 'ḓ', 'ḑ', 'đ'),
'e': ('ê', 'ẹ', 'ę', 'è', 'ḛ', 'ě', 'ɇ', 'ė', 'ĕ', 'é', 'ë', 'ē', 'ȩ'),
'f': ('ḟ', 'ƒ'),
'g': ('ǧ', 'ġ', 'ǵ', 'ğ', 'ɡ', 'ǥ', 'ĝ', 'ģ', 'ɢ'),
'h': ('ȟ', 'ḫ', 'ḩ', 'ḣ', 'ɦ', 'ḥ', 'ḧ', 'ħ', 'ẖ', 'ⱨ', 'ĥ'),
'i': ('ɩ', 'ǐ', 'í', 'ɪ', 'ỉ', 'ȋ', 'ɨ', 'ï', 'ī', 'ĩ', 'ị', 'î', 'ı', 'ĭ', 'į', 'ì'),
'j': ('ǰ', 'ĵ', 'ʝ', 'ɉ'),
'k': ('ĸ', 'ǩ', 'ⱪ', 'ḵ', 'ķ', 'ᴋ', 'ḳ'),
'l': ('ĺ', 'ł', 'ɫ', 'ļ', 'ľ'),
'm': ('ᴍ', 'ṁ', 'ḿ', 'ṃ', 'ɱ'),
'n': ('ņ', 'ǹ', 'ń', 'ň', 'ṅ', 'ṉ', 'ṇ', 'ꞑ', 'ñ', 'ŋ'),
'o': ('ö', 'ó', 'ȯ', 'ỏ', 'ô', 'ᴏ', 'ō', 'ò', 'ŏ', 'ơ', 'ő', 'õ', 'ọ', 'ø'),
'p': ('ṗ', 'ƿ', 'ƥ', 'ṕ'),
'q': ('ʠ',),
'r': ('ʀ', 'ȓ', 'ɍ', 'ɾ', 'ř', 'ṛ', 'ɽ', 'ȑ', 'ṙ', 'ŗ', 'ŕ', 'ɼ', 'ṟ'),
's': ('ṡ', 'ș', 'ŝ', 'ꜱ', 'ʂ', 'š', 'ś', 'ṣ', 'ş'),
't': ('ť', 'ƫ', 'ţ', 'ṭ', 'ṫ', 'ț', 'ŧ'),
'u': ('ᴜ', 'ų', 'ŭ', 'ū', 'ű', 'ǔ', 'ȕ', 'ư', 'ù', 'ů', 'ʉ', 'ú', 'ȗ', 'ü', 'û', 'ũ', 'ụ'),
'v': ('ᶌ', 'ṿ', 'ᴠ', 'ⱴ', 'ⱱ', 'ṽ'),
'w': ('ᴡ', 'ẇ', 'ẅ', 'ẃ', 'ẘ', 'ẉ', 'ⱳ', 'ŵ', 'ẁ'),
'x': ('ẋ', 'ẍ'),
'y': ('ŷ', 'ÿ', 'ʏ', 'ẏ', 'ɏ', 'ƴ', 'ȳ', 'ý', 'ỿ', 'ỵ'),
'z': ('ž', 'ƶ', 'ẓ', 'ẕ', 'ⱬ', 'ᴢ', 'ż', 'ź', 'ʐ'),
'ae': ('æ',),
'oe': ('œ',),
}
glyphs_ascii = {
'0': ('o',),
'1': ('l', 'i'),
'3': ('8',),
'6': ('9',),
'8': ('3',),
'9': ('6',),
'b': ('d', 'lb'),
'c': ('e',),
'd': ('b', 'cl', 'dl'),
'e': ('c',),
'g': ('q',),
'h': ('lh'),
'i': ('1', 'l'),
'k': ('lc'),
'l': ('1', 'i'),
'm': ('n', 'nn', 'rn'),
'n': ('m', 'r'),
'o': ('0',),
'q': ('g',),
'w': ('vv',),
'rn': ('m',),
'cl': ('d',),
}
latin_to_cyrillic = {
'a': 'а', 'b': 'ь', 'c': 'с', 'd': 'ԁ', 'e': 'е', 'g': 'ԍ', 'h': 'һ',
'i': 'і', 'j': 'ј', 'k': 'к', 'l': 'ӏ', 'm': 'м', 'o': 'о', 'p': 'р',
'q': 'ԛ', 's': 'ѕ', 't': 'т', 'v': 'ѵ', 'w': 'ԝ', 'x': 'х', 'y': 'у',
}
qwerty = {
'1': '2q', '2': '3wq1', '3': '4ew2', '4': '5re3', '5': '6tr4', '6': '7yt5', '7': '8uy6', '8': '9iu7', '9': '0oi8', '0': 'po9',
'q': '12wa', 'w': '3esaq2', 'e': '4rdsw3', 'r': '5tfde4', 't': '6ygfr5', 'y': '7uhgt6', 'u': '8ijhy7', 'i': '9okju8', 'o': '0plki9', 'p': 'lo0',
'a': 'qwsz', 's': 'edxzaw', 'd': 'rfcxse', 'f': 'tgvcdr', 'g': 'yhbvft', 'h': 'ujnbgy', 'j': 'ikmnhu', 'k': 'olmji', 'l': 'kop',
'z': 'asx', 'x': 'zsdc', 'c': 'xdfv', 'v': 'cfgb', 'b': 'vghn', 'n': 'bhjm', 'm': 'njk'
}
qwertz = {
'1': '2q', '2': '3wq1', '3': '4ew2', '4': '5re3', '5': '6tr4', '6': '7zt5', '7': '8uz6', '8': '9iu7', '9': '0oi8', '0': 'po9',
'q': '12wa', 'w': '3esaq2', 'e': '4rdsw3', 'r': '5tfde4', 't': '6zgfr5', 'z': '7uhgt6', 'u': '8ijhz7', 'i': '9okju8', 'o': '0plki9', 'p': 'lo0',
'a': 'qwsy', 's': 'edxyaw', 'd': 'rfcxse', 'f': 'tgvcdr', 'g': 'zhbvft', 'h': 'ujnbgz', 'j': 'ikmnhu', 'k': 'olmji', 'l': 'kop',
'y': 'asx', 'x': 'ysdc', 'c': 'xdfv', 'v': 'cfgb', 'b': 'vghn', 'n': 'bhjm', 'm': 'njk'
}
azerty = {
'1': '2a', '2': '3za1', '3': '4ez2', '4': '5re3', '5': '6tr4', '6': '7yt5', '7': '8uy6', '8': '9iu7', '9': '0oi8', '0': 'po9',
'a': '2zq1', 'z': '3esqa2', 'e': '4rdsz3', 'r': '5tfde4', 't': '6ygfr5', 'y': '7uhgt6', 'u': '8ijhy7', 'i': '9okju8', 'o': '0plki9', 'p': 'lo0m',
'q': 'zswa', 's': 'edxwqz', 'd': 'rfcxse', 'f': 'tgvcdr', 'g': 'yhbvft', 'h': 'ujnbgy', 'j': 'iknhu', 'k': 'olji', 'l': 'kopm', 'm': 'lp',
'w': 'sxq', 'x': 'wsdc', 'c': 'xdfv', 'v': 'cfgb', 'b': 'vghn', 'n': 'bhj'
}
keyboards = [qwerty, qwertz, azerty]
def __init__(self, domain, dictionary=[], tld_dictionary=[]):
self.subdomain, self.domain, self.tld = domain_tld(domain)
self.domain = idna.decode(self.domain)
self.dictionary = list(dictionary)
self.tld_dictionary = list(tld_dictionary)
self.domains = set()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return
def _bitsquatting(self):
masks = [1, 2, 4, 8, 16, 32, 64, 128]
chars = set('abcdefghijklmnopqrstuvwxyz0123456789-')
for i, c in enumerate(self.domain):
for mask in masks:
b = chr(ord(c) ^ mask)
if b in chars:
yield self.domain[:i] + b + self.domain[i+1:]
def _cyrillic(self):
cdomain = self.domain
for l, c in self.latin_to_cyrillic.items():
cdomain = cdomain.replace(l, c)
for c, l in zip(cdomain, self.domain):
if c == l:
return []
return [cdomain]
def _homoglyph(self):
md = lambda a, b: {k: set(a.get(k, [])) | set(b.get(k, [])) for k in set(a.keys()) | set(b.keys())}
glyphs = md(self.glyphs_ascii, self.glyphs_idn_by_tld.get(self.tld, self.glyphs_unicode))
def mix(domain):
for i, c in enumerate(domain):
for g in glyphs.get(c, []):
yield domain[:i] + g + domain[i+1:]
for i in range(len(domain)-1):
win = domain[i:i+2]
for c in {win[0], win[1], win}:
for g in glyphs.get(c, []):
yield domain[:i] + win.replace(c, g) + domain[i+2:]
result1 = set(mix(self.domain))
result2 = set()
for r in result1:
result2.update(set(mix(r)))
return result1 | result2
def _hyphenation(self):
return {self.domain[:i] + '-' + self.domain[i:] for i in range(1, len(self.domain))}
def _insertion(self):
result = set()
for i in range(0, len(self.domain)-1):
prefix, orig_c, suffix = self.domain[:i], self.domain[i], self.domain[i+1:]
for c in (c for keys in self.keyboards for c in keys.get(orig_c, [])):
result.update({
prefix + c + orig_c + suffix,
prefix + orig_c + c + suffix
})
return result
def _omission(self):
return {self.domain[:i] + self.domain[i+1:] for i in range(len(self.domain))}
def _repetition(self):
return {self.domain[:i] + c + self.domain[i:] for i, c in enumerate(self.domain)}
def _replacement(self):
for i, c in enumerate(self.domain):
pre = self.domain[:i]
suf = self.domain[i+1:]
for layout in self.keyboards:
for r in layout.get(c, ''):
yield pre + r + suf
def _subdomain(self):
for i in range(1, len(self.domain)-1):
if self.domain[i] not in ['-', '.'] and self.domain[i-1] not in ['-', '.']:
yield self.domain[:i] + '.' + self.domain[i:]
def _transposition(self):
return {self.domain[:i] + self.domain[i+1] + self.domain[i] + self.domain[i+2:] for i in range(len(self.domain)-1)}
def _vowel_swap(self):
vowels = 'aeiou'
for i in range(0, len(self.domain)):
for vowel in vowels:
if self.domain[i] in vowels:
yield self.domain[:i] + vowel + self.domain[i+1:]
def _plural(self):
for i in range(2, len(self.domain)-2):
yield self.domain[:i+1] + ('es' if self.domain[i] in ('s', 'x', 'z') else 's') + self.domain[i+1:]
def _addition(self):
result = set()
if '-' in self.domain:
parts = self.domain.split('-')
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))}
result.update({self.domain + chr(i) for i in (*range(48, 58), *range(97, 123))})
return result
def _dictionary(self):
result = set()
for word in self.dictionary:
if not (self.domain.startswith(word) and self.domain.endswith(word)):
result.update({
self.domain + '-' + word,
self.domain + word,
word + '-' + self.domain,
word + self.domain
})
if '-' in self.domain:
parts = self.domain.split('-')
for word in self.dictionary:
result.update({
'-'.join(parts[:-1]) + '-' + word,
word + '-' + '-'.join(parts[1:])
})
return result
def _tld(self):
if self.tld in self.tld_dictionary:
self.tld_dictionary.remove(self.tld)
return set(self.tld_dictionary)
def generate(self, fuzzers=[]):
self.domains = set()
if not fuzzers or '*original' in fuzzers:
self.domains.add(Permutation(fuzzer='*original', domain='.'.join(filter(None, [self.subdomain, self.domain, self.tld]))))
for f_name in fuzzers or [
'addition', 'bitsquatting', 'cyrillic', 'homoglyph', 'hyphenation',
'insertion', 'omission', 'plural', 'repetition', 'replacement',
'subdomain', 'transposition', 'vowel-swap', 'dictionary',
]:
try:
f = getattr(self, '_' + f_name.replace('-', '_'))
except AttributeError:
pass
else:
for domain in f():
self.domains.add(Permutation(fuzzer=f_name, domain='.'.join(filter(None, [self.subdomain, domain, self.tld]))))
if not fuzzers or 'tld-swap' in fuzzers:
for tld in self._tld():
self.domains.add(Permutation(fuzzer='tld-swap', domain='.'.join(filter(None, [self.subdomain, self.domain, tld]))))
if not fuzzers or 'various' in fuzzers:
if '.' in self.tld:
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain, self.tld.split('.')[-1]]))))
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + self.tld]))))
if '.' not in self.tld:
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + self.tld, self.tld]))))
if self.tld != 'com' and '.' not in self.tld:
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + '-' + self.tld, 'com']))))
self.domains.add(Permutation(fuzzer='various', domain='.'.join(filter(None, [self.subdomain, self.domain + self.tld, 'com']))))
if self.subdomain:
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain + self.domain, self.tld])))
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain.replace('.', '') + self.domain, self.tld])))
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain + '-' + self.domain, self.tld])))
self.domains.add(Permutation(fuzzer='various', domain='.'.join([self.subdomain.replace('.', '-') + '-' + self.domain, self.tld])))
def _punycode(domain):
try:
domain['domain'] = idna.encode(domain['domain']).decode()
except Exception:
domain['domain'] = ''
return domain
self.domains = set(map(_punycode, self.domains))
for domain in self.domains.copy():
if not VALID_FQDN_REGEX.match(domain.get('domain')):
self.domains.discard(domain)
def permutations(self, registered=False, unregistered=False, dns_all=False, unicode=False):
if (registered and not unregistered):
domains = [x.copy() for x in self.domains if x.is_registered()]
elif (unregistered and not registered):
domains = [x.copy() for x in self.domains if not x.is_registered()]
else:
domains = [x.copy() for x in self.domains]
if not dns_all:
def _cutdns(x):
if x.is_registered():
for k in ('dns_ns', 'dns_a', 'dns_aaaa', 'dns_mx'):
if k in x:
x[k] = x[k][:1]
return x
domains = map(_cutdns, domains)
if unicode:
def _punydecode(x):
x.domain = idna.decode(x.domain)
return x
domains = map(_punydecode, domains)
return sorted(domains)
class Scanner(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._stop_event = threading.Event()
self.daemon = True
self.id = 0
self.jobs = queue
self.lsh_init = ''
self.lsh_effective_url = ''
self.phash_init = None
self.screenshot_dir = None
self.url = None
self.option_extdns = False
self.option_geoip = False
self.option_lsh = None
self.option_phash = False
self.option_banners = False
self.option_mxcheck = False
self.nameservers = []
self.useragent = ''
@staticmethod
def _send_recv_tcp(host, port, data=b'', timeout=2.0, recv_bytes=1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
resp = b''
try:
sock.connect((host, port))
if data:
sock.send(data)
resp = sock.recv(recv_bytes)
except Exception as e:
_debug(e)
finally:
sock.close()
return resp.decode('utf-8', errors='ignore')
def _banner_http(self, ip, vhost):
response = self._send_recv_tcp(ip, 80,
'HEAD / HTTP/1.1\r\nHost: {}\r\nUser-Agent: {}\r\n\r\n'.format(vhost, self.useragent).encode())
if not response:
return ''
headers = response.splitlines()
for field in headers:
if field.lower().startswith('server: '):
return field[8:]
return ''
def _banner_smtp(self, mx):
response = self._send_recv_tcp(mx, 25)
if not response:
return ''
hello = response.splitlines()[0]
if hello.startswith('220'):
return hello[4:].strip()
return ''
def _mxcheck(self, mxhost, domain_from, domain_rcpt):
r'''
Detects potential email honey pots waiting for mistyped emails to arrive.
Note: Some mail servers only pretend to accept incorrectly addressed
emails - this technique is used to prevent "directory harvesting attack".
'''
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(REQUEST_TIMEOUT_SMTP)
sock.connect((mxhost, 25))
except Exception:
return False
for cmd in [
'EHLO {}\r\n'.format(mxhost),
'MAIL FROM: randombob1986@{}\r\n'.format(domain_from),
'RCPT TO: randomalice1986@{}\r\n'.format(domain_rcpt),
# And that's how the cookie crumbles
]:
try:
resp = sock.recv(512)
except Exception:
break
if not resp:
break
if resp[0] != 0x32: # status code != 2xx
break
sock.send(cmd.encode())
else:
sock.close()
return True
sock.close()
return False
def stop(self):
self._stop_event.set()
def is_stopped(self):
return self._stop_event.is_set()
def run(self):
if self.option_extdns:
if self.nameservers:
resolv = Resolver(configure=False)
resolv.nameservers = self.nameservers
else:
resolv = Resolver()
resolv.search = []
resolv.lifetime = REQUEST_TIMEOUT_DNS * REQUEST_RETRIES_DNS
resolv.timeout = REQUEST_TIMEOUT_DNS
EDNS_PAYLOAD = 1232
resolv.use_edns(edns=True, ednsflags=0, payload=EDNS_PAYLOAD)
resolv.rotate = True
if hasattr(resolv, 'resolve'):
resolve = resolv.resolve