-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathspoonmap.py
More file actions
executable file
·4347 lines (3893 loc) · 197 KB
/
Copy pathspoonmap.py
File metadata and controls
executable file
·4347 lines (3893 loc) · 197 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
# Author: Spoonman (Larry.Spohn@TrustedSec.com)
# QA and Personal Pythonian Consultant: Bandrel (Justin.Bollinger@TrustedSec.com)
import contextlib
import datetime
import glob as _glob
import ipaddress
import json
import os
from pathlib import Path
import re
import resource
import shutil
import socket
import subprocess
import sys
import tempfile
import termios
import threading
import time
from queue import Queue
import xml.etree.ElementTree as etree
_COLOR_INFO = '\x1b[38;5;51m' # electric cyan — "currently doing X"
_COLOR_PROGRESS = '\x1b[38;5;118m' # neon lime green — completion status / results
_COLOR_RESULT = '\x1b[38;5;226m' # electric yellow — output paths / final summary
_COLOR_ERROR = '\x1b[38;5;198m' # hot pink — errors and warnings
_COLOR_RESET = '\x1b[0m'
def _raise_fd_limit():
"""Raise RLIMIT_NOFILE to 65535 (or the hard limit, whichever is lower).
Called as preexec_fn in every masscan subprocess so libpcap can open raw
sockets without hitting the default 1024-descriptor soft limit
("accept: Too many open files").
"""
try:
_, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (min(65535, hard), hard))
except (ValueError, resource.error):
pass # already at hard limit or no permission; masscan will error on its own
def verify_python_version():
import sys
if sys.version_info[0] == 2:
print('Python 3.6+ is required')
quit(1)
elif sys.version_info[0] == 3 and sys.version_info[1] < 6:
print('Python 3.6+ is required')
quit(1)
def save_terminal_state():
"""Save the current terminal state"""
try:
return termios.tcgetattr(sys.stdin)
except (termios.error, OSError):
return None
def restore_terminal_state(state):
"""Restore terminal state and reset terminal"""
if state:
try:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, state)
except (termios.error, OSError):
pass
# Always try to reset terminal using stty as a fallback
try:
subprocess.run(['stty', 'sane'], check=False, stderr=subprocess.DEVNULL)
except (OSError, subprocess.SubprocessError):
pass
def _format_eta(seconds):
s = int(seconds)
if s < 60:
return f'~{s} second{"s" if s != 1 else ""}'
m = s // 60
if m < 60:
return f'~{m} minute{"s" if m != 1 else ""}'
h, rem_m = divmod(m, 60)
if rem_m == 0:
return f'~{h} hour{"s" if h != 1 else ""}'
return f'~{h} hour{"s" if h != 1 else ""} {rem_m} minute{"s" if rem_m != 1 else ""}'
def _print_completion_status(label, completed, total, start_time):
pct = '{:.0%}'.format(completed / total)
msg = f'\n{label} Completion Status: {pct}'
remaining = total - completed
if completed >= 2 and remaining > 0:
elapsed = time.time() - start_time
eta = (elapsed / completed) * remaining
msg += f' — ETA: {_format_eta(eta)}'
print(_COLOR_PROGRESS + msg + _COLOR_RESET)
def _count_hosts_in_file(filepath):
"""Return total IP address count for all entries in a target/exclusions file.
Each line may be a bare IP, a CIDR, or a hostname.
CIDRs are expanded to their full address count via ipaddress.
Hostnames count as 1. Blank lines and # comments are skipped.
Returns None if the file cannot be opened.
"""
count = 0
try:
with open(filepath, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
try:
count += ipaddress.ip_network(line, strict=False).num_addresses
except ValueError:
count += 1 # hostname — resolves to one IP
except OSError:
return None
return count
def _build_discovery_target_file(target_file, exclusions_file, disc):
"""Pre-subtract exclusions from target ranges and write a masscan-ready file.
Masscan builds its randomization permutation over the full target space
before applying --excludefile, so passing a 3M-IP target with 2.96M
excluded hosts causes it to iterate at ~72 effective pps instead of 1000.
Pre-computing the difference here gives masscan a file containing only the
~230k IPs it will actually probe, restoring full rate efficiency.
Returns (filtered_file_path, accurate_host_count). If no exclusions apply,
returns (target_file, raw_count) unchanged so callers omit --excludefile.
"""
def _parse_ranges(filepath):
"""Parse IPs/CIDRs/ranges from a masscan-style target or exclude file.
Handles three formats masscan accepts but ipaddress rejects:
- Inline comments: 10.0.0.0/8 # note
- Range notation: 10.0.0.1-10.0.0.254
- Netmask notation: 10.0.0.0 255.255.0.0
"""
ranges = []
try:
with open(filepath) as fh:
for line in fh:
# Strip inline comments before parsing
line = line.split('#')[0].strip()
if not line:
continue
# Standard CIDR or bare IP
try:
net = ipaddress.ip_network(line, strict=False)
ranges.append((int(net.network_address),
int(net.broadcast_address)))
continue
except ValueError:
pass
# Range notation: A.B.C.D-E.F.G.H
if '-' in line:
parts = line.split('-', 1)
try:
start = int(ipaddress.IPv4Address(parts[0].strip()))
end = int(ipaddress.IPv4Address(parts[1].strip()))
if start <= end:
ranges.append((start, end))
continue
except ValueError:
pass
# Netmask notation: A.B.C.D M.M.M.M
parts = line.split()
if len(parts) == 2:
try:
net = ipaddress.ip_network(f'{parts[0]}/{parts[1]}', strict=False)
ranges.append((int(net.network_address),
int(net.broadcast_address)))
except ValueError:
pass
except OSError:
pass
return ranges
def _merge(ranges):
out = []
for s, e in sorted(ranges):
if out and s <= out[-1][1] + 1:
out[-1] = (out[-1][0], max(out[-1][1], e))
else:
out.append((s, e))
return out
def _subtract(targets, excls):
result = []
ei = 0
for ts, te in targets:
cur = ts
while ei < len(excls) and excls[ei][1] < cur:
ei += 1
j = ei
while j < len(excls) and excls[j][0] <= te:
es, ee = excls[j]
if es > cur:
result.append((cur, es - 1))
cur = max(cur, ee + 1)
if cur > te:
break
j += 1
if cur <= te:
result.append((cur, te))
return result
target_ranges = _parse_ranges(target_file)
if not target_ranges:
return target_file, 0
raw_count = sum(e - s + 1 for s, e in target_ranges)
if not exclusions_file or not os.path.exists(exclusions_file):
return target_file, raw_count
excl_ranges = _parse_ranges(exclusions_file)
if not excl_ranges:
return target_file, raw_count
remaining = _subtract(_merge(target_ranges), _merge(excl_ranges))
if not remaining:
filtered_file = os.path.join(disc, 'discovery_targets_filtered.txt')
open(filtered_file, 'w').close()
return filtered_file, 0
filtered_file = os.path.join(disc, 'discovery_targets_filtered.txt')
count = 0
with open(filtered_file, 'w') as fh:
for start, end in remaining:
for net in ipaddress.summarize_address_range(
ipaddress.IPv4Address(start), ipaddress.IPv4Address(end)):
fh.write(str(net) + '\n')
count += net.num_addresses
return filtered_file, count
def ascii_art(): # pragma: no cover -- cosmetic banner, no branches to verify
print(r'''
________ _____ _______ _________________
__ ___/______________________ | / /__ |/ /__ |__ __ \
_____ \___ __ \ __ \ __ \_ |/ /__ /|_/ /__ /| |_ /_/ /
____/ /__ /_/ / /_/ / /_/ / /| / _ / / / _ ___ | ____/
/____/ _ .___/\____/\____//_/ |_/ /_/ /_/ /_/ |_/_/
/_/
''')
def is_hostname(line):
"""
Determine if a line is a hostname (not an IP address or CIDR range)
Args:
line: The line to check
Returns:
True if the line appears to be a hostname, False if it's an IP/CIDR
"""
line = line.strip()
if not line or line.startswith('#'):
return False
# Check if it's a CIDR notation
if '/' in line:
return False
# Check if it's an IP address (simple regex)
ip_pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
if re.match(ip_pattern, line):
return False
# If it contains letters or is a domain-like string, treat as hostname
return True
def resolve_hostname(hostname):
"""
Resolve a hostname to an IP address
Args:
hostname: The hostname to resolve
Returns:
IP address string, or None if resolution fails
"""
try:
ip = socket.gethostbyname(hostname.strip())
return ip
except (socket.gaierror, socket.herror, OSError) as e:
print(_COLOR_ERROR + f'Warning: Could not resolve hostname {hostname}: {e}' + _COLOR_RESET)
return None
def _write_if_changed(path, content):
"""Write *content* to *path* only if it differs from the current contents.
Preserves the file's mtime when the content is unchanged so mtime-based
resume freshness checks stay valid across re-runs (e.g. an unchanged
resolved_targets.txt must not appear newer than the discovery output it
produced). Returns True if the file was (re)written, False if left as-is.
"""
try:
with open(path) as fh:
if fh.read() == content:
return False
except (OSError, UnicodeDecodeError):
pass # missing/unreadable → (re)write below
with open(path, 'w') as fh:
fh.write(content)
return True
def preprocess_targets(target_file, output_path):
"""
Preprocess the target file to separate hostnames from IPs.
Creates a resolved-IP target file and a hostname mapping file.
Args:
target_file: Path to the original target file
output_path: Directory for output files
Returns:
Tuple of (resolved_target_file, ip_to_hostname_map)
"""
ip_to_hostname = {}
masscan_targets = []
print(_COLOR_INFO + 'Preprocessing target file...' + _COLOR_RESET)
with open(target_file, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if is_hostname(line):
# Resolve hostname to IP
print(f'Resolving hostname: {line}')
ip = resolve_hostname(line)
if ip:
print(f' {line} -> {ip}')
ip_to_hostname[ip] = line
masscan_targets.append(ip)
else:
print(f' Skipping {line} (resolution failed)')
else:
# It's already an IP or CIDR, add as-is
masscan_targets.append(line)
# Write resolved IP list (used by both nmap and masscan paths). Rewritten
# only when the content changed, so an unchanged target set preserves the
# file's mtime and resume correctly skips discovery already completed against
# it; a changed target set bumps the mtime and forces re-discovery.
os.makedirs(_disc(output_path), exist_ok=True)
masscan_file = os.path.join(_disc(output_path), 'resolved_targets.txt')
_write_if_changed(masscan_file, ''.join(f'{target}\n' for target in masscan_targets))
# Save IP-to-hostname mapping (also content-stable to avoid needless churn)
mapping_file = os.path.join(_disc(output_path), 'ip_hostname_map.json')
_write_if_changed(mapping_file, json.dumps(ip_to_hostname, indent=2))
print(_COLOR_INFO + f'Resolved {len(ip_to_hostname)} hostnames to IPs' + _COLOR_RESET)
print(_COLOR_INFO + f'Target file: {masscan_file}' + _COLOR_RESET)
return masscan_file, ip_to_hostname
def _get_scripts_for_port(dest_port, target_scan):
"""Return comma-separated NSE script list for dest_port, or None.
On External scans, sensitive ports are additionally layered with vuln checks
(see _external_exposure_scripts) so their exposure findings carry known-vuln
status; duplicates are removed while preserving order.
"""
table = EXTERNAL_PORT_SCRIPTS if target_scan == 'External' else INTERNAL_PORT_SCRIPTS
scripts = table.get(dest_port)
if target_scan == 'External':
extra = _external_exposure_scripts(dest_port)
if extra:
merged = ','.join([scripts, extra]) if scripts else extra
seen, ordered = set(), []
for tok in (t.strip() for t in merged.split(',')):
if tok and tok not in seen:
seen.add(tok)
ordered.append(tok)
return ','.join(ordered)
return scripts
def _parse_masscan_ping_xml(xml_file):
"""Return set of IPs from a masscan --ping XML output file."""
ips = set()
if not os.path.exists(xml_file) or os.stat(xml_file).st_size == 0:
return ips
try:
root = etree.parse(xml_file)
for host in root.findall('host'):
addr_elem = host.find('address')
if addr_elem is not None:
ips.add(addr_elem.attrib['addr'])
except etree.ParseError:
pass
return ips
def _parse_nmap_sn_xml(xml_file):
"""Return set of IPs from a nmap -sn XML output where status is 'up'."""
ips = set()
if not os.path.exists(xml_file) or os.stat(xml_file).st_size == 0:
return ips
try:
root = etree.parse(xml_file)
for host in root.findall('host'):
status = host.find('status')
if status is not None and status.attrib.get('state') == 'up':
addr_elem = host.find('address')
if addr_elem is not None:
ips.add(addr_elem.attrib['addr'])
except etree.ParseError:
pass
return ips
def _discovery_wait(target_count: int) -> str:
"""Adaptive --wait value for masscan discovery sweeps based on target count."""
if target_count <= 512:
return '1'
if target_count <= 4096:
return '2'
return '3'
def _stream_masscan_progress(proc):
"""Read masscan stderr and display its \\r-based progress on one updating stdout line.
Masscan emits status using bare \\r (no \\n), so readline() would stall
until the process exits. Reading byte-by-byte and splitting on \\r lets
us display each update as it arrives. Clears the line when done.
"""
buf = b''
while True:
ch = proc.stderr.read(1)
if not ch:
break
if ch == b'\r':
line = buf.decode('utf-8', errors='replace').strip()
if line:
sys.stdout.write(f'\r {line:<78}')
sys.stdout.flush()
buf = b''
elif ch != b'\n':
buf += ch
sys.stdout.write('\r' + ' ' * 80 + '\r')
sys.stdout.flush()
def _discover_external_masscan(target_file, disc, max_rate, exclusions_file, target_count):
"""Single masscan TCP SYN sweep for external host discovery. Returns set of live IPs."""
xml_file = os.path.join(disc, 'discovery_masscan_external.xml')
print(_COLOR_INFO + 'Host discovery: running masscan (external)...' + _COLOR_RESET)
masscan_cmd = [
'masscan', '-p', DISCOVERY_MASSCAN_PORTS_EXTERNAL, '--open',
'--max-rate', max_rate,
'--retries', '2',
'-iL', target_file,
'-oX', xml_file,
'--wait', _discovery_wait(target_count),
]
if exclusions_file:
masscan_cmd.extend(['--excludefile', exclusions_file])
term_state = save_terminal_state()
progress_thread = None
try:
proc = subprocess.Popen(masscan_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
preexec_fn=_raise_fd_limit)
progress_thread = threading.Thread(target=_stream_masscan_progress, args=(proc,), daemon=True)
progress_thread.start()
proc.wait()
progress_thread.join()
except KeyboardInterrupt:
proc.kill()
proc.wait()
if progress_thread:
progress_thread.join()
restore_terminal_state(term_state)
raise
except FileNotFoundError:
print(_COLOR_ERROR + 'Error: masscan not found. Please install masscan.' + _COLOR_RESET)
restore_terminal_state(term_state)
return set()
finally:
restore_terminal_state(term_state)
ips = _parse_masscan_ping_xml(xml_file)
print(_COLOR_PROGRESS + f'Host discovery (masscan external): {len(ips)} host(s)' + _COLOR_RESET)
return ips
def _discover_internal_masscan(target_file, disc, max_rate, exclusions_file, target_count):
"""Single masscan TCP SYN sweep for internal host discovery. Returns set of live IPs.
Rate capped to INTERNAL_DISCOVERY_MAX_RATE. Port list trimmed to
DISCOVERY_TCP_PORTS_INTERNAL (5 ports) for target sets above
INTERNAL_DISCOVERY_STATE_CEILING to keep peak firewall state table entries bounded.
"""
if target_count > INTERNAL_DISCOVERY_STATE_CEILING:
tcp_port_str = DISCOVERY_TCP_PORTS_INTERNAL
else:
tcp_port_str = DISCOVERY_MASSCAN_PORTS_INTERNAL
capped_rate = str(min(int(max_rate), INTERNAL_DISCOVERY_MAX_RATE))
xml_file = os.path.join(disc, 'discovery_masscan_internal.xml')
print(_COLOR_INFO + 'Host discovery: running masscan (internal)...' + _COLOR_RESET)
masscan_cmd = [
'masscan', '-p', tcp_port_str, '--open',
'--max-rate', capped_rate,
'--retries', '1',
'-iL', target_file,
'-oX', xml_file,
'--wait', _discovery_wait(target_count),
]
if exclusions_file:
masscan_cmd.extend(['--excludefile', exclusions_file])
term_state = save_terminal_state()
progress_thread = None
try:
proc = subprocess.Popen(masscan_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
preexec_fn=_raise_fd_limit)
progress_thread = threading.Thread(target=_stream_masscan_progress, args=(proc,), daemon=True)
progress_thread.start()
proc.wait()
progress_thread.join()
except KeyboardInterrupt:
proc.kill()
proc.wait()
if progress_thread:
progress_thread.join()
restore_terminal_state(term_state)
raise
except FileNotFoundError:
print(_COLOR_ERROR + 'Error: masscan not found. Please install masscan.' + _COLOR_RESET)
restore_terminal_state(term_state)
return set()
finally:
restore_terminal_state(term_state)
ips = _parse_masscan_ping_xml(xml_file)
print(_COLOR_PROGRESS + f'Host discovery (masscan internal): {len(ips)} host(s)' + _COLOR_RESET)
return ips
def _external_host_discovery(target_file, disc, max_rate, exclusions_file, target_count):
"""Masscan TCP SYN sweep + nmap -sn for external host discovery.
Returns set of live IPs (union of both passes).
"""
masscan_ips = _discover_external_masscan(
target_file, disc, max_rate, exclusions_file, target_count)
nmap_ips = _nmap_host_discovery(target_file, disc, '', exclusions_file)
return masscan_ips | nmap_ips
def _internal_host_discovery(target_file, disc, max_rate, exclusions_file, target_count):
"""Masscan TCP SYN sweep + concurrent nmap -sn for internal host discovery.
For target sets ≤ HOST_DISCOVERY_NMAP_THRESHOLD, nmap -sn runs in a background
thread concurrently with the masscan sweep to eliminate the sequential wait.
Returns set of live IPs (union of both passes when nmap runs).
"""
nmap_ips: set = set()
nmap_errors: list = []
nmap_thread = None
if target_count <= HOST_DISCOVERY_NMAP_THRESHOLD:
def _run_nmap():
try:
result = _nmap_host_discovery(target_file, disc, '', exclusions_file)
nmap_ips.update(result)
except Exception as exc:
nmap_errors.append(exc)
nmap_thread = threading.Thread(target=_run_nmap, daemon=True)
nmap_thread.start()
try:
masscan_ips = _discover_internal_masscan(
target_file, disc, max_rate, exclusions_file, target_count)
except KeyboardInterrupt:
if nmap_thread is not None:
nmap_thread.join()
raise
if nmap_thread is not None:
nmap_thread.join()
if nmap_errors:
print(_COLOR_ERROR + f'Warning: nmap discovery error: {nmap_errors[0]}' + _COLOR_RESET)
return masscan_ips | nmap_ips
def _host_discovery(target_file, output_path, max_rate, exclusions_file,
scan_type='Internal', resume=False):
"""Run host discovery and write live_hosts_discovery.txt.
External scans run a single masscan TCP SYN sweep (curated safe ports) and
nmap -sn, then take the union for best coverage.
Internal scans run a single masscan TCP SYN sweep concurrently with nmap -sn
(for target sets ≤ HOST_DISCOVERY_NMAP_THRESHOLD). The masscan port list is
trimmed to 5 ports for target sets > INTERNAL_DISCOVERY_STATE_CEILING to
keep peak firewall state table entries bounded regardless of range size.
Returns live_hosts_discovery.txt path or None.
"""
disc = _disc(output_path)
os.makedirs(disc, exist_ok=True)
discovery_file = os.path.join(disc, 'live_hosts_discovery.txt')
# Resume: reuse cached discovery only if it is newer than the target file.
# If the target set changed since the cache was written, re-discover so
# newly added ranges are not silently skipped.
targets_mtime = os.path.getmtime(target_file) if os.path.exists(target_file) else 0
if (resume
and os.path.exists(discovery_file)
and os.path.getmtime(discovery_file) >= targets_mtime):
with open(discovery_file) as fh:
count = sum(1 for line in fh if line.strip())
print(_COLOR_INFO + f'Resume: skipping host discovery ({count} hosts cached)' + _COLOR_RESET)
return discovery_file
# Pre-subtract exclusions so masscan's permutation only covers actual targets.
# Without this, masscan iterates over the full target range at the configured
# rate and skips excluded IPs mid-permutation — reducing effective pps to
# rate × (included / total). The filtered file eliminates that overhead.
filtered_target, target_count = _build_discovery_target_file(
target_file, exclusions_file, disc)
# Exclusions are now baked into filtered_target; pass None so sub-functions
# don't also add --excludefile to masscan/nmap command lines.
discovery_excl = None if filtered_target != target_file else exclusions_file
if filtered_target != target_file:
print(_COLOR_INFO
+ f'Host discovery: pre-filtered to {target_count:,} target IPs'
+ _COLOR_RESET)
if scan_type == 'External':
live_ips = _external_host_discovery(
filtered_target, disc, max_rate, discovery_excl, target_count)
else: # Internal
live_ips = _internal_host_discovery(
filtered_target, disc, max_rate, discovery_excl, target_count)
total = len(live_ips)
print(_COLOR_PROGRESS + f'Host discovery total: {total} unique live host(s)' + _COLOR_RESET)
if not live_ips:
print(_COLOR_ERROR
+ 'Warning: host discovery found 0 live hosts — probe will scan full target range.'
+ _COLOR_RESET)
return None
with open(discovery_file, 'w') as fh:
for ip in sorted(live_ips, key=lambda x: tuple(int(o) for o in x.split('.'))):
fh.write(ip + '\n')
return discovery_file
def _nmap_host_discovery(target_file, disc, source_port, exclusions_file):
"""Run nmap -sn (ICMP echo probe only); return set of live IPs."""
output_xml = os.path.join(disc, 'discovery_nmap.xml')
cmd = [
'nmap', '-sn', '-T4',
'--min-parallelism', '256',
'--max-retries', '1',
'-PE', # ICMP echo only — TCP SYN probes risk RST from routers for non-existent hosts
*(['--source-port', source_port] if source_port else []),
'-iL', target_file,
'-oX', output_xml,
]
if exclusions_file:
cmd += ['--excludefile', exclusions_file]
print(_COLOR_INFO + 'Host discovery: running nmap -sn...' + _COLOR_RESET)
term_state = save_terminal_state()
try:
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
proc.wait()
except KeyboardInterrupt:
proc.kill()
proc.wait()
restore_terminal_state(term_state)
raise
except FileNotFoundError:
print(_COLOR_ERROR + 'Error: nmap not found.' + _COLOR_RESET)
restore_terminal_state(term_state)
return set()
finally:
restore_terminal_state(term_state)
live_ips = set()
if not os.path.exists(output_xml) or os.stat(output_xml).st_size == 0:
return live_ips
try:
root = etree.parse(output_xml)
for host in root.findall('host'):
status = host.find('status')
if status is None or status.attrib.get('state') != 'up':
continue
addr = host.find('address[@addrtype="ipv4"]')
if addr is not None:
live_ips.add(addr.attrib['addr'])
except etree.ParseError as e:
print(_COLOR_ERROR + f'Error parsing nmap discovery XML: {e}' + _COLOR_RESET)
print(_COLOR_PROGRESS + f'Host discovery (nmap -sn): {len(live_ips)} host(s)' + _COLOR_RESET)
return live_ips
def _run_masscan_batch(batch, rate, output_file, target_file, source_port, exclusions_file, wait_secs=2):
"""Run masscan for one batch and return {port_key: set_of_ips}."""
masscan_cmd = [
'masscan',
'-p', ','.join(batch),
'--open',
'--max-rate', rate,
*(['--source-port', source_port] if source_port else []),
'-iL', target_file,
'-oX', output_file,
'--retries', '4',
'--wait', str(max(3, wait_secs)),
]
if exclusions_file:
masscan_cmd.extend(['--excludefile', exclusions_file])
term_state = save_terminal_state()
try:
masscan_process = subprocess.Popen(
masscan_cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=_raise_fd_limit,
)
masscan_process.wait()
except KeyboardInterrupt:
print(f'Killing PID {str(masscan_process.pid)}...')
masscan_process.kill()
masscan_process.wait()
restore_terminal_state(term_state)
raise
except FileNotFoundError:
print(_COLOR_ERROR + 'Error: masscan not found. Please install masscan.' + _COLOR_RESET)
restore_terminal_state(term_state)
quit(1)
except Exception as e:
print(_COLOR_ERROR + f'Error running masscan: {e}' + _COLOR_RESET)
restore_terminal_state(term_state)
quit(1)
finally:
restore_terminal_state(term_state)
if masscan_process.returncode == 1:
quit(1)
if not os.path.exists(output_file) or os.stat(output_file).st_size == 0:
return {}
results = {}
try:
root = etree.parse(output_file)
for host in root.findall('host'):
ip_address = host.findall('address')[0].attrib['addr']
ports_elem = host.find('ports')
if ports_elem is not None:
port_elem = ports_elem.find('port')
if port_elem is not None:
protocol = port_elem.attrib.get('protocol', 'tcp')
portid = port_elem.attrib.get('portid', '')
port_key = f'U:{portid}' if protocol == 'udp' else portid
results.setdefault(port_key, set()).add(ip_address)
except etree.ParseError as e:
print(_COLOR_ERROR + f'Error parsing masscan XML: {e}' + _COLOR_RESET)
return results
def _select_probe_ports(dest_ports, max_ports=5, priority=None):
"""Return up to max_ports ports from dest_ports, priority ports first."""
if priority is None:
priority = PROBE_PORT_PRIORITY
dest_set = set(dest_ports)
probe = [p for p in priority if p in dest_set][:max_ports]
if len(probe) < max_ports:
probed = set(probe)
extras = [p for p in dest_ports if p not in probed]
probe = probe + extras[:max_ports - len(probe)]
return probe
def _calc_scan_wait(host_count, rate):
"""Return --wait seconds for masscan to prevent inter-scan saturation.
Small target ranges (e.g. /24) complete each port scan in a fraction of a
second, creating a sharp traffic burst that saturates the network for ~30 s.
Larger ranges take longer to scan, spreading the load so no cooldown is
needed. Returns 0 when scan_duration >= recovery_window.
The recovery_window scales linearly with host count up to /24 (256 hosts).
Very small targets (e.g. 4 discovered hosts) send so few packets that no
saturation occurs and no inter-scan wait is needed.
"""
if not host_count or host_count <= 0:
return 2 # safe default when count is unknown
scan_duration = host_count / max(1, int(rate))
# Calibrated at 30 s for /24 (256 hosts). Scale proportionally for
# smaller bursts — fewer hosts → fewer packets → less network stress.
recovery_window = 30 * min(host_count, 256) / 256
return max(0, int(recovery_window - scan_duration))
def _disc(output_path):
"""Return the discovery subdirectory path."""
return os.path.join(output_path, 'discovery')
def _port_fname(key: str) -> str:
"""Return a filesystem-safe filename stem for a port key.
'U:631' → 'U_631' (colon → underscore so NTFS/HGFS shares don't mangle it)
'445' → '445' (TCP keys are unchanged)
"""
return key.replace(':', '_')
def _fname_port(stem: str) -> str:
"""Reverse of _port_fname: convert a filename stem back to a port key.
'U_631' → 'U:631'
'445' → '445'
"""
if stem.startswith('U_'):
return 'U:' + stem[2:]
return stem
# Result dirs and files written during a scan run.
_RESULT_DIRS = ('discovery', 'nmap_results', 'nse_results', 'live_hosts')
_RESULT_FILES = ('all_live_hosts.txt', 'spoonmap_output.xml',
'spoonmap_output.json',
'findings.txt', 'findings.md', 'findings.json')
def _previous_results_exist(output_path):
"""Return True if any prior scan output is present under output_path."""
for d in _RESULT_DIRS:
p = os.path.join(output_path, d)
if os.path.isdir(p) and os.listdir(p):
return True
for f in _RESULT_FILES:
if os.path.exists(os.path.join(output_path, f)):
return True
return False
def _delete_previous_results(output_path):
"""Remove all prior scan output under output_path."""
for d in _RESULT_DIRS:
p = os.path.join(output_path, d)
if os.path.isdir(p):
shutil.rmtree(p)
for f in _RESULT_FILES:
p = os.path.join(output_path, f)
if os.path.exists(p):
os.remove(p)
def _nmap_udp_discovery(udp_port, target_file, output_path, source_port,
exclusions_file, resume=False):
"""Run nmap UDP scan for a single port; return set of candidate IPs.
Uses --open (which in nmap captures 'open' and 'open|filtered' states) so
that protocol-specific services only detectable by NSE probes are not missed
by the banner/script phase. The resulting IPs are written to
live_hosts/portU_N.txt (colon-free for NTFS compatibility) for consumption by nmap_scan().
"""
port_num = udp_port[2:] # strip 'U:'
output_file = f'{_disc(output_path)}/masscan_results/port{_port_fname(udp_port)}.xml'
# Resume: reuse cached UDP results only if newer than the target file, so a
# changed target set forces a re-scan rather than reusing stale hosts.
targets_mtime = os.path.getmtime(target_file) if os.path.exists(target_file) else 0
if (resume
and os.path.exists(output_file)
and os.path.getmtime(output_file) >= targets_mtime):
live_file = f'{_disc(output_path)}/live_hosts/port{_port_fname(udp_port)}.txt'
if os.path.exists(live_file):
with open(live_file) as fh:
return {line.strip() for line in fh if line.strip()}
return set()
cmd = [
'nmap', '-T4', '-sU', '-Pn',
'-p', port_num,
'--open',
'--max-retries', '2',
'--host-timeout', '30s',
'--min-rate', '500',
*(['--source-port', source_port] if source_port else []),
'-iL', target_file,
'-oX', output_file,
]
if exclusions_file:
cmd += ['--excludefile', exclusions_file]
print(_COLOR_INFO + f'UDP discovery: scanning port {port_num} with nmap...' + _COLOR_RESET)
term_state = save_terminal_state()
try:
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
proc.wait()
except KeyboardInterrupt:
proc.kill()
proc.wait()
restore_terminal_state(term_state)
raise
except FileNotFoundError:
print(_COLOR_ERROR + 'Error: nmap not found.' + _COLOR_RESET)
restore_terminal_state(term_state)
return set()
finally:
restore_terminal_state(term_state)
ips = set()
if not os.path.exists(output_file) or os.stat(output_file).st_size == 0:
return ips
try:
root = etree.parse(output_file)
for host in root.findall('host'):
addr = host.find('address[@addrtype="ipv4"]')
if addr is None:
continue
ip = addr.attrib['addr']
for port_elem in host.findall('.//port'):
state_elem = port_elem.find('state')
if state_elem is not None and state_elem.attrib.get('state') in ('open', 'open|filtered'):
ips.add(ip)
except etree.ParseError as e:
print(_COLOR_ERROR + f'Error parsing nmap UDP XML: {e}' + _COLOR_RESET)
return ips
def _nmap_port_discovery(dest_ports, target_file, source_port, exclusions_file,
scan_type='Full', resume=False, max_rate=None, total_hosts=None):
"""Run nmap -T4 port discovery in place of masscan for small target sets.
Writes live_hosts/port{N}.txt files in the same format as mass_scan() so
the downstream nmap_scan() banner/script phase is unaffected.
Returns a status_summary string matching the mass_scan() convention.
"""
disc = _disc(output_path)
os.makedirs(f'{disc}/masscan_results', exist_ok=True)
os.makedirs(f'{disc}/live_hosts', exist_ok=True)
output_file = f'{disc}/masscan_results/portDirect.xml'
targets_mtime = os.path.getmtime(target_file) if os.path.exists(target_file) else 0
status_summary = '\nSummary'
# Resume: if output already exists and is newer than the targets file, reload from live_hosts/
if (resume
and os.path.exists(output_file)
and os.path.getmtime(output_file) >= targets_mtime):
print(_COLOR_INFO + 'Resume: skipping completed nmap port discovery' + _COLOR_RESET)
live_hosts_dir = f'{disc}/live_hosts'
if os.path.exists(live_hosts_dir):
for fname in sorted(os.listdir(live_hosts_dir)):
if not (fname.startswith('port') and fname.endswith('.txt')
and not fname.endswith('_hostnames.txt')):
continue
port_key = _fname_port(fname[4:-4])
with open(os.path.join(live_hosts_dir, fname)) as fh:
ips = {line.strip() for line in fh if line.strip()}
if ips:
status_update = f'\nHosts Found on Port {port_key}: {len(ips)}'
status_summary += status_update
print(_COLOR_PROGRESS + status_update + _COLOR_RESET)
return status_summary
# UDP ports are handled separately via _nmap_udp_discovery(); only TCP here.
if scan_type == 'Full':
port_spec = '1-65535'
else:
port_spec = ','.join(dest_ports)
scan_flags = ['-sS']
try:
with open(target_file) as _tf:
_target_count = sum(1 for ln in _tf if ln.strip())