-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathfirewall.sh
More file actions
6636 lines (6342 loc) · 241 KB
/
firewall.sh
File metadata and controls
6636 lines (6342 loc) · 241 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/sh
#############################################################################################################
# #
# ███████╗██╗ ██╗██╗ ██╗███╗ ██╗███████╗████████╗ #
# ██╔════╝██║ ██╔╝╚██╗ ██╔╝████╗ ██║██╔════╝╚══██╔══╝ #
# ███████╗█████╔╝ ╚████╔╝ ██╔██╗ ██║█████╗ ██║ #
# ╚════██║██╔═██╗ ╚██╔╝ ██║╚██╗██║██╔══╝ ██║ #
# ███████║██║ ██╗ ██║ ██║ ╚████║███████╗ ██║ #
# ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ #
# #
# Router Firewall And Security Enhancements #
# By Adamm - https://github.com/Adamm00/IPSet_ASUS #
# 23/02/2026 - v8.0.10 #
#############################################################################################################
export PATH="/sbin:/bin:/usr/sbin:/usr/bin:$PATH"
printf '\033[?7l'
clear
sed -n '2,14p' "$0"
export LC_ALL=C
mkdir -p /tmp/skynet/lists
mkdir -p /jffs/addons/shared-whitelists
skynetloc="$(grep -ow "skynetloc=.* # Skynet" /jffs/scripts/firewall-start 2>/dev/null | grep -vE "^#" | awk '{print $1}' | cut -c 11-)"
skynetcfg="${skynetloc}/skynet.cfg"
skynetlog="${skynetloc}/skynet.log"
skynetevents="${skynetloc}/events.log"
skynetipset="${skynetloc}/skynet.ipset"
LOCK_FILE="/tmp/skynet.lock"
# Default to the NVRAM’s WAN interface name, but if the protocol is PPPoE, override to ppp0
iface="$(nvram get wan0_ifname)"
[ "$(nvram get wan0_proto)" = "pppoe" ] && iface="ppp0"
trap 'Release_Lock' INT TERM EXIT
case "$1" in
uninstall|disable) ;; # Skip NTP check for these modes
*)
ntptimer="0"
while [ "$(nvram get ntp_ready)" != "1" ] && [ "$ntptimer" -lt "300" ]; do
ntptimer=$((ntptimer + 1))
if [ "$ntptimer" -eq 60 ]; then
echo
Log info -s "Waiting for NTP to synchronize..."
fi
sleep 1
done
if [ "$ntptimer" -ge 300 ]; then
Log error -s "NTP synchronization failed after 5 minutes. Please check your configuration!"
echo
exit 1
fi
;;
esac
stime="$(date +%s)"
# If we haven’t yet determined an install directory and the script is running in a real terminal,
# force the command to “install” so the installer logic kicks in automatically.
if [ -z "${skynetloc}" ] && tty >/dev/null 2>&1; then
set "install"
fi
###############
#- Functions -#
###############
Check_Lock() {
# Open FD 9 for locking
exec 9<>"$LOCK_FILE"
# Try non-blocking lock
if ! flock -n 9; then
locked_cmd=$(cut -d'|' -f1 "$LOCK_FILE" 2>/dev/null)
locked_pid=$(cut -d'|' -f2 "$LOCK_FILE" 2>/dev/null)
lock_timestamp=$(cut -d'|' -f3 "$LOCK_FILE" 2>/dev/null)
current_time=$(date +%s)
# Re-entrant lock handling
if [ "$locked_pid" = "$$" ]; then
return 0
fi
# If we have a non-empty PID and that process exists
if [ -n "$locked_pid" ] && [ -d "/proc/$locked_pid" ]; then
age=$(( current_time - lock_timestamp ))
if [ "$age" -gt 1800 ] 2>/dev/null; then
# Stale lock: kill and re-acquire
if kill "$locked_pid" 2>/dev/null; then
Log info -s "Killed stale Skynet process (pid=$locked_pid) after $age seconds"
fi
: > "$LOCK_FILE"
if ! flock -n 9; then
Log error -s "Lock acquisition failed after killing stale process - Exiting (pid=$locked_pid)"
echo; exit 1
fi
else
# Active lock held by running process
Log error -s "Lock File Detected ($locked_cmd) (pid=$locked_pid, runtime=${age}s) - Exiting"
echo; exit 1
fi
else
# We *know* flock says the file is locked, but the metadata is missing
# or corrupt. That usually means another Skynet instance is in the
# middle of writing the lock line. Safer to just bail.
Log error -s "Lock file busy but metadata invalid (pid='$locked_pid') - another Skynet instance is running - Exiting"
echo; exit 1
fi
fi
# We now hold the lock — record this invocation
: > "$LOCK_FILE"
echo "$0 $*|$$|$(date +%s)" >&9
}
Release_Lock() {
[ ! -f "$LOCK_FILE" ] && exec 9>&- && return
pid=$(cut -d'|' -f2 "$LOCK_FILE")
[ "$pid" != "$$" ] && return
# We own the lock
exec 9>&-
rm -f "$LOCK_FILE"
}
Find_Install_Dir() {
# Skip for installer/info commands
case "$1" in
install|uninstall|disable|update|restart|info) return 0 ;;
esac
if [ ! -d "${skynetloc}" ] || [ ! -w "${skynetloc}" ]; then
Check_Lock "$@"
MAX_RETRIES=10
attempt=1
# Wait until skynetloc exists as a directory and is writable
while [ "$attempt" -le "$MAX_RETRIES" ] && { [ ! -d "$skynetloc" ] || [ ! -w "$skynetloc" ]; }; do
Log info -s "USB install directory not ready — sleeping 10s ($attempt/$MAX_RETRIES)"
sleep 10
attempt=$(( attempt + 1 ))
done
# Final verification
if [ ! -d "$skynetloc" ] || [ ! -w "$skynetloc" ]; then
Log error -s "Problem with USB install location — please fix immediately!"
Log error -s "To change location run: sh $0 install"
echo
exit 1
fi
fi
}
# Prints in color if either stdout or stderr is a terminal, otherwise plain
Print_Colored() {
# $1 = ANSI color code (e.g. "1;31"), $2 = text
if [ -t 1 ] || [ -t 2 ]; then
printf '\033[%sm%s\033[0m\n' "$1" "$2"
else
printf '%s\n' "$2"
fi
}
# Specific wrappers
Red() { Print_Colored '1;31' "$1"; }
Grn() { Print_Colored '1;32' "$1"; }
Blue() { Print_Colored '1;36' "$1"; }
Ylow() { Print_Colored '1;33' "$1"; }
# Check if a swap file (not just partition) is active
Check_Swap() {
grep -qsF "file" "/proc/swaps"
}
Check_Settings() {
# Grab and set local version
localver="$(Filter_Version < "$0")"
# require config file
if [ ! -f "$skynetcfg" ]; then
Log error -s "Configuration File Not Detected - Please Use ( sh $0 install ) To Continue"
echo; exit 1
fi
# SWAP Checks
swaplocation="$(awk 'NR==2 { print $1 }' /proc/swaps)"
if [ -z "$swaplocation" ] && ! Check_Swap; then
Log error -s "Skynet Requires A SWAP File - Install One ( $0 debug swap install )"
echo; exit 1
fi
if Check_Swap && [ -z "$(grep -E 'swapon [^#]+' /jffs/scripts/post-mount | cut -d ' ' -f2)" ]; then
Log error -s "SWAPON Entry Missing - Fix This By Running ( $0 debug swap uninstall ) Then ( $0 debug swap install )"
echo; exit 1
fi
if grep -q '^partition' /proc/swaps; then
Log error -s "SWAP Partitions Not Supported - Please Use SWAP File"
echo; exit 1
fi
# warn if too small (<1GB)
swap_kb=$(du -k "$swaplocation" 2>/dev/null | awk '{print $1}') || swap_kb=0
if [ "$swap_kb" -gt 0 ] && [ "$swap_kb" -lt 1048576 ]; then
Log error -s "SWAP File Too Small (<1GB) - Please Fix Immediately!"
fi
# load banmalware and update cronjobs
case "$banmalwareupdate" in
daily)
Load_Cron banmalwaredaily
;;
weekly)
Load_Cron banmalwareweekly
;;
esac
if Is_Enabled "$autoupdate"; then
Load_Cron "autoupdate"
else
Load_Cron "checkupdate"
fi
# ensure firewall symlink & alias
if [ -d "/opt/bin" ] && [ ! -L "/opt/bin/firewall" ]; then
ln -s /jffs/scripts/firewall /opt/bin
fi
if ! grep -F "sh /jffs/scripts/firewall" /jffs/configs/profile.add; then
echo "alias firewall=\"sh /jffs/scripts/firewall\" # Skynet" >> /jffs/configs/profile.add
fi
# enable jffs2_scripts & fw_enable_x
if [ "$(nvram get jffs2_scripts)" != "1" ]; then
nvram set jffs2_scripts=1
nvram commit
Log info -s "Custom JFFS Scripts Enabled - Please Manually Reboot To Apply Changes"
fi
if [ "$(nvram get fw_enable_x)" != "1" ]; then
nvram set fw_enable_x=1
nvram commit
restartfirewall="1"
fi
case "$(nvram get fw_log_x)" in
drop|both)
;;
*)
nvram set fw_log_x=drop
nvram commit
restartfirewall=1
;;
esac
# set syslog location on newer models that use /jffs
pids=$(pidof syslogd) || pids=
for pid in $pids; do
exe_path=$(readlink "/proc/$pid/exe") || continue
[ "$exe_path" != "/bin/busybox" ] && continue
if grep -qF '/jffs/syslog.log' "/proc/$pid/cmdline"; then
syslogloc="/jffs/syslog.log"
syslog1loc="/jffs/syslog.log-1"
break
fi
done
# scribe plugin install
if [ -f "/opt/bin/scribe" ] && [ ! -f "/opt/etc/syslog-ng.d/skynet" ] && [ -f "/opt/share/syslog-ng/examples/skynet" ]; then
Log info -s "Installing Scribe Plugin"
rm -rf "/opt/etc/syslog-ng.d/firewall" "/opt/etc/logrotate/firewall"
cp -p "/opt/share/syslog-ng/examples/skynet" "/opt/etc/syslog-ng.d"
syslogloc="$(grep -m1 "file(" "/opt/etc/syslog-ng.d/skynet" | awk -F '"' '{print $2}')"
killall -HUP syslog-ng
elif [ -f "/opt/bin/scribe" ] && [ -f "/opt/etc/syslog-ng.d/skynet" ] && [ "$syslogloc" = "/tmp/syslog.log" ]; then
syslogloc="$(grep -m1 "file(" "/opt/etc/syslog-ng.d/skynet" | awk -F '"' '{print $2}')"
fi
if nvram get wan0_ipaddr | Is_PrivateIP; then
Log error -s "Private WAN IP Detected $(nvram get wan0_ipaddr) - Please Put Your Modem In Bridge Mode / Disable CG-NAT"
fi
# Set default log size if not set
if [ -z "$logsize" ]; then
logsize="10"
fi
}
Check_Connection() {
# Usage:
# Check_Connection # 1 attempt
# Check_Connection 5 # 5 attempts, 3s apart
# Check_Connection 5 10 # 5 attempts, 10s apart
retries="${1:-1}" # default: 1 attempt (backwards compatible)
delay="${2:-3}" # default: 3 seconds between attempts
[ "$retries" -lt 1 ] && retries=1
[ "$delay" -lt 1 ] && delay=1
attempt=1
while [ "$attempt" -le "$retries" ]; do
# 1) Grab the numeric gateway IP from the routing table
gw="$(route -n | awk '$1=="0.0.0.0"{print $2; exit}')"
# 2) Quick ping gateway (1 s timeout) if we have a gateway
if [ -n "$gw" ] && ping -c1 -W1 "$gw" >/dev/null 2>&1; then
return 0
fi
# 3) Quick ping a reliable public IP (1 s timeout)
if ping -c1 -W1 1.1.1.1 >/dev/null 2>&1; then
return 0
fi
# 4) ARP fallback on the known $iface (1 s timeout) if we have a gateway
if [ -n "$gw" ] && arping -c1 -w1 -I "$iface" "$gw" >/dev/null 2>&1; then
return 0
fi
# If this wasn't the last attempt, wait and retry
if [ "$attempt" -lt "$retries" ]; then
sleep "$delay"
fi
attempt=$((attempt + 1))
done
# Final failure: print a single message like the original function
if [ -z "$gw" ]; then
Log error -s "Connection Error Detected - Unable To Determine Gateway Or Reach Public IP"
else
Log error -s "Connection Error Detected - Unable To Reach Gateway ($gw) Or Public IP"
fi
return 1
}
Check_Files() {
# 1) Ensure each script has a proper shebang
for name in "$@"; do
path="/jffs/scripts/$name"
if [ ! -f "$path" ]; then
echo '#!/bin/sh' > "$path"
echo >> "$path"
elif ! head -n1 "$path" | grep -q '^#!/bin/sh'; then
sed -i '1s~^~#!/bin/sh\n~' "$path"
fi
done
# service-event: inject debug‑genstats if missing
if ! grep -vE '^#' /jffs/scripts/service-event | grep -qF 'sh /jffs/scripts/firewall debug genstats'; then
sed -i '\~# Skynet~d' /jffs/scripts/service-event
echo "if [ \"\$1\" = \"start\" ] && [ \"\$2\" = \"SkynetStats\" ]; then sh /jffs/scripts/firewall debug genstats; fi # Skynet" \
>> /jffs/scripts/service-event
fi
# 3) unmount: ensure swapoff entry
if ! grep -qE '^swapoff ' /jffs/scripts/unmount; then
sed -i '\~swapoff ~d' /jffs/scripts/unmount
echo 'swapoff -a 2>/dev/null # Skynet' >> /jffs/scripts/unmount
fi
# 4) services-stop: ensure firewall‑save alias
if ! grep -vE '^#' /jffs/scripts/services-stop | grep -qF 'sh /jffs/scripts/firewall save'; then
echo 'sh /jffs/scripts/firewall save # Skynet' >> /jffs/scripts/services-stop
fi
# 5) post-mount: ensure at least one blank line
if [ "$(wc -l < /jffs/scripts/post-mount)" -lt 2 ]; then
echo >> /jffs/scripts/post-mount
fi
# 6) final perms
chmod 755 /jffs/scripts/firewall \
/jffs/scripts/firewall-start \
/jffs/scripts/services-stop \
/jffs/scripts/service-event \
/jffs/scripts/post-mount \
/jffs/scripts/unmount
}
Check_Security() {
if Is_Enabled "$securemode"; then
# Disable WAN SSH Access for ASUSWRT-Merlin
if [ "$(nvram get sshd_enable)" = "1" ] && [ "$(uname -o)" = "ASUSWRT-Merlin" ]; then
Log error -s "Insecure Setting Detected - Disabling WAN SSH Access"
nvram set sshd_enable="2"
nvram commit
restartfirewall="1"
fi
# Disable WAN SSH Access for ASUSWRT-Merlin-LTS
if [ "$(nvram get sshd_wan)" = "1" ] && [ "$(uname -o)" = "ASUSWRT-Merlin-LTS" ]; then
Log error -s "Insecure Setting Detected - Disabling WAN SSH Access"
nvram set sshd_wan="0"
nvram commit
restartfirewall="1"
fi
# Disable WAN GUI Access
if [ "$(nvram get misc_http_x)" = "1" ]; then
Log error -s "Insecure Setting Detected - Disabling WAN GUI Access"
nvram set misc_http_x="0"
nvram commit
restartfirewall="1"
fi
fi
# Check for PPTP VPN compromise
if [ "$(nvram get pptpd_enable)" = "1" ] && nvram get pptpd_clientlist | grep -qE 'i[0-9]{7}|p[0-9]{7}'; then
Log error -s "PPTP VPN Server Shows Signs Of Compromise - Disabling Immediately!"
nvram set pptpd_enable="0"
nvram set pptpd_broadcast="0"
nvram commit
service stop_pptpd
service restart_samba
restartfirewall="1"
fi
# Detect and handle VPNFilter malware
if [ -e "/var/run/tor" ] || [ -e "/var/run/torrc" ] || [ -e "/var/run/tord" ] || [ -e "/var/run/vpnfilterm" ] || [ -e "/var/run/vpnfilterw" ]; then
Log error -s "Suspected VPNFilter Malware Found - Investigate Immediately!"
Log error -s "Caching Potential VPNFilter Malware: ${skynetloc}/vpnfilter.tar.gz"
tar -czf "${skynetloc}/vpnfilter.tar.gz" "/var/run/tor" "/var/run/torrc" "/var/run/tord" "/var/run/vpnfilterm" "/var/run/vpnfilterw" >/dev/null 2>&1
rm -rf "/var/run/tor" "/var/run/torrc" "/var/run/tord" "/var/run/vpnfilterm" "/var/run/vpnfilterw"
restartfirewall="1"
fi
# Detect chkupdate.sh malware
if [ -f "/jffs/chkupdate.sh" ] || [ -f "/tmp/update" ] || [ -f "/tmp/.update.log" ] || [ -f "/jffs/runtime.log" ] || grep -qsF "upgrade.sh" "/jffs/scripts/openvpn-event"; then
Log error -s "Warning! Router Malware Detected (chkupdate.sh) - Investigate Immediately!"
grep -hoE '([0-9]{1,3}\.){3}[0-9]{1,3}' "/jffs/chkupdate.sh" "/tmp/update" "/tmp/.update.log" "/jffs/runtime.log" "/jffs/scripts/openvpn-event" 2>/dev/null | awk '!x[$0]++' | while IFS= read -r ip; do
echo "add Skynet-Blacklist $ip comment \"Malware: chkupdate.sh\""
done | ipset restore -!
fi
# Detect updater malware
if [ -f "/jffs/updater" ] || [ -f "/jffs/p32" ] || [ -f "/tmp/pawns-cli" ] || [ -f "/tmp/updateservice" ] || nvram get "jffs2_exec" | grep -qF "/jffs/updater" || nvram get "script_usbmount" | grep -qF "/jffs/updater" || nvram get "script_usbumount" | grep -qF "/jffs/updater" || nvram get "vpn_server_custom" | grep -qF "/jffs/updater" || nvram get "vpn_server1_custom" | grep -qF "/jffs/updater" || cru l | grep -qF "/jffs/updater"; then
Log error -s "Warning! Router Malware Detected (/jffs/updater) - Investigate Immediately!"
Log error -s "Caching Potential Updater Malware: ${skynetloc}/malwareupdater.tar.gz"
nvram savefile "/tmp/nvramoutput.txt"
tar -czf "${skynetloc}/malwareupdater.tar.gz" "/jffs/updater" "/jffs/p32" "/tmp/pawns-cli" "/tmp/updateservice" "/tmp/nvramoutput.txt" "/root/.profile" >/dev/null 2>&1
rm -rf "/jffs/updater" "/jffs/p32" "/tmp/pawns-cli" "/tmp/updateservice" "/tmp/nvramoutput.txt"
echo > "/root/.profile"
cru d updater
nvram unset jffs2_exec
nvram unset script_usbmount
nvram unset script_usbumount
nvram unset vpn_server_custom
nvram unset vpn_server1_custom
nvram set vpn_server_state=0
nvram set vpn_server1_state=0
nvram commit
restartfirewall="1"
fi
}
Clean_Temp() {
rm -rf /tmp/skynet/*
mkdir -p /tmp/skynet/lists
}
IPSet_Wrapper() {
mode="$1" # add | del | import | flush | deport
setname="$2"
input="$3" # IP, file, or -
filtermode="$4" # --filtermode or auto-detect
comment="$5"
# Validate allowed sets
case "$setname" in
Skynet-Whitelist|Skynet-Blacklist|Skynet-IOT|Skynet-BlockedRanges) ;;
*) echo "[✘] Invalid IPSet: $setname" >&2; return 1 ;;
esac
# Validate mode
case "$mode" in
add|del|import|flush|deport) ;;
*) echo "[✘] Invalid mode: $mode" >&2; return 1 ;;
esac
# Fast flush path
if [ "$mode" = "flush" ]; then
ipset flush "$setname"
return 0
fi
# Input source
if [ "$input" = "-" ]; then
data="$(cat)"
elif [ -f "$input" ]; then
data="$(cat "$input")"
else
data="$input"
fi
# Auto-detect if input is raw ipset format (restore-ready)
if [ "$mode" = "import" ] && echo "$data" | head -n 1 | grep -qE '^(add|del) '; then
echo "$data" | ipset restore -!
return 0
fi
# Filter unless disabled
case "$filtermode" in
nofilter)
;; # Skip all filtering
skip-filter-ip)
data="$(echo "$data" | Filter_PrivateIP)"
;;
*)
data="$(echo "$data" | Filter_IP | Filter_PrivateIP)"
;;
esac
# DEPORT: selective delete only
if [ "$mode" = "deport" ]; then
echo "$data" | awk -v set="$setname" '{ printf "del %s %s\n", set, $1 }' | ipset restore -!
return 0
fi
# ADD / DEL / IMPORT
echo "$data" | awk -v mode="$mode" -v set="$setname" -v comment="$comment" '
{
ip = $1
if (mode == "add" || mode == "import") {
if (comment != "")
printf "add %s %s comment \"%s\"\n", set, ip, comment
else
printf "add %s %s\n", set, ip
} else if (mode == "del") {
printf "del %s %s\n", set, ip
}
}' | ipset restore -!
}
Unload_IPTables() {
iptables -t raw -D PREROUTING -i wgs+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
iptables -t raw -D PREROUTING -i tun2+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
iptables -t raw -D PREROUTING -i "$iface" -m set ! --match-set Skynet-MasterWL src -m set --match-set Skynet-Master src -j DROP 2>/dev/null
iptables -t raw -D PREROUTING -i br+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
iptables -t raw -D OUTPUT -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
iptables -D logdrop -m state --state NEW -j LOG --log-prefix "DROP " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
ip6tables -D logdrop -m state --state NEW -j LOG --log-prefix "DROP " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
iptables -D logdrop -m state --state NEW -m limit --limit 4/sec -j LOG --log-prefix "DROP " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
ip6tables -D logdrop -m state --state NEW -m limit --limit 4/sec -j LOG --log-prefix "DROP " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
}
Load_IPTables() {
if [ "$(nvram get wgs_enable)" = "1" ]; then
iptables -t raw -I PREROUTING -i wgs+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
fi
if [ "$(nvram get vpn_server1_state)" != "0" ] || [ "$(nvram get vpn_server2_state)" != "0" ]; then
iptables -t raw -I PREROUTING -i tun2+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
fi
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "inbound" ]; then
iptables -t raw -I PREROUTING -i "$iface" -m set ! --match-set Skynet-MasterWL src -m set --match-set Skynet-Master src -j DROP 2>/dev/null
fi
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "outbound" ]; then
iptables -t raw -I PREROUTING -i br+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
iptables -t raw -I OUTPUT -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP 2>/dev/null
fi
}
Unload_LogIPTables() {
iptables -t raw -D PREROUTING -i wgs+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
iptables -t raw -D PREROUTING -i tun2+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
iptables -t raw -D PREROUTING -i "$iface" -m set ! --match-set Skynet-MasterWL src -m set --match-set Skynet-Master src -j LOG --log-prefix "[BLOCKED - INBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
iptables -t raw -D PREROUTING -i br+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
iptables -t raw -D OUTPUT -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
iptables -D logdrop -m state --state NEW -j LOG --log-prefix "[BLOCKED - INVALID] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -j LOG --log-prefix "[BLOCKED - IOT] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
}
Load_LogIPTables() {
if Is_Enabled "$logmode"; then
if [ "$(nvram get wgs_enable)" = "1" ]; then
pos1="$(iptables --line -vnL PREROUTING -t raw | grep -F "Skynet-Master dst" | grep -F "DROP" | grep -F "wgs" | awk '{print $1}')"
iptables -t raw -I PREROUTING "$pos1" -i wgs+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
fi
if [ "$(nvram get vpn_server1_state)" != "0" ] || [ "$(nvram get vpn_server2_state)" != "0" ]; then
pos2="$(iptables --line -vnL PREROUTING -t raw | grep -F "Skynet-Master dst" | grep -F "DROP" | grep -F "tun" | awk '{print $1}')"
iptables -t raw -I PREROUTING "$pos2" -i tun2+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
fi
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "inbound" ]; then
pos3="$(iptables --line -nL PREROUTING -t raw | grep -F "Skynet-Master src" | grep -F "DROP" | awk '{print $1}')"
iptables -t raw -I PREROUTING "$pos3" -i "$iface" -m set ! --match-set Skynet-MasterWL src -m set --match-set Skynet-Master src -j LOG --log-prefix "[BLOCKED - INBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
fi
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "outbound" ]; then
pos4="$(iptables --line -vnL PREROUTING -t raw | grep -F "Skynet-Master dst" | grep -F "DROP" | grep -vF "tun" | grep -vF "wgs" | awk '{print $1}')"
iptables -t raw -I PREROUTING "$pos4" -i br+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
pos5="$(iptables --line -nL OUTPUT -t raw | grep -F "Skynet-Master dst" | grep -F "DROP" | awk '{print $1}')"
iptables -t raw -I OUTPUT "$pos5" -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
fi
if [ "$(nvram get fw_log_x)" = "drop" ] || [ "$(nvram get fw_log_x)" = "both" ] && Is_Enabled "$loginvalid"; then
pos6="$(iptables --line -nL logdrop | grep -F "DROP" | awk '{print $1}')"
iptables -I logdrop "$pos6" -m state --state NEW -j LOG --log-prefix "[BLOCKED - INVALID] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
fi
if Is_Enabled "$iotblocked" && Is_Enabled "$iotlogging"; then
pos7="$(iptables --line -nL FORWARD | grep -F "Skynet-IOT" | grep -F "DROP" | awk '{print $1}')"
iptables -I FORWARD "$pos7" -i br+ -m set --match-set Skynet-IOT src -j LOG --log-prefix "[BLOCKED - IOT] " --log-tcp-sequence --log-tcp-options --log-ip-options 2>/dev/null
fi
fi
}
Unload_IOTTables() {
if Is_Enabled "$iotblocked"; then
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -o wgs+ -j ACCEPT 2>/dev/null
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -o tun2+ -j ACCEPT 2>/dev/null
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -j DROP 2>/dev/null
if [ -n "$iotports" ]; then
if [ "$iotproto" = "all" ] || [ "$iotproto" = "udp" ]; then
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p udp -m udp -m multiport --dports "$iotports" -j ACCEPT 2>/dev/null
fi
if [ "$iotproto" = "all" ] || [ "$iotproto" = "tcp" ]; then
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p tcp -m tcp -m multiport --dports "$iotports" -j ACCEPT 2>/dev/null
fi
else
if [ "$iotproto" = "all" ] || [ "$iotproto" = "udp" ]; then
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p udp -m udp --dport 123 -j ACCEPT 2>/dev/null
fi
if [ "$iotproto" = "all" ] || [ "$iotproto" = "tcp" ]; then
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p tcp -m tcp --dport 123 -j ACCEPT 2>/dev/null
fi
fi
iptables -D FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p icmp -j ACCEPT 2>/dev/null
fi
}
Load_IOTTables() {
if Is_Enabled "$iotblocked"; then
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -j DROP 2>/dev/null
if [ "$(nvram get vpn_server1_state)" != "0" ] || [ "$(nvram get vpn_server2_state)" != "0" ]; then
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -o tun2+ -j ACCEPT 2>/dev/null
fi
if [ "$(nvram get wgs_enable)" = "1" ]; then
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -o wgs+ -j ACCEPT 2>/dev/null
fi
if [ -n "$iotports" ]; then
if [ "$iotproto" = "all" ] || [ "$iotproto" = "udp" ]; then
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p udp -m udp -m multiport --dports "$iotports" -j ACCEPT 2>/dev/null
fi
if [ "$iotproto" = "all" ] || [ "$iotproto" = "tcp" ]; then
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p tcp -m tcp -m multiport --dports "$iotports" -j ACCEPT 2>/dev/null
fi
else
if [ "$iotproto" = "all" ] || [ "$iotproto" = "udp" ]; then
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p udp -m udp --dport 123 -j ACCEPT 2>/dev/null
fi
if [ "$iotproto" = "all" ] || [ "$iotproto" = "tcp" ]; then
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p tcp -m tcp --dport 123 -j ACCEPT 2>/dev/null
fi
fi
iptables -I FORWARD -i br+ -m set --match-set Skynet-IOT src -o "$iface" -p icmp -j ACCEPT 2>/dev/null
fi
}
Check_IPSets() {
ipset -L -n Skynet-MasterWL >/dev/null 2>&1 || fail="${fail}#1 "
ipset -L -n Skynet-Blacklist >/dev/null 2>&1 || fail="${fail}#2 "
ipset -L -n Skynet-BlockedRanges >/dev/null 2>&1 || fail="${fail}#3 "
ipset -L -n Skynet-Master >/dev/null 2>&1 || fail="${fail}#4 "
ipset -L -n Skynet-IOT >/dev/null 2>&1 || fail="${fail}#5 "
if [ -n "$fail" ]; then return 1; fi
}
Check_IPTables() {
raw_rules=$(iptables-save -t raw)
filter_rules=$(iptables-save -t filter)
#6: WireGuard DROP
if [ "$(nvram get wgs_enable)" = "1" ]; then
echo "$raw_rules" | grep -Fq -- '-A PREROUTING -i wgs+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP' || fail="${fail}#6 "
fi
#7: OpenVPN DROP
if [ "$(nvram get vpn_server1_state)" != "0" ] || [ "$(nvram get vpn_server2_state)" != "0" ]; then
echo "$raw_rules" | grep -Fq -- '-A PREROUTING -i tun2+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP' || fail="${fail}#7 "
fi
#8: Inbound on $iface
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "inbound" ]; then
echo "$raw_rules" | grep -Fq -- "-A PREROUTING -i $iface -m set ! --match-set Skynet-MasterWL src -m set --match-set Skynet-Master src -j DROP" || fail="${fail}#8 "
fi
#9 & #10: Outbound on br+ and OUTPUT
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "outbound" ]; then
echo "$raw_rules" | grep -Fq -- '-A PREROUTING -i br+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP' || fail="${fail}#9 "
echo "$raw_rules" | grep -Fq -- '-A OUTPUT -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j DROP' || fail="${fail}#10 "
fi
#11–17: IOT blocking
if Is_Enabled "$iotblocked"; then
if [ "$(nvram get wgs_enable)" = "1" ]; then
echo "$filter_rules" | grep -Fq -- '-A FORWARD -i br+ -o wgs+ -m set --match-set Skynet-IOT src -j ACCEPT' || fail="${fail}#11 "
fi
if [ "$(nvram get vpn_server1_state)" != "0" ] || [ "$(nvram get vpn_server2_state)" != "0" ]; then
echo "$filter_rules" | grep -Fq -- '-A FORWARD -i br+ -o tun2+ -m set --match-set Skynet-IOT src -j ACCEPT' || fail="${fail}#12 "
fi
echo "$filter_rules" | grep -Fq -- '-A FORWARD -i br+ -m set --match-set Skynet-IOT src -j DROP' || fail="${fail}#13 "
if [ -n "$iotports" ]; then
if [ "$iotproto" = "all" ] || [ "$iotproto" = "udp" ]; then
echo "$filter_rules" | grep -Fq -- "-A FORWARD -i br+ -m set --match-set Skynet-IOT src -o $iface -p udp -m udp -m multiport --dports $iotports -j ACCEPT" || fail="${fail}#14 "
fi
if [ "$iotproto" = "all" ] || [ "$iotproto" = "tcp" ]; then
echo "$filter_rules" | grep -Fq -- "-A FORWARD -i br+ -m set --match-set Skynet-IOT src -o $iface -p tcp -m tcp -m multiport --dports $iotports -j ACCEPT" || fail="${fail}#15 "
fi
else
if [ "$iotproto" = "all" ] || [ "$iotproto" = "udp" ]; then
echo "$filter_rules" | grep -Fq -- "-A FORWARD -i br+ -o $iface -p udp -m set --match-set Skynet-IOT src -m udp --dport 123 -j ACCEPT" || fail="${fail}#16 "
fi
if [ "$iotproto" = "all" ] || [ "$iotproto" = "tcp" ]; then
echo "$filter_rules" | grep -Fq -- "-A FORWARD -i br+ -o $iface -p tcp -m set --match-set Skynet-IOT src -m tcp --dport 123 -j ACCEPT" || fail="${fail}#17 "
fi
fi
fi
#18–24: LOG rules
if Is_Enabled "$logmode"; then
#18: OpenVPN LOG
if { [ "$(nvram get vpn_server1_state)" != "0" ] || [ "$(nvram get vpn_server2_state)" != "0" ]; }; then
echo "$raw_rules" \
| grep -Fq -- '-A PREROUTING -i tun2+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] "' || fail="${fail}#18 "
fi
#19: WireGuard LOG
if [ "$(nvram get wgs_enable)" = "1" ]; then
echo "$raw_rules" \
| grep -Fq -- '-A PREROUTING -i wgs+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] "' || fail="${fail}#19 "
fi
#20: IoT LOG
if Is_Enabled "$iotblocked" && Is_Enabled "$iotlogging"; then
echo "$filter_rules" \
| grep -Fq -- '-A FORWARD -i br+ -m set --match-set Skynet-IOT src -j LOG --log-prefix "[BLOCKED - IOT] "' || fail="${fail}#20 "
fi
#21: Inbound LOG
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "inbound" ]; then
echo "$raw_rules" \
| grep -Fq -- "-A PREROUTING -i $iface -m set ! --match-set Skynet-MasterWL src -m set --match-set Skynet-Master src -j LOG --log-prefix \"[BLOCKED - INBOUND] \"" || fail="${fail}#21 "
fi
#22: Outbound PREROUTING LOG
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "outbound" ]; then
echo "$raw_rules" \
| grep -Fq -- '-A PREROUTING -i br+ -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] "' || fail="${fail}#22 "
fi
#23: Outbound OUTPUT LOG
if [ "$filtertraffic" = "all" ] || [ "$filtertraffic" = "outbound" ]; then
echo "$raw_rules" \
| grep -Fq -- '-A OUTPUT -m set ! --match-set Skynet-MasterWL dst -m set --match-set Skynet-Master dst -j LOG --log-prefix "[BLOCKED - OUTBOUND] "' || fail="${fail}#23 "
fi
#24: Invalid LOG
if [ "$(nvram get fw_log_x)" != "off" ] && Is_Enabled "$loginvalid"; then
echo "$filter_rules" \
| grep -Fq -- '-A logdrop -m state --state NEW -j LOG --log-prefix "[BLOCKED - INVALID] "' || fail="${fail}#24 "
fi
fi
[ -n "$fail" ] && return 1 || return 0
}
Unload_IPSets() {
ipset -q destroy Skynet-Master
ipset -q destroy Skynet-MasterWL
ipset -q destroy Skynet-Blacklist
ipset -q destroy Skynet-BlockedRanges
ipset -q destroy Skynet-Whitelist
ipset -q destroy Skynet-WhitelistDomains
ipset -q destroy Skynet-IOT
}
Unload_Cron() {
# If no argument or "all", reset $@ to the full list
if [ -z "$1" ] || [ "$1" = "all" ]; then
set -- "save" "banmalware" "autoupdate" "checkupdate" "genstats"
fi
for job in "$@"; do
case "$job" in
save)
cru d Skynet_save
;;
banmalware)
cru d Skynet_banmalware
;;
autoupdate)
cru d Skynet_autoupdate
;;
checkupdate)
cru d Skynet_checkupdate
;;
genstats)
cru d Skynet_genstats
;;
*)
echo "[*] Warning: Unknown Cron Job '$job'"
;;
esac
done
}
Load_Cron() {
for job in "$@"; do
case "$job" in
save)
cru a Skynet_save "0 * * * * sh /jffs/scripts/firewall save"
;;
banmalwaredaily)
hour=$(Generate_Random_Number 1 23)
cru a Skynet_banmalware "25 $hour * * * sh /jffs/scripts/firewall banmalware"
;;
banmalwareweekly)
hour=$(Generate_Random_Number 1 23)
cru a Skynet_banmalware "25 $hour * * Mon sh /jffs/scripts/firewall banmalware"
;;
autoupdate)
min=$(Generate_Random_Number 3 23)
cru a Skynet_autoupdate "$min 1 * * Mon sh /jffs/scripts/firewall update"
;;
checkupdate)
min=$(Generate_Random_Number 3 23)
cru a Skynet_checkupdate "$min 1 * * Mon sh /jffs/scripts/firewall update check"
;;
genstats)
min=$(Generate_Random_Number 28 57)
cru a Skynet_genstats "$min */12 * * * sh /jffs/scripts/firewall debug genstats"
;;
*)
echo "[*] Warning: Unknown Cron Job '$job'"
;;
esac
done
}
Generate_Random_Number() {
awk -v min="$1" -v max="$2" -v freq=1 'BEGIN{"tr -cd 0-9 </dev/urandom | head -c 6" | getline seed; srand(seed); for(i=0;i<freq;i++)print int(min+rand()*(max-min+1))}'
}
Is_IP() {
grep -qE '^(((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.){3}(25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\/(32))?)$'
}
Is_Range() {
grep -qE '^(((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.){3}(25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\/(1?[0-9]|2?[0-9]|3?[0-1])){1})$'
}
Is_IPRange() {
grep -qE '^(((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.){3}(25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\/(1?[0-9]|2?[0-9]|3?[0-2]))?)$'
}
Is_MAC() {
grep -qE '^([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}$'
}
Is_Port() {
grep -qE '^[0-9]{1,5}$'
}
Is_ASN() {
grep -qiE '^AS[0-9]{1,6}$'
}
Is_Numeric() {
case "$1" in
*[!0-9]*) return 1 ;; # If any non-digit, fail
"") return 1 ;; # If empty, fail
*) return 0 ;; # Otherwise, success
esac
}
Strip_Domain() {
sed 's~http[s]*://~~;s~/.*~~;s~www\.~~g;\~^$~d' | awk '!x[$0]++'
}
LAN_CIDR_Lookup() {
if [ "$(echo "$1" | cut -c1-8)" = "192.168." ]; then
echo "192.168.0.0/16"
elif [ "$(echo "$1" | cut -c1-4)" = "172." ]; then
echo "172.16.0.0/12"
elif [ "$(echo "$1" | cut -c1-3)" = "10." ]; then
echo "10.0.0.0/8"
fi
}
Generate_Ban_Stats() {
case "$1" in
1)
if Is_Enabled "$lookupcountry"; then
country="$(curl -fsSL --retry 3 --max-time 6 "https://api.db-ip.com/v2/free/${statdata}/countryCode/" 2>/dev/null | grep -E '^[A-Z]{2}$' || echo '**')"
fi
# banreason: single AWK for both blacklist and CIDR, star only on CIDR
banreason="$(
grep -E '^add Skynet-(Blacklist|BlockedRanges) ' "$skynetipset" |
awk -v ip="$statdata" '
function trim(s) { sub(/^ +| +$/, "", s); return s }
function do_print(cidr) {
pos = index($0, "comment \"")
if (pos) {
s = substr($0, pos+9); sub(/"$/, "", s)
printf "%s", trim(s)
if (cidr) printf "*"
printf "\n"
}
}
BEGIN { split(ip,A,"."); ipn=A[1]*16777216 + A[2]*65536 + A[3]*256 + A[4] }
# exact blacklist
$1=="add" && $2=="Skynet-Blacklist" && $3==ip { do_print(0); exit }
# CIDR ranges
$1=="add" && $2=="Skynet-BlockedRanges" {
split($3,P,"/"); net=P[1]; prefix=P[2]
split(net,B,"."); netn=B[1]*16777216 + B[2]*65536 + B[3]*256 + B[4]
if (prefix==32 && ipn==netn) { do_print(0); exit }
else if (prefix==24 && A[1]==B[1]&&A[2]==B[2]&&A[3]==B[3]) { do_print(1); exit }
else if (prefix==16 && A[1]==B[1]&&A[2]==B[2]) { do_print(1); exit }
else if (prefix==8 && A[1]==B[1]) { do_print(1); exit }
else {
sh=32-prefix; div=1
for(i=0;i<sh;i++) div*=2
if (int(ipn/div)==int(netn/div)) { do_print(1); exit }
}
}
'
)"
[ -z "$banreason" ] && ! ipset -q test Skynet-Blacklist "$ipaddr" && ! ipset -q test Skynet-BlockedRanges "$ipaddr" && banreason="No Longer Blacklisted"
[ "${#banreason}" -gt 45 ] && banreason="$(printf '%s' "$banreason" | cut -c1-45)"
printf '%-15s %-4s | %-55s | %-45s | %-60s \n' "$statdata" "$country" "https://otx.alienvault.com/indicator/ip/${statdata}" "$banreason" "$(grep -F "$statdata" /tmp/skynet/skynetstats.txt | awk '{print $1}' | xargs)"
;;
2)
hits="$(echo "$statdata" | awk '{print $1}')"
ipaddr="$(echo "$statdata" | awk '{print $2}')"
if Is_Enabled "$lookupcountry"; then
country="$(curl -fsSL --retry 3 --max-time 6 "https://api.db-ip.com/v2/free/${ipaddr}/countryCode/" 2>/dev/null | grep -E '^[A-Z]{2}$' || echo '**')"
fi
# banreason: single AWK for both blacklist and CIDR, star only on CIDR
banreason="$(
grep -E '^add Skynet-(Blacklist|BlockedRanges) ' "$skynetipset" |
awk -v ip="$ipaddr" '
function trim(s) { sub(/^ +| +$/, "", s); return s }
function do_print(cidr) {
pos = index($0, "comment \"")
if (pos) {
s = substr($0, pos+9); sub(/"$/, "", s)
printf "%s", trim(s)
if (cidr) printf "*"
printf "\n"
}
}
BEGIN { split(ip,A,"."); ipn=A[1]*16777216 + A[2]*65536 + A[3]*256 + A[4] }
# exact blacklist
$1=="add" && $2=="Skynet-Blacklist" && $3==ip { do_print(0); exit }
# CIDR ranges
$1=="add" && $2=="Skynet-BlockedRanges" {
split($3,P,"/"); net=P[1]; prefix=P[2]
split(net,B,"."); netn=B[1]*16777216 + B[2]*65536 + B[3]*256 + B[4]
if (prefix==32 && ipn==netn) { do_print(0); exit }
else if (prefix==24 && A[1]==B[1]&&A[2]==B[2]&&A[3]==B[3]) { do_print(1); exit }
else if (prefix==16 && A[1]==B[1]&&A[2]==B[2]) { do_print(1); exit }
else if (prefix==8 && A[1]==B[1]) { do_print(1); exit }
else {
sh=32-prefix; div=1
for(i=0;i<sh;i++) div*=2
if (int(ipn/div)==int(netn/div)) { do_print(1); exit }
}
}
'
)"
[ -z "$banreason" ] && ! ipset -q test Skynet-Blacklist "$ipaddr" && ! ipset -q test Skynet-BlockedRanges "$ipaddr" && banreason="No Longer Blacklisted"
[ "${#banreason}" -gt 45 ] && banreason="$(printf '%s' "$banreason" | cut -c1-45)"
printf '%-10s | %-15s %-4s | %-55s | %-45s | %-60s\n' "${hits}x" "$ipaddr" "$country" "https://otx.alienvault.com/indicator/ip/${ipaddr}" "$banreason" "$(grep -F "$ipaddr" /tmp/skynet/skynetstats.txt | awk '{print $1}' | xargs)"
;;
*)
echo "[*] Error - No Stats Specified To Load"
;;
esac
}
Display_Header() {
case "$1" in
1)
printf '\n\n%-20s | %-55s | %-45s | %-60s\n' "--------------" "--------------" "--------------" "----------------------"
printf '%-20s | %-55s | %-45s | %-60s\n' "| IP Address |" "| AlienVault |" "| Ban Reason |" "| Associated Domains |"
printf '%-20s | %-55s | %-45s | %-60s\n\n' "--------------" "--------------" "--------------" "----------------------"
;;
2)
printf '\n\n%-10s | %-20s | %-55s | %-45s | %-60s\n' "--------" "--------------" "--------------" "--------------" "----------------------"
printf '%-10s | %-20s | %-55s | %-45s | %-60s\n' "| Hits |" "| IP Address |" "| AlienVault |" "| Ban Reason |" "| Associated Domains |"
printf '%-10s | %-20s | %-55s | %-45s | %-60s\n\n' "--------" "--------------" "--------------" "--------------" "----------------------"
;;
3)
printf '\n\n%-10s | %-10s | %-60s\n' "--------" "--------" "--------------"
printf '%-10s | %-10s | %-60s\n' "| Hits |" "| Port |" "| SpeedGuide |"