forked from nitefood/asn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasn
More file actions
executable file
·4874 lines (4612 loc) · 211 KB
/
Copy pathasn
File metadata and controls
executable file
·4874 lines (4612 loc) · 211 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 bash
# ╭──────────────────────────────────────────────────────────────────────────────────────╮
# │ ASN / IPv4 / IPv6 / Prefix / AS Path / Organization lookup and server tool │
# │ │
# │Project homepage: │
# │ │
# │ https://github.com/nitefood/asn │
# │ │
# │Usage: │
# │ │
# │ (Launch the script without parameters or visit the project's homepage for usage info)│
# ╰──────────────────────────────────────────────────────────────────────────────────────╯
ASN_VERSION="0.81.0"
# ╭──────────────────╮
# │ Helper functions │
# ╰──────────────────╯
docurl(){
# shellcheck disable=SC2124
if [ "$ASN_DEBUG" = true ]; then
sed_args=()
[ -n "$IPINFO_TOKEN" ] && sed_args+=("-e" "s/$IPINFO_TOKEN/######/g")
[ -n "$IQS_TOKEN" ] && sed_args+=("-e" "s/$IQS_TOKEN/######/g")
[ -n "$CLOUDFLARE_TOKEN" ] && sed_args+=("-e" "s/$CLOUDFLARE_TOKEN/######/g")
if [ "${#sed_args[@]}" -gt 0 ]; then
# mask API tokens in debug output to prevent accidental exposure
parm=$(sed "${sed_args[@]}" <<<"$@")
else
parm="$@"
fi
DebugPrint "${yellow}curl $parm${default}"
curloutput=$(curl "$@")
echo "$curloutput"
curloutput_jsonp=$(jq -C '.' <<<"$curloutput" 2>/dev/null)
[[ -n "$curloutput_jsonp" ]] && echo -e "$curloutput_jsonp" >> "$ASN_LOGFILE" || echo "$curloutput" >> "$ASN_LOGFILE"
echo "" >> "$ASN_LOGFILE"
else
curl "$@"
fi
}
WhoisASN(){
found_asname=$(host -t TXT "AS${1}.asn.cymru.com" | grep -v "NXDOMAIN" | awk -F'|' 'NR==1{print substr($NF,2,length($NF)-2)}')
if [ -n "$found_asname" ]; then
((json_resultcount++))
pwhois_full_asn_info=$(whois -h whois.pwhois.org "registry source-as=$1")
# fetch last org only (in case there are multiple orgs listed for this AS)
pwhois_asn_info=$(tac <<<"$pwhois_full_asn_info" | grep -m1 -E "^Org-Name")
pwhois_asn_info+="\n"
pwhois_asn_info+=$(tac <<<"$pwhois_full_asn_info" | grep -m1 -E "^Create-Date")
found_holder=$(docurl -m5 -s "https://stat.ripe.net/data/as-overview/data.json?resource=AS$1&sourceapp=nitefood-asn" | jq -r 'select (.data.holder != null) | .data.holder')
# RIPE usually outputs holder as "ASNAME - actual company name", trim it to just the company name in such cases
found_holder=$(awk -F' - ' '{ if ( $2 ) {print $2} else {print} }' <<<"$found_holder")
found_org=$(echo -e "$pwhois_asn_info" | grep -E "^Org-Name:" | cut -d ':' -f 2 | sed 's/^[ \t]*//')
[[ -z "$found_org" ]] && found_org="N/A"
found_abuse_contact=$(docurl -m5 -s "https://stat.ripe.net/data/abuse-contact-finder/data.json?resource=AS$asn&sourceapp=nitefood-asn" | jq -r 'select (.data.abuse_contacts[0] != null) | .data.abuse_contacts[0]')
[[ -z "$found_abuse_contact" ]] && found_abuse_contact="-"
pwhois_createdate=$(echo -e "$pwhois_asn_info" | grep -E "^Create-Date:" | cut -d ':' -f 2- | sed 's/^[ \t]*//')
if [ "$JSON_OUTPUT" = true ]; then
[[ -z "$pwhois_createdate" ]] && found_createdate="" || found_createdate=$(date -d "$pwhois_createdate" "+%Y-%m-%dT%H:%M:%S")
else
[[ -z "$pwhois_createdate" ]] && found_createdate="N/A" || found_createdate=$(date -d "$pwhois_createdate" "+%Y-%m-%d %H:%M:%S")
fi
fi
}
QueryRipestat(){
StatusbarMessage "Retrieving BGP data for AS$1 ($found_asname)"
# BGP routing stats
ripestat_routing_data=$(docurl -m5 -s "https://stat.ripe.net/data/routing-status/data.json?resource=AS$1&sourceapp=nitefood-asn")
if [ -n "$ripestat_routing_data" ]; then
ripestat_ipv4=$(jq -r '.data.announced_space.v4.prefixes' <<<"$ripestat_routing_data")
ripestat_ipv6=$(jq -r '.data.announced_space.v6.prefixes' <<<"$ripestat_routing_data")
ripestat_bgp=$(jq -r '.data.observed_neighbours' <<<"$ripestat_routing_data")
fi
# BGP neighbours list
StatusbarMessage "Retrieving peering data for AS$1 ($found_asname)"
ripestat_neighbours_data=$(docurl -m10 -s "https://stat.ripe.net/data/asn-neighbours/data.json?resource=AS$1&sourceapp=nitefood-asn")
upstream_peers=$(jq -r '.data.neighbours | sort_by(.power) | reverse[] | select (.type=="left") | .asn' <<<"$ripestat_neighbours_data")
downstream_peers=$(jq -r '.data.neighbours | sort_by(.power) | reverse[] | select (.type=="right") | .asn' <<<"$ripestat_neighbours_data")
uncertain_peers=$(jq -r '.data.neighbours | sort_by(.power) | reverse[] | select (.type=="uncertain") | .asn' <<<"$ripestat_neighbours_data")
if [ "$JSON_OUTPUT" = true ]; then
json_abuse_contacts=$(docurl -m5 -s "https://stat.ripe.net/data/abuse-contact-finder/data.json?resource=AS$1&sourceapp=nitefood-asn" | jq -cM 'select (.data.abuse_contacts != null) | .data.abuse_contacts')
[[ -z "$json_abuse_contacts" ]] && json_abuse_contacts="[]"
json_upstream_peers=$(jq -c --slurp --raw-input 'split("\n") | map(select(length > 0))' <<<"$upstream_peers")
json_downstream_peers=$(jq -c --slurp --raw-input 'split("\n") | map(select(length > 0))' <<<"$downstream_peers")
json_uncertain_peers=$(jq -c --slurp --raw-input 'split("\n") | map(select(length > 0))' <<<"$uncertain_peers")
else
RESOLVE_COUNT=8
OUTPUT_PEERS_PER_LINE=4
# resolve AS names of the first n upstreams
upstream_peercount=$(echo "$upstream_peers" | wc -l)
resolved_upstream_peers=""
count=0
for peer in $(echo -e "$upstream_peers" | head -n $RESOLVE_COUNT); do
(( count++ ))
peername=$(docurl -m10 -s "https://stat.ripe.net/data/as-overview/data.json?resource=AS$peer&sourceapp=nitefood-asn" | jq -r '.data.holder' | sed 's/ - .*//' )
if [ "$IS_ASN_CHILD" = true ]; then
resolved_upstream_peers+="${greenbg} <a href=\"/asn_lookup&AS$peer\" class=\"hidden_underline\" style=\"background-color: $htmlgreen; color: $htmlblack;\">$peername ($peer)</a> ${default} "
else
resolved_upstream_peers+="${greenbg} $peername ($peer) ${default} "
fi
[[ $(( count % OUTPUT_PEERS_PER_LINE )) -eq 0 ]] && resolved_upstream_peers+="\n"
done
# and add the remaining ones as AS numbers only
unresolved_peercount=$(( upstream_peercount - RESOLVE_COUNT ))
if [ "$unresolved_peercount" -ge 1 ]; then
resolved_upstream_peers+="and more: "
for peer in $(echo -e "$upstream_peers" | tail -n $unresolved_peercount ); do
if [ "$IS_ASN_CHILD" = true ]; then
resolved_upstream_peers+="<a href=\"/asn_lookup&AS$peer\" class=\"hidden_underline\" style=\"color: $htmlgreen;\">$peer</a>${default} "
else
resolved_upstream_peers+="${green}${peer}${default} "
fi
done
fi
upstream_peers="$resolved_upstream_peers"
# resolve AS names of the first n downstreams
downstream_peercount=$(echo "$downstream_peers" | wc -l)
resolved_downstream_peers=""
count=0
for peer in $(echo -e "$downstream_peers" | head -n $RESOLVE_COUNT); do
(( count++ ))
peername=$(docurl -m10 -s "https://stat.ripe.net/data/as-overview/data.json?resource=AS$peer&sourceapp=nitefood-asn" | jq -r '.data.holder' | sed 's/ - .*//' )
if [ "$IS_ASN_CHILD" = true ]; then
resolved_downstream_peers+="${yellowbg} <a href=\"/asn_lookup&AS$peer\" class=\"hidden_underline\" style=\"background-color: $htmlyellow; color: $htmlblack;\">$peername ($peer)</a> ${default} "
else
resolved_downstream_peers+="${yellowbg} $peername ($peer) ${default} "
fi
[[ $(( count % OUTPUT_PEERS_PER_LINE )) -eq 0 ]] && resolved_downstream_peers+="\n"
done
# and add the remaining ones as AS numbers only
unresolved_peercount=$(( downstream_peercount - RESOLVE_COUNT ))
if [ "$unresolved_peercount" -ge 1 ]; then
resolved_downstream_peers+="and more: "
for peer in $(echo -e "$downstream_peers" | tail -n $unresolved_peercount ); do
if [ "$IS_ASN_CHILD" = true ]; then
resolved_downstream_peers+="<a href=\"/asn_lookup&AS$peer\" class=\"hidden_underline\" style=\"color: $htmlyellow;\">$peer</a>${default} "
else
resolved_downstream_peers+="${yellow}${peer}${default} "
fi
done
fi
downstream_peers="$resolved_downstream_peers"
# resolve AS names of the first n uncertains
uncertain_peercount=$(echo "$uncertain_peers" | wc -l)
resolved_uncertain_peers=""
count=0
for peer in $(echo -e "$uncertain_peers" | head -n $RESOLVE_COUNT); do
(( count++ ))
peername=$(docurl -m10 -s "https://stat.ripe.net/data/as-overview/data.json?resource=AS$peer&sourceapp=nitefood-asn" | jq -r '.data.holder' | sed 's/ - .*//' )
if [ "$IS_ASN_CHILD" = true ]; then
resolved_uncertain_peers+="${lightgreybg} <a href=\"/asn_lookup&AS$peer\" class=\"hidden_underline\" style=\"background-color: $htmllightgray; color: $htmlblack;\">$peername ($peer)</a> ${default} "
else
resolved_uncertain_peers+="${lightgreybg} $peername ($peer) ${default} "
fi
[[ $(( count % OUTPUT_PEERS_PER_LINE )) -eq 0 ]] && resolved_uncertain_peers+="\n"
done
# and add the remaining ones as AS numbers only
unresolved_peercount=$(( uncertain_peercount - RESOLVE_COUNT ))
if [ "$unresolved_peercount" -ge 1 ]; then
resolved_uncertain_peers+="and more: "
for peer in $(echo -e "$uncertain_peers" | tail -n $unresolved_peercount ); do
if [ "$IS_ASN_CHILD" = true ]; then
resolved_uncertain_peers+="<a href=\"/asn_lookup&AS$peer\" class=\"hidden_underline\" style=\"color: $htmlwhite;\">$peer</a>${default} "
else
resolved_uncertain_peers+="${white}${peer}${default} "
fi
done
fi
uncertain_peers="$resolved_uncertain_peers"
fi
StatusbarMessage "Retrieving prefix allocations and announcements for AS$1 ($found_asname)"
ipv4_inetnums=""
ipv6_inetnums=""
json_ipv4_other_inetnums=""
json_ipv6_other_inetnums=""
ripe_prefixes=$(docurl -m10 -s "https://stat.ripe.net/data/announced-prefixes/data.json?resource=$1&sourceapp=nitefood-asn" | jq -r '.data.prefixes[].prefix')
json_ripe_prefixes=$(jq -cM --slurp --raw-input 'split("\n") | map(select(length > 0)) | {v4:map(select(contains(":")|not)), v6:map(select(contains(":")))}' <<<"$ripe_prefixes")
ipv4_ripe_prefixes=$(grep -v ":" <<<"$ripe_prefixes" | grep -Ev "^$" | sort)
ipv4_ripe_prefixes_count=$(wc -l <<<"$ipv4_ripe_prefixes")
ipv6_ripe_prefixes=$(grep ":" <<<"$ripe_prefixes" | grep -Ev "^$" | sort)
ipv6_ripe_prefixes_count=$(wc -l <<<"$ipv6_ripe_prefixes")
# open persistent tcp connection to RIPE whois server
exec 6<>/dev/tcp/whois.ripe.net/43
prefixcounter=0
for prefix in $ipv6_ripe_prefixes; do
((prefixcounter++))
StatusbarMessage "Retrieving information for IPv6 prefix $prefixcounter/$ipv6_ripe_prefixes_count"
# old way (one whois lookup per prefix)
# inet6nums=$(whois -h whois.ripe.net -- "-T inet6num -K -L --resource $prefix" | \
# grep -m2 inet6num | cut -d ':' -f 2- | sed 's/^[ \t]*//')
# new way (direct tcp connection to whois server with persistent whois connection)
echo -e "-k -T inet6num -K -L --resource $prefix" >&6
whoisoutput=""
# read whois output from the tcp stream line by line
while IFS= read -r -u 6 whoisoutputline; do
if [ -n "$whoisoutputline" ]; then
whoisoutput+="$whoisoutputline\n"
continue
fi
# last line was empty, check if next line is empty too
# if we get two empty lines in a row, the whois output is finished
IFS= read -r -u 6 whoisoutputline
[[ -z "$whoisoutputline" ]] && break || whoisoutput+="$whoisoutputline\n"
done
inet6nums=$(echo -e "$whoisoutput" | grep -m2 inet6num | cut -d ':' -f 2- | sed 's/^[ \t]*//')
for inet6num in $inet6nums; do
# exclude RIR supernets
prefix_size=$(echo "$inet6num" | cut -d '/' -f 2)
[[ "$prefix_size" -le 12 ]] && continue || ipv6_inetnums+="${inet6num}\n"
done
done
prefixcounter=0
lookedup_parents_cache=""
for prefix in $ipv4_ripe_prefixes; do
((prefixcounter++))
StatusbarMessage "Retrieving information for IPv4 prefix $prefixcounter/$ipv4_ripe_prefixes_count"
# old way (one whois lookup per prefix)
# parent_inetnum=$(whois -h whois.ripe.net -- "-T inetnum -K -L --resource $prefix" | \
# grep -E -m1 "^inetnum" | awk '{print $2"-"$4}' | xargs ipcalc -r 2>/dev/null | grep -v "deaggregate")
# new way (direct tcp connection to whois server with persistent whois connection)
echo -e "-k -T inetnum -K -L --resource $prefix" >&6
whoisoutput=""
# read whois output from the tcp stream line by line
while IFS= read -r -u 6 whoisoutputline; do
if [ -n "$whoisoutputline" ]; then
whoisoutput+="$whoisoutputline\n"
continue
fi
# last line was empty, check if next line is empty too
# if we get two empty lines in a row, the whois output is finished
IFS= read -r -u 6 whoisoutputline
[[ -z "$whoisoutputline" ]] && break || whoisoutput+="$whoisoutputline\n"
done
parent_inetnum=$(echo -e "$whoisoutput" | grep -E -m1 "^inetnum")
if [ -n "$parent_inetnum" ]; then
parent_inetnum=$(awk '{print $2"-"$4}' <<<"$parent_inetnum")
parent_inetnum=$(IpcalcDeaggregate "$parent_inetnum")
# check if the inetnum containing this prefix is being announced by the same AS as the prefix itself, otherwise
# it means it's part of a larger supernet by some other AS (e.g. larger carrier allocating own prefix to smaller customer)
if ! grep -q "$parent_inetnum" <<<"$lookedup_parents_cache"; then
# this parent inetnum hasn't been looked up yet
lookedup_parents_cache+="$parent_inetnum\n"
LookupASNAndRouteFromIP "$parent_inetnum"
if [ -z "$found_asname" ] || [ "$1" = "$found_asn" ]; then
# the target AS is also announcing the larger inetnum, or nobody is announcing it. Either way consider it part of the target's resources
ipv4_inetnums+="$parent_inetnum\n"
else
# the larger inetnum is being announced by another AS, only add the announced (smaller) prefix to the list
ipv4_inetnums+="$prefix\n"
fi
else
# this parent inetnum has already been looked up
# if it's not present in the list of ipv4_inetnums, it means it's part of a larger supernet by some other AS.
# therefore we only add the announced (smaller) prefix to the list
if ! grep -q "$parent_inetnum" <<<"$ipv4_inetnums"; then
ipv4_inetnums+="$prefix\n"
fi
fi
else
ipv4_inetnums+="$prefix\n"
fi
done
# close persistent tcp connection to RIPE whois server
if { true >&6; } 2<> /dev/null; then
echo -e "-k" >&6
fi
if [ "$ADDITIONAL_INETNUM_LOOKUP" = true ]; then
# fetch further inetnums allocated to this AS from pWhois
StatusbarMessage "Identifying additional INETNUMs (not announced or announced by other AS) allocated to AS$1"
pwhois_prefixes=$(PwhoisListPrefixesForOrg "$found_org")
pwhois_unique_prefixes=$(comm -13 <(echo -e "$ipv4_ripe_prefixes" | sort) <(echo -e "$pwhois_prefixes" | sort))
pwhois_unique_prefixes=$(comm -13 <(echo -e "$lookedup_parents_cache" | sort) <(echo -e "$pwhois_unique_prefixes" | sort))
if [ -n "$pwhois_unique_prefixes" ]; then
pwhois_unique_prefixes_count=$(wc -l <<<"$pwhois_unique_prefixes")
StatusbarMessage "Identifying origin AS for $pwhois_unique_prefixes_count additional IPv4 prefix(es)"
# NEW WAY (bulk query to Team Cymru whois server)
# map the unique prefixes pWhois reported to an array
mapfile -t pwhois_unique_prefixes_array < <(echo -e "$pwhois_unique_prefixes")
# assemble a bulk Team Cymru whois lookup query for the new prefixes found in pWhois.
# we'll check if they're announced by the target AS, by different one, or by no one at all
# (e.g. target AS has delegated announcements for this prefix to another AS, or is not announcing it)
# and compile a list to integrate into the allocated IP resources for this AS
teamcymru_bulk_query="begin\n"
for prefix in $pwhois_unique_prefixes; do
teamcymru_bulk_query+="$prefix\n"
done
teamcymru_bulk_query+="end"
prefixcounter=0
for single_prefix_data in $(echo -e "$teamcymru_bulk_query" | ncat --no-shutdown whois.cymru.com 43 | grep "|" | sed 's/\ *|\ */|/g'); do
prefix="${pwhois_unique_prefixes_array[$prefixcounter]}"
prefix_originator_asn=$(echo "$single_prefix_data" | cut -d '|' -f 1)
if [ "$prefix_originator_asn" = "$1" ]; then
# prefix originator is same as target AS, add this prefix to the allocated IP resources for this AS
ipv4_inetnums+="$prefix\n"
elif [ "$prefix_originator_asn" = "NA" ]; then
# prefix not announced, add this prefix to the allocated IP resources for this AS with a "not announced" remark
if [ "$JSON_OUTPUT" = true ]; then
[[ -n "$json_ipv4_other_inetnums" ]] && json_ipv4_other_inetnums+=","
json_ipv4_other_inetnums+="{\"prefix\":\"$prefix\",\"origin_asn\":\"\",\"origin_org\":\"\", \"is_announced\":false}"
elif [ "$IS_ASN_CHILD" = true ]; then
# skip colors, they will be added along with hyperlinks later
ipv4_inetnums+=$(printf "%-18s → not announced" "$prefix")
ipv4_inetnums+="\n"
else
ipv4_inetnums+=$(printf "${dim}%-18s → ${red}not announced${default}${green}" "$prefix")
ipv4_inetnums+="\n"
fi
else
# prefix is announced by a different AS, add this prefix to the allocated IP resources for this AS
prefix_originator_org=$(echo "$single_prefix_data" | cut -d '|' -f 3)
if [ "$JSON_OUTPUT" = true ]; then
[[ -n "$json_ipv4_other_inetnums" ]] && json_ipv4_other_inetnums+=","
json_ipv4_other_inetnums+="{\"prefix\":\"$prefix\",\"origin_asn\":\"$prefix_originator_asn\",\"origin_org\":\"$prefix_originator_org\", \"is_announced\":true}"
elif [ "$IS_ASN_CHILD" = true ]; then
# skip colors, they will be added along with hyperlinks later
ipv4_inetnums+=$(printf "%-18s → announced by AS%s %s" "$prefix" "${prefix_originator_asn}" "${prefix_originator_org}")
ipv4_inetnums+="\n"
else
ipv4_inetnums+=$(printf "%-18s ${dim}→ announced by ${default}${red}AS%s ${default}${green}%s" "$prefix" "${prefix_originator_asn}" "${prefix_originator_org}")
ipv4_inetnums+="\n"
fi
fi
((prefixcounter++))
done
# OLD WAY (one lookup per prefix)
# for prefix in $pwhois_unique_prefixes; do
# # found a new prefix in pWhois, check if it's announced by a different AS
# # (e.g. target AS has delegated announcements for this prefix to another AS)
# ((prefixcounter++))
# StatusbarMessage "Identifying origin AS for additional IPv4 prefix $prefixcounter/$pwhois_unique_prefixes_count"
# LookupASNAndRouteFromIP "$prefix"
# prefix_originator_asn="$found_asn"
# if [ -z "$prefix_originator_asn" ] || [ "$prefix_originator_asn" = "$1" ]; then
# # prefix originator is same as target AS, or prefix not announced
# # add this prefix to the allocated IP resources for this AS
# ipv4_inetnums+="$prefix\n"
# else
# # this prefix is allocated to target AS, but is being announced by a different AS
# prefix_originator_org=$(docurl -m5 -s "https://stat.ripe.net/data/as-overview/data.json?resource=AS${found_asn}&sourceapp=nitefood-asn" | \
# jq -r 'select (.data.holder != null) | .data.holder' | \
# awk -F' - ' '{ if ( $2 ) {print $2} else {print} }' \
# )
# if [ "$JSON_OUTPUT" = true ]; then
# [[ -n "$json_ipv4_other_inetnums" ]] && json_ipv4_other_inetnums+=","
# json_ipv4_other_inetnums+="{\"prefix\":\"$prefix\",\"origin_asn\":\"$prefix_originator_asn\",\"origin_org\":\"$prefix_originator_org\"}"
# else
# ipv4_inetnums+="$prefix (announced by AS${prefix_originator_asn} - ${prefix_originator_org})\n"
# fi
# fi
# done
fi
fi
if [ -n "$ipv4_inetnums" ]; then
ipv4_inetnums=$(echo -e "$ipv4_inetnums" | sort -iu)
if [ "$IS_ASN_CHILD" = true ] && [ "$JSON_OUTPUT" = false ]; then
# HTML output
html=""
for inetnum in $ipv4_inetnums; do
if grep -q "announced by" <<<"$inetnum"; then
# handle special case "<prefix> → announced by AS<asn>"
actual_inetnum=${inetnum:0:18}
originator=$(cut -d ' ' -f 7 <<<"$inetnum")
rest_of_line=$(cut -d ' ' -f 8- <<<"$inetnum")
html+="<a href=\"/asn_lookup&$actual_inetnum\" class=\"hidden_underline\" style=\"color: $htmlgreen;\">$actual_inetnum</a>"
html+="<span style=\"font-style: italic; color: $htmldarkgreen\"> → announced by </span>"
html+="<a href=\"/asn_lookup&$originator\" class=\"hidden_underline\" style=\"color: $htmlred;\">$originator</a> ${rest_of_line}\n"
elif grep -q "not announced" <<<"$inetnum"; then
# handle special case "<prefix> → not announced"
actual_inetnum=${inetnum:0:18}
html+="<a href=\"/asn_lookup&$actual_inetnum\" class=\"hidden_underline\" style=\"font-style: italic; color: $htmldarkgreen;\">$actual_inetnum</a>"
html+="<span style=\"font-style: italic; color: $htmldarkred\"> → not announced</span>\n"
else
html+="<a href=\"/asn_lookup&$inetnum\" class=\"hidden_underline\" style=\"color: $htmlgreen;\">$inetnum</a>\n"
fi
done
ipv4_inetnums="$html"
fi
fi
if [ -n "$ipv6_inetnums" ]; then
ipv6_inetnums=$(echo -e "$ipv6_inetnums" | sort -u)
if [ "$IS_ASN_CHILD" = true ] && [ "$JSON_OUTPUT" = false ]; then
html=""
for inet6num in $ipv6_inetnums; do
html+="<a href=\"/asn_lookup&$inet6num\" class=\"hidden_underline\" style=\"color: $htmlyellow;\">$inet6num</a>\n"
done
ipv6_inetnums="$html"
fi
fi
if [ "$JSON_OUTPUT" = true ]; then
json_ipv4_aggregated_inetnums=$(jq -cM --slurp --raw-input 'split("\n") | map(select(length > 0))' <<<"$ipv4_inetnums")
json_ipv6_aggregated_inetnums=$(jq -cM --slurp --raw-input 'split("\n") | map(select(length > 0))' <<<"$ipv6_inetnums")
fi
StatusbarMessage
}
RIPESuggestASN(){
TRIM_WHITESPACES=false
input=$(tr '[:lower:]' '[:upper:]' <<<"$1")
ripe_suggest_output=""
while true; do
for input_variation in "${input}" "AS_${input}" "AS-${input}" "${input}_AS" "${input}-AS"; do
StatusbarMessage "Retrieving suggested ASNs for ${bluebg}${input_variation}${lightgreybg}"
# lookup input variation (AS_<input>, AS-<input>, <input>_AS, <input>-AS)
ripe_suggest_output+=$(docurl -m10 -s "https://stat.ripe.net/data/searchcomplete/data.json?resource=${input_variation}&sourceapp=nitefood-asn" | \
jq -r '.data.categories[] | select ( .category == "ASNs" ) | .suggestions[]')
done
StatusbarMessage
if [ -n "$ripe_suggest_output" ]; then
found_suggestions=$(jq -r '.description' <<<"$ripe_suggest_output" | sort -u)
for suggestion in $found_suggestions; do
echo -e "\n${green}$suggestion${default}"
for suggestion_asn in $(jq -r 'select (.description=="'"$suggestion"'") | .value' <<<"$ripe_suggest_output" | awk 'NR==1{print}'); do
echo -en "\t${yellow}$suggestion_asn${default} (Rank: "
GetCAIDARank "${suggestion_asn:2}"
echo -en "${caida_asrank_recap}"
echo "${default})"
done
done
echo ""
return
elif [ "$TRIM_WHITESPACES" = false ]; then
TRIM_WHITESPACES=true
oldinput="$input"
# shellcheck disable=SC2001
input=$(echo "$oldinput" | sed 's/[ \t]*//g')
if [ "$input" = "$oldinput" ]; then
echo -e "\n${redbg}No suggestions found${default}\n"
return
else
continue
fi
else
echo -e "\n${redbg}No suggestions found${default}\n"
return
fi
done
}
WhoisIP(){
# $1: (mandatory) IP to lookup
# $2: (optional) if set to anything, only perform a generic whois lookup (skip pWhois/RPKI/IXP lookups)
local WHOIS_TIMEOUT=20
[[ "$JSON_OUTPUT" = true ]] && ((json_resultcount++))
GENERIC_WHOIS_LOOKUP_ONLY=false
[[ "$#" -gt 1 ]] && GENERIC_WHOIS_LOOKUP_ONLY=true
full_whois_data=$(timeout $WHOIS_TIMEOUT whois "$1" 2>/dev/null)
network_whois_data=$(echo -e "$full_whois_data" | grep -i -E "^netname:|^orgname:|^org-name:|^owner:|^descr:|^country:")
# fetch whois inetnum and later compare to cymru prefix, in order to find smallest match (sometimes whois and cymru/pwhois prefix data diverge)
whois_inetnum=$(IpcalcDeaggregate "$(grep -E -m1 "inet[6]?num|NetRange"<<<"$full_whois_data" | awk '{print $2 $3 $4}')")
# handle problematic IPs where whois gives out wrong info
[[ "$whois_inetnum" = "192.168.1.1/32" ]] && whois_inetnum="$found_route"
ixp_data=""
ixp_geo=""
ip_type_json_output=""
# Check if input is a bogon address
if [ "$IS_BOGON" = false ]; then
ip_type_json_output+="\"is_bogon\":false"
if [ "$GENERIC_WHOIS_LOOKUP_ONLY" = false ]; then
hostname=$(RdnsLookup "$1")
[[ -z "$hostname" ]] && hostname="-"
abuse_whois_data=$(
grep -E "^OrgAbuseEmail:|^abuse-c:|^% Abuse|^abuse-mailbox:|^E-Mail" <<<"$full_whois_data" |
grep -v "search-apnic-not-arin@apnic.net" |
awk '{print $NF}' |
tr -d \'
)
abusecontacts=$(AbuseLookupForPrefix "$abuse_whois_data" "$1")
fi
if [ "$UNANNOUNCED_PREFIX" = false ] && [ "$GENERIC_WHOIS_LOOKUP_ONLY" = false ]; then
# Prefix found in the Team Cymru DB, perform pWhois lookup and CAIDA rank lookup
PwhoisLookup "$1"
GetCAIDARank "$found_asn"
else
# No data in the Team Cymru DB for this IP (unannounced prefix), or pWhois being skipped
if [ "$GENERIC_WHOIS_LOOKUP_ONLY" = false ]; then
[[ -z "$network_whois_data" ]] && PrintErrorAndExit "Error: no data found for $input"
found_asn="N/A (address not announced)"
found_asname=""
fi
IPGeoRepLookup "$1"
IPShodanLookup "$1"
# check if it's an IXP, otherwise fall back to generic whois
[[ "$GENERIC_WHOIS_LOOKUP_ONLY" = false ]] && IsIXP "$1"
if [ -n "$ixp_data" ]; then
if [ "$JSON_OUTPUT" = true ]; then
pwhois_org="$ixp_data"
else
pwhois_org="${bluebg} IXP ${default} ${blue}${ixp_data}${default}"
ip_type_data=" ${yellowbg} Internet Exchange ${default}"
fi
else
pwhois_org=$(echo -e "$network_whois_data" | grep -i -E "^orgname:|^org-name:|^owner:" | cut -d ':' -f 2 | sed 's/^[ \t]*//' | while read -r line; do echo -n "$line / "; done | sed 's/ \/ $//')
fi
[[ -z "$pwhois_org" ]] && pwhois_org="N/A"
found_route=$(echo -e "$network_whois_data" | grep -i -m2 -E "^descr:" | cut -d ':' -f 2 | sed 's/^[ \t]*//' | while read -r line; do if [ -n "$line" ]; then echo -n "$line / "; fi; done | sed 's/ \/ $//')
[[ -z "$found_route" ]] && found_route="N/A"
pwhois_net=$(echo -e "$network_whois_data" | grep -i -E "^netname:" | cut -d ':' -f 2 | sed 's/^[ \t]*//' | while read -r line; do echo -n "$line / "; done | sed 's/ \/ $//')
[[ -z "$pwhois_net" ]] && pwhois_net="N/A"
if [ -n "$ixp_geo" ]; then
pwhois_geo="$ixp_geo"
elif [ -n "$ip_geo_data" ]; then
pwhois_geo="$ip_geo_data"
else
pwhois_geo=$(echo -e "$network_whois_data" | grep -m1 -i -E "^country:" | cut -d ':' -f 2 | sed 's/^[ \t]*//')
geo_cc_json_output="$pwhois_geo"
fi
[[ -z "$pwhois_geo" ]] && pwhois_geo="N/A"
fi
[[ -n "$ixp_data" ]] && ip_type_json_output+=",\"is_ixp\":true" || ip_type_json_output+=",\"is_ixp\":false"
else
# bogon address, skip lookups
ip_type_json_output+="\"is_bogon\":true"
ip_type_json_output+=",\"bogon_type\":\"$json_bogon_type\""
hostname="-"
found_asn="-"
pwhois_org="IANA"
found_route="N/A"
abusecontacts="-"
pwhois_net=$(echo -e "$network_whois_data" | grep -i -E "^netname:" | cut -d ':' -f 2 | sed 's/^[ \t]*//' | while read -r line; do echo -n "$line / "; done | sed 's/ \/ $//')
found_asname=""
ip_type_data=" $bogon_tag"
pwhois_geo="-"
ip_rep_data="-"
fi
indent=$(( longest+4 ))
if [ -n "$found_asname" ]; then
output_asname="${green}($found_asname)"
else
output_asname=""
fi
rpki_output=""
if [ "$UNANNOUNCED_PREFIX" = false ] && [ "$GENERIC_WHOIS_LOOKUP_ONLY" = false ]; then
# we skip RPKI lookup in both cases because if SKIP_WHOIS=true then we're being
# called from TraceASPath, and RPKI lookup will be performed there subsequently
StatusbarMessage "Checking RPKI validity for ${bluebg}AS${found_asn}${lightgreybg} and prefix ${bluebg}${found_route}${lightgreybg}"
RPKILookup "$found_asn" "$found_route"
StatusbarMessage
[[ "$JSON_OUTPUT" = false ]] && echo ""
elif [ "$IS_BOGON" = false ]; then
rpki_output="${red}N/A (address not announced)${default}"
else
rpki_output="-"
fi
found_subprefix="$found_route"
whois_routename=""
# compare cymru net with whois net and pick longer (smaller), while retaining larger for route information.
# we want to identify subnets to which target IPs belong, even when they aren't
# announced directly but within a larger route.
if [ "$found_route" != "N/A" ] && [ "$found_route" != "$whois_inetnum" ]; then
foundroute_prefixlen=$(cut -d '/' -f 2 <<<"$found_route")
whois_prefixlen=$(cut -d '/' -f 2 <<<"$whois_inetnum")
if (( whois_prefixlen > foundroute_prefixlen )) 2>/dev/null; then
found_subprefix="$whois_inetnum"
# lookup route name (RIPE)
whois_routename=$(timeout $WHOIS_TIMEOUT whois "$found_route" | grep -m1 -E "^descr:" | cut -d ':' -f 2 | sed 's/^ *//g')
fi
fi
if [ "$JSON_OUTPUT" = true ]; then
# JSON output
final_json_output+="{"
final_json_output+="\"ip\":\"$1\","
grep -q ":" <<<"$1" && ipversion="6" || ipversion="4"
final_json_output+="\"ip_version\":\"$ipversion\","
[[ "$hostname" != "-" ]] && final_json_output+="\"reverse\":\"$hostname\","
final_json_output+="\"org_name\":\"$pwhois_org\","
# next field can be == $found_route or can be different (smaller) in case the IP belongs to a subnet (of $found_route) that's not routed directly
final_json_output+="\"net_range\":\"$found_subprefix\","
final_json_output+="\"net_name\":\"$pwhois_net\","
if [ -n "$abusecontacts" ] && [ "$abusecontacts" != "-" ]; then
final_json_output+="\"abuse_contacts\":$abusecontacts,"
fi
final_json_output+="\"routing\":{"
if [ -n "$found_asname" ]; then
final_json_output+="\"is_announced\":true,"
final_json_output+="\"as_number\":\"$found_asn\","
final_json_output+="\"as_name\":\"${found_asname//\"/\\\"}\","
final_json_output+="\"as_rank\":\"${caida_asrank//\"/\\\"}\","
final_json_output+="\"route\":\"$found_route\","
final_json_output+="\"route_name\":\"$whois_routename\","
final_json_output+="\"roa_count\":\"$roacount_json_output\","
final_json_output+="\"roa_validity\":\"$roavalidity_json_output\""
else
final_json_output+="\"is_announced\":false,"
if [ "$found_route" != "N/A" ]; then
final_json_output+="\"net_name\":\"$found_route ($pwhois_net)\""
else
final_json_output+="\"net_name\":\"$pwhois_net\""
fi
fi
final_json_output+="},\"type\":{$ip_type_json_output}"
if [ "$IS_BOGON" != true ]; then
final_json_output+=",\"geolocation\":{"
final_json_output+="\"city\":\"$geo_city_json_output\","
final_json_output+="\"region\":\"$geo_region_json_output\","
final_json_output+="\"country\":\"$geo_country_json_output\","
final_json_output+="\"cc\":\"$geo_cc_json_output\""
final_json_output+="}"
fi
else
# Normal output
printf "${white}%${longest}s${default} ┌${bluebg}PTR${default} %s\n" "$1" "$hostname"
if [ "$IS_ASN_CHILD" = true ] && [ -n "$found_asname" ]; then
summary_asn="<a href=\"/asn_lookup&AS$found_asn\" style=\"color: $htmlred;\">$found_asn</a>"
ipinfolink="<a href=\"https://ipinfo.io/AS$found_asn/$found_route\" target=\"_blank\" style=\"color: $htmlyellow; font-style: italic;\">ipinfo.io</a>"
summary_ipinfo=" <span style=\"font-size: 75%; color: $htmlyellow;\">($ipinfolink🔗)</span>"
else
summary_asn="$found_asn"
summary_ipinfo=""
fi
printf "${white}%${indent}s${bluebg}ASN${default} ${red}%s %s${default}\n" "├" "$summary_asn" "$output_asname"
[[ "$UNANNOUNCED_PREFIX" = false ]] && printf "${white}%${indent}s${bluebg}RNK${default} ${default}%s${default}\n" "├" "$caida_asrank_recap"
printf "${white}%${indent}s${bluebg}ORG${default} ${green}%s${default}\n" "├" "$pwhois_org"
if [ "$found_subprefix" != "$found_route" ]; then
# target IP belongs to a subnet announced within a larger route
printf "${white}%${indent}s${bluebg}NET${default} ${yellow}%s (%s)${default}\n" "├" "$found_subprefix" "$pwhois_net"
[[ -n "$whois_routename" ]] && whois_routename=" ($whois_routename)"
printf "${white}%${indent}s${bluebg}ROU${default} ${yellow}%s%s%s${default}\n" "├" "$found_route" "$whois_routename" "$summary_ipinfo"
else
# target IP belongs to a subnet announced directly
printf "${white}%${indent}s${bluebg}NET${default} ${yellow}%s (%s)%s${default}\n" "├" "$found_subprefix" "$pwhois_net" "$summary_ipinfo"
fi
printf "${white}%${indent}s${bluebg}ABU${default} ${blue}%s${default}\n" "├" "$abusecontacts"
printf "${white}%${indent}s${bluebg}ROA${default} %s\n" "├" "$rpki_output"
[[ -n "$ip_type_data" ]] && printf "${white}%${indent}s${bluebg}TYP${default}%s\n" "├" "${ip_type_data}"
printf "${white}%${indent}s${bluebg}GEO${default} ${magenta}%s${default}" "├" "$pwhois_geo"
if [ "$IS_ASN_CHILD" = true ] && [ -n "$flag_icon_cc" ]; then
# signal to the parent connhandler the correct country flag to display for this IP
echo -n " #COUNTRYCODE $flag_icon_cc"
fi
printf "\n"
fi
}
IsBogon(){
bogon_tag=""
IS_BOGON=false
# Bogon regex patterns
# IPv4
localhostregex='(^127\.)' # RFC 1122 localhost
thisnetregex='(^0\.)' # RFC 1122 'this' network
privateregex='(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)' # RFC 1918 private space - cheers https://stackoverflow.com/a/11327345/5377165
cgnregex='(^100\.6[4-9]\.)|(^100\.[7-9][0-9]\.)|(^100\.1[0-1][0-9]\.)|(^100\.12[0-7]\.)' # RFC 6598 Carrier grade nat space
llregex='(^169\.254\.)' # RFC 3927 link local
ietfprotoregex='(^192\.0\.0\.)' # IETF protocol assignments
testnetregex='(^192\.0\.2\.)|(^198\.51\.100\.)|(^203\.0\.113\.)' # RFC 5737 TEST-NET
benchmarkregex='(^192\.1[8-9]\.)' # RFC 2544 Network interconnect device benchmark testing
sixtofouranycast='(^192\.88\.99\.)' # RFC 7526 6to4 anycast relay
multicastregex='(^22[4-9]\.)|(^23[0-9]\.)' # Multicast
reservedregex='(^24[0-9]\.)|(^25[0-5]\.)' # Reserved for future use/limited broadcast (255.255.255.255)
# IPv6
unspecifiedv6regex='(^::$)' # RFC 4291 Unspecified Address (::)
loopbackv6regex='(^::1$)' # RFC 4291 Loopback Address (::1)
ipv4mappedv6regex="^(:{1,2}|0:0:0:0:0:)ffff:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$" # RFC 4291 IPv4-mapped IPv6 addresses (::ffff:0:0/96)
rtbhv6regex='(^100::)' # RFC 6666 Remotely triggered black hole addresses (100::/64)
orchidv6regex='(^2001:1[0-9a-f]:)' # RFC 4843 Overlay routable cryptographic hash identifiers (ORCHID) (2001:10::/28)
docv6regex='(^2001:db8:)' # RFC 3849 Documentation (2001:db8::/32)
docexpandedv6regex='(^3fff:)' # RFC 9637 Expanded IPv6 Documentation Space (3fff::/20)
ulav6regex='(^[f][cd])' # RFC 4193 Unique Local Address (fc00::/7)
llv6regex='(^fe8[0-9a-f]:)|(^fe9[0-9a-f]:)|(^fea[0-9a-f]:)|(^feb[0-9a-f]:)' # RFC 4291 Link-Local Addresses (fe80::/10)
multicastv6regex='(^ff0[0-9a-df])|(^ff[1-9a-f])|(^ff[bcdef])' # RFC 4291 Multicast Addresses (ff00::/8, except for ff0e::/16 which is defined in RFC7346 as IPv6 Multicast Global Scope and therefore should be routable)
if grep -q ':' <<<"$1"; then
# perform IPv6 bogon checks
lowercaseipv6=$(tr '[:upper:]' '[:lower:]' <<<"$1")
if [[ "$lowercaseipv6" =~ $unspecifiedv6regex ]]; then
bogon_tag="rfc4291 (IPv6 Unspecified Address)"
MTR_TRACING=false
elif [[ "$lowercaseipv6" =~ $loopbackv6regex ]]; then
bogon_tag="rfc4291 (IPv6 Loopback Address)"
MTR_TRACING=false
elif [[ "$lowercaseipv6" =~ $ipv4mappedv6regex ]]; then
bogon_tag="rfc4291 (IPv4-mapped IPv6 addresses)"
elif [[ "$lowercaseipv6" =~ $rtbhv6regex ]]; then
bogon_tag="rfc6666 (Remotely triggered black hole IPv6 addresses)"
elif [[ "$lowercaseipv6" =~ $orchidv6regex ]]; then
bogon_tag="rfc4843 (ORCHID - Overlay routable cryptographic hash identifiers)"
elif [[ "$lowercaseipv6" =~ $docv6regex ]]; then
bogon_tag="rfc3849 (IPv6 Documentation Space)"
elif [[ "$lowercaseipv6" =~ $docexpandedv6regex ]]; then
bogon_tag="rfc9637 (Expanded IPv6 Documentation Space)"
elif [[ "$lowercaseipv6" =~ $ulav6regex ]]; then
bogon_tag="rfc4193 (IPv6 Unique Local Address)"
elif [[ "$lowercaseipv6" =~ $llv6regex ]]; then
bogon_tag="rfc4291 (IPv6 Link-Local Addresses)"
elif [[ "$lowercaseipv6" =~ $multicastv6regex ]]; then
bogon_tag="rfc4291 (IPv6 Multicast Addresses)"
MTR_TRACING=false
fi
else
# perform IPv4 bogon checks
if [[ "$1" =~ $localhostregex ]]; then
bogon_tag="rfc1122 (Localhost)"
MTR_TRACING=false
elif [[ "$1" =~ $thisnetregex ]]; then
bogon_tag="rfc1122 ('this' network)"
MTR_TRACING=false
elif [[ "$1" =~ $privateregex ]]; then
bogon_tag="rfc1918 (Private Space)"
elif [[ "$1" =~ $cgnregex ]]; then
bogon_tag="rfc6598 (CGN Space)"
elif [[ "$1" =~ $llregex ]]; then
bogon_tag="rfc3927 (Link-Local)"
elif [[ "$1" =~ $ietfprotoregex ]]; then
bogon_tag="(Reserved for IETF protocol assignments)"
elif [[ "$1" =~ $testnetregex ]]; then
bogon_tag="rfc5737 (Reserved for Test Networks)"
elif [[ "$1" =~ $benchmarkregex ]]; then
bogon_tag="rfc2544 (Reserved for Network device benchmark testing)"
elif [[ "$1" =~ $sixtofouranycast ]]; then
bogon_tag="rfc7526 (6to4 anycast relay)"
elif [[ "$1" =~ $multicastregex ]]; then
bogon_tag="(Multicast Address)"
MTR_TRACING=false
elif [[ "$1" =~ $reservedregex ]]; then
bogon_tag="(Reserved Address)"
MTR_TRACING=false
fi
fi
if [ -n "$bogon_tag" ]; then
IS_BOGON=true
json_bogon_type="$bogon_tag"
bogon_tag="${yellowbg} BOGON ${default} ${bogon_tag}"
fi
}
LookupASNAndRouteFromIP(){
found_asn=""
found_route=""
found_asname=""
IsBogon "$1"
if [ "$IS_BOGON" = false ]; then
if echo "$1" | grep -q ':'; then
# whois query for IPv6 addresses
output=$(whois -h whois.cymru.com " -f -p -u $1" | sed 's/\ *|\ */|/g')
found_asn=$(echo "$output" | awk -F'[|]' 'NR==1{print $1}')
if [ "$found_asn" = "NA" ]; then
# Team Cymru has no data for this IPv6. Inform WhoisIP() that we will have to fall back to a generic whois lookup.
found_asn=""
UNANNOUNCED_PREFIX=true
else
found_asname=$(echo "$output" | awk -F'[|]' 'NR==1{print $4}')
found_route=$(echo "$output" | awk -F'[|]' 'NR==1{print $3}')
UNANNOUNCED_PREFIX=false
# lookup CAIDA rank info for the origin AS
GetCAIDARank "$found_asn"
fi
else
# Query RIPEStat for IPv4 addresses
output=$(docurl -m5 -s "https://stat.ripe.net/data/prefix-overview/data.json?resource=$1&sourceapp=nitefood-asn")
if jq -r '.data.announced' <<<"$output" | grep -q "true"; then
found_asn=$(jq -r '.data.asns[0].asn' <<<"$output")
found_asname=$(jq -r '.data.asns[0].holder' <<<"$output")
# look up the country this ASN is located in
country=$(docurl -m5 -s "https://stat.ripe.net/data/rir-stats-country/data.json?resource=AS${found_asn}" | jq -r '.data.located_resources[0].location')
[[ "$country" != "null" ]] && found_asname="${found_asname}, ${country}"
found_route=$(jq -r '.data.resource' <<<"$output")
UNANNOUNCED_PREFIX=false
else
# RIPEStat has no data for this IPv4. Fallback to Team Cymru DNS query (faster than whois)
rev=$(echo "$1" | cut -d '/' -f 1 | awk -F'.' '{printf $4 "." $3 "." $2 "." $1}')
output=$(host -t TXT "$rev.origin.asn.cymru.com" | awk -F'"' 'NR==1{print $2}' | sed 's/\ *|\ */|/g')
found_asn=$(echo "$output" | awk -F'[|]' 'NR==1{print $1}' | cut -d ' ' -f 1) # final cut gets first origin AS only if cymru has multiple
if [ -n "$found_asn" ]; then
found_asname=$(host -t TXT "AS$found_asn.asn.cymru.com" | grep -v "NXDOMAIN" | awk -F'|' 'NR==1{print substr($NF,2,length($NF)-2)}')
found_route=$(echo "$output" | awk -F'[|]' 'NR==1{print $2}')
UNANNOUNCED_PREFIX=false
else
# Team Cymru has no data for this IPv4 either. Inform WhoisIP() that we will have to fall back to a generic whois lookup.
UNANNOUNCED_PREFIX=true
fi
fi
fi
else
# bogon address, consider it unannounced
UNANNOUNCED_PREFIX=true
fi
}
ResolveHostnameToIPList(){
raw_host_output=$(host "$1" 2>/dev/null)
if echo -e "$raw_host_output" | grep -q "mail is handled"; then
host_output=$(echo "$raw_host_output" | grep -B100 -A0 -m1 "mail is handled" | sed '$d')
else
host_output="$raw_host_output"
fi
ip=$(echo "$host_output" | grep -Eo "$ipv4v6regex")
echo -e "$ip\n"
}
PrintErrorAndExit(){
if [ "$JSON_OUTPUT" = true ]; then
# json output
status_json_output="fail"
reason_json_output="${1//\"/\\\"}"
json_resultcount=0
PrintJsonOutput
elif [ "$IS_ASN_CHILD" = true ]; then
echo -e "\n${redbg}${1}${default}\n" # get the error in the html report
tput sgr0
tput cnorm # show cursor
else
# normal output
echo -e "\n${redbg}${1}${default}" >&2
tput sgr0
tput cnorm # show cursor
fi
exit 1
}
PrintUsage(){
# if an argument is passed, it will be displayed on stderr and the script will exit with error
script_name=$(basename "$0")
JSON_OUTPUT=false
BoxHeader "ASN / RPKI validity / BGP stats / IPv4v6 / Prefix / ASPath / Organization / IP reputation lookup tool" >&2
echo -e "\nVERSION:\n\n ${ASN_VERSION}" \
"\n\nUSAGE:\n\n $script_name [${green}OPTIONS${default}] [${blue}TARGET${default}]" \
"\n $script_name [${red}-v${default}] ${red}-l${default} [${red}SERVER OPTIONS${default}]" \
"\n\nOPTIONS:" \
"\n\n ${green}-t (enable trace)\n\t${default}Enable AS path trace to the ${blue}TARGET${default} (this is the default behavior)" \
"\n\n ${green}-n (no trace|no additional INETNUM lookups)\n\t${default}Disable tracing the AS path to the ${blue}TARGET${default} (for IP targets) or" \
"\n\tDisable additional (unannounced / announced by other AS) INETNUM lookups for the ${blue}TARGET${default} (for AS targets)" \
"\n\n ${green}-d (detailed)\n\t${default}Output detailed hop info during the AS path trace to the ${blue}TARGET${default}" \
"\n\tThis option also enables RPKI validation/BGP hijacking detection for every hop" \
"\n\n ${green}-a (ASN Suggest)\n\t${default}Lookup AS names and numbers matching ${blue}TARGET${default}" \
"\n\n ${green}-u (Transit/Upstream lookup)\n\t${default}Inspect BGP updates and ASPATHs for the ${blue}TARGET${default} address/prefix and identify possible transit/upstream autonomous systems" \
"\n\n ${green}-c (Country CIDR)\n\t${default}Lookup all IPv4/v6 CIDR blocks allocated to the ${blue}TARGET${default} country" \
"\n\n ${green}-g (Bulk Geolocate)\n\t${default}Geolocate all IPv4/v6 addresses passed as ${blue}TARGET${default}" \
"\n\tThis mode supports multiple targets, stdin input and IP extraction from input, e.g." \
"\n\t'asn -g < /var/log/apache2/error.log' or 'echo 1.1.1.1 2.2.2.2 | asn -g'" \
"\n\n ${green}-s (Shodan scan)\n\t${default}Query Shodan's InternetDB for CVE/CPE/Tags/Ports/Hostnames data about ${blue}TARGET${default}" \
"\n\tThis mode supports multiple targets and stdin input, e.g." \
"\n\t'asn -s < iplist' or 'echo 1.1.1.0/24 google.com | asn -s'" \
"\n\n ${green}-o (organization search)\n\t${default}Force ${blue}TARGET${default} to be treated as an Organization Name" \
"\n\n ${green}-m (monochrome output)\n\t${default}Disable colored output" \
"\n\n ${green}-v (verbose)\n\t${default}Enable (and log to \$HOME/asndebug.log) debug messages (URLs being queried and variable names being assigned)." \
"\n\tAPI call response data (i.e. the JSON output) is logged to the logfile.${default}" \
"\n\n ${green}-j (compact JSON output)\n\t${default}Set output to compact JSON mode (ideal for machine parsing)" \
"\n\n ${green}-J (pretty-printed JSON output)\n\t${default}Set output to pretty-printed JSON mode" \
"\n\n ${green}-h (help)\n\t${default}Show this help screen" \
"\n\n ${red}-l (lookup server)\n\t${default}Launch the script in server mode. See ${red}SERVER OPTIONS${default} below" \
"\n\nTARGET:" \
"\n\n ${blue}<AS Number>${default}\n\tLookup matching ASN and BGP announcements/neighbours data." \
"\n\t(Supports \"as123\" and \"123\" formats - case insensitive)" \
"\n\n ${blue}<IPv4/IPv6>${default}\n\tLookup matching route(4/6), IP reputation and ASN data" \
"\n\n ${blue}<Prefix>${default}\n\tLookup matching ASN data" \
"\n\n ${blue}<host.name.tld>${default}\n\tLookup matching IP, route and ASN data. Supports multiple IPs - e.g. DNS RR" \
"\n\n ${blue}<URL>${default}\n\tExtract hostname/IP from the URL and lookup relative data. Supports any protocol prefix, non-standard ports and prepended credentials" \
"\n\n ${blue}<Organization Name>${default}\n\tSearch by company name and lookup network ranges exported by (or related to) the company" \
"\n\nSERVER OPTIONS:" \
"\n\n ${red}BIND_ADDRESS${default}\n\tIP address (v4/v6) to bind the listening server to (e.g. '$script_name -l 0.0.0.0')\n\tDefault value: ${red}${DEFAULT_SERVER_BINDADDR_v4} (IPv4) or ${DEFAULT_SERVER_BINDADDR_v6} (IPv6)${default}" \
"\n\n ${red}BIND_PORT${default}\n\tTCP Port to bind the listening server to (e.g. '$script_name -l 12345')\n\tDefault value: ${red}${DEFAULT_SERVER_BINDPORT}${default}" \
"\n\n ${red}BIND_ADDRESS${default} ${red}BIND_PORT${default}\n\tIP address and port to bind the listening server to (e.g. '$script_name -l ::1 12345')" \
"\n\n ${red}-v (verbose)\n\t${default}Enable verbose output and debug messages in server mode${default}" \
"\n\n ${red}--allow host[,host,...]\n\t${default}Allow only given hosts to connect to the server${default}" \
"\n\n ${red}--allowfile file\n\t${default}A file of hosts allowed to connect to the server${default}" \
"\n\n ${red}--deny host[,host,...]\n\t${default}Deny given hosts from connecting to the server${default}" \
"\n\n ${red}--denyfile file\n\t${default}A file of hosts denied from connecting to the server${default}" \
"\n\n ${red}-m, --max-conns <n>\n\t${default}The maximum number of simultaneous connections accepted by the server. 100 is the default.${default}" \
"\n\n\n Note: Every option in server mode (after -l) is passed directly to the ncat listener." \
"\n Refer to ${blue}man ncat${default} for more details on the available commands." \
"\n Unless specified, the default IP:PORT values of ${DEFAULT_SERVER_BINDADDR_v4}:${DEFAULT_SERVER_BINDPORT} (for IPv4) or [${DEFAULT_SERVER_BINDADDR_v6}]:${DEFAULT_SERVER_BINDPORT} (for IPv6) will be used (e.g. 'asn -l')" \
"\n\n Example server usage:" \
"\n\t${blue}asn -l${default}" \
"\n\t (starts server on default IP(v4/v6):PORT)\n" \
"\n\t${blue}asn -l 0.0.0.0 --allow 192.168.0.0/24,192.168.1.0/24,192.168.2.245${default}" \
"\n\t (binds to all availables IPv4 interfaces on the default port, allowing only connections from the three specified subnets)\n" \
"\n\t${blue}asn -l :: 2222 --allow 2001:DB8::/32${default}" \
"\n\t (binds to all availables IPv6 interfaces on port 2222, allowing only connections from the specified prefix)\n" \
"\n\t${blue}asn -v -l 0.0.0.0 --allowfile \"~/goodips.txt\" -m 5${default}" \
"\n\t (verbose mode, bind to all IPv4 interfaces, use an allowfile with allowed addresses, accept a maximum of 5 concurrent connections)\n" \
"\n Bookmarklet configuration page:" \
"\n\tplease visit ${blue}http://127.0.0.1:49200/asn_bookmarklet${default} and follow the instructions. More documentation is available on github (link below)." \
"\n\n\nProject homepage: ${yellow}https://github.com/nitefood/asn${default}\n" >&2
[[ -n "$1" ]] && PrintErrorAndExit "$1"
}
PwhoisLookup(){
StatusbarMessage "Collecting pWhois data"
pwhois_output=$(whois -h whois.pwhois.org "$1")
StatusbarMessage
if echo "$pwhois_output" | grep -vq "That IP address doesn't appear"; then
# pwhois_asn=$(echo "$pwhois_output" | grep -E "^Origin-AS" | cut -d ':' -f 2 | sed 's/^ //')
# pwhois_prefix=$(echo "$pwhois_output" | grep -E "^Prefix" | cut -d ':' -f 2 | sed 's/^ //')
pwhois_asorg=$(echo "$pwhois_output" | grep -E "^AS-Org-Name" | cut -d ':' -f 2 | sed 's/^ //')
# group all "Org-Name" fields on a single line
pwhois_org=$(echo "$pwhois_output" | grep -E "^Org-Name" | cut -d ':' -f 2 | sed 's/^[ \t]*//g' | while read -r line; do echo -n "$line / "; done | sed 's/ \/ $//')
pwhois_net=$(echo "$pwhois_output" | grep -E "^Net-Name" | cut -d ':' -f 2 | sed 's/^ //')
# if pWhois' Net-Name=Org-Name, then it's more useful to use AS-Org-Name instead of Org-Name (unless AS-Org-Name is empty)
if [ -n "$pwhois_asorg" ] && [ "$pwhois_net" = "$pwhois_org" ]; then
pwhois_org="$pwhois_asorg"
fi
IPGeoRepLookup "$1"
IPShodanLookup "$1"
pwhois_geo="$ip_geo_data"
if [ -z "$ip_geo_data" ]; then
if echo "$pwhois_output" | grep -q -E "^Geo-"; then
# use "Geo-" fields in pWhois output
cityfield="Geo-City"
regionfield="Geo-Region"
ccfield="Geo-CC"
else
cityfield="City"
regionfield="Region"
ccfield="Country-Code"
fi
pwhois_city=$(echo "$pwhois_output" | grep -m1 -E "^${cityfield}" | cut -d ':' -f 2 | sed 's/^ //')
pwhois_region=$(echo "$pwhois_output" | grep -m1 -E "^${regionfield}" | cut -d ':' -f 2 | sed 's/^ //')
pwhois_cc=$(echo "$pwhois_output" | grep -m1 -E "^${ccfield}" | cut -d ':' -f 2 | sed 's/^ //')
flag_icon_cc=$(tr '[:upper:]' '[:lower:]' <<<"$pwhois_cc")
if [ "$pwhois_city" = "NULL" ] || [ "$pwhois_region" = "NULL" ]; then
pwhois_geo="$pwhois_cc"
else
pwhois_geo="$pwhois_city, $pwhois_region ($pwhois_cc)"
fi
fi
else
pwhois_output="";
fi
}
RdnsLookup(){
# reverse DNS (PTR) lookup.
# get first lookup result only (in case of multiple PTR records) and remove trailing dot and CR (Cygwin) from hostname
rdns=$(host "$1" | awk 'NR==1{sub(/\.\r?$/, "", $NF); print $NF}')
if echo "$rdns" | grep -E -q "NXDOMAIN|SERVFAIL|REFUSED|^record$"; then rdns=""; fi
echo "$rdns"
}
AbuseLookupForPrefix(){
# $1="whois data", $2=prefix
if [ -n "$mtr_output" ] && [ "$DETAILED_TRACE" = false ]; then
# skip abuse lookup for individual trace hops in non-detailed mode
return
fi
abuse_whois_data="$1"
prefix="$2"
abuselist=""
if grep -q '@' <<<"$abuse_whois_data"; then
# there's at least one email among the abuse contacts found in whois data
for abusecontact in $(echo -e "$abuse_whois_data"); do
if grep -q '@' <<<"$abusecontact"; then
[[ -n "$abuselist" ]] && abuselist+="\n"
abuselist+="$abusecontact"
fi
done
else
# abuse contacts found in whois data do not contain any email (but likely NIC handles only), fall back to RIPE API
resolvedabuse=$(docurl -m5 -s "https://stat.ripe.net/data/abuse-contact-finder/data.json?resource=$2&sourceapp=nitefood-asn" | jq -r 'select (.data.abuse_contacts != null) | .data.abuse_contacts[]')
if ! grep -q '@' <<<"$resolvedabuse"; then
# RIPE API didn't give back an email, second and last fall back to DSHIELD API
dshield_abuse_contact=$(docurl -m15 -s --user-agent "nitefood/asn" "https://isc.sans.edu/api/ip/$2?json" | jq -r 'select (.ip.asabusecontact != null) | .ip.asabusecontact')
if grep -q '@' <<<"$dshield_abuse_contact"; then
resolvedabuse="$dshield_abuse_contact"
fi
fi
[[ -n "$resolvedabuse" ]] && abuselist="$resolvedabuse"
fi
if [ "$JSON_OUTPUT" = true ]; then
# json output
if [ -n "$abuselist" ]; then
echo -e "$abuselist" | jq -cM --slurp --raw-input 'split("\n") | map(select(length > 0)) | unique'
fi
else
# normal output
if [ -n "$abuselist" ]; then
# use jq to join contacts together and separate them with the " / " multi-character delimiter, while getting rid of spurious newlines
echo -e "$abuselist" | jq -r --slurp --raw-input 'split("\n") | map(select(length > 0)) | unique | join(" / ")'
else
echo "-"
fi
fi
}
HopPrint(){
StatusbarMessage
# shellcheck disable=SC2124
output="$@"
# create hyperlinks if running in server mode
if [ "$IS_ASN_CHILD" = true ]; then
[[ -z "$ixp_tag" ]] && htmlcolor="$htmlwhite" || htmlcolor="$htmlblue"
# extract and trim duplicate IPs from the trace output line