This repository was archived by the owner on Mar 23, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscan.py
More file actions
executable file
·1177 lines (905 loc) · 34.1 KB
/
scan.py
File metadata and controls
executable file
·1177 lines (905 loc) · 34.1 KB
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
# run service-specific scans based on the result of Nmap service scans.
import argparse
import asyncio
import csv
import curses
import datetime
import functools
import inspect
import ipaddress
import json
import os
import pathlib
import random
import re
import signal
import string
import subprocess
import sys
import time
import tomllib as toml
try:
# https://github.com/tiran/defusedxml
import defusedxml.ElementTree
except:
sys.exit("this script requires the 'defusedxml' module.\nplease install it via 'pip3 install defusedxml'.")
TITLE = "recon scanner"
PROGRESS_BAR_LENGTH = 10
PROGRESS_BAR_STYLES = {
'pipe': ['|', ':'],
'hash': ['#', ':'],
'dot': ['●', '⋅'],
}
PROGRESS_BAR_STYLE = 'pipe'
UI = None
TARGETS = {}
STOPPING = False
QUITTING = False
MAIN_PROGRESS_BAR_LENGTH = len("estimated time of completion: yyyy-mm-dd HH:MM") - len(TITLE) - 1
FOOTER_MESSAGES = [
"[q] quit: kill all running scans",
"[s] stop gracefully: wait for the currently running scans to finish",
]
# error/debug log
LOG_FILE = None
# default timeout (in seconds) after which a command will be cancelled
MAX_TIME = 60*60
PATH_TO_SCANNERS = pathlib.Path(
pathlib.Path(__file__).resolve().parent,
"scanners"
)
PATH_TO_DEFAULT_CONFIG_FILE = pathlib.Path(
pathlib.Path(__file__).resolve().parent,
"config",
"scanner.toml"
)
class UserInterface:
'''
`curses` user interface,
incl. keyboard event listener
'''
def __init__(self, window, screen_width, screen_height):
self.window = window
self.window.nodelay(True)
self.screen_height = screen_height
self.header = curses.newpad(4, screen_width)
self.main = curses.newpad(screen_height + 1, screen_width + 1)
self.footer = curses.newpad(len(FOOTER_MESSAGES), screen_width)
self.progress_x_pos = None
self.start_time = datetime.datetime.now()
self.progress = None
asyncio.create_task(self.listen_for_keypress())
async def listen_for_keypress(self):
global STOPPING, QUITTING
while True:
key = self.window.getch()
if key == -1:
await asyncio.sleep(0.1)
continue
if key == curses.KEY_RESIZE:
self.update()
continue
match chr(key):
case 'q':
QUITTING = True
cancel_tasks()
break
case 's':
STOPPING = True
self.update()
break
def estimate_time_of_completion(self):
if not self.progress:
return "estimating time of completion ..."
now = datetime.datetime.now()
duration = (now - self.start_time)
estimated_time_of_completion = self.start_time + duration / self.progress
return f"estimated time of completion: {estimated_time_of_completion.strftime('%Y-%m-%d %H:%M')}"
def render_progress(self, partial, total, length=PROGRESS_BAR_LENGTH, style=PROGRESS_BAR_STYLE):
progress = []
progress += [PROGRESS_BAR_STYLES[style][0]] * int(partial / total * length)
progress += [PROGRESS_BAR_STYLES[style][1]] * (length - len(progress))
return ''.join(progress)
def update_progress_x_pos(self):
self.progress_x_pos = 0
for target_address in TARGETS.keys():
name_length = len(target_address)
if name_length > self.progress_x_pos:
self.progress_x_pos = name_length
self.progress_x_pos += 1
def update(self):
if self.progress_x_pos is None:
self.update_progress_x_pos()
self.window.clear()
self.window.refresh()
screen_height, screen_width = self.window.getmaxyx()
self.main.clear()
line = 0
number_of_targets_completed = 0
number_of_scans_total = 0
number_of_scans_completed_total = 0
for target in TARGETS.values():
number_of_scans = len(target.scans)
number_of_scans_total += number_of_scans
number_of_scans_completed = target.number_of_scans_completed
number_of_scans_completed_total += number_of_scans_completed
if number_of_scans_completed == number_of_scans:
number_of_targets_completed += 1
continue
if not target.active:
continue
target_is_active = False
for scan in target.scans.values():
if scan.active and not scan.completed:
target_is_active = True
break
if not target_is_active:
continue
if line < self.screen_height:
self.main.addstr(line, 0, f"{target.address}")
if not STOPPING:
self.main.addstr(line, self.progress_x_pos, self.render_progress(number_of_scans_completed, number_of_scans))
line += 1
for scan in target.scans.values():
if line >= self.screen_height:
break
if not scan.active:
continue
scan_description = ': '.join(scan.description[1:])
self.main.addstr(line, 0, scan_description)
line += 1
line += 1
self.main.refresh(
0, 0,
4, 0,
screen_height - 1, screen_width - 1
)
self.progress = number_of_scans_completed_total / number_of_scans_total
self.header.clear()
self.header.addstr(0, 0, TITLE, curses.A_BOLD)
self.header.addstr(1, 0, f"running {number_of_scans_total} scans, targeting {len(TARGETS)} hosts")
if STOPPING:
self.header.addstr(0, len(TITLE) + 1, "... stopping ...", curses.A_BOLD)
self.header.addstr(2, 0, "waiting for the running scans to finish ...")
else:
self.header.addstr(
0, len(TITLE) + 1,
self.render_progress(
number_of_scans_completed_total,
number_of_scans_total,
length = MAIN_PROGRESS_BAR_LENGTH,
style = 'hash',
),
curses.A_BOLD,
)
self.header.addstr(2, 0, self.estimate_time_of_completion())
self.header.refresh(
0, 0,
0, 0,
screen_height - 1, screen_width - 1
)
self.footer.clear()
if not (STOPPING or QUITTING):
for n, msg in enumerate(FOOTER_MESSAGES):
self.footer.addstr(n, 0, msg, curses.A_DIM)
self.footer.refresh(
0, 0,
screen_height - len(FOOTER_MESSAGES), 0,
screen_height - 1, screen_width - 1
)
class Service:
def __init__(self, transport_protocol, port, application_protocol, description):
self.transport_protocol = transport_protocol.strip()
self.port = int(port)
self.application_protocol = application_protocol.strip()
self.description = description
self.scanned = False
class Target:
def __init__(self, address, directory):
self.semaphore = None # limiting the number of concurrently running scans
self.address = address.strip()
self.hostnames = []
self.directory = directory
self.services = []
self.scans = {} # dictionary of `Scan`s
self.active = False
self.number_of_scans_completed = 0
class ScanDefinition:
# as parsed from the scanner config (`scanner.toml`)
def __init__(self, service, name, command, run_once):
self.service = service
self.name = name.strip()
self.command = command.strip()
self.run_once = run_once
class Scan:
def __init__(self, target, host, port, description, command):
self.target = target
self.host = host.strip() # address or hostname
self.port = port
self.description = description # [<host>, <transport protocol>/<port>, <service>, <hostname>, <name>]
self.command = command.strip() # the command string
self.active = False
self.completed = False
self.return_code = None
def set_complete(self, return_code):
self.return_code = return_code
self.completed = True
self.active = False
self.target.number_of_scans_completed += 1
class CommandLog:
path = None
lock = None # ensures that only a single thread can write to the commands log
delimiter = ','
@classmethod
def init(cls, path, lock, header, delimiter):
cls.path = path
cls.lock = lock
cls.delimiter = delimiter
if not path.exists(): # do not overwrite the log
with open(cls.path, 'w') as f:
csv.writer(f, delimiter=delimiter, quoting=csv.QUOTE_MINIMAL, dialect='unix').writerow(header)
@classmethod
async def add_entry(cls, entry):
async with cls.lock:
with open(cls.path, 'a') as f:
csv.writer(f, delimiter=cls.delimiter, quoting=csv.QUOTE_MINIMAL, dialect='unix').writerow(entry)
def log(msg):
if not LOG_FILE:
return
with open(LOG_FILE, 'a') as f:
current_task = asyncio.current_task()
if current_task:
task_name = current_task.get_name()
else:
task_name = 'main'
method_name = inspect.stack()[1].function
f.write(f"[{task_name}]\t[{method_name}]\t{msg}\n")
def freeze_variables(*args, frame_index=1, **kvargs):
'''
this function's purpose is to correctly format f-strings [1] (e.g. commands),
defined in different frames (i.e. coroutines).
[1]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings
'''
frame = sys._getframe(frame_index)
vals = {}
vals.update(frame.f_globals)
vals.update(frame.f_locals)
vals.update(kvargs)
# add global variables from the config
if 'globals' in CONFIG:
vals.update(CONFIG['globals'])
return string.Formatter().vformat(' '.join(args), args, vals)
def create_summary(target: Target):
services_file = pathlib.Path(target.directory.parent, f'{target.address}.md')
with open(services_file, 'w') as f:
for service in target.services:
description = service.application_protocol
if service.description:
description = service.description
f.write(f"* {service.port} ({service.transport_protocol}): `{description}`\n")
async def run_command(scan: Scan):
# make sure that only a specific number of scans are running per target
async with scan.target.semaphore:
if STOPPING:
return
scan.active = True
UI.update()
scan_description = ': '.join(scan.description)
log(f"[{scan_description}]\tstarted")
timestamp_start = time.time()
return_code = 0
if DRY_RUN:
# add some random delay, just for fun
await asyncio.sleep(random.randrange(1, 10))
else:
# create/start the async process
process = await asyncio.create_subprocess_shell(
scan.command,
stdout = asyncio.subprocess.PIPE,
stderr = asyncio.subprocess.PIPE,
executable = '/bin/bash',
)
try:
# wait for the process to finish within the specified timeout (in seconds)
# https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for
await asyncio.wait_for(process.wait(), timeout=MAX_TIME)
return_code = process.returncode
if return_code is None:
return_code = 0
if return_code not in (0, 'timeout'):
error_msg = await process.stderr.read()
error_msg = error_msg.decode().strip()
log(f"[{scan_description}]\t{error_msg}")
except asyncio.exceptions.TimeoutError:
log(f"[{scan_description}]\ttimeout")
process.terminate()
return_code = "timeout"
except asyncio.exceptions.CancelledError:
log(f"[{scan_description}]\tcancelled")
return_code = "cancelled"
timestamp_completion = time.time()
await CommandLog.add_entry([timestamp_start, timestamp_completion, scan.host, scan.port, scan.command, return_code])
scan.set_complete(return_code)
UI.update()
if return_code not in ('timeout', 'cancelled'):
log(f"[{scan_description}]\tdone")
def find_suitable_scans(transport_protocol, application_protocol):
scan_definitions = []
# iterate over each service config
for service_config in CONFIG['services']:
service_name = service_config['name']
if 'transport_protocol' in service_config:
if not re.search(service_config['transport_protocol'], transport_protocol):
continue
if 'application_protocol' in service_config:
if not re.search(service_config['application_protocol'], application_protocol):
continue
# iterate over each scan of a specific service config
for scan_config in service_config['scans']:
scan_name = scan_config['name']
if 'transport_protocol' in scan_config:
if not re.search(scan_config['transport_protocol'], transport_protocol):
continue
if 'application_protocol' in scan_config:
if not re.search(scan_config['application_protocol'], application_protocol):
continue
log(f"suitable scan for '{transport_protocol}/{application_protocol}' found: '{service_name}:{scan_name}'")
scan_definitions.append(
ScanDefinition(
service_name,
scan_name,
scan_config['command'],
scan_config['run_once'] if 'run_once' in scan_config else False,
)
)
return scan_definitions
def result_file_exists(results_directory, file_name):
result_files = 0
for result_file in results_directory.glob(f'{file_name}.*'):
if OVERWRITE:
result_file.unlink()
else:
result_files += 1
if result_files > 0 and not OVERWRITE:
log(f"'{results_directory}/{file_name}.*' exists and we must not overwrite them.")
return True
def get_address_type(address):
try:
ip_address = ipaddress.ip_address(address)
match ip_address.version:
case 4:
return 'IPv4'
case 6:
return 'IPv6'
except ValueError:
return 'hostname'
def queue_service_scan_hostname(target: Target, service: Service, scan_definition: ScanDefinition):
'''
queue a scan of a service that recognizes the concept of a hostname in contrast/addition to an IP address (e.g. HTTP, TLS)
'''
results_directory = target.directory
# these variables are required for the scan command (i.e. `freeze_variables`)
transport_protocol = service.transport_protocol
port = service.port
application_protocol = service.application_protocol
address = target.address
hostnames = target.hostnames
if len(hostnames) == 0:
hostnames.append(address)
scheme = 'http'
if application_protocol.startswith('ssl|') or application_protocol.startswith('tls|'):
scheme = 'https'
application_protocol = 'http'
# we have to run the scan for each hostname associated with the target
for hostname in hostnames:
file_name = f'{scan_definition.service},{transport_protocol},{port},{hostname},{scan_definition.name}'
result_file = pathlib.Path(results_directory, file_name)
# run scan only if result file does not yet exist or "overwrite_results" flag is set
if result_file_exists(results_directory, file_name):
continue # with another hostname
scan_ID = (transport_protocol, port, application_protocol, hostname, scan_definition.service, scan_definition.name)
if scan_ID in target.scans:
continue # with another hostname
description = [
address,
f"{transport_protocol}/{port}",
scan_definition.service,
hostname,
scan_definition.name,
]
log(f"[{': '.join(description)}]")
address_type = get_address_type(hostname)
target.scans[scan_ID] = Scan(
target,
hostname,
port,
description,
freeze_variables(scan_definition.command),
)
def queue_service_scan_address(target: Target, service: Service, scan_definition: ScanDefinition):
'''
queue a scan of a service that does not recognize the concept of a hostname
'''
results_directory = target.directory
# these variables are required for the scan command (i.e. `freeze_variables`)
transport_protocol = service.transport_protocol
port = service.port
application_protocol = service.application_protocol
address = target.address
if '|' in application_protocol:
# e.g. "ssl|smtp" or "tls|smtp"
_, application_protocol = application_protocol.split('|')
# does this service belong to a group that should only be scanned once (e.g. SMB)?
if scan_definition.run_once:
file_name = f'{scan_definition.service},{scan_definition.name}'
result_file = pathlib.Path(results_directory, file_name)
# run scan only if result file does not yet exist or "overwrite_results" flag is set
if result_file_exists(results_directory, file_name):
return # continue with another service of the target
description = [
address,
scan_definition.service,
scan_definition.name,
]
scan_ID = (scan_definition.service, scan_definition.name)
if scan_ID in target.scans:
return # continue with another service of the target
else: # service does not belong to a group that should only be scanned once
file_name = f'{scan_definition.service},{transport_protocol},{port},{scan_definition.name}'
result_file = pathlib.Path(results_directory, file_name)
# run scan only if result file does not yet exist or "overwrite_results" flag is set
if result_file_exists(results_directory, file_name):
return # continue with another service of the target
description = [
address,
f"{transport_protocol}/{port}",
scan_definition.service,
scan_definition.name,
]
scan_ID = (transport_protocol, port, application_protocol, scan_definition.service, scan_definition.name)
if scan_ID in target.scans:
return # continue with another service of the target
log(f"[{': '.join(description)}]")
address_type = get_address_type(address)
target.scans[scan_ID] = Scan(
target,
address,
port,
description,
freeze_variables(scan_definition.command),
)
async def scan_services(target: Target):
address = target.address
log(f"[{address}]\tstarted")
tasks = set()
for scan in target.scans.values():
if STOPPING:
break
tasks.add(
asyncio.create_task(
run_command(scan)
)
)
await asyncio.gather(*tasks)
log(f"[{address}]\tdone")
async def scan_target(semaphore: asyncio.Semaphore, target: Target):
target.directory.mkdir(exist_ok=True)
# sort the target's services based on its port
target.services.sort(key=lambda service: service.port)
create_summary(target)
# make sure that only a specific number of targets are scanned in parallel
async with semaphore:
if STOPPING:
return
target.active = True
log(f"[{target.address}]")
await scan_services(target)
log(f"[{target.address}]\tdone")
def parse_result_file(base_directory, result_file, targets, unique_services, scan_filters):
# https://nmap.org/book/nmap-dtd.html
# nmaprun
# host
# address ("addr")
# hostnames
# hostname ("name", type="user")
# ports
# port (protocol, portid)
# state (state="open")
# service (name, product, version, extrainfo, tunnel, )
nmaprun = defusedxml.ElementTree.parse(result_file).getroot()
for host in nmaprun.iter('host'):
address = host.find('address').get('addr')
if address not in targets:
target = Target(address, pathlib.Path(base_directory, address))
targets[address] = target
else:
target = targets[address]
try:
hostname = host.find("./hostnames/hostname[@type='user']").get('name')
if hostname not in target.hostnames:
target.hostnames.append(hostname)
except:
pass
log(f"host: {address} ({','.join(target.hostnames)})")
for port in host.findall('./ports/port/state[@state="open"]/..'):
transport_protocol = port.get('protocol')
port_ID = port.get('portid')
service_tuple = (address, transport_protocol, port_ID)
if service_tuple in unique_services:
continue
log(f"service: {service_tuple}")
unique_services.append(service_tuple)
service = port.find('service')
if service is None:
application_protocol = 'unknown'
description = 'unknown'
else:
application_protocol = service.get('name')
# sometimes, Nmap identifies HTTPS as `name="http" ... tunnel="ssl"` instead of `name="https"`.
# we prepend the tunnel info to the application protocol:
# '<tunnel>|<application protocol>'
if service.get('tunnel'):
log(f"'{application_protocol}' is tunneled through '{service.get('tunnel')}'")
application_protocol = service.get('tunnel') + '|' + application_protocol
descriptions = []
if service.get('product'):
descriptions.append(service.get('product'))
if service.get('version'):
descriptions.append(service.get('version'))
if service.get('extrainfo'):
descriptions.append(service.get('extrainfo'))
description = " ".join(descriptions)
match_count = 0
for filter_key, filter_pattern in scan_filters:
if filter_key == 'host' and re.fullmatch(filter_pattern, address):
log(f"{filter_key} '{address}' matches '{filter_pattern}'")
match_count += 1
continue
if filter_key == 'protocol' and re.fullmatch(filter_pattern, transport_protocol):
log(f"{filter_key} '{transport_protocol}' matches '{filter_pattern}'")
match_count += 1
continue
if filter_key == 'port' and re.fullmatch(filter_pattern, port_ID):
log(f"{filter_key} '{port_ID}' matches '{filter_pattern}'")
match_count += 1
continue
if filter_key == 'service' and re.fullmatch(filter_pattern, application_protocol):
log(f"{filter_key} '{application_protocol}' matches '{filter_pattern}'")
match_count += 1
continue
if match_count == len(scan_filters):
log("targeting service")
target.services.append(
Service(
transport_protocol,
port_ID,
application_protocol,
description,
)
)
def parse_result_files(base_directory, result_files, scan_filters):
targets = {}
# a service is uniquely identified by the tuple (host, transport protocol, port number)
unique_services = []
for result_file in result_files:
print(f"parsing '{result_file}' ...")
log(f"parsing '{result_file}' ...")
parse_result_file(base_directory, result_file, targets, unique_services, scan_filters)
# filter targets with at least 1 service
return {key: target for key, target in targets.items() if len(target.services) > 0}
def update_scan_config(scan_config, new_scan_config):
log(f"updating scan '{scan_config['name']}' ...")
if 'transport_protocol' in new_scan_config:
log(f"updating transport protocol regex: '{new_scan_config['transport_protocol']}'")
scan_config['transport_protocol'] = new_scan_config['transport_protocol']
if 'application_protocol' in new_scan_config:
log(f"updating application protocol regex: '{new_scan_config['application_protocol']}'")
scan_config['application_protocol'] = new_scan_config['application_protocol']
if 'command' in new_scan_config:
log(f"updating command: '{new_scan_config['command']}'")
scan_config['command'] = new_scan_config['command']
if 'run_once' in scan_config:
log(f"updating run-once flag: '{new_scan_config['run_once']}'")
scan_config['run_once'] = new_scan_config['run_once']
def update_service_config(service_config, new_service_config):
log(f"updating service '{service_config['name']}' ...")
if 'transport_protocol' in new_service_config:
log(f"updating transport protocol regex: '{new_service_config['transport_protocol']}'")
service_config['transport_protocol'] = new_service_config['transport_protocol']
if 'application_protocol' in new_service_config:
log(f"updating application protocol regex: '{new_service_config['application_protocol']}'")
service_config['application_protocol'] = new_service_config['application_protocol']
if 'scans' not in new_service_config:
return
if 'scans' not in service_config:
log("setting scans")
service_config['scans'] = new_service_config['scans']
return
for scan_config in new_service_config['scans']:
scan_name = scan_config['name']
log(f"scan name: '{scan_name}'")
append_config = True
for sc in service_config['scans']:
if sc['name'] == scan_name:
update_scan_config(sc, scan_config)
append_config = False
break
if append_config:
log("appending scan")
service_config['scans'].append(scan_config)
def update_config(config, new_config):
if 'globals' in new_config:
# https://peps.python.org/pep-0584/
config['globals'] |= new_config['globals']
if 'services' not in new_config:
return
if 'services' not in config:
config['services'] = new_config['services']
return
for service_config in new_config['services']:
service_name = service_config['name']
append_config = True
for sc in config['services']:
if sc['name'] == service_name:
update_service_config(sc, service_config)
append_config = False
break
if append_config:
log(f"appending service '{service_name}'")
config['services'].append(service_config)
def load_config(config_files):
config = None
if not config_files:
log(f"loading default configuration file '{PATH_TO_DEFAULT_CONFIG_FILE}' ...")
if not PATH_TO_DEFAULT_CONFIG_FILE.exists():
log("the file does not exist")
sys.exit("the default configuration file does not exist!")
with open(PATH_TO_DEFAULT_CONFIG_FILE, 'rb') as f:
config = toml.load(f)
return config
# user-specified configuration files
for config_file_path in config_files:
log(f"loading config '{config_file_path}'")
if not config_file_path.exists():
log("the specified configuration file does not exist")
continue
with open(config_file_path, 'rb') as f:
match config_file_path.suffix.strip('.'):
case 'toml':
new_config = toml.load(f)
case 'json':
new_config = json.load(f)
case _:
log(f"unsupported file type: {config_file_path.suffix}")
continue
if config is None:
config = new_config
else:
log("updating config ...")
update_config(config, new_config)
return config
async def process(stdscr, args):
loop = asyncio.get_running_loop()
for signame in ('SIGINT', 'SIGTERM'):
loop.add_signal_handler(
getattr(signal, signame),
cancel_tasks
)
# hide cursor
curses.curs_set(0)
# necessary, otherwise the colors are inverted when running the scanner via SSH
curses.use_default_colors()
global DRY_RUN
DRY_RUN = args.dry_run
global OVERWRITE
OVERWRITE = args.overwrite_results
global MAX_TIME
MAX_TIME = args.max_time
if not os.geteuid() == 0 and not (args.ignore_uid or DRY_RUN):
sys.exit('depending on what commands/tools this script executes it might have to be run by the root user (i.e. with "sudo").\nyou could try and ignore this warning by using the `--ignore-uid` flag.')
# limit the number of concurrently scanned targets
concurrent_targets = asyncio.Semaphore(args.concurrent_targets)
base_directory = args.output.resolve()
base_directory.mkdir(exist_ok=True)
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
global LOG_FILE
LOG_FILE = pathlib.Path(
base_directory,
f'scanner_{timestamp}.log'
)
log(f"base directory: '{base_directory}'")
global CONFIG
CONFIG = load_config(args.config)
config_file = pathlib.Path(
base_directory,
f'config_{timestamp}.json'
)
log(f"writing configuration to '{config_file}' ...")
with open(config_file, 'w') as f:
json.dump(CONFIG, f)
CommandLog.init(
pathlib.Path(base_directory, 'commands.csv'),
asyncio.Lock(),
['start time', 'completion time', 'host', 'port', 'command', 'return code'],
args.delimiter
)
for input_path in args.input:
input_file = input_path.resolve()
if not input_file.exists():
sys.exit(f"input file '{input_file}' does not exist!")
if len(args.filter):
OVERWRITE = True
global TARGETS
TARGETS = parse_result_files(base_directory, args.input, args.filter)
log(f"parsed {len(TARGETS)} targets")
# find suitable scans for each target and queue them for later.
# this has to be done outside any subthread/task,
# so that the total number of scans is know from the start.
for target in TARGETS.values():
# iterate over the services found to be running on the target
for service in target.services:
transport_protocol = service.transport_protocol
application_protocol = service.application_protocol
suitable_scans = find_suitable_scans(transport_protocol, application_protocol)
# mark the service as "scanned" if at least 1 suitable scan was found; even though there is not even a scan scheduled yet
service.scanned = (len(suitable_scans) > 0)
# iterate over each suitable scan and queue it for later
for scan_definition in suitable_scans:
if scan_definition.service in ('http', 'tls'):
queue_service_scan_hostname(target, service, scan_definition)
else:
queue_service_scan_address(target, service, scan_definition)
# create services.csv file and initialize its header
with open(pathlib.Path(base_directory, 'services.csv'), 'w') as f:
csv.writer(f, delimiter=args.delimiter, quoting=csv.QUOTE_MINIMAL, dialect='unix').writerow(['host', 'transport_protocol', 'port', 'service', 'scanned'])
global UI
UI = UserInterface(stdscr, 80, args.concurrent_targets * (args.concurrent_scans + 2) + 4)
# each target in its own task ...
tasks = set()
for target in TARGETS.values():
# limit the number of concurrent scans per target
target.semaphore = asyncio.Semaphore(args.concurrent_scans)
tasks.add(
asyncio.create_task(
scan_target(