-
Notifications
You must be signed in to change notification settings - Fork 0
/
shodan.py
executable file
·1262 lines (1087 loc) · 45.5 KB
/
shodan.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/python3
# vim: et:ts=4:sts=4:sw=4:fileencoding=utf-8
r"""
Usage:
python3 {script} [-t] [--to-myself-only] \
[--product PRODUCT] \
[--country COUNTRY] \
[--component COMPONENT] \
[--macro MACRO] \
[--url httpX://HOST:PORT]
[--rerun (EMAIL|REGEX)]
e.g.,
python3 {script} -t --product MikroTik --country CA \
--component coinhive --macro {CHECK_COINHIVE}
python3 {script} -t --query "country:CA avtech" \
--macro {WEAK_AVTECH}
python3 {script} -t --query "http.status:200 country:CA" \
--component jenkins --macro {WEAK_JENKINS}
python3 {script} -t --macro {WEAK_AVTECH} --url http://SUSPECT:PORT
python3 {script} --to-myself-only --rerun [email protected]
python3 {script} --to-myself-only --rerun '.*\.ca$'
Using --to-myself-only will limit recipients to oneself.
Using -t will spare from using Shodan when testing code changes. This will
also limit email recipients to oneself.
{message}
"""
import os
if os.name == "nt":
# Check if executing the Windows build of Python from a Cygwin shell.
if "TZ" in os.environ:
# The Windows build of Python (as opposed to the Cygwin one) appears
# confused with the TZ variable set by the Cygwin shell. The former
# sets time.timezone to 0, time.altzone to -3600 (-1 hr) in the
# presence of TZ="America/New_York", which turns the local time zone to
# UTC.
del os.environ["TZ"]
import time
from collections import namedtuple
from functools import cmp_to_key
from urllib import request, parse
from urllib.error import HTTPError, URLError
from http.client import BadStatusLine, CannotSendRequest, IncompleteRead
from http import HTTPStatus
import ssl
import json
import base64
from pprint import pformat
from ipaddress import ip_address, IPv4Address, IPv6Address
import struct, socket, sys
import smtplib
from email.mime.text import MIMEText
import re
from contextlib import contextmanager
SEND_PAGES = 3
IPS_LIMIT = 4
TEST_IPS = ("23.16.26.111", "216.232.223.192", "174.94.137.145")
CHECK_COINHIVE = "check_coinhive"
WEAK_AVTECH = "weak_avtech"
WEAK_JENKINS = "weak_jenkins"
MACROS = (CHECK_COINHIVE, WEAK_AVTECH, WEAK_JENKINS)
MACRO_VULNS = {
CHECK_COINHIVE: "Infected MikroTik",
WEAK_AVTECH: "Weak AVTech",
WEAK_JENKINS: "Weak Jenkins"
}
MACRO_SMELLS = {
CHECK_COINHIVE: "showing Coinhive",
WEAK_AVTECH: "exhibiting known exploits or factory-defined authentication",
WEAK_JENKINS: "showing Jenkins jobs"
}
MACRO_PRODUCTS = {
CHECK_COINHIVE: "MikroTik",
WEAK_AVTECH: "AVTech",
WEAK_JENKINS: "Jenkins"
}
MACRO_LEGENDS = {
CHECK_COINHIVE: """Adversaries discovered a weakness in the device by
taking control of it and setting up Coinhive in its HTML code. This
finding is not exhaustive. There may be other vulnerable routers or
routers that were infected but whose attackers did not set up Coinhive.
https://www.zdnet.com/article/mikrotik-routers-enslaved-in-massive-coinhive-cryptojacking-campaign/
https://www.securityweek.com/remotely-exploitable-vulnerability-discovered-mikrotiks-routeros""",
WEAK_AVTECH: """Adversaries may discover (or already discovered) a chance
to take control of the device due to a weakness in the firmware or leaving
the default password unchanged.
https://seclists.org/bugtraq/2016/Oct/26
https://www.exploit-db.com/exploits/40500""",
WEAK_JENKINS: """Jenkins servers left without a password protection allow
downloading source code, configuration files and build results. The server
software and its plugins may have vulnerabilities of varying severities.
https://www.jenkins.io/security/advisories/"""
}
RESERVATION = """None of these findings imply that the owners of the devices or machines
were responsible for malicious activities. Instead, they became or may
become victims of remote attacks. Once successful, the attackers take
control of the device and use it for other activities."""
SHODAN_TIMEOUT = 15
SHODAN_LARGE_TIMEOUT = 45
URL_TIMEOUT = 5
REPEAT_SLEEP = 5
NETWORK_ERRORS = (socket.timeout,
socket.error, socket.herror, socket.gaierror,
OSError,
BadStatusLine, CannotSendRequest, IncompleteRead,
ConnectionRefusedError, ConnectionResetError,
URLError)
# The following address family limit is implemented only in
# myip_shodan.
FORCE_IP_FAMILY = "IPv4"
class Usage(SystemExit):
def __init__(self, message=None):
super(Usage, self).__init__(__doc__.format(script=os.path.basename(__file__),
CHECK_COINHIVE=CHECK_COINHIVE,
WEAK_AVTECH=WEAK_AVTECH,
WEAK_JENKINS=WEAK_JENKINS,
message=("\nError: %s\n" % (message,) if message else "")))
def local_timestamp(s_since_epoch=None):
if s_since_epoch is not None:
if s_since_epoch < 0:
return "infinity"
elif s_since_epoch == 0:
return "olden times"
t = time.localtime(s_since_epoch)
is_dst = time.daylight and t.tm_isdst
zone = time.altzone if is_dst else time.timezone
strtime = time.strftime("%Y-%m-%d %H:%M:%S", t)
utcoff = -zone
if utcoff > 0:
utcsign = "+"
else:
utcsign = "-"
utcoff = -utcoff
strtime += ("%s%02d%02d" % (utcsign, utcoff // 3600, (utcoff % 3600) // 60))
return strtime
def process_http_error(e, quiet=False):
code = e.getcode()
try:
body = e.read().decode("utf-8", errors="replace")
except (HTTPError,) + NETWORK_ERRORS as e2:
body = ""
sys.stderr.write(" *** Error reading HTTP response to {url}: original code {code}, body unavailable due to {classname}\n".format(url=e.geturl(),
code=e.getcode(), classname=e2.__class__.__name__))
code = 0
else:
if ((code < HTTPStatus.OK) or (code >= HTTPStatus.BAD_REQUEST)) and not quiet:
sys.stderr.write(" *** HTTP response to {url}: code {code}, body {body!r}...\n".format(url=e.geturl(),
code=e.getcode(), body=body[:20]))
return (code, body)
process_http_response = process_http_error
def log_network_error(e, url):
sys.stderr.write(" *** Network {classname} in {url}\n".format(classname=e.__class__.__name__,
url=url))
def log_error(e, url):
sys.stderr.write(" *** {classname} in {url}\n".format(classname=e.__class__.__name__,
url=url))
def sleep_with_banner(repeatsleep):
sys.stderr.write(" *** Repeating in {repeatsleep}s...\n".format(repeatsleep=repeatsleep))
time.sleep(repeatsleep)
def resilient_send(req, timeout=URL_TIMEOUT, repeatsleep=REPEAT_SLEEP, debuglevel=0):
url = req.full_url
if url.startswith("https:"):
handlerclass = request.HTTPSHandler
else:
handlerclass = request.HTTPHandler
# Verify SSL certificates and host names
handler = handlerclass(debuglevel=debuglevel)
opener = request.build_opener(handler)
# rdap.org does not like Python agents
opener.addheaders = [(header, value)
for header, value in opener.addheaders
if header.lower() != 'user-agent']
while True:
try:
with opener.open(req, timeout=timeout) as response:
(code, body) = process_http_response(response, True)
break
except HTTPError as e:
(code, body) = process_http_error(e, True)
backendmsg = str(body)
if "timed out" in backendmsg:
# A backend timed out. Rinse, repeat.
sys.stderr.write(" *** Backend time out\n")
pass
elif "Request rate limit reached" in backendmsg:
sys.stderr.write(" *** Rate limit reached\n")
pass
else:
break
except NETWORK_ERRORS as e:
log_network_error(e, url)
sleep_with_banner(repeatsleep)
try:
return (code, json.loads(body))
except json.decoder.JSONDecodeError as e:
# log_error(e, url + " with response " + body)
return (code, {"body": body})
# https://blog.cloudflare.com/rfc8482-saying-goodbye-to-any/
def getipaddr(host, port=None):
if isinstance(host, (IPv4Address, IPv6Address)):
return host
# isinstance(host, str)
# Convert both 'xx.xx.xx.xx' and 'HOSTNAME' to
# ipaddress.IPvXAddress for sorting.
for tryfamily in (socket.AddressFamily.AF_INET, socket.AddressFamily.AF_INET6):
try:
for (fam, typ, proto, cname, sockaddr) in socket.getaddrinfo(host, port, tryfamily, socket.SocketKind.SOCK_STREAM):
(addr, port) = sockaddr[:2]
return ip_address(addr)
except socket.gaierror as e:
log_network_error(e, host)
continue
return host
IP_FAMILIES = (
(socket.AddressFamily.AF_INET, "IPv4"),
(socket.AddressFamily.AF_INET6, "IPv6"),
)
# This is not thread-safe because it modifies the global (module socket)
@contextmanager
def fam_socket(fam):
# https://stackoverflow.com/questions/1150332/source-interface-with-python-and-urllib2
orig_getaddrinfo = socket.getaddrinfo
orig_socket = socket.socket
def fam_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
nonlocal orig_getaddrinfo
return orig_getaddrinfo(host, port,
fam if family == 0 else family,
type, proto, flags)
class fam_socket(orig_socket):
def __init__(self, *a, **k):
# print("Handling a socket init with family %s, args %s, kw %s\n" % (fam, a, k))
repl_args = (fam,) + a[1:]
# print("New args %s\n" % (repl_args,))
super().__init__(*repl_args, **k)
try:
socket.getaddrinfo = fam_getaddrinfo
socket.socket = fam_socket
yield socket
finally:
socket.getaddrinfo = orig_getaddrinfo
socket.socket = orig_socket
def myip_shodan(testing, **kwargs):
url = "https://api.shodan.io/tools/myip"
sys.stderr.write("Inquiring shodan.io on my IP address...\n")
if testing:
return (HTTPStatus.OK, "45.56.111.4")
shodan_key = get_shodan_key()
def request_myip():
nonlocal url, shodan_key, kwargs
(code, myip) = resilient_send(request.Request(url,
parse.urlencode((
("key", shodan_key),
)).encode("ascii")),
timeout=kwargs.get("timeout", SHODAN_TIMEOUT),
repeatsleep=kwargs.get("repeatsleep", REPEAT_SLEEP),
debuglevel=kwargs.get("debuglevel", 0))
if code != HTTPStatus.OK:
raise ValueError("The tools/myip API failed.")
return myip
myip = None
for ipfamily in IP_FAMILIES:
if (FORCE_IP_FAMILY == "IPv4/v6") or (ipfamily[1] == FORCE_IP_FAMILY):
try:
if FORCE_IP_FAMILY == "IPv4/v6":
myip = request_myip()
else:
with fam_socket(ipfamily[0]) as socket:
myip = request_myip()
break
except NETWORK_ERRORS as e:
log_network_error(e, url)
return myip
def get_shodan_key():
with open(os.path.expanduser("~/.config/shodan/api_key")) as f:
shodan_key = f.read().strip()
return shodan_key
def info_shodan(testing, **kwargs):
url = "https://api.shodan.io/api-info"
sys.stderr.write("Inquiring shodan.io on API usage limits...\n")
if testing:
return (HTTPStatus.OK, {"https": False,
"monitored_ips": 8586,
"plan": "dev",
"query_credits": 10,
"scan_credits": 100,
"telnet": False,
"unlocked": True,
"unlocked_left": 10,
"usage_limits": {"monitored_ips": 16,
"query_credits": 100,
"scan_credits": 100}})
shodan_key = get_shodan_key()
return resilient_send(request.Request(url,
parse.urlencode((
("key", shodan_key),
)).encode("ascii")),
timeout=kwargs.get("timeout", SHODAN_TIMEOUT),
repeatsleep=kwargs.get("repeatsleep", REPEAT_SLEEP),
debuglevel=kwargs.get("debuglevel", 0))
def search_shodan(page, **kwargs):
url = "https://api.shodan.io/shodan/host/search"
argsmap = (
("product", "product"),
("component", "http.component"),
("country", "country"),
("ip", "ip"),
)
def shodan_jenkins_fixup(kw):
if kw.get("component") == "jenkins":
del kw["component"]
q = kw.get("query")
if q is None:
q = "x-jenkins"
else:
q = "%s %s" % (q, "x-jenkins")
kw["query"] = q
shodan_fixups = (shodan_jenkins_fixup,)
# Avoid changing the caller's dictionary
kw = dict(kwargs)
for shodan_fixup in shodan_fixups:
shodan_fixup(kw)
testing = kw.pop("testing", False)
querypieces = []
query = kw.get("query")
if query is not None:
querypieces.append(query)
for (funcarg, shodanarg) in argsmap:
funcval = kw.get(funcarg)
if funcval is not None:
querypieces.append("{key}:{value}".format(key=shodanarg, value=funcval))
queryargvalue = " ".join(querypieces)
sys.stderr.write("Inquiring shodan.io with \"%s\" (page %d)...\n" % (queryargvalue, page,))
if testing:
MACRO_FIXTURES = kw.pop("MACRO_FIXTURES")
IP_SEARCH_FIXTURES = kw.pop("IP_SEARCH_FIXTURES")
if page > 1:
return (HTTPStatus.OK, {"matches": []})
qlow = queryargvalue.lower()
for macro in MACROS:
macrolow = MACRO_PRODUCTS[macro].lower()
if macrolow in qlow:
return (HTTPStatus.OK, {"matches": MACRO_FIXTURES[macro]})
if "ip:" in qlow:
return (HTTPStatus.OK, {
"matches": IP_SEARCH_FIXTURES,
"total": len(IP_SEARCH_FIXTURES)
})
else:
raise Usage("Only products {products}, as well as IP lookups, are mocked as Shodan results"
.format(products=", ".join(sorted(MACRO_PRODUCTS.keys()))))
shodan_key = get_shodan_key()
return resilient_send(request.Request("%s?%s" % (url,
parse.urlencode((
("key", shodan_key),
("query", queryargvalue),
("page", page),
))),
method="GET"),
timeout=kw.get("timeout", SHODAN_TIMEOUT),
repeatsleep=kw.get("repeatsleep", REPEAT_SLEEP),
debuglevel=kw.get("debuglevel", 0))
# https://gist.github.com/dfee/6ed3a4b05cfe7a6faf40a2102408d5d8
IPV4SEG = r'(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])'
IPV4ADDR = r'(?:(?:' + IPV4SEG + r'\.){3,3}' + IPV4SEG + r')'
IPV6SEG = r'(?:(?:[0-9a-fA-F]){1,4})'
IPV6GROUPS = (
r'(?:' + IPV6SEG + r':){7,7}' + IPV6SEG, # 1:2:3:4:5:6:7:8
r'(?:' + IPV6SEG + r':){1,7}:', # 1:: 1:2:3:4:5:6:7::
r'(?:' + IPV6SEG + r':){1,6}:' + IPV6SEG, # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8
r'(?:' + IPV6SEG + r':){1,5}(?::' + IPV6SEG + r'){1,2}', # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8
r'(?:' + IPV6SEG + r':){1,4}(?::' + IPV6SEG + r'){1,3}', # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8
r'(?:' + IPV6SEG + r':){1,3}(?::' + IPV6SEG + r'){1,4}', # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8
r'(?:' + IPV6SEG + r':){1,2}(?::' + IPV6SEG + r'){1,5}', # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8
IPV6SEG + r':(?:(?::' + IPV6SEG + r'){1,6})', # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8
r':(?:(?::' + IPV6SEG + r'){1,7}|:)', # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
r'fe80:(?::' + IPV6SEG + r'){0,4}%[0-9a-zA-Z]{1,}', # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)
r'::(?:ffff(?::0{1,4}){0,1}:){0,1}[^\s:]' + IPV4ADDR, # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
r'(?:' + IPV6SEG + r':){1,4}:[^\s:]' + IPV4ADDR, # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)
)
IPV6ADDR = '|'.join(['(?:{})'.format(g) for g in IPV6GROUPS[::-1]]) # Reverse rows for greedy match
IPV4ADDR_COMPILED = re.compile(IPV4ADDR)
IPV6ADDR_COMPILED = re.compile(IPV6ADDR)
RDAP_BOOTSTRAP = "https://rdap.org"
def whoseip(ip, whoserole, debuglevel=0, unittesting=False, **fixtures):
r"""
Obtain email addresses of a given role for the given IP address.
>>> unittesting
True
>>> print('#'); whoseip('71.17.138.152', 'abuse', debuglevel, unittesting, **fixtures)
#...
>>> print('#'); whoseip('109.87.56.48', 'abuse', debuglevel, unittesting, **fixtures)
#...
>>> print('#'); whoseip('build.automotivelinux.org', 'abuse', debuglevel, unittesting, **fixtures)
#...
>>> print('#'); whoseip('ci.jwfh.ca', 'abuse', debuglevel, unittesting, **fixtures)
#...
[]
"""
def get_roles_addresses(entities):
er = [(e.get("roles", []), e.get("remarks", []),
dict([(k, v) for (k, obj, kind, v) in e.get("vcardArray", [None, []])[1]]))
for e in entities]
for e in entities:
if "entities" in e:
er.extend(get_roles_addresses(e["entities"]))
return er
if IPV4ADDR_COMPILED.match(ip) or IPV6ADDR_COMPILED.match(ip):
url = "%s/ip/%s" % (RDAP_BOOTSTRAP, ip,)
if unittesting:
(code, whoseobj) = fixtures["WHOSEIP_FIXTURES"][ip]
else:
(code, whoseobj) = resilient_send(request.Request(url), debuglevel=debuglevel)
# print(pformat(whoseobj))
if code != HTTPStatus.OK:
return []
else:
splits = ip.split(".")
while True:
if len(splits) < 2:
return []
domain = ".".join(splits)
url = "%s/domain/%s" % (RDAP_BOOTSTRAP, domain,)
if unittesting:
(code, whoseobj) = fixtures["WHOSEIP_FIXTURES"][domain]
else:
(code, whoseobj) = resilient_send(request.Request(url), debuglevel=debuglevel)
# print(pformat(whoseobj))
if code != HTTPStatus.OK:
del splits[0]
else:
break
try:
entroles = get_roles_addresses(whoseobj["entities"])
except (KeyError, IndexError) as e:
sys.stderr.write(" *** whoseip(%r, %r) %s %s in %s\n" % (ip, whoserole,
e.__class__.__name__,
e, pformat(whoseobj)))
return []
roleemails = {}
for roles, remarks, addr in entroles:
if "email" in addr:
for remark in remarks:
if "Unvalidated" in remark["title"]:
break
else:
email = addr["email"]
if "@" not in email:
# Empty or "EMAIL REDACTED FOR PRIVACY"
# sys.stderr.write(" *** whoseip(%r, %r) got an invalid email %r in roles %r\n" % (ip, whoserole,
# email, roles))
continue
for role in roles:
if role in roleemails:
if email not in roleemails[role]:
roleemails[role].append(email)
else:
roleemails[role] = [email]
for tryrole in (whoserole, "technical", "administrative"):
if tryrole in roleemails:
return roleemails[tryrole]
return []
def read_sent_emails(sent_name):
sent_emails = {}
if os.path.exists(sent_name):
with open(os.path.expanduser(sent_name)) as f:
for line in f:
line = line.strip()
if not line:
continue
(email, iptext) = line.split(None, 1)
if email.endswith(":"):
email = email[:-1]
ips = []
for ipstr in iptext.split():
if ipstr.endswith(","):
ipstr = ipstr[:-1]
ips.append(ip_address(ipstr))
sent_emails[email] = ips
return sent_emails
def write_sent_emails(testing, to_myself_only, sent_name, sent_emails):
if testing or to_myself_only:
return
with open(os.path.expanduser(sent_name), "w") as f:
for e in sorted(sent_emails.keys()):
ehosts = sent_emails[e]
f.write("%s: %s\n" % (e, ", ".join(str(ehost) for ehost in ehosts)))
class HTTPChecker(namedtuple("HTTPChecker",
("path", "headers", "bodysearch", "host_hint_extractor"),
defaults=(None,))):
pass
def jenkins_host_extractor(json):
if "primaryView" in json:
p = json["primaryView"]
if "url" in p:
u = p["url"]
urlobj = parse.urlparse(u)
return urlobj.hostname
return None
def build_httpchecker(macro):
httpchecker = []
if macro is None:
pass
elif macro == CHECK_COINHIVE:
httpchecker.append(HTTPChecker(path="/", headers=(), bodysearch="coinhive"))
elif macro == WEAK_AVTECH:
avtech_path = "/cgi-bin/nobody/Machine.cgi?action=get_capability"
avtech_headers = ((b"Authorization", b"Basic %s" % (base64.b64encode(b"admin:admin"),)),)
avtech_bodysearch = "Firmware.Version"
httpchecker.append(HTTPChecker(path=avtech_path, headers=(), bodysearch=avtech_bodysearch))
httpchecker.append(HTTPChecker(path=avtech_path, headers=avtech_headers, bodysearch=avtech_bodysearch))
elif macro == WEAK_JENKINS:
jenkins_path = "/api/json"
jenkins_bodysearch = "\"jobs\""
httpchecker.append(HTTPChecker(path=jenkins_path, headers=(), bodysearch=jenkins_bodysearch,
host_hint_extractor=jenkins_host_extractor))
else:
raise Usage("Unknown macro \"%s\"" % (macro,))
return httpchecker
def check(macro, httpchecker, baseurl, opener, findings=None, host_hints=None):
if len(httpchecker) == 0:
# Assume the host vulnerable in the absence of HTTP checks
return True
for checker in httpchecker:
body = ""
url = baseurl + checker.path
try:
req = request.Request(url)
for (name, value) in checker.headers:
req.add_header(name, value)
with opener.open(req, timeout=URL_TIMEOUT) as response:
(code, body) = process_http_response(response, True)
except HTTPError as e:
(code, body) = process_http_error(e, True)
except NETWORK_ERRORS as e:
log_network_error(e, url)
return False
if checker.bodysearch.lower() in body.lower():
finding = "Got {bodysearch!r} in {url}{headersinfo}".format(bodysearch=checker.bodysearch,
url=url,
headersinfo=(" with default %s" % (checker.headers[0][0].decode("ascii"),)
if len(checker.headers) > 0 else ""))
if findings is not None:
findings.append(finding)
if ((host_hints is not None) and (len(host_hints) == 0) and
(checker.host_hint_extractor is not None)):
try:
body_json = json.loads(body)
except json.decoder.JSONDecodeError as e:
body_json = {}
log_error(e, url)
host_hint = checker.host_hint_extractor(body_json)
if host_hint is not None:
host_hints.append(host_hint)
sys.stderr.write(" %s\n" % (finding,))
return True
sys.stderr.write(" *** The product appears protected against %s at %s\n" % (macro, baseurl,))
return False
# https://stackoverflow.com/questions/390250/elegant-ways-to-support-equivalence-equality-in-python-classes
class HostLog(namedtuple("HostLog", ("ip", "ts", "vuln", "findings"))):
# https://docs.python.org/3/library/collections.html#collections.namedtuple
__slots__ = ()
def __str__(self):
return "{ip!s:>15} {ts} {vuln:<17} {finds}".format(finds = ", ".join(self.findings),
**self._asdict())
def cmp_hosts(a, b):
r"""
unknown < str < IPv4Address < IPv6Address
Comparisons left-to-right (including own types): 4 + 3 + 2 + 1 = 10
Comparisons right-to-left (excluding own types): 3 + 2 + 1 = 6
Sub-total: 16
Optimizing away LTR unknown-to-others: -2
Optimizing away LTR str-to-IPv{4,6}: -1
Optimizing away RTL IPv6-to-others: -2
Optimizing away RTL IPv4-to-others: -1
Total: 10
>>> lst = [ip_address("127.0.0.2"), ip_address("::1"), ip_address("127.0.0.1"), "foobar.test", "abc.def.test"]
>>> lst.sort(key=cmp_to_key(cmp_hosts))
>>> lst
['foobar.test', 'abc.def.test', IPv4Address('127.0.0.1'), IPv4Address('127.0.0.2'), IPv6Address('::1')]
"""
if type(a) is str:
if type(b) is str:
# "hosta.tld" <> "hostb.tld" lexicographically
return a < b
elif (type(b) is IPv4Address) or (type(b) is IPv6Address):
# str < {IPv{4,6}Address,unknown}
return -1
else:
# str > unknown
return +1
elif type(a) is IPv4Address:
if type(b) is IPv4Address:
# IPv4Address <> IPv4Address
return -1 if (a < b) else (0 if (a == b) else +1)
elif type(b) is IPv6Address:
# IPv4Address < IPv6Address
return -1
elif type(b) is str:
# IPv4Address > str
# IPv4Address > unknown
return +1
elif type(a) is IPv6Address:
if type(b) is IPv6Address:
# IPv6Address <> IPv6Address
return -1 if (a < b) else (0 if (a == b) else +1)
else:
# IPv6Address > IPv4Address
# IPv6Address > str
# IPv6Address > unknown
return +1
elif (type(b) is IPv4Address) or (type(b) is IPv6Address):
# unknown < IPv{4,6}Address
return -1
else:
# unknown <> unknown
return -1 if (a < b) else (0 if (a == b) else +1)
host_comparing_key_getter = cmp_to_key(cmp_hosts)
def log_hosts(testing, macro, hosts, openers, httpcheckers, debuglevel=0):
logs = []
found_macros = {}
for hostrec in hosts:
host = ip_address(hostrec["ip"])
port = hostrec["port"]
is_ssl = "ssl" in hostrec
url = "http%s://%s:%s" % ("s" if is_ssl else "", host, port)
sys.stderr.write(" %s\n" % (url,))
product = hostrec.get("product", "").lower()
guessed = False
if macro is None:
check_macros = MACROS
else:
check_macros = [macro]
for check_macro in check_macros:
product_guess = MACRO_PRODUCTS[check_macro].lower()
if (macro is not None) or (product_guess in product) or (len(product.strip()) == 0):
guessed = True
vuln = MACRO_VULNS[check_macro]
else:
continue
httpchecker = httpcheckers[check_macro]
findings = []
ts = local_timestamp()
if check(check_macro, httpchecker, url, openers[is_ssl], findings):
found_macros[check_macro] = 1
ip = getipaddr(host, port)
# Not looking up owners of the host name "host" here as this
# method "log_hosts" is only used to "recheck" IP addresses
# already nested by their owner email addresses.
hostlog = HostLog(ip, ts, vuln, findings)
logs.append(hostlog)
sys.stderr.write(" %s\n" % (hostlog,))
if not guessed:
sys.stderr.write(" %s\n" % ("No product" if product is None
else "Unexpected product %s" % (product,)))
return found_macros, logs
def record_hosts(testing, hosts, macro, openers, httpchecker, ready_emaillogs, all_emails, debuglevel=0):
page_emails = {}
for (host, port, is_ssl) in hosts:
sys.stderr.write("%s\n" % (host,))
url = "http%s://%s%s" % ("s" if is_ssl else "", host, "" if port is None else (":%s" % (port,)))
findings = []
host_hints = []
ts = local_timestamp()
if check(macro, httpchecker, url, openers[is_ssl], findings, host_hints):
hosts_to_report = [host]
if len(host_hints) > 0:
hosts_to_report.append(host_hints[0])
found_emails = False
for rephost in hosts_to_report:
lookup_name = str(rephost)
ip = getipaddr(rephost, port)
for e in whoseip(lookup_name, "abuse", debuglevel):
found_emails = True
if e in page_emails:
# Quiet down even though this may record a related IP
# address under the same email address.
pass
else:
sys.stderr.write(" %s\n" % (e,))
page_ehosts = page_emails.get(e, [])
ready_ehostlogs = ready_emaillogs.get(e, [])
all_ehosts = all_emails.get(e, [])
if ip not in all_ehosts:
page_ehosts.append(ip)
ready_ehostlogs.append(HostLog(ip, ts, MACRO_VULNS[macro], findings))
all_ehosts.append(ip)
page_emails[e] = page_ehosts
ready_emaillogs[e] = ready_ehostlogs
all_emails[e] = all_ehosts
if not found_emails:
sys.stderr.write(" *** No abuse notification emails found for %s\n" % (host,))
sys.stderr.write("\n")
for e in sorted(page_emails.keys()):
page_ehosts = page_emails[e]
page_ehosts.sort(key=host_comparing_key_getter)
sys.stderr.write("%s: %s\n" % (e, ", ".join(str(page_ehost) for page_ehost in page_ehosts)))
for e in sorted(ready_emaillogs.keys()):
ready_ehostlogs = ready_emaillogs[e]
ready_ehostlogs.sort(key=host_comparing_key_getter)
for e in sorted(all_emails.keys()):
all_ehosts = all_emails[e]
all_ehosts.sort(key=host_comparing_key_getter)
def extract_thing(shodanquery):
if shodanquery:
pieces = shodanquery.split()
thing_pieces = []
for piece in pieces:
if ":" not in piece:
thing_pieces.append(piece)
return " ".join(thing_pieces)
else:
return ""
def send_logs_mail(testing,
myaddr, to_myself_only, myipaddr,
rerun, matched_macros, logs):
if len(logs) == 0:
if to_myself_only:
sys.stderr.write("Nothing to send by email for %s (to myself).\n" % (rerun,))
return
if testing:
sys.stderr.write("Testing email for %s by sending it just to myself...\n" % (rerun,))
else:
sys.stderr.write("Sending email for %s%s...\n" % (rerun,
" to myself" if to_myself_only else ""))
msg = MIMEText("""
Hello {rerun},
The following address(es) appeared vulnerable to abuse and botnets, according
to the requests shown below. This initiative sent the requests from the IP
address {myipaddr}.
{logstr}
Legend:
{legend}
Reservation:
{reservation}
Best regards,
A community cleanup initiative
https://github.com/frantic-search/community-cleanup
""".format(rerun=rerun,
myipaddr=myipaddr,
logstr="\n ".join(str(hostlog) for hostlog in sorted(logs)),
legend="\n\n".join(("%s: %s" % (MACRO_VULNS[m], MACRO_LEGENDS[m])) for m in matched_macros),
reservation=RESERVATION))
recipients = [myaddr]
if not testing and not to_myself_only:
recipients.append(rerun)
msg["Subject"] = "%sCommunity cleanup checking back" % ("TESTING: " if testing else "",)
msg["From"] = myaddr
msg["To"] = rerun
s = smtplib.SMTP("localhost")
s.sendmail(myaddr, recipients, msg.as_string())
s.quit()
def send_mail(testing,
ready_emaillogs, myaddr, to_myself_only,
shodanquery, product, component, macro):
if len(ready_emaillogs) == 0:
sys.stderr.write("Nothing to send by email from the last few pages of the results.\n")
return
if macro in MACRO_PRODUCTS:
prodname = MACRO_PRODUCTS[macro]
elif product:
prodname = product
else:
prodname = extract_thing(shodanquery) or "internet thing"
if macro in MACRO_SMELLS:
smell = MACRO_SMELLS[macro]
elif component:
smell = "running \"%s\"" % (component,)
else:
smell = None
for e in sorted(ready_emaillogs.keys()):
if testing:
sys.stderr.write("Testing email for %s by sending it just to myself...\n" % (e,))
else:
sys.stderr.write("Sending an email for %s%s...\n" % (e,
" to myself" if to_myself_only else ""))
ehostlogs = ready_emaillogs[e]
msg = MIMEText("""
Hello {email},
Your {product} at the following address(es) appeared vulnerable to abuse and botnets{because}:
{logstr}
{legendpiece}Reservation:
{reservation}
Best regards,
A community cleanup initiative
https://github.com/frantic-search/community-cleanup
""".format(email=e, product=prodname,
because=("" if smell is None else "\nbecause of %s" % (smell,)),
logstr="\n ".join(str(ehostlog) for ehostlog in ehostlogs),
legendpiece=("Legend:\n %s: %s\n\n" % (MACRO_VULNS[macro], MACRO_LEGENDS[macro],)
if macro in MACRO_LEGENDS else ""),
reservation=RESERVATION))
recipients = [myaddr]
if not testing and not to_myself_only:
recipients.append(e)
msg["Subject"] = "%sCommunity cleanup: your %s needs attention" % ("TESTING: " if testing else "",
prodname,)
msg["From"] = myaddr
msg["To"] = e
s = smtplib.SMTP("localhost")
s.sendmail(myaddr, recipients, msg.as_string())
s.quit()
def chunks(seq, n):
"""
Yield successive n-sized chunks from seq.
>>> tuple(chunks(range(14), 3))
((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13))
>>> tuple(chunks(range(12), 3))
((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
"""
it = iter(seq)
while True:
chunk = []
for i in range(n):
try:
chunk.append(next(it))
except StopIteration:
if i > 0:
yield tuple(chunk)
return
yield tuple(chunk)
def recheck(macro, rerun, ips,
myaddr, myipaddr, to_myself_only,
openers, httpcheckers,
debuglevel,
testing=False,
**fixtures):
if testing:
ips = tuple(ip_address(ip) for ip in TEST_IPS)
logs = []
matched_macros = {}
continue_chunks = True
for ips_chunk in chunks(ips, IPS_LIMIT):
ips_chunk_str = ",".join(str(ip) for ip in ips_chunk)
page = 1
while True:
(shodan_code, shodan_results) = search_shodan(page,
ip=ips_chunk_str,
debuglevel=debuglevel,
timeout=SHODAN_LARGE_TIMEOUT,
testing=testing,
**fixtures)
if shodan_code != HTTPStatus.OK:
sys.stderr.write("Unexpected Shodan code %d, response:\n%s\n" % (shodan_code, pformat(shodan_results),))
sleep_with_banner(REPEAT_SLEEP)
continue
if "matches" not in shodan_results:
sys.stderr.write("Missing \"matches\" in response:\n%s\n" % (pformat(shodan_results),))
sleep_with_banner(REPEAT_SLEEP)
continue
nummatches = len(shodan_results["matches"])
if nummatches == 0:
sys.stderr.write(" No more matches\n")