-
Notifications
You must be signed in to change notification settings - Fork 79
/
analyze_hosts.py
executable file
·1425 lines (1316 loc) · 47.6 KB
/
analyze_hosts.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 -*-
"""analyze_hosts - scans one or more hosts for security misconfigurations
Copyright (C) 2015-2023 Peter Mosmans [Go Forward]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
"""
import argparse
import io
import datetime
import json
import logging
import os
import queue
import re
import signal
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import warnings
try:
import nmap
except ImportError:
print(
"[-] Please install python-nmap, e.g. pip3 install python-nmap", file=sys.stderr
)
sys.exit(-1)
try:
import requests
import yaml
import Wappalyzer
except ImportError as exception:
print(
f"[-] Please install required modules, e.g. pip3 install -r requirements.txt: {exception}",
file=sys.stderr,
)
sys.stderr.flush()
# Workaround for https://github.com/chorsley/python-Wappalyzer/issues/40
warnings.simplefilter("ignore")
NAME = "analyze_hosts"
__version__ = "1.15.0"
ALLPORTS = [
(22, "ssh"),
(25, "smtp"),
(80, "http"),
(443, "https"),
(465, "smtps"),
(993, "imaps"),
(995, "pop3s"),
(8080, "http-proxy"),
]
SSL_PORTS = [25, 443, 465, 993, 995]
# Default list of allowed open ports, different ports will generate an alert
ALLOWED_OPEN_PORTS = [
80,
443,
]
NIKTO_ALERTS = [
"+ OSVDB-",
"Entry '/index.php/user/register/' in robots.txt returned a non-forbidden or redirect HTTP code",
"Retrieved access-control-allow-origin header: *",
"Retrieved x-powered-by header",
"The anti-clickjacking X-Frame-Options header is not present",
"This might be interesting",
"Uncommon header",
"created without the httponly flag",
"entries which should be manually viewed",
]
NMAP_ALERTS = [
"3des-cbc",
"arcfour",
"blowfish-cbc",
"cast128-cbc",
"diffie-hellman-group-exchange-sha1",
"diffie-hellman-group1-sha1",
"diffie-hellman-group14-sha1",
"ecdh-sha2-nistp",
"ecdsa",
"hmac-md5",
"hmac-sha1",
"http-php-version",
"message_signing: disabled",
"mountd ",
"msrpc",
"netbios-ssn ",
"ssh-dss",
"umac-64",
]
# All these keywords will be suffixed with ': '
NMAP_INFO = [
"Computer name",
"Domain name",
"NetBIOS computer name",
"authentication_level",
"banner",
"challenge_response",
"http-server-header",
"http-title",
"message_signing",
"nbstat" "smb-security-mode",
"smtp-open-relay",
]
NMAP_ARGUMENTS = ["-sV", "--open"] # A list of default arguments to pass to nmap
NMAP_SCRIPTS = [
"banner",
"dns-nsid",
"dns-recursion",
"http-cisco-anyconnect",
"http-php-version",
"http-title",
"http-trace",
"ntp-info",
"ntp-monlist",
"nbstat",
"rdp-enum-encryption",
"rpcinfo",
"sip-methods",
"smb-os-discovery",
"smb-security-mode",
"smtp-open-relay",
"ssh2-enum-algos",
"vnc-info",
"xmlrpc-methods",
"xmpp-info",
]
TESTSSL_ALERTS = [
"(deprecated)",
"DES-CBC3",
"NOT ok",
"TLS1: ",
"VULNERABLE",
]
TESTSSL_UNTRUSTED = [
"NOT ok (self signed CA in chain)",
"NOT ok -- neither CRL nor OCSP URI provided",
]
# A regular expression of prepend characters to remove in a line
REMOVE_PREPEND_LINE = r"^[| _+]*"
UNKNOWN = -1
# The program has the following loglevels:
# logging.DEBUG = 10 debug messages (module constant)
# logging.INFO = 20 verbose status messages (module constant)
COMMAND = 23 # tool command line
STATUS = 25 # generic status messages
# ERROR = 40 recoverable error messages (module constant)
# CRITICAL = 50 abort program (module constant)
# The following levels are used for the actual scanning output:
LOGS = 30 # scan output / logfiles
ALERT = 35 # vulnerabilities found
class LogFormatter(logging.Formatter):
"""Class to format log messages based on their type."""
# pylint: disable=protected-access
FORMATS = {
logging.DEBUG: logging._STYLES["{"][0]("[d] {message}"),
logging.INFO: logging._STYLES["{"][0]("[*] {message}"),
"STATUS": logging._STYLES["{"][0]("[+] {message}"),
"ALERT": logging._STYLES["{"][0]("[!] {message}"),
logging.ERROR: logging._STYLES["{"][0]("[-] {message}"),
logging.CRITICAL: logging._STYLES["{"][0]("[-] FATAL: {message}"),
"DEFAULT": logging._STYLES["{"][0]("{message}"),
}
def format(self, record):
self._style = self.FORMATS.get(record.levelno, self.FORMATS["DEFAULT"])
return logging.Formatter.format(self, record)
class LogFilter: # pylint: disable=too-few-public-methods
"""Class to remove certain log levels."""
def __init__(self, filterlist):
self.__filterlist = filterlist
def filter(self, logRecord): # pylint: disable=invalid-name
"""Remove logRecord if it is part of filterlist."""
return logRecord.levelno not in self.__filterlist
def abort_program(text, error_code=-1):
"""Log critical error @text and exit program with @error_code."""
logging.critical(text)
sys.exit(error_code)
def analyze_url(url, port, options, logfile, host_results):
"""Analyze a URL using wappalyzer and execute corresponding scans."""
wappalyzer = Wappalyzer.Wappalyzer.latest()
page = requests_get(url, options)
if not page:
logging.debug("%s Got no reply - cannot analyze that", url)
return
if page.status_code in [400] and "http://" in url:
# Retry with a different protocol, as the site might also be securely accessible
url = url.replace("http://", "https://")
page = requests_get(url, options)
if page.status_code == 200:
webpage = Wappalyzer.WebPage(url, page.text, page.headers)
analysis = wappalyzer.analyze(webpage)
# Format logmessage as info message, so that it ends up in logfile
logging.log(LOGS, "[*] %s Analysis: %s", url, analysis)
if "Drupal" in analysis:
do_droopescan(url, port, "drupal", options, logfile, host_results)
if "Joomla" in analysis:
do_droopescan(url, port, "joomla", options, logfile, host_results)
if "WordPress" in analysis:
do_wpscan(url, port, options, logfile)
else:
logging.debug("%s Got result %s - cannot analyze that", url, page.status_code)
def requests_get(url, options, headers=None, allow_redirects=True):
"""Generic wrapper around requests object."""
# Don't try this at home, kids! Disabling SSL verification
verify = False
if not headers:
headers = {"User-Agent": options["user_agent"]}
if not verify:
# pylint: disable=E1101
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.InsecureRequestWarning
)
proxies = None
if options["proxy"]:
proxies = {
"http": f"http://{options['proxy']}",
"https": f"https://{options['proxy']}",
}
try:
request = requests.get(
url,
headers=headers,
proxies=proxies,
verify=verify,
allow_redirects=allow_redirects,
)
except (
requests.exceptions.ConnectionError,
requests.exceptions.RequestException,
) as exception:
logging.log(STATUS, "%s Could not connect: %s", url, exception)
request = None
return request
def http_checks(host, port, protocol, options, logfile, host_results):
"""Perform various HTTP checks."""
ssl = False
if "ssl" in protocol or "https" in protocol:
ssl = True
url = f"https://{host}:{port}"
else:
url = f"http://{host}:{port}"
if options["nikto"]:
do_nikto(host, port, options, logfile, host_results)
if options["framework"]:
analyze_url(url, port, options, logfile, host_results)
if options["http"] or options["compression"]:
check_compression(url, port, options, host_results, use_ssl=ssl)
if options["http"] or options["headers"]:
check_headers(url, port, options, host_results, use_ssl=ssl)
if options["http"] or options["redirect"]:
check_redirect(url, port, options, host_results)
if options["http"] or options["trace"]:
check_trace(host, port, options, logfile, host_results)
def tls_checks(host, port, protocol, options, logfile, host_results):
"""Perform various SSL/TLS checks."""
if options["ssl"]:
do_testssl(host, port, protocol, options, logfile, host_results)
if options["sslcert"]:
download_cert(host, port, options, logfile)
def check_redirect(url, port, options, host_results):
"""Check for insecure open redirect."""
request = requests_get(
url,
options,
headers={"Host": "EVIL-INSERTED-HOST", "User-Agent": options["user_agent"]},
allow_redirects=False,
)
if (
request
and request.status_code == 302
and "Location" in request.headers
and "EVIL-INSERTED-HOST" in request.headers["Location"]
):
add_item(
host_results,
url,
port,
options,
f"{url} vulnerable to open insecure redirect: {request.headers['Location']}",
ALERT,
)
def check_headers(url, port, options, host_results, use_ssl=False):
"""Check HTTP headers for omissions / insecure settings."""
request = requests_get(
url,
options,
headers={"User-Agent": options["user_agent"]},
allow_redirects=False,
)
if not request:
return
logging.debug(
"%s Received status %s and the following headers: %s",
url,
request.status_code,
request.headers,
)
security_headers = ["X-Content-Type-Options", "X-XSS-Protection"]
if use_ssl:
security_headers.append("Strict-Transport-Security")
if request.status_code == 200:
if "X-Frame-Options" not in request.headers:
add_item(
host_results,
url,
port,
options,
f"{url} lacks an X-Frame-Options header",
ALERT,
)
elif "*" in request.headers["X-Frame-Options"]:
add_item(
host_results,
url,
port,
options,
f"{url} has an insecure X-Frame-Options header: {request.headers['X-Frame-Options']}",
ALERT,
)
for header in security_headers:
if header not in request.headers:
add_item(
host_results,
url,
port,
options,
f"{url} lacks a {header} header",
ALERT,
)
def check_compression(url, port, options, host_results, use_ssl=False):
"""Check which compression methods are supported."""
request = requests_get(url, options, allow_redirects=True)
if not request:
return
if request.history:
# check if protocol was changed: if so, abort checks
if (not use_ssl and "https" in request.url) or (
use_ssl and "https" not in request.url
):
logging.debug(
"%s protocol has changed while testing to %s - aborting compression test",
url,
request.url,
)
return
url = request.url
for compression in [
"br",
"bzip2",
"compress",
"deflate",
"exi",
"gzip",
"identity",
"lzma",
"pack200-gzip",
"peerdist",
"sdch",
"xpress",
"xz",
]:
request = requests_get(
url,
options,
headers={
"User-Agent": options["user_agent"],
"Accept-Encoding": compression,
},
allow_redirects=False,
)
if request and request.status_code == 200:
if "Content-Encoding" in request.headers:
if compression in request.headers["Content-Encoding"]:
add_item(
host_results,
url,
port,
options,
f"{url} supports {compression} compression",
ALERT,
)
def is_admin():
"""Check whether script is executed using root privileges."""
if os.name == "nt":
try:
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin()
except ImportError:
return False
else:
return os.geteuid() == 0 # pylint: disable=no-member
def preflight_checks(options):
"""Check if all tools are there, and disable tools automatically."""
try:
if options["resume"]:
if (
not os.path.isfile(options["queuefile"])
or not os.stat(options["queuefile"]).st_size
):
abort_program(f"Queuefile {options['queuefile']} is empty")
else:
if (
os.path.isfile(options["queuefile"])
and os.stat(options["queuefile"]).st_size
):
if options["force"]:
os.remove(options["queuefile"])
else:
abort_program(
f"Queuefile {options['queuefile']} already exists.\n"
+ " Use --resume to resume with previous targets, "
+ "or use --force to overwrite the queuefile"
)
except (IOError, OSError) as exception:
logging.error("FAILED: Could not read %s (%s)", options["queuefile"], exception)
for basic in ["nmap"]:
options[basic] = True
if options["udp"] and not is_admin() and not options["dry_run"]:
logging.error("UDP portscan needs root permissions")
if options["framework"]:
try:
import requests
import Wappalyzer
options["droopescan"] = True
options["wpscan"] = True
except ImportError:
logging.error("Disabling --framework due to missing Python libraries")
options["framework"] = False
if options["wpscan"] and not is_admin():
logging.error("Disabling --wpscan as this option needs root permissions")
options["wpscan"] = False
options["timeout"] = options["testssl.sh"]
for tool in [
"nmap",
"curl",
"droopescan",
"nikto",
"testssl.sh",
"timeout",
"wpscan",
]:
if options[tool]:
logging.debug("Checking whether %s is present... ", tool)
version = "--version"
if tool == "nikto":
version = "-Version"
elif tool == "droopescan":
version = "stats"
result, stdout, stderr = execute_command(
[get_binary(tool), version], options, keep_endings=False
)
options[f"version_{tool}"] = stdout
if not result:
if tool == "nmap":
if not options["dry_run"] and not options["no_portscan"]:
abort_program("Could not execute nmap, which is necessary")
logging.error(
"Could not execute %s, disabling checks (%s)", tool, stderr
)
options[tool] = False
else:
logging.debug(stdout)
def prepare_nmap_arguments(options):
"""Prepare nmap command line arguments."""
arguments = NMAP_ARGUMENTS
scripts = NMAP_SCRIPTS
if is_admin():
arguments.append("-sS")
if options["udp"]:
arguments.append("-sU")
elif options["no_portscan"]:
arguments.append("-sn")
else:
arguments.append("-sT")
if options["allports"]:
arguments.append("-p1-65535")
elif options["port"]:
arguments.append("-p" + options["port"])
if options["no_portscan"] or options["up"]:
arguments.append("-Pn")
if options["whois"]:
scripts += "asn-query", "fcrdns,whois-ip", "whois-domain"
if scripts:
arguments.append("--script=" + ",".join(scripts))
options["nmap_arguments"] = " ".join(arguments)
def execute_command(cmd, options, logfile=False, keep_endings=True):
"""Execute system command.
If logfile is provided, will add the command as well as stdout and stderr
to the logfile.
Args:
cmd (str): Command to execute
options (dictionary): Options
logfile (str): Name of logfile
Returns:
Result value, stdout, stderr (tuple)
"""
stdout = ""
stderr = ""
result = False
logging.debug(" ".join(cmd))
if options["dry_run"]:
return True, stdout, stderr
try:
process = subprocess.run(cmd, encoding="utf-8", text=True, capture_output=True)
# For easier processing, split string into lines
stdout = process.stdout.splitlines(keep_endings)
stderr = process.stderr.splitlines(keep_endings)
result = not process.returncode
except OSError as exception:
logging.error("Error while executing %s: %s", cmd, exception)
except Exception as exception:
logging.error("Exception while executing %s: %s", cmd, exception)
if logfile:
append_logs(logfile, options, " ".join(cmd), "")
append_logs(logfile, options, stdout, stderr)
return result, stdout, stderr
def download_cert(host, port, options, logfile):
"""Download an SSL certificate and append it to the logfile."""
try:
cert = ssl.get_server_certificate((host, port))
append_logs(logfile, options, cert, "")
except ssl.SSLError:
pass
def append_logs(logfile, options, stdout, stderr):
"""Append unicode text strings to unicode type logfile."""
if options["dry_run"]:
return
try:
if stdout:
with io.open(logfile, encoding="utf-8", mode="a+") as open_file:
open_file.write(compact_strings(stdout, options))
if stderr:
with io.open(logfile, encoding="utf-8", mode="a+") as open_file:
open_file.write(compact_strings(stderr, options))
except IOError:
logging.error("Could not write to %s", logfile)
def append_file(logfile, options, input_file):
"""Append content from input_file to logfile, and delete input_file."""
if options["dry_run"]:
return
try:
if os.path.isfile(input_file) and os.stat(input_file).st_size:
with open(input_file, "r") as read_file:
logging.debug("Appending input_file to logfile")
append_logs(logfile, options, read_file.read().splitlines(True), [])
os.remove(input_file)
except (IOError, OSError) as exception:
logging.error("FAILED: Could not read %s (%s)", input_file, exception)
def compact_strings(lines, options):
"""Remove empty and remarked lines."""
if options["compact"]:
return "".join([x for x in lines if not (x == "\n") and not x.startswith("#")])
return "".join(lines)
def check_trace(host, port, options, logfile, host_results):
"""Check for HTTP TRACE method."""
if options["trace"]:
command = [
get_binary("curl"),
"-sIA",
"'{0}'".format(options["user_agent"]),
"--connect-timeout",
str(options["timeout"]),
"-X",
"TRACE",
f"{host}:{port}",
]
_result, _stdout, _stderr = execute_command(
command, options, logfile
) # pylint: disable=unused-variable
def do_droopescan(url, port, cms, options, logfile, host_results):
"""Perform a droopescan of type cms."""
if options["droopescan"]:
logging.debug("Performing %s droopescan on %s", cms, url)
command = [get_binary("droopescan"), "scan", cms, "--quiet", "--url", url]
_result, _stdout, _stderr = execute_command(
command, options, logfile
) # pylint: disable=unused-variable
def do_nikto(host, port, options, logfile, host_results):
"""Perform a nikto scan."""
command = [
get_binary("nikto"),
"-ask",
"no",
"-host",
f"{host}:{port}",
"-maxtime",
f'{options["maxtime"]}s',
"-nointeractive",
"-vhost",
f"{host}",
]
if port == 443:
command.append("-ssl")
if options["proxy"]:
command += ["-useproxy", f'https://{options["proxy"]}']
elif options["proxy"]:
command += ["-useproxy", f'http://{options["proxy"]}']
if options["username"] and options["password"]:
command += ["-id", f'{options["username"]}:{options["password"]}']
parameters = read_parameters(options["settings"], host, port)
if "nikto_output" in parameters:
command += "-output", parameters["nikto_output"]
if "nikto_plugins" in parameters:
command += "-Plugins", parameters["nikto_plugins"]
if "nikto_tuning" in parameters:
command += "-Tuning", parameters["nikto_tuning"]
if options["timeout"]:
command = [get_binary("timeout"), str(options["maxtime"])] + command
logging.info("%s Starting nikto on port %s", host, port)
_result, stdout, _stderr = execute_command(
command, options, logfile
) # pylint: disable=unused-variable
check_strings_for_alerts(stdout, NIKTO_ALERTS, host_results, host, port, options)
def read_parameters(settings, host, port):
"""Read tuning dictionary per host-port combination from the settings dictionary."""
parameters = {}
if (
"targets" in settings
and host in settings["targets"]
and "ports" in settings["targets"][host]
):
parameters = next(
(
item
for item in settings["targets"][host]["ports"]
if item["port"] == port
),
{},
)
return parameters
def do_portscan(host, options, logfile, stop_event, host_results):
"""Perform a portscan.
Args:
host: Target host.
options: Dictionary object containing options.
logfile: Filename where logfile will be written to.
stop_event: Event handler for stop event
host_results: Host results dictionary
Returns:
A list with tuples of open ports and the protocol.
"""
ports = []
open_ports = []
if not options["nmap"]:
if options["port"]:
ports = [int(port) for port in options["port"].split(",") if port.isdigit()]
return zip(ports, ["unknown"] * len(ports))
return ALLPORTS
if ":" in host:
options["nmap_arguments"] += " -6"
logging.info("%s Starting nmap", host)
logging.log(COMMAND, "nmap %s %s", options["nmap_arguments"], host)
if options["dry_run"]:
return ALLPORTS
try:
temp_file = f"nmap-{host}-{next(tempfile._get_candidate_names())}" # pylint: disable=protected-access
scanner = nmap.PortScanner()
scanner.scan(
hosts=host,
arguments=f"{options['nmap_arguments']} -oN {temp_file}",
)
for ip_address in [
x for x in scanner.all_hosts() if scanner[x] and scanner[x].state() == "up"
]:
ports = [
port
for port in scanner[ip_address].all_tcp()
if scanner[ip_address]["tcp"][port]["state"] == "open"
]
for port in ports:
open_ports.append([port, scanner[ip_address]["tcp"][port]["name"]])
check_nmap_log_for_alerts(temp_file, host_results, host, options)
append_file(logfile, options, temp_file)
if open_ports:
logging.info("%s Found open TCP ports %s", host, open_ports)
else:
# Format logmessage as info message, so that it ends up in logfile
logging.log(LOGS, "[*] %s No open ports found", host)
except (AssertionError, nmap.PortScannerError) as exception:
if stop_event.is_set():
logging.debug("%s nmap interrupted", host)
else:
logging.log(
STATUS,
"%s Issue with nmap %s: %s",
host,
options["nmap_arguments"],
exception,
)
open_ports = [UNKNOWN]
finally:
if os.path.isfile(temp_file):
os.remove(temp_file)
host_results["ports"] = ports
return open_ports
def check_nmap_log_for_alerts(logfile, host_results, host, options):
"""Check for keywords in logfile and log them as alert."""
try:
if os.path.isfile(logfile) and os.stat(logfile).st_size:
with open(logfile, "r") as read_file:
log = read_file.read().splitlines()
port = 0
for line in log: # Highly inefficient 'brute-force' check
# Grab the last open port number to use that for the alert
if (
" open " in line
and "/" in line[:7]
and line[: (line.index("/"))].isdecimal()
):
port = int(line[: (line.index("/"))])
for keyword in NMAP_INFO:
if f"{keyword}: " in line:
add_item(host_results, host, port, options, line, logging.INFO)
for keyword in NMAP_ALERTS:
if keyword in line:
add_item(host_results, host, port, options, line, ALERT)
except (IOError, OSError) as exception:
logging.error("FAILED: Could not read %s (%s)", logfile, exception)
def check_strings_for_alerts(
strings, keywords, host_results, host, port, options, negate=[]
):
"""Check for keywords in strings and log them as alerts."""
for line in strings: # Highly inefficient 'brute-force' check
for keyword in keywords:
if keyword in line:
if not negate:
add_item(host_results, host, port, options, line, ALERT)
else:
for item in negate:
if item in line:
line = ""
if line:
add_item(host_results, host, port, options, line, ALERT)
def add_item(host_results, host, port, options, line, logging_type):
"""Log item, and add line to the corresponding key in host_results.
Set options["exit"] code when alerts are found.
logging_type can be INFO or ALERT.
"""
# Don't log anything if no port has been set
if not port:
return
filtered_line = re.sub(REMOVE_PREPEND_LINE, "", line).strip()
if logging_type == logging.INFO:
key = "info"
else:
key = "alerts"
if options["exit_code"]:
options["exit"] = 1
if key not in host_results:
host_results[key] = {}
if port not in host_results[key]:
host_results[key][port] = [filtered_line]
else:
host_results[key][port].append(filtered_line)
logging.log(logging_type, f"{host}:{port} {filtered_line}")
def get_binary(tool):
"""Convert tool command to its environment variable, if it is set."""
if tool.split(".")[0].upper() in os.environ:
tool = os.environ[tool.split(".")[0].upper()]
return tool
def do_testssl(host, port, protocol, options, logfile, host_results):
"""Check SSL/TLS configuration and vulnerabilities."""
# --color 0 Don't use color escape codes
# --warnings off Skip connection warnings
# --quiet Don't output the banner
#
# The following settings are default, and can be overwritten using the 'testssl' parameter
# --each-cipher Checks each local cipher remotely
# --fs Check (perfect) forward secrecy settings
# --protocols Check TLS/SSL protocols
# --server-defaults Display the server's default picks and certificate info
# --starttls protocol Use starttls protocol
# --vulnerable Test for all vulnerabilities
if not options["testssl.sh"]:
return
command = [
get_binary("testssl.sh"),
"--color",
"0",
"--quiet",
"--warnings",
"off",
]
parameters = read_parameters(options["settings"], host, port)
if "testssl" in parameters:
for parameter in parameters["testssl"]:
command.append(parameter)
else:
command += [
"--each-cipher",
"--fs",
"--protocols",
"--server-defaults",
"--vulnerable",
]
if options["timeout"]:
command = [get_binary("timeout"), str(options["maxtime"])] + command
if "smtp" in protocol:
command += ["--starttls", "smtp"]
logging.info("%s Starting testssl.sh on port %s", host, port)
_result, stdout, _stderr = execute_command(
command + [f"{host}:{port}"], # pylint: disable=unused-variable
options,
logfile,
)
negate = []
if "testssl_untrusted" in parameters and bool(parameters["testssl_untrusted"]):
negate = TESTSSL_UNTRUSTED
check_strings_for_alerts(
stdout, TESTSSL_ALERTS, host_results, host, port, options, negate
)
def do_wpscan(url, port, options, logfile):
"""Run WPscan."""
if options["wpscan"]:
logging.info("Starting WPscan on " + url)
command = [
get_binary("wpscan"),
"--format",
"cli-no-color",
"--no-banner",
"--update",
"--ignore-main-redirect",
"--url",
url,
]
_result, _stdout, _stderr = execute_command(
command, options, logfile
) # pylint: disable=unused-variable
def prepare_queue(options):
"""Prepare a file which holds all hosts (targets) to scan."""
expanded = False
try:
if not options["inputfile"]:
expanded = next(
tempfile._get_candidate_names()
) # pylint: disable=protected-access
with open(expanded, "a") as inputfile:
inputfile.write(options["target"])
options["inputfile"] = expanded
with open(options["inputfile"], "r") as inputfile:
targets = []
for host in [
line for line in inputfile.read().splitlines() if line.strip()
]:
if options["dry_run"] or not re.match(r".*[\.:].*[-/][0-9]+", host):
targets.append(host)
else:
arguments = "-nsL"
scanner = nmap.PortScanner()
scanner.scan(hosts=f"{host}", arguments=arguments)
if "." in scanner.all_hosts():
targets += sorted(
scanner.all_hosts(),
key=lambda x: tuple(map(int, x.split("."))),
)
else:
targets += scanner.all_hosts()
with open(options["queuefile"], "a") as queuefile:
for target in targets:
queuefile.write(target + "\n")
if expanded:
os.remove(expanded)
except IOError as exception:
abort_program(f"Could not read/write file: {exception}")
def remove_from_queue(finished_queue, options, stop_event):
"""Remove a host from the queue file."""
while not stop_event.is_set() or finished_queue.qsize():
try:
host = finished_queue.get(block=False)
with open(options["queuefile"], "r+") as queuefile:
hosts = queuefile.read().splitlines()
queuefile.seek(0)
for i in hosts:
if i != host:
queuefile.write(i + "\n")
queuefile.truncate()
if not os.stat(options["queuefile"]).st_size:
os.remove(options["queuefile"])
finished_queue.task_done()
logging.debug("%s Removed from queue", host)
except queue.Empty:
time.sleep(1)
logging.debug("Exiting remove_from_queue thread")
def process_host(
options, host_queue, output_queue, finished_queue, stop_event, results
):
"""
Worker thread: Process each host atomic, add output files to output_queue,
and finished hosts to finished_queue.
"""
while host_queue.qsize() and not stop_event.wait(0.01):
try:
host = host_queue.get()
host_logfile = (
host + "-" + next(tempfile._get_candidate_names())
) # pylint: disable=protected-access
logging.debug(
"%s Processing (%s items left in host queue)", host, host_queue.qsize()
)
host_results = {}
open_ports = do_portscan(
host, options, host_logfile, stop_event, host_results
)
expected_ports = ALLOWED_OPEN_PORTS
if (
"targets" in options["settings"]
and host in options["settings"]["targets"]
and "allowed_ports" in options["settings"]["targets"][host]
):
expected_ports = options["settings"]["targets"][host]["allowed_ports"]
if open_ports:
if UNKNOWN in open_ports: