-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathscancannon.sh
More file actions
executable file
·2680 lines (2376 loc) · 102 KB
/
Copy pathscancannon.sh
File metadata and controls
executable file
·2680 lines (2376 loc) · 102 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
#!/bin/bash
set -euo pipefail
# This script is safe to `source`: the top level only defines functions and
# globals. The imperative flow lives in main(), invoked at the very bottom and
# only when the file is executed directly (see the BASH_SOURCE guard there).
# The test suite relies on this to load the real functions without running a scan.
#Logging
LOG_FILE="scancannon.log"
# ===== PROJECT / OUTPUT LAYOUT =====
# Scans are grouped into projects so results from different engagements stay
# separate. A project lives under ./projects/<slug>/ with its own results/ and
# history/ (scan snapshots for diffing). RESULTS_DIR defaults to ./results —
# used by the test suite and as a fallback — and the project menu repoints it
# under the selected project.
PROJECTS_ROOT="./projects"
PROJECT_SLUG=""
PROJECT_DIR=""
RESULTS_DIR="./results"
# Public Suffix List (downloaded on demand for -d runs) for accurate
# registrable-domain extraction; falls back to a built-in table when absent.
PSL_FILE="./public_suffix_list.dat"
# Scan-diff state (populated by _sc_compute_changes, rendered by generate_report).
DELTA_ADDED=0
DELTA_REMOVED=0
DELTA_BASELINE=""
_sc_start() {
exec > >(tee -a "$LOG_FILE") 2>&1
echo ""
echo "███████╗ ██████╗ █████╗ ███╗ ██╗ ██████╗ █████╗ ███╗ ██╗███╗ ██╗ ██████╗ ███╗ ██╗";
echo "██╔════╝██╔════╝██╔══██╗████╗ ██║██╔════╝██╔══██╗████╗ ██║████╗ ██║██╔═══██╗████╗ ██║";
echo "███████╗██║ ███████║██╔██╗ ██║██║ ███████║██╔██╗ ██║██╔██╗ ██║██║ ██║██╔██╗ ██║";
echo "╚════██║██║ ██╔══██║██║╚██╗██║██║ ██╔══██║██║╚██╗██║██║╚██╗██║██║ ██║██║╚██╗██║";
echo "███████║╚██████╗██║ ██║██║ ╚████║╚██████╗██║ ██║██║ ╚████║██║ ╚████║╚██████╔╝██║ ╚████║";
echo "╚══════╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═══╝";
echo -e "••¤(×[¤ ScanCannon v1.9 by J0hnnyXm4s ¤]×)¤••\n"
}
# ===== PROGRESS TRACKING SYSTEM =====
# Progress tracking variables
PROGRESS_FILE="./scancannon_progress.tmp"
SCRIPT_START_TIME=$(date +%s)
TOTAL_PHASES=0
CURRENT_PHASE=0
SPINNER_CHARS="⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
SPINNER_INDEX=0
# Calculate total phases upfront. Each CIDR is now a single orchestrated phase
# (the heavy per-CIDR work happens inside scan_cidr), plus a fixed set of
# setup/finalize phases: init, TLD download, packet filters, finalizing,
# aggregating, generating report — 6 in total, padded to 8 for headroom.
calculate_total_phases() {
local phases=$(( 8 + ${#CIDR_RANGES[@]} ))
TOTAL_PHASES=$phases
echo "$phases" > "$PROGRESS_FILE"
echo "0" >> "$PROGRESS_FILE" # current phase
}
# Visual progress bar with spinner
show_progress_with_spinner() {
local percent="$1"
local message="$2"
local bar_length=40
local filled_length=$((percent * bar_length / 100))
# Create progress bar
local bar=""
for ((i=0; i<filled_length; i++)); do bar+="█"; done
for ((i=filled_length; i<bar_length; i++)); do bar+="░"; done
# Get spinner character
local spinner_char="${SPINNER_CHARS:$((SPINNER_INDEX % ${#SPINNER_CHARS})):1}"
SPINNER_INDEX=$((SPINNER_INDEX + 1))
printf "\r%s [%s] %3d%% %s" "$spinner_char" "$bar" "$percent" "$message"
}
# Enhanced progress with time estimation
track_phase_progress() {
local phase_name="$1"
local current_target="${2:-}"
CURRENT_PHASE=$((CURRENT_PHASE + 1))
local current_time
current_time=$(date +%s)
local elapsed=$((current_time - SCRIPT_START_TIME))
# Calculate ETA
local eta_formatted="calculating..."
if [ "$CURRENT_PHASE" -gt 1 ]; then
local avg_time_per_phase=$((elapsed / CURRENT_PHASE))
local remaining_phases=$((TOTAL_PHASES - CURRENT_PHASE))
local eta_seconds=$((remaining_phases * avg_time_per_phase))
local eta_time=$((current_time + eta_seconds))
if [ "$MACOS" -eq 1 ]; then
eta_formatted=$(date -r "$eta_time" '+%H:%M:%S')
else
eta_formatted=$(date -d "@$eta_time" '+%H:%M:%S')
fi
fi
local percent=$((CURRENT_PHASE * 100 / TOTAL_PHASES))
[ "$percent" -gt 100 ] && percent=100
# Update progress file
echo "$CURRENT_PHASE" > "${PROGRESS_FILE}.tmp" && mv "${PROGRESS_FILE}.tmp" "$PROGRESS_FILE"
echo "$percent" >> "$PROGRESS_FILE"
# Format message with target if provided
local full_message="$phase_name"
if [ -n "$current_target" ]; then
full_message="$phase_name ($current_target)"
fi
# Show visual progress
show_progress_with_spinner "$percent" "$full_message"
# Also log detailed progress
printf "\n[Phase %d/%d] %s | ETA: %s | Elapsed: %dm%ds\n" \
"$CURRENT_PHASE" "$TOTAL_PHASES" "$full_message" "$eta_formatted" \
"$((elapsed / 60))" "$((elapsed % 60))"
}
# Cleanup progress files
cleanup_progress() {
rm -f "$PROGRESS_FILE" "${PROGRESS_FILE}.tmp" 2>/dev/null
}
# Detect OS early — needed by many helpers, and harmless when sourced.
if [ "$(uname)" = "Darwin" ]; then MACOS=1; else MACOS=0; fi
# Check for updates (only when run directly; skipped when sourced by tests).
_sc_check_for_updates() {
# Use the same branch name for checking and pulling
REMOTE_TIMESTAMP1=$(git log origin/master -n 1 --pretty=format:%cd scancannon.sh | awk '{print $1, $3, $2, $5, $4}')
LOCAL_TIMESTAMP=$(date -r "scancannon.sh" +%s)
if [ "$MACOS" = 1 ]; then
REMOTE_TIMESTAMP=$(date -j -f "%a %d %b %Y %T" "$REMOTE_TIMESTAMP1" +%s)
else
REMOTE_TIMESTAMP=$(date -d "$REMOTE_TIMESTAMP1" +%s)
fi
if [[ "$REMOTE_TIMESTAMP" -gt "$LOCAL_TIMESTAMP" ]]; then
read -r -p "A new version of ScanCannon is available. Do you want to update? [y/N]: " update_choice
case "$update_choice" in
y|Y )
if git pull origin master; then
echo "ScanCannon has been updated successfully."
else
echo "Failed to update ScanCannon via git. Please manually download the latest version from https://github.com/johnnyxmas/ScanCannon/"
fi
;;
* )
echo "Update skipped. Continuing with the current version."
;;
esac
fi
}
#Help Text:
function helptext() {
echo -e "\nScanCannon: a program to enumerate and parse a large range of public networks, primarily for determining potential attack vectors"
echo "usage: scancannon.sh [-u] [-a] [-V] [-n target] -d domain | -c CIDR | -f file (at least one target required)"
echo ""
echo " -d domain Resolve a domain to its owning CIDR range via whois (repeatable)"
echo " Accepts a bare domain (example.com) or URL (https://sub.example.com/path)"
echo " URLs are automatically stripped to domain + TLD"
echo " -c CIDR Specify a CIDR range directly (repeatable)"
echo " -f file Read CIDR ranges from a file, one per line (repeatable)"
echo " Blank lines and lines beginning with '#' are ignored"
echo " File entries are scanned as-is (ASN discovery is skipped)"
echo " -F Force ASN-based network discovery on -f file entries"
echo " (default: file entries scan as-is; use -F to expand them)"
echo " -u Perform UDP scan on common ports (53, 161, 500) using nmap"
echo " -a Perform API endpoint detection on HTTP/HTTPS services (requires curl)"
echo " Also harvests TLS certificate SANs to discover more hostnames"
echo " -V CVE hinting: run nmap's 'vulners' NSE against detected versions"
echo " -n target Notify on completion. 'target' is either 'desktop' (macOS/notify-send)"
echo " or a webhook URL (ntfy/Slack-style POST, requires curl)"
echo " -p name Project name. Results go under ./projects/<name>/ and are diffed"
echo " against that project's previous scan. Skips the interactive"
echo " project menu (useful for automation)"
echo ""
echo " At least one -d, -c, or -f flag is required. You may combine them."
echo ""
echo " Environment tunables:"
echo " NMAP_MAX_PARALLEL hosts scanned concurrently per CIDR (default 4)"
echo " DNS_MAX_PARALLEL domains resolved concurrently (default 8)"
echo " CIDR_MAX_PARALLEL CIDR ranges scanned concurrently (default 1)"
echo " WHOIS_CACHE_TTL whois cache lifetime in seconds (default 86400)"
echo ""
echo " Examples:"
echo " scancannon.sh -d example.com"
echo " scancannon.sh -c 203.0.113.0/24"
echo " scancannon.sh -f CIDRs.txt"
echo " scancannon.sh -d https://example.com -c 10.0.0.0/24 -f CIDRs.txt"
echo " scancannon.sh -uaV -d example.com"
echo " scancannon.sh -a -n desktop -c 203.0.113.0/24"
echo " scancannon.sh -n https://ntfy.sh/my-scans -d example.com"
}
# Function to validate CIDR notation
function validate_cidr() {
local cidr="$1"
local line_num="$2"
local file_name="$3"
# Skip empty lines and comments
if [[ -z "$cidr" || "$cidr" =~ ^[[:space:]]*# ]]; then
return 0
fi
# Single awk call for comprehensive validation
echo "$cidr" | awk -v line_num="$line_num" -v file_name="$file_name" '
{
# Remove leading/trailing whitespace
gsub(/^[[:space:]]+|[[:space:]]+$/, "")
# Split IP and CIDR parts
if (match($0, /^([0-9]{1,3}\.){3}[0-9]{1,3}(\/[0-9]+)?$/)) {
split($0, parts, "/")
ip = parts[1]
cidr = parts[2]
# Validate IP octets
split(ip, octets, ".")
if (length(octets) != 4) {
print "ERROR: Invalid IP address format '\''" $0 "'\'' in " file_name " at line " line_num
exit 1
}
for (i in octets) {
if (octets[i] < 0 || octets[i] > 255 || octets[i] !~ /^[0-9]+$/) {
print "ERROR: Invalid IP octet '\''" octets[i] "'\'' in '\''" $0 "'\'' in " file_name " at line " line_num
exit 1
}
}
# Validate CIDR if present
if (cidr != "" && (cidr < 0 || cidr > 32)) {
print "ERROR: Invalid CIDR notation '\''/" cidr "'\'' in '\''" $0 "'\'' in " file_name " at line " line_num
exit 1
}
exit 0
} else {
print "ERROR: Invalid CIDR format '\''" $0 "'\'' in " file_name " at line " line_num
print "Expected format: x.x.x.x or x.x.x.x/y (where x is 0-255 and y is 0-32)"
exit 1
}
}'
}
# Function to extract base domain+TLD from a URL or hostname
# e.g. "https://sub.example.com/path?q=1" → "example.com"
# e.g. "mail.example.co.uk" → "example.co.uk" (best-effort for 2-part TLDs)
# Read a CIDR list file: echo each normalized, validated CIDR (bare IPs -> /32),
# skipping blank lines and '#' comments. Returns 1 (message on stderr) on the
# first invalid entry so callers can abort with file/line context.
read_cidr_file() {
local file="$1" line num=0
while IFS= read -r line || [ -n "$line" ]; do
num=$((num + 1))
# strip leading/trailing whitespace
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
[ -z "$line" ] && continue
case "$line" in \#*) continue ;; esac
if ! validate_cidr "$line" "$num" "$file" >&2; then
return 1
fi
# normalize a bare IP to /32
if [[ "$line" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
line="${line}/32"
fi
printf '%s\n' "$line"
done < "$file"
return 0
}
# Download/refresh the Public Suffix List (>30 days old or missing). Best-effort:
# on failure extract_domain falls back to the built-in MULTI_LABEL_SUFFIXES table.
ensure_psl() {
local max_age=$((30 * 86400)) need=1
if [ -s "$PSL_FILE" ]; then
local mtime now
now=$(date +%s)
if [ "${MACOS:-0}" -eq 1 ]; then
mtime=$(stat -f %m "$PSL_FILE" 2>/dev/null || echo 0)
else
mtime=$(stat -c %Y "$PSL_FILE" 2>/dev/null || echo 0)
fi
[ $((now - mtime)) -lt "$max_age" ] && need=0
fi
[ "$need" -eq 0 ] && return 0
echo "Fetching Public Suffix List for accurate domain extraction..."
if wget -q https://publicsuffix.org/list/public_suffix_list.dat -O "${PSL_FILE}.tmp" 2>/dev/null; then
mv "${PSL_FILE}.tmp" "$PSL_FILE"
else
rm -f "${PSL_FILE}.tmp"
echo " WARNING: could not fetch PSL; using the built-in ccTLD table."
fi
return 0
}
# Reduce a hostname to its registrable domain using Public Suffix List rules
# (handles wildcard '*' and exception '!' rules). Reads $PSL_FILE.
public_suffix_domain() {
awk -v host="$1" -v pslfile="$PSL_FILE" '
function join(A, a, b, s, k) { s=""; for (k=a; k<=b; k++) s = s (k>a?".":"") A[k]; return s }
BEGIN {
while ((getline line < pslfile) > 0) {
gsub(/\r/, "", line)
if (line == "" || line ~ /^\/\//) continue
sub(/[ \t].*/, "", line) # first field only
if (line == "") continue
if (substr(line,1,1) == "!") exc[substr(line,2)] = 1
else rule[line] = 1
}
n = split(host, L, ".")
if (n < 2) { print host; exit }
found = 0; ps_start = n # default rule "*": suffix = last label
for (i = 1; i <= n; i++) # exception rules take precedence
if (join(L,i,n) in exc) { ps_start = i + 1; found = 1; break }
if (!found)
for (i = 1; i <= n; i++) { # longest (most-labels) match wins
if (join(L,i,n) in rule) { ps_start = i; break }
if (i < n && ("*." join(L,i+1,n)) in rule) { ps_start = i; break }
}
reg_start = ps_start - 1
if (reg_start < 1) reg_start = ps_start # host is itself a public suffix
print join(L, reg_start, n)
}'
}
# Known multi-label public suffixes. IANA's TLD list only contains single
# labels (uk, au, ...), so registrable domains under these (example.co.uk) need
# an explicit table to avoid collapsing to the suffix itself (co.uk). This is a
# pragmatic subset of the Public Suffix List, used when $PSL_FILE is unavailable.
MULTI_LABEL_SUFFIXES=(
co.uk org.uk gov.uk ac.uk me.uk ltd.uk plc.uk net.uk sch.uk
com.au net.au org.au edu.au gov.au id.au
co.nz net.nz org.nz govt.nz ac.nz
co.za org.za net.za gov.za ac.za
co.jp or.jp ne.jp go.jp ac.jp ad.jp
com.br net.br org.br gov.br edu.br
com.cn net.cn org.cn gov.cn edu.cn
com.mx com.ar com.tr com.sg com.hk com.tw com.ua com.pl com.ru
co.in net.in org.in gov.in co.kr or.kr co.il org.il
)
function extract_domain() {
local input="$1"
# Strip protocol (http://, https://, ftp://, etc.)
local hostname
hostname=$(echo "$input" | sed -E 's|^[a-zA-Z]+://||')
# Strip path, query string, port, trailing slashes
hostname=$(echo "$hostname" | sed -E 's|[:/].*||; s|/$||')
# Strip "www." prefix
hostname=$(echo "$hostname" | sed -E 's|^www\.||i')
# Normalize case (domains are case-insensitive)
hostname=$(echo "$hostname" | tr '[:upper:]' '[:lower:]')
if [ -z "$hostname" ]; then
echo ""
return 1
fi
# Prefer the Public Suffix List when present (downloaded during -d setup);
# fall back to the built-in table offline and in tests.
if [ -s "$PSL_FILE" ]; then
local reg
reg=$(public_suffix_domain "$hostname")
if [ -n "$reg" ]; then
echo "$reg"
return 0
fi
fi
local nlabels
nlabels=$(echo "$hostname" | awk -F'.' '{print NF}')
if [ "$nlabels" -le 2 ]; then
echo "$hostname"
return 0
fi
# If the final two labels form a known multi-label suffix (co.uk, com.au),
# keep three labels; otherwise the registrable domain is the last two.
local last2 suffix
last2=$(echo "$hostname" | awk -F'.' '{print $(NF-1)"."$NF}')
for suffix in "${MULTI_LABEL_SUFFIXES[@]}"; do
if [ "$last2" = "$suffix" ]; then
echo "$hostname" | awk -F'.' '{print $(NF-2)"."$(NF-1)"."$NF}'
return 0
fi
done
echo "$hostname" | awk -F'.' '{print $(NF-1)"."$NF}'
}
# ===== NETWORK DISCOVERY ENGINE =====
# Shared infrastructure for both -d (domain) and -c (CIDR) inputs.
# Pipeline: IP → whois (CIDR + ASN + Org) → RADB (all ASN prefixes) → interactive selection
# ----- whois with on-disk cache + retry/backoff -----
# Large ASN sweeps fire many whois queries (network discovery AND per-domain
# resolution). whois servers routinely rate-limit, producing empty replies and
# "N/A,N/A,N/A" gaps. cached_whois() serves fresh cached answers, retries with
# backoff on empty replies, and falls back to a stale cache entry rather than
# returning nothing. Same argument vector as `whois`, e.g.:
# cached_whois 203.0.113.1
# cached_whois -h whois.radb.net -- "-i origin AS64500"
WHOIS_CACHE_DIR="${WHOIS_CACHE_DIR:-./.scancannon_cache/whois}"
WHOIS_CACHE_TTL="${WHOIS_CACHE_TTL:-86400}" # seconds; default 1 day
WHOIS_MAX_RETRIES="${WHOIS_MAX_RETRIES:-3}"
cached_whois() {
mkdir -p "$WHOIS_CACHE_DIR" 2>/dev/null || true
local key cache_file
# Key on the full argument vector so IP and RADB queries don't collide.
key=$(printf '%s' "$*" | cksum | awk '{print $1 "_" $2}')
cache_file="${WHOIS_CACHE_DIR}/${key}"
# Serve a fresh, non-empty cache hit.
if [ -s "$cache_file" ]; then
local now mtime
now=$(date +%s)
if [ "${MACOS:-0}" -eq 1 ]; then
mtime=$(stat -f %m "$cache_file" 2>/dev/null || echo 0)
else
mtime=$(stat -c %Y "$cache_file" 2>/dev/null || echo 0)
fi
if [ $((now - mtime)) -lt "$WHOIS_CACHE_TTL" ]; then
cat "$cache_file"
return 0
fi
fi
# Query live, retrying with linear backoff on empty replies.
local attempt=1 out=""
while [ "$attempt" -le "$WHOIS_MAX_RETRIES" ]; do
out=$(whois "$@" 2>/dev/null)
if [ -n "$out" ]; then
printf '%s' "$out" > "$cache_file" 2>/dev/null || true
printf '%s' "$out"
return 0
fi
sleep $((attempt * 2))
attempt=$((attempt + 1))
done
# All live attempts failed — better a stale answer than none.
if [ -s "$cache_file" ]; then
cat "$cache_file"
return 0
fi
return 1
}
# Helper: convert an IP range (start - end) to CIDR notation
function inetnum_to_cidr() {
local start_ip="$1"
local end_ip="$2"
local IFS='.'
read -r a b c d <<< "$start_ip"
local start_int=$(( (a << 24) + (b << 16) + (c << 8) + d ))
read -r a b c d <<< "$end_ip"
local end_int=$(( (a << 24) + (b << 16) + (c << 8) + d ))
unset IFS
local diff=$(( end_int - start_int + 1 ))
local prefix=32
local size=1
while [ "$size" -lt "$diff" ] && [ "$prefix" -gt 0 ]; do
prefix=$((prefix - 1))
size=$((size * 2))
done
echo "${start_ip}/${prefix}"
}
# Helper: extract the first IP from a CIDR (network address)
function cidr_first_ip() {
echo "$1" | cut -d'/' -f1
}
# Extract ALL CIDRs from whois output (not just the first match)
function extract_cidrs_from_whois() {
local whois_output="$1"
local cidrs=()
# ARIN format: CIDR lines (may contain comma-separated ranges)
while IFS= read -r line; do
# Split comma-separated CIDRs on one line
local cleaned
cleaned=$(echo "$line" | sed 's/^CIDR:[[:space:]]*//')
IFS=',' read -ra parts <<< "$cleaned"
for part in "${parts[@]}"; do
part=$(echo "$part" | tr -d '[:space:]')
if [ -n "$part" ]; then
cidrs+=("$part")
fi
done
done < <(echo "$whois_output" | grep -i '^CIDR:')
# RIPE/APNIC format: inetnum lines → convert to CIDR
while IFS= read -r line; do
local range
range=$(echo "$line" | sed 's/^[^:]*:[[:space:]]*//')
local range_start range_end
range_start=$(echo "$range" | awk -F' - ' '{gsub(/[[:space:]]/, "", $1); print $1}')
range_end=$(echo "$range" | awk -F' - ' '{gsub(/[[:space:]]/, "", $2); print $2}')
if [ -n "$range_start" ] && [ -n "$range_end" ]; then
local c
c=$(inetnum_to_cidr "$range_start" "$range_end")
if [ -n "$c" ]; then cidrs+=("$c"); fi
fi
done < <(echo "$whois_output" | grep -i '^inetnum:')
# NetRange lines → convert to CIDR
while IFS= read -r line; do
local range
range=$(echo "$line" | sed 's/^[^:]*:[[:space:]]*//')
local range_start range_end
range_start=$(echo "$range" | awk -F' - ' '{gsub(/[[:space:]]/, "", $1); print $1}')
range_end=$(echo "$range" | awk -F' - ' '{gsub(/[[:space:]]/, "", $2); print $2}')
if [ -n "$range_start" ] && [ -n "$range_end" ]; then
local c
c=$(inetnum_to_cidr "$range_start" "$range_end")
if [ -n "$c" ]; then cidrs+=("$c"); fi
fi
done < <(echo "$whois_output" | grep -i '^NetRange:')
# route: field
while IFS= read -r line; do
local r
r=$(echo "$line" | awk '{print $2}')
if [ -n "$r" ]; then cidrs+=("$r"); fi
done < <(echo "$whois_output" | grep -iE '^route:')
# Deduplicate and print
if [ ${#cidrs[@]} -gt 0 ]; then
printf '%s\n' "${cidrs[@]}" | sort -u -t'/' -k1,1V -k2,2n
fi
}
# Extract ASN(s) from whois output
function extract_asn_from_whois() {
local whois_output="$1"
local asns=()
# ARIN format: OriginAS
while IFS= read -r line; do
local asn
asn=$(echo "$line" | sed 's/^[^:]*:[[:space:]]*//' | grep -oE 'AS[0-9]+')
if [ -n "$asn" ]; then asns+=("$asn"); fi
done < <(echo "$whois_output" | grep -i '^OriginAS:')
# RIPE/APNIC format: origin
while IFS= read -r line; do
local asn
asn=$(echo "$line" | sed 's/^[^:]*:[[:space:]]*//' | grep -oE 'AS[0-9]+')
if [ -n "$asn" ]; then asns+=("$asn"); fi
done < <(echo "$whois_output" | grep -i '^origin:')
# Deduplicate
if [ ${#asns[@]} -gt 0 ]; then
printf '%s\n' "${asns[@]}" | sort -u
fi
}
# Extract organization name from whois output
# Checks fields in priority order: OrgName > org-name > descr > netname
function extract_org_from_whois() {
local whois_output="$1"
local result=""
# Check in priority order — OrgName is most authoritative. Covers ARIN
# (OrgName/Organization), RIPE/APNIC (org-name/descr/netname).
for field in 'OrgName' 'Organization' 'org-name' 'descr' 'netname'; do
result=$(echo "$whois_output" | grep -i "^${field}:" | head -1 | sed 's/^[^:]*:[[:space:]]*//')
if [ -n "$result" ]; then
echo "$result"
return 0
fi
done
echo ""
}
# Extract ALL org-related strings from whois for cloud detection
# Returns all unique values from OrgName, org-name, netname, descr fields
function extract_all_org_fields() {
local whois_output="$1"
echo "$whois_output" | grep -iE '^(OrgName|org-name|descr|netname|Organization):' | \
sed 's/^[^:]*:[[:space:]]*//' | sort -u
}
# ===== CLOUD / VPS PROVIDER DETECTION =====
# Check if the organization name belongs to a major cloud/VPS provider.
# Scanning these shared-infrastructure ranges is not useful for target enumeration
# because the CIDR ranges belong to the provider, not the target organization.
# Returns 0 (true) if cloud provider detected, 1 (false) otherwise.
CLOUD_PROVIDER_PATTERNS=(
"amazon"
"google"
"microsoft"
"digitalocean"
"vultr"
"choopa"
"constant company"
"linode"
"akamai"
"oracle"
"ovh"
"hetzner"
"cloudflare"
"alibaba"
"alicloud"
"softlayer"
"ibm cloud"
"rackspace"
"fastly"
"scaleway"
"upcloud"
"kamatera"
"leaseweb"
"contabo"
"hostinger"
"ionos"
)
function is_cloud_provider() {
local org_name="$1"
if [ -z "$org_name" ]; then
return 1
fi
local org_lower
org_lower=$(echo "$org_name" | tr '[:upper:]' '[:lower:]')
for pattern in "${CLOUD_PROVIDER_PATTERNS[@]}"; do
if [[ "$org_lower" == *"$pattern"* ]]; then
return 0
fi
done
return 1
}
# Query RADB (or similar IRR) for all prefixes announced by an ASN
function discover_asn_prefixes() {
local asn="$1"
local prefixes=()
echo " Querying RADB for all prefixes announced by $asn..."
local radb_output
radb_output=$(cached_whois -h whois.radb.net -- "-i origin $asn")
if [ -n "$radb_output" ]; then
while IFS= read -r line; do
local prefix
prefix=$(echo "$line" | awk '{print $2}')
if [ -n "$prefix" ]; then
prefixes+=("$prefix")
fi
done < <(echo "$radb_output" | grep -iE '^route:')
fi
# Deduplicate and print
if [ ${#prefixes[@]} -gt 0 ]; then
printf '%s\n' "${prefixes[@]}" | sort -u -t'/' -k1,1V -k2,2n
fi
}
# Full network discovery for a single IP address
# Returns all discovered CIDR ranges via DISCOVERED_RANGES array
function discover_networks_for_ip() {
local ip="$1"
local source_label="${2:-$ip}"
DISCOVERED_RANGES=()
DISCOVERED_ORG=""
DISCOVERED_ASNS=()
echo " Looking up $ip via whois..."
local whois_output
whois_output=$(cached_whois "$ip")
if [ -z "$whois_output" ]; then
echo " WARNING: whois returned no data for $ip"
return 1
fi
# Extract organization
DISCOVERED_ORG=$(extract_org_from_whois "$whois_output")
# Check if the IP belongs to a cloud/VPS provider
# Check primary org name AND all org-related whois fields for thorough detection
local cloud_detected=false
local cloud_match_org="$DISCOVERED_ORG"
if is_cloud_provider "$DISCOVERED_ORG"; then
cloud_detected=true
else
# Also check all org-related fields (OrgName, netname, descr, Organization)
while IFS= read -r org_field; do
if [ -n "$org_field" ] && is_cloud_provider "$org_field"; then
cloud_detected=true
cloud_match_org="$org_field"
break
fi
done < <(extract_all_org_fields "$whois_output")
fi
if [ "$cloud_detected" = true ]; then
echo ""
echo " ╔══════════════════════════════════════════════════════════════╗"
echo " ║ ⚠️ CLOUD/VPS PROVIDER DETECTED ║"
echo " ╠══════════════════════════════════════════════════════════════╣"
printf " ║ IP : %-49s║\n" "$ip"
printf " ║ Org : %-49s║\n" "${cloud_match_org:0:49}"
echo " ╠══════════════════════════════════════════════════════════════╣"
echo " ║ This IP is hosted on shared cloud/VPS infrastructure. ║"
echo " ║ The CIDR ranges belong to the provider, NOT the target. ║"
echo " ║ Scanning these ranges would scan the entire provider's ║"
echo " ║ network, which is not useful and potentially dangerous. ║"
echo " ╚══════════════════════════════════════════════════════════════╝"
echo ""
read -r -p " Do you still want to proceed with network discovery for this IP? [y/N]: " cloud_choice
case "$cloud_choice" in
y|Y )
echo " Proceeding with cloud-hosted network discovery as requested."
;;
* )
echo " Skipping this IP."
return 2 # Cloud provider skipped by user choice
;;
esac
fi
# Extract direct CIDRs from whois
local direct_cidrs
direct_cidrs=$(extract_cidrs_from_whois "$whois_output")
# Extract ASNs
local asn_list
asn_list=$(extract_asn_from_whois "$whois_output")
if [ -n "$asn_list" ]; then
while IFS= read -r asn; do
DISCOVERED_ASNS+=("$asn")
done <<< "$asn_list"
fi
# Collect all prefixes: direct whois CIDRs + ASN-announced prefixes
local all_prefixes=()
# Add direct CIDRs
if [ -n "$direct_cidrs" ]; then
while IFS= read -r cidr; do
all_prefixes+=("$cidr")
done <<< "$direct_cidrs"
fi
# Query RADB for each ASN
if [ ${#DISCOVERED_ASNS[@]} -gt 0 ]; then
for asn in "${DISCOVERED_ASNS[@]}"; do
local asn_prefixes
asn_prefixes=$(discover_asn_prefixes "$asn")
if [ -n "$asn_prefixes" ]; then
while IFS= read -r prefix; do
all_prefixes+=("$prefix")
done <<< "$asn_prefixes"
fi
done
fi
# Deduplicate final list
if [ ${#all_prefixes[@]} -gt 0 ]; then
while IFS= read -r range; do
DISCOVERED_RANGES+=("$range")
done < <(printf '%s\n' "${all_prefixes[@]}" | sort -u -t'/' -k1,1V -k2,2n)
fi
}
# Interactive range selection — present discovered ranges, let user choose
# Sets SELECTED_RANGES array with the user's selections
function interactive_range_selection() {
local source_label="$1"
shift
local ranges=("$@")
SELECTED_RANGES=()
if [ ${#ranges[@]} -eq 0 ]; then
echo " No CIDR ranges discovered."
return 1
fi
if [ ${#ranges[@]} -eq 1 ]; then
echo ""
echo " Discovered 1 CIDR range for $source_label:"
echo " [1] ${ranges[0]}"
echo ""
echo " WARNING: Make sure you have authorization to scan this network!"
read -r -p " Proceed with scanning ${ranges[0]}? [y/N]: " confirm
case "$confirm" in
y|Y ) SELECTED_RANGES=("${ranges[0]}"); return 0 ;;
* ) echo " Scan cancelled."; return 1 ;;
esac
fi
echo ""
echo " ╔══════════════════════════════════════════════════════════════╗"
echo " ║ Network Discovery Results ║"
echo " ╠══════════════════════════════════════════════════════════════╣"
printf " ║ Source : %-50s║\n" "${source_label:0:50}"
if [ -n "$DISCOVERED_ORG" ]; then
printf " ║ Org : %-50s║\n" "${DISCOVERED_ORG:0:50}"
fi
if [ ${#DISCOVERED_ASNS[@]} -gt 0 ]; then
local asn_str
asn_str=$(printf '%s ' "${DISCOVERED_ASNS[@]}")
printf " ║ ASN(s) : %-50s║\n" "${asn_str:0:50}"
fi
printf " ║ Ranges : %-50s║\n" "${#ranges[@]} CIDR block(s) discovered"
echo " ╚══════════════════════════════════════════════════════════════╝"
echo ""
echo " Discovered CIDR ranges:"
for i in "${!ranges[@]}"; do
printf " [%2d] %s\n" "$((i + 1))" "${ranges[$i]}"
done
echo ""
echo " WARNING: Make sure you have authorization to scan these networks!"
echo ""
echo " Enter your selection:"
echo " • 'all' — scan all discovered ranges"
echo " • comma-separated nums — e.g. '1,3,5' to select specific ranges"
echo " • 'none' or empty — cancel"
echo ""
read -r -p " Selection: " selection
# Parse selection
if [ -z "$selection" ] || [ "$selection" = "none" ]; then
echo " Scan cancelled."
return 1
fi
if [ "$selection" = "all" ]; then
SELECTED_RANGES=("${ranges[@]}")
echo " Selected all ${#ranges[@]} range(s)."
return 0
fi
# Parse comma-separated numbers
IFS=',' read -ra nums <<< "$selection"
for num in "${nums[@]}"; do
num=$(echo "$num" | tr -d '[:space:]')
if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le ${#ranges[@]} ]; then
SELECTED_RANGES+=("${ranges[$((num - 1))]}")
else
echo " WARNING: Ignoring invalid selection '$num'"
fi
done
if [ ${#SELECTED_RANGES[@]} -eq 0 ]; then
echo " No valid ranges selected. Scan cancelled."
return 1
fi
echo " Selected ${#SELECTED_RANGES[@]} range(s)."
return 0
}
# ===== HIGH-LEVEL DISCOVERY FUNCTIONS =====
# Resolve a domain (-d flag) to CIDR ranges via full ASN discovery pipeline
function resolve_domain_to_cidr() {
local input="$1"
# Extract clean domain+TLD (strips URLs, subdomains, paths)
local hostname
hostname=$(extract_domain "$input")
if [ -z "$hostname" ]; then
echo "ERROR: Could not extract domain from '$input'"
return 1
fi
echo " Input: $input"
echo " Domain: $hostname"
echo ""
# Resolve ALL A records for the domain
echo " Resolving all A records for $hostname..."
local all_ips=()
while IFS= read -r ip; do
if [ -n "$ip" ]; then
all_ips+=("$ip")
fi
done < <(dig +short "$hostname" A 2>/dev/null | grep -E '^[0-9]+\.')
if [ ${#all_ips[@]} -eq 0 ]; then
echo "ERROR: Could not resolve '$hostname' to any IP address."
echo "Make sure the hostname is correct and DNS is reachable."
return 1
fi
echo " Found ${#all_ips[@]} IP(s): ${all_ips[*]}"
echo ""
# Run full discovery for each unique IP, collect all ranges
local all_ranges=()
local all_asns=()
local org_name=""
local cloud_skip_count=0
for ip in "${all_ips[@]}"; do
echo " ── Discovering networks for IP: $ip ──"
local disc_rc=0
discover_networks_for_ip "$ip" "$hostname" || disc_rc=$?
if [ "$disc_rc" -eq 2 ]; then
# Cloud provider detected for this IP — skip it
cloud_skip_count=$((cloud_skip_count + 1))
continue
elif [ "$disc_rc" -ne 0 ]; then
echo " WARNING: Network discovery failed for $ip (exit code $disc_rc), skipping."
continue
fi
if [ -n "$DISCOVERED_ORG" ] && [ -z "$org_name" ]; then
org_name="$DISCOVERED_ORG"
fi
if [ ${#DISCOVERED_ASNS[@]} -gt 0 ]; then
for asn in "${DISCOVERED_ASNS[@]}"; do
all_asns+=("$asn")
done
fi
if [ ${#DISCOVERED_RANGES[@]} -gt 0 ]; then
for range in "${DISCOVERED_RANGES[@]}"; do
all_ranges+=("$range")
done
fi
done
# If ALL IPs were cloud-hosted, return error
if [ "$cloud_skip_count" -eq "${#all_ips[@]}" ]; then
echo ""
echo " ERROR: All ${#all_ips[@]} IP(s) for '$hostname' are hosted on cloud/VPS providers."
echo " No scannable networks found. Skipping this domain."
return 2
fi
# Deduplicate
local unique_ranges=()
if [ ${#all_ranges[@]} -gt 0 ]; then
while IFS= read -r range; do
unique_ranges+=("$range")
done < <(printf '%s\n' "${all_ranges[@]}" | sort -u -t'/' -k1,1V -k2,2n)
fi
local unique_asns=()
if [ ${#all_asns[@]} -gt 0 ]; then
while IFS= read -r asn; do
unique_asns+=("$asn")
done < <(printf '%s\n' "${all_asns[@]}" | sort -u)
fi
# Store for display in interactive_range_selection
DISCOVERED_ORG="$org_name"
if [ ${#unique_asns[@]} -gt 0 ]; then
DISCOVERED_ASNS=("${unique_asns[@]}")
else
DISCOVERED_ASNS=()
fi
# Interactive selection
if interactive_range_selection "$hostname" "${unique_ranges[@]}"; then
RESOLVED_CIDRS=("${SELECTED_RANGES[@]}")
return 0
else
return 1
fi
}
# Discover related networks for a -c CIDR range via ASN discovery pipeline
function discover_networks_for_cidr() {
local cidr_input="$1"