-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip-array_ipt_functions
10397 lines (10030 loc) · 360 KB
/
ip-array_ipt_functions
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
# ------------------------------------------------------------------------- #
#*# ###### #
# # # # # ##### ##### ## # #
# # # # # # # # # # # # #
# ###### ##### # # # # # # # # #
# # ####### ##### ##### ###### #
# # # # # # # # # # #
### # # # # # # # # # #
# ------------------------------------------------------------------------- #
#
# Copyright (C) 2005-2018 Mart Frauenlob aka AllKind
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ------------------------------------------------------------------------- #
#
# IP-ARRAY IPTABLES FUNCTIONS
#
# ------------------------------------------------------------------------- #
# ------------------------------------------------------------------------- #
# IPTABLES VALIDATION FUNCTIONS
# ------------------------------------------------------------------------- #
val_ip4_addr() { # validate IPv4 addresses
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local str_regex="((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
IPSTRING=""
if [[ $1 = 0/0 ]]; then
IPSTRING="IPNET"
elif [[ $1 =~ ^${str_regex}$ ]]; then
IPSTRING="IPADDR"
elif [[ $1 =~ ^${str_regex}(/([3][0-2]|[1-2]?[0-9]))?$ ]]; then
IPSTRING="IPNET"
elif [[ $1 =~ ^${str_regex}/${str_regex}$ ]]; then
IPSTRING="IPNETMASK"
elif [[ $1 =~ ^${str_regex}-${str_regex}$ ]]; then
if (($(decodeaddr ${1%-*}) > $(decodeaddr ${1#*-}))); then
log -E "IP range \`$1' is not valid."
return 1
fi
IPSTRING="IPRANGE"
else
log -E "IPv4 address specification \`$1' is not valid."
return 1
fi
return 0
#case "${str_ip_addr}" in
# # IP string is global shortcut
# (0/0 | 0.0.0.0/0)
# IPSTRING="IPNET"
# return 0
# ;;
# # IP string is single IP
# (+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]]))
# val_oct_range ${str_ip_addr//./ } || {
# log -E "IP address \`${str_ip_addr}' is not valid."
# return 1
# }
# IPSTRING="IPADDR"
# ;;
# # IP string is IP/CIDR Mask
# (+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])/+([[:digit:]]))
# local ip_addr="${str_ip_addr%/*}"
# local mask="${str_ip_addr#*/}"
# val_oct_range ${ip_addr//./ } || {
# log -E "IP address \`${ip_addr}' is not valid."
# return 1
# }
# val_ipv4_cidr_mask "${mask}" || {
# log -E "Netmask \`${mask}' of IP address \`${ip_addr}' is not valid."
# return 1
# }
# IPSTRING="IPNET"
# ;;
# # IP string is IP/Netmask
# (+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])/+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]]))
# local ip_addr="${str_ip_addr%/*}"
# local mask="${str_ip_addr#*/}"
# val_oct_range ${ip_addr//./ } || {
# log -E "IP address \`${ip_addr}' is not valid."
# return 1
# }
# val_ipv4_netmask "${mask}" || {
# log -E "Netmask \`${mask}' of IP address \`${ip_addr}' is not valid."
# return 1
# }
# IPSTRING="IPNETMASK"
# ;;
# # IP string is IP-range
# (+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])-+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]]))
# for range_ip in ${str_ip_addr/-/ }; do
# val_oct_range ${range_ip//./ } || {
# log -E "IP range \`${range_ip}' is not valid."
# return 1
# }
# done
# if (($(decodeaddr ${str_ip_addr%-*}) > $(decodeaddr ${str_ip_addr#*-}))); then
# log -E "IP range \`${range_ip}' is not valid."
# return 1
# fi
# IPSTRING="IPRANGE"
# ;;
# (*) log -E "IPv4 address specification \`${str_ip_addr}' is not valid."
# return 1
#esac
} # -------------------------------------------------------------------------
classify_ip4_addr() { # classify IPv4 addresses
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$1" in
# IP string is global shortcut
(0/0 | 0.0.0.0/0) printf "IPNET\n" ;;
# IP string is single IP
(+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])) printf "IPADDR\n" ;;
# IP string is IP/Mask
(+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])/+([[:digit:]])) printf "IPNET\n" ;;
(+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])/+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])) printf "IPNET\n" ;;
# IP string is IP-range
(+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]])-+([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]]))
printf "IPRANGE\n"
;;
(*) log -E "Unknown error while processing \`$1'."; return 1 ;;
esac
} # -------------------------------------------------------------------------
val_ipv4_addr_no_range() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
val_ip4_addr "$1" || return 1
[[ ${IPSTRING} != IPRANGE ]] || {
log -E "IP-range address not valid in context."
return 1
}
} # -------------------------------------------------------------------------
val_state() { # validate state specifications
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local str
#check_str_unique "${1//,/ }" || return 1
#for str in $(string_toupper "$(IFS=, split_val ${1})"); do
for str in $(string_toupper "${1//,/ }"); do
case "${str}" in
(NEW|ESTABLISHED|RELATED|INVALID|UNTRACKED)
continue
;;
*) log -E "Invalid state entry \`$1'."
return 1
esac
done
} # -------------------------------------------------------------------------
val_rej_type() { # validate reject target types
[[ $2 ]] || { reqparm $FUNCNAME 2; return 1; }
case "$(string_tolower "$1")" in
tcp-reset)
if [[ $2 != @(tcp|6) ]]; then
log -E "tcp-reset is only valid with tcp."
return 1
fi
;;
icmp-net-unreachable|icmp-host-unreachable|icmp-port-unreachable|icmp-proto-unreachable|\
icmp-net-prohibited|icmp-host-prohibited|icmp-admin-prohibited)
return 0
;;
*) log -E "Invalid reject target type: \`$1'."
return 1
esac
} # -------------------------------------------------------------------------
validate_reject_type() { # validate reject target types
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$(string_tolower "$1")" in
tcp-reset|icmp-net-unreachable|icmp-host-unreachable|icmp-port-unreachable|icmp-proto-unreachable|\
icmp-net-prohibited|icmp-host-prohibited|icmp-admin-prohibited)
return 0
;;
*) log -E "Invalid reject type: \`$1'."
return 1
esac
} # -------------------------------------------------------------------------
val_limit() { # validate iptables limit match values
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local err_msg="Illegal limit specification \`${@}'."
set -- ${@//\// }
local limit_num=$1 limit_val=$2
val_numeric_quiet ${limit_num} || { log -E "${err_msg}"; return 1; }
if [[ ${limit_val} ]]; then
case "$(string_tolower "${limit_val}")" in
s|m|h|d|second|minute|hour|day)
return 0
;;
*) log -E "${err_msg}"
return 1
esac
fi
} # -------------------------------------------------------------------------
val_icmp_type() { # validate an icmp type[/code]
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local icmptype="$1"
local itc
case "${icmptype}" in
+([[:digit:]]))
if ! val_8bit "${icmptype}"; then
log -E "ICMP type \`${icmptype}' not legal."
return 1
fi
;;
+([[:digit:]])@(/)+([[:digit:]]))
for itc in ${@//\// }; do
if ! val_8bit "${itc}"; then
log -E "ICMP type or code \`${itc}' not legal."
return 1
fi
done
;;
*) if ! lsearch "$(string_tolower "${icmptype}")" ${VALID_ICMP_TYPES}; then
log -E "ICMP type \`${icmptype}' not legal."
return 1
fi
esac
return 0
} # -------------------------------------------------------------------------
val_proto() { # validate protocol specifications
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local -i p_idx
local val_prot="$(string_tolower "$1")"
case "$val_prot" in
all|tcp|udp|icmp)
return 0
;;
+([[:digit:]]))
val_8bit "$val_prot" && return
;;
*+([[:alpha:]])*)
for p_idx in ${!PROTOCOLS_ARRAY[@]}; do
[[ ${PROTOCOLS_ARRAY[p_idx]} = $val_prot ]] && return
done
;;
esac
log -E "Invalid protocol specification \`$val_prot'."
return 1
} # -------------------------------------------------------------------------
val_loglevel() { # validate syslog loglevel values
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$(string_tolower "$1")" in
[[:digit:]])
if (($1 < 0 || ${1} > 7)); then
log -E "Invalid loglevel value \`$1'. Must be between '0-7'."
return 1
fi
;;
alert|crit|debug|emerg|err|info|notice|warning)
return 0
;;
error|panic|warn)
log -W "Loglevel \`$1' is deprecated."
return 0
;;
*) log -E "Invalid loglevel value \`$1'."
return 1
esac
} # -------------------------------------------------------------------------
val_tos() { # validate TOS specifications allowed within iptables
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$(string_tolower "$1")" in
minimize-delay|maximize-throughput|maximize-reliability|minimize-cost|normal-service)
return 0
;;
0|2|4|8|16|0[xX]00|0[xX]02|0[xX]04|0[xX]08|0[xX]10)
return 0
;;
*) log -E "Invalid TOS value \`$1'. See \`iptables -m tos -h' for help."
return 1
esac
} # -------------------------------------------------------------------------
validate_target() { # target name validation
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$1" in
ACCEPT|DROP|RETURN) return 0 ;; # catch some known
CHECKSUM|ECN|LOG|CLASSIFY|MARK|CONNMARK|CONNSECMARK|SECMARK|DSCP|MASQUERADE|NETMAP|\
REDIRECT|REJECT|SET|DNAT|SNAT|RAWDNAT|RAWSNAT|QUEUE|NFQUEUE|TCPOPTSTRIP|TOS|TTL|TCPMSS|\
ULOG|NFLOG|TPROXY) # these are registered
if check_tgt_exist $1; then return 0
else
log -t "$1"
return 1
fi
;;
*) val_userdef_chain_target "$1" || return 1
esac
} # -------------------------------------------------------------------------
val_table() { # validate iptables table names
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$1" in
filter|nat)
(($(subst_var "ENABLE_$(string_toupper "$1")") == 1)) || {
log -E "\`$1' table is disabled by configuration."
return 1
}
;;
mangle)
if ((ENABLE_MANGLE == 0 && ENABLE_TC_SHAPING == 0)); then
log -E "\`$1' table is disabled by configuration."
return 1
fi
;;
raw)
if ((ENABLE_RAW == 0)); then
log -E "\`$1' table is disabled by configuration."
return 1
fi
if ((RAW_TABLE_PRESENT == 0)); then
log -E "\`$1' table is not present on the local system."
return 1
fi
;;
rawpost)
if ((ENABLE_RAWPOST == 0)); then
log -E "\`$1' table is disabled by configuration."
return 1
fi
if ((RAWPOST_TABLE_PRESENT == 0)); then
log -E "\`$1' table is not present on the local system."
return 1
fi
;;
security)
if ((ENABLE_SECURITY == 0)); then
log -E "\`$1' table is disabled by configuration."
return 1
fi
if ((SECURITY_TABLE_PRESENT == 0)); then
log -E "\`$1' table is not present on the local system."
return 1
fi
;;
*) log -E "Illegal iptables table name: \`$1'."; return 1
esac
} # -------------------------------------------------------------------------
val_builtin_chain() { # validate iptables builtin chain names
[[ $2 ]] || { reqparm $FUNCNAME 2; return 1; }
case "$1" in
filter|security) [[ $2 != @(INPUT|OUTPUT|FORWARD) ]] || return 0 ;;
nat) [[ $2 != @(PREROUTING|OUTPUT|POSTROUTING) ]] || return 0 ;;
mangle)
# mangle table chains prior to kernel 2.4.18
if ((ALL_MANGLE_CHAINS_PRESENT == 0)); then
[[ $2 != @(OUTPUT|PREROUTING) ]] || return 0
else
# mangle table chains in kernel version greater than 2.4.17
[[ $2 != @(INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING) ]] || return 0
fi
;;
raw) [[ $2 != @(OUTPUT|PREROUTING) ]] || return 0 ;;
rawpost) [[ $2 != POSTROUTING ]] || return 0 ;;
esac
log -E "Illegal iptables chain name: \`$2'."
return 1
} # -------------------------------------------------------------------------
val_userdef_chain_target() { # validate a user defined iptables chain or target name
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local str_tgt="$1"
[[ ${str_tgt} = goto:* ]] && str_tgt="${str_tgt#goto:}"
((${#str_tgt} > 30)) && {
log -E "Chain or target names must not exceed a maximum of 30 characters."
return 1
}
case "${str_tgt}" in
+([[:graph:]])*)
[[ ${str_tgt:0:1} = @('!'|'-') ]] && {
log -E "Chain or target names must not begin with \`${str_tgt:0:1}'."
return 1
}
[[ ${str_tgt} = +(*[,]*) ]] && {
log -E "${ME} does not allow commas in chain or target names."
return 1
}
return 0
;;
*+([[:space:]])*)
log -E "Iptables does support space class characters in chain or target names, but ${ME} forbids it."
return 1
;;
esac
return 0
} # -------------------------------------------------------------------------
val_policy_target() { # validate iptables policy targets
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$1" in
ACCEPT|DROP) return 0 ;;
*) log -E "Illegal iptables policy target: \`$1'."
return 1
esac
} # -------------------------------------------------------------------------
val_limit_burst() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
val_numeric_quiet "$1" || {
log -E "Invalid burst value \`$1'."
return 1
}
} # -------------------------------------------------------------------------
val_icmp_types() { # validate a multiple icmp types string
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
#local i_type str_i_types="$(IFS=, split_val ${@/ })"
local i_type str_i_types="${@//,/ }"
check_multi_negation ${str_i_types} || return 1
for i_type in ${str_i_types/!/}; do
val_icmp_type "${i_type}" || return 1
done
} # -------------------------------------------------------------------------
validate_nat_ip() { # validate the ip address of a nat ip definition
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local str_ip str_natip="$1"
string_negated "${str_natip}" && {
log -E "Negating NAT source or destination IP is not allowed."
return 1
}
for str_ip in ${str_natip//-/ }; do val_ip4_addr ${str_ip} || return 1; done
} # -------------------------------------------------------------------------
val_nat_port() { # validate nat port specifications
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local nport
for nport in ${1//-/ }; do val_port ${nport} || return 1; done
} # -------------------------------------------------------------------------
val_port() { # validate port specifications
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
[[ $1 = ':' ]] && return 0
local pval val_port="$1"
case "$val_port" in
@(+([[:digit:]]):)) val_port="${1%:}" ;;
@(+([[:digit:]]):+([[:digit:]]))) val_port="${1/:/ }" ;;
esac
for pval in $val_port; do
case "$pval" in
+([[:digit:]]))
if ! val_16bit "$pval"; then
log -E "Invalid port specification \`$pval'."
return 1
fi
;;
*+([[:alpha:]])*)
if ! lsearch "$val_port" "${SERVICES_ARRAY[@]}"; then
log -E "Invalid port specification \`$pval'."
return 1
fi
;;
*) log -E "Invalid port specification \`$pval'."
return 1
esac
done
} # -------------------------------------------------------------------------
val_multi_ports() { # validate a multiport port definition string
#local m_port str_m_ports="$(IFS=, split_val ${@})"
local m_port str_m_ports="${@//,/ }"
if check_match_exist multiport; then
check_multi_negation_first_allowed $str_m_ports || return 1
else
check_multi_negation $str_m_ports || return 1
fi
for m_port in ${str_m_ports#!}; do
val_port "$m_port" || return 1
done
} # -------------------------------------------------------------------------
val_port_range() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local str_prange="$1"
local str_failcmd='eval log -E "Invalid port-range specification: $str_prange"; return 1'
local IFS='-'
set -- $1
local str_rb="$1" str_re="$2"
unset IFS
(($# == 2)) || $str_failcmd
val_numeric "$str_rb" && val_numeric "$str_re" || $str_failcmd
val_16bit "$str_rb" && val_16bit "$str_re" || $str_failcmd
if ((str_rb >= str_re)); then $str_failcmd; fi
} # -------------------------------------------------------------------------
val_port_range_word() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local str_prange="$1"
local str_failcmd='eval log -E "Invalid port-range specification: $str_prange"; return 1'
local IFS='-'
set -- $1
local str_rb="$1" str_re="$2"
unset IFS
case "$str_prange" in
+([[:digit:]])-+([[:digit:]]))
(($# == 2)) || $str_failcmd
val_16bit "$str_rb" && val_16bit "$str_re" || $str_failcmd
if ((str_rb >= str_re)); then $str_failcmd; fi
;;
\[*+([[:alpha:]])*\]-\[*+([[:alpha:]])*\])
str_re="${str_prange##*\[}"; str_re="${str_re%\]}"
str_rb="${str_prange%%\]*}"; str_rb="${str_rb#\[}"
lsearch "$str_rb" "${SERVICES_ARRAY[@]}" && lsearch "$str_re" "${SERVICES_ARRAY[@]}" || $str_failcmd
;;
\[*+([[:alpha:]])*\]-+([[:word:]]))
str_re="${str_prange##*-}"
str_rb="${str_prange%%\]*}"; str_rb="${str_rb#\[}"
lsearch "$str_rb" "${SERVICES_ARRAY[@]}" && lsearch "$str_re" "${SERVICES_ARRAY[@]}" || $str_failcmd
;;
+([[:word:]])-\[*+([[:alpha:]])*\])
str_re="${str_prange##*\[}"; str_re="${str_re%\]}"
str_rb="${str_prange%%-*}"
lsearch "$str_rb" "${SERVICES_ARRAY[@]}" && lsearch "$str_re" "${SERVICES_ARRAY[@]}" || $str_failcmd
;;
+([[:word:]])-+([[:word:]]))
(($# == 2)) || $str_failcmd
lsearch "$str_rb" "${SERVICES_ARRAY[@]}" && lsearch "$str_re" "${SERVICES_ARRAY[@]}" || $str_failcmd
;;
*) $str_failcmd
esac
} # -------------------------------------------------------------------------
val_ttl() { # validate TTL manipulation values
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
#if (($1 < 0 || ${1} > 255)); then
if ! val_8bit "$1"; then
log -E "TTL value must be between 0 and 255."
return 1
fi
} # -------------------------------------------------------------------------
val_tcp_flags() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
set -- ${1/-/ }
local str_mask="${1//,/ }" str_comp="${2//,/ }" str_flag
check_str_unique "${str_mask}" || return 1
check_str_unique "${str_comp}" || return 1
for str_flag in ${str_mask} ${str_comp}; do
[[ ${str_flag} = @(SYN|ACK|FIN|RST|URG|PSH|ALL|NONE) ]] || return 1
done
} # -------------------------------------------------------------------------
val_dscp() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
case "$1" in
+([[:digit:]])|0[xX]+([[:xdigit:]]))
val_6bit "$1" || {
log -E "DSCP value \`$1' is out of bounds."
return 1
}
;;
BE|EF|AF[1-4][1-3]|CS[1-4]) : ;;
*) log -i "$1" "DSCP descriptor"
return 1
esac
} # -------------------------------------------------------------------------
val_nf_mark() { # validate netfilter mark and mark-mask values
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
val_32bit "$1" || {
log -E "Mark value or mask \`$1' is out of bounds. Should be 32bit: 0-0xFFFFFFFF (4294967295)."
return 1
}
} # -------------------------------------------------------------------------
val_rt_realm() { # validate a named routing realm
local -i i
for i in ${!RT_REALMS_ARRAY[@]}; do
[[ $1 = ${RT_REALMS_ARRAY[i]} ]] && return
done
log -E "Cannot find named routing realm \`$1'."
return 1
} # -------------------------------------------------------------------------
val_dccp_types() { # validate dccp protocol types
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
set -- $(split_val , ' ' "$1")
while (($#)); do
case "$1" in
REQUEST|RESPONSE|DATA|ACK|DATAACK|CLOSEREQ|CLOSE|RESET|SYNC|SYNCACK|INVALID) shift ;;
*) log -E "Invalid dccp type: \`$1'."
return 1
esac
done
return 0
} # -------------------------------------------------------------------------
val_sctp_chunk_types() { # validate sctp protocol chunk types
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
set -- $(split_val , ' ' "$1")
while (($#)); do
case "$1" in
DATA|ABORT|SHUT_DOWN_COMPLETE|INIT|INIT_ACK|SACK|HEARTBEAT|HEARTBEAT_ACK|SHUTDOWN|SHUTDOWN_ACK|ERROR|COOKIE_ECHO|COOKIE_ACK|ECN_ECNE|CN_CWR|ASCONF|ASCONF_ACK|FORWARD_TSN) : ;;
DATA:+([IUBEiube])|@(SHUT_DOWN_COMPLETE|ABORT):[Tt]) : ;;
*) log -E "Invalid sctp chunk type: \`$1'."
return 1
esac
shift
done
return 0
} # -------------------------------------------------------------------------
val_spi() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local str_spi
set -- ${1/:/ }
for str_spi in "$@"; do
val_numeric "$str_spi" || return 1
val_32bit "$str_spi" || {
log -E "SPI value \`$str_spi' is out of range."
return 1
}
done
if [[ $2 ]]; then
val_range "$1" "$2" || return 1
fi
} # -------------------------------------------------------------------------
val_set_flags() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
if (( $(members_in_string $(split_val , ' ' "$1") ) > 6)); then
log -E "A maximum of 6 set flags can be specified."
return 1
fi
} # -------------------------------------------------------------------------
val_ipt_tgt() { # validate existence of iptables targets
[[ $4 ]] || { reqparm $FUNCNAME 4; return 1; }
declare -i mandatory=$1
local ttarget="$2" ttable="$3" str_dn="dn "
shift 3
[[ $DEBUG_INFO ]] && str_dn=""
log -e "${PF}checking for $ttarget target"
if $str_dn run_ipt -t "$ttable" -A $BIC_TEST_CHAIN "$@"; then
if ((BASH_VERSINFO[0] < 4)); then
ARR_TARGET_EXIST[${#ARR_TARGET_EXIST[@]}]="$2"
else
ARR_TARGET_EXIST[$ttarget]=1
fi
else
if ((BASH_VERSINFO[0] >= 4)); then
ARR_TARGET_EXIST[$ttarget]=0
fi
if ((mandatory == 1)); then
log -E "iptables target \`$ttarget' does not exist."
return $ER_FAIL
else
log -W "iptables target \`$ttarget' does not exist."
fi
fi
} # -------------------------------------------------------------------------
val_ipt_mod() { # validate existence of iptables modules
[[ $4 ]] || { reqparm $FUNCNAME 4; return 1; }
declare -i mandatory=$1
local tmod=$2 ttable=$3 str_dn="dn"
shift 3
[[ $DEBUG_INFO ]] && str_dn=""
log -e "${PF}checking for $tmod extension"
if $str_dn run_ipt -t "$ttable" -A $BIC_TEST_CHAIN "$@"; then
if ((BASH_VERSINFO[0] < 4)); then
ARR_MATCH_EXIST[${#ARR_MATCH_EXIST[@]}]="$2"
else
ARR_MATCH_EXIST[$tmod]=1
fi
else
if ((BASH_VERSINFO[0] >= 4)); then
ARR_MATCH_EXIST[$tmod]=0
fi
if ((mandatory == 1)); then
log -E "iptables module \`$tmod' does not exist."
return $ER_FAIL
else
log -W "iptables module \`$tmod' does not exist."
fi
fi
} # -------------------------------------------------------------------------
check_ipt_targets() { # check for iptables targets, which are used by IP-Array
((${#IPARRAY_TARGETS[@]})) || { log -u 'IPARRAY_TARGETS'; return 1; }
local -i t_idx
if ((NO_IPT_COMPAT_CHECK)); then
log -w "Not performing checks for iptables targets"
for t_idx in ${!IPARRAY_TARGETS[@]}; do
set -- ${IPARRAY_TARGETS[t_idx]}
if ((BASH_VERSINFO[0] < 4)); then
ARR_TARGET_EXIST[${#ARR_TARGET_EXIST[@]}]="$2"
else
ARR_TARGET_EXIST[$2]=1
fi
done
else
log -I "Checking for iptables targets"
for t_idx in ${!IPARRAY_TARGETS[@]}; do
val_ipt_tgt ${IPARRAY_TARGETS[t_idx]} || return
done
fi
readonly ARR_TARGET_EXIST
[[ $DEBUG_INFO ]] && dbg_arr ARR_TARGET_EXIST || :
} # -------------------------------------------------------------------------
check_ipt_modules() { # check for iptables match extension modules, which are used by IP-Array
((${#IPARRAY_MODULES[@]})) || { log -u 'IPARRAY_MODULES'; return 1; }
local -i m_idx
if ((NO_IPT_COMPAT_CHECK)); then
log -w "Not performing checks for iptables match extensions"
for m_idx in ${!IPARRAY_MODULES[@]}; do
set -- ${IPARRAY_MODULES[m_idx]}
if ((BASH_VERSINFO[0] < 4)); then
ARR_MATCH_EXIST[${#ARR_MATCH_EXIST[@]}]="$2"
else
ARR_MATCH_EXIST[$2]=1
fi
done
else
log -I "Checking for iptables match extension"
for m_idx in ${!IPARRAY_MODULES[@]}; do
# eval needed for bpf match (caused error for iptables 1.4.21)
eval val_ipt_mod ${IPARRAY_MODULES[m_idx]} || return
done
fi
readonly ARR_MATCH_EXIST
[[ $DEBUG_INFO ]] && dbg_arr ARR_MATCH_EXIST || :
} # -------------------------------------------------------------------------
check_match_exist() { # check if a match has been registered existing or not
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
if ((BASH_VERSINFO[0] < 4)); then
if ! lsearch $1 ${ARR_MATCH_EXIST[@]}; then
log -s $1
return 1
fi
else
if ! (( ${ARR_MATCH_EXIST[$1]:-0} == 1 )); then
log -s $1
return 1
fi
fi
} # -------------------------------------------------------------------------
check_tgt_exist() { # check if a target has been registered existing or not
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
if ((BASH_VERSINFO[0] < 4)); then
if ! lsearch $1 ${ARR_TARGET_EXIST[@]}; then
log -t $1
return 1
fi
else
if ! (( ${ARR_TARGET_EXIST[$1]:-0} == 1 )); then
log -t $1
return 1
fi
fi
} # -------------------------------------------------------------------------
check_set_exist() {
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
lsearch "$1" $(show_array_column CREATED_SETS_ARRAY)
} # -------------------------------------------------------------------------
# ------------------------------------------------------------------------- #
# ACTION FUNCTIONS
# ------------------------------------------------------------------------- #
add_rule() { # add iptables commands to the command array
[[ $2 ]] || { reqparm $FUNCNAME 2; return 1; }
local str_tbl="$1" str_chn="$2"
shift 2
local str_arr="IPT_$(string_toupper "$str_tbl")_CMD_ARRAY"
if [[ $str_tbl = @(filter|nat|mangle|raw|rawpost|security) ]]; then
eval ${str_arr}[$(arr_members_sum $str_arr)]='"-t $str_tbl -A $str_chn ${@//$'\t'/}"'
#eval ${str_arr}[$(arr_members_sum $str_arr)]='"-t $str_tbl -A $(escape_varname str_chn) $(printf "%q " "${@}";printf "\n")"'
else
log -E "Illegal iptables table name: \`$str_tbl'."
return $ER_CONF
fi
} # -------------------------------------------------------------------------
insert_ipt_rule() {
[[ $2 ]] || { reqparm $FUNCNAME 2; return 1; }
local str_tbl="$1" str_chn="$2"
shift 2
local str_arr="IPT_$(string_toupper "${str_tbl}")_CMD_ARRAY"
if [[ ${str_tbl} = @(filter|nat|mangle|raw|rawpost|security) ]]; then
eval ${str_arr}[$(arr_members_sum ${str_arr})]='"-t ${str_tbl} -I ${str_chn} ${@//$'\t'/}"'
else
log -E "Illegal iptables table name: \`${str_tbl}'."
return $ER_CONF
fi
} # -------------------------------------------------------------------------
create_chain() { # create an iptables chain
[[ $2 ]] || { reqparm $FUNCNAME 2; return 1; }
local str_tbl="$1" str_chain="$2" str_silent="$3"
local -i c_idx
val_table "${str_tbl}" || {
raise_cfg_err_count
return 0
}
val_userdef_chain_target "${str_chain}" || {
raise_cfg_err_count
return 0
}
for c_idx in ${!CREATED_CHAINS_ARRAY[@]}; do
set -- ${CREATED_CHAINS_ARRAY[c_idx]}
if [[ $1 = ${str_tbl} && $2 = ${str_chain} ]]; then
[[ ${str_silent} = --silent ]] || {
log -W "\`${str_chain}' in ${str_tbl} table has already been created"
}
return 0
fi
done
log -e "creating chain: ${str_chain} table=${str_tbl}"
IPT_CCHAIN_ARRAY[${#IPT_CCHAIN_ARRAY[@]}]="-t ${str_tbl} -N ${str_chain}"
CREATED_CHAINS_ARRAY[${#CREATED_CHAINS_ARRAY[@]}]="${str_tbl} ${str_chain}"
} # -------------------------------------------------------------------------
#delete_chain() { # delete an iptables chain
#[[ $2 ]] || { reqparm $FUNCNAME 2; return 1; }
#local str_tbl="$1" str_chain="$2"
#local -i c_idx
#val_table "${str_tbl}" || {
# raise_cfg_err_count
# return 0
#}
#val_userdef_chain_target "${str_chain}" || {
# raise_cfg_err_count
# return 0
#}
#for c_idx in ${!CREATED_CHAINS_ARRAY[@]}; do
# set -- ${CREATED_CHAINS_ARRAY[c_idx]}
# [[ $1 = ${str_tbl} && $2 = ${str_chain} ]] && {
# IPT_CMD_ARRAY[${#IPT_CMD_ARRAY[@]}]="\"${IPT}\" -t ${str_tbl} -F ${str_chain}"
# IPT_CMD_ARRAY[${#IPT_CMD_ARRAY[@]}]="\"${IPT}\" -t ${str_tbl} -X ${str_chain}"
# return 0
# }
#done
#log -W "\`${str_chain}' in ${str_tbl} table has not been created before"
#return 0
#}
# -------------------------------------------------------------------------
fail_lockdown() { # error condition lockdown rules
dn set_default_policies_immediate
dn flushdel_tables_immediate
dn allow_loopback_immediate
allow_admin_connection
} # -------------------------------------------------------------------------
emerge_ips_restore() { # restore ipset data in error case in error case
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
((USE_IPSET)) || return 0
local str_file="${SAVE_DIR}/$1"
if [[ -r $str_file ]]; then
run_ipset -F -q
run_ipset -X -q
if run_ipset -R <"$str_file"; then
ERRORS_MSG_ARRAY[${#ERRORS_MSG_ARRAY[@]}]="log -N 'ipset rules successfully restored from: $str_file'"
else
ERRORS_MSG_ARRAY[${#ERRORS_MSG_ARRAY[@]}]="log -F 'restoring ipset rules from: $str_file.'"
return $ER_FAIL
fi
else
ERRORS_MSG_ARRAY[${#ERRORS_MSG_ARRAY[@]}]="log -x '$str_file'"
return $ER_NOEX
fi
} # -------------------------------------------------------------------------
emerge_ipt_restore() { # restore the firewall with iptables-restore in error case
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
if ((IPTSAVE_FAILS)); then
ERRORS_MSG_ARRAY[${#ERRORS_MSG_ARRAY[@]}]="log -E 'IPTSAVE_FAILS is set to $IPTSAVE_FAILS.'"
return $ER_FAIL
fi
local str_c="" str_file="${SAVE_DIR}/$1"
if ((USE_COUNTERS)); then
str_c="--counters "
fi
if [[ -r $str_file ]]; then
if "$IPT_RESTORE" $str_c <"$str_file"; then
ERRORS_MSG_ARRAY[${#ERRORS_MSG_ARRAY[@]}]="log -N 'iptables rules successfully restored from: $str_file'"
else
ERRORS_MSG_ARRAY[${#ERRORS_MSG_ARRAY[@]}]="log -F 'restoring iptables rules from: $str_file.'"
return $ER_FAIL
fi
else
ERRORS_MSG_ARRAY[${#ERRORS_MSG_ARRAY[@]}]="log -x '$str_file'"
return $ER_NOEX
fi
} # -------------------------------------------------------------------------
ips_restore() { # restore ipset data
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
((USE_IPSET)) || return 0
local str_file="${SAVE_DIR}/$1"
if [[ -r $str_file ]]; then
log -w "Destroying existing sets"
run_ipset -F -q
run_ipset -X -q
if run_ipset -R <"$str_file"; then
log -N "ipset rules successfully restored from: \`$str_file'"
else
log -F "restoring ipset rules from: \`$str_file'."
return $ER_FAIL
fi
else
log -x "$str_file"
return $ER_NOEX
fi
} # -------------------------------------------------------------------------
ipt_restore() { # restore the firewall with iptables-restore
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
if ((IPTSAVE_FAILS)); then
log -E "\`IPTSAVE_FAILS' is set to \`$IPTSAVE_FAILS'."
return $ER_FAIL
fi
local str_c="" str_file="${SAVE_DIR}/$1"
if ((USE_COUNTERS)); then
str_c="--counters "
fi
if [[ -r $str_file ]]; then
if "$IPT_RESTORE" $str_c <"$str_file"; then
log -N "iptables rules successfully restored from: \`$str_file'"
else
log -F "restoring iptables rules from: \`$str_file'."
return $ER_FAIL
fi
else
log -x "$str_file"
return $ER_NOEX
fi
} # -------------------------------------------------------------------------
set_default_policies_immediate() { # set (IP-Array) default policies
local table c chain rest
log -I "Immediately applying default policies"
if ! [[ -r $IP_TABLES_NAMES ]]; then
log -W "\`$IP_TABLES_NAMES' does not exist, module ip_tables is not loaded"
dn run_ipt -nL
fi
while read -t $GLOBAL_READ_TIMEOUT table; do
while read -t $GLOBAL_READ_TIMEOUT c chain rest; do
if [[ $c = Chain ]]; then
if [[ $table = filter ]]; then
if [[ $chain = @(@(IN|OUT)PUT|FORWARD) ]]; then
dn run_ipt -t $table -P $chain 'DROP' || continue
fi
else
if [[ $chain = @(@(IN|OUT)PUT|FORWARD|@(PRE|POST)ROUTING) ]]; then
dn run_ipt -t $table -P $chain 'ACCEPT' || continue
fi
fi
fi
done < <(run_ipt -t $table -nL)
done < "$IP_TABLES_NAMES"
} # -------------------------------------------------------------------------
flush_table() { # flush all chains in a specified table
[[ $1 ]] || { reqparm $FUNCNAME 1; return 1; }
local tgt_tbl="$1"
val_table "$tgt_tbl" || return
local c chain rest
log -S "Flushing chains in "$tgt_tbl" table"
while read -t $GLOBAL_READ_TIMEOUT c chain rest; do
if [[ $c = Chain ]]; then
IPT_FLUSH_ARRAY[${#IPT_FLUSH_ARRAY[@]}]="-t $tgt_tbl -F $chain"
fi
done < <(run_ipt -t "$tgt_tbl" -nL)
IPT_FLUSH_ARRAY[${#IPT_FLUSH_ARRAY[@]}]="-t "$tgt_tbl" -X"
} # -------------------------------------------------------------------------
flushdel_tables_immediate() { # immediately flush and delete existing tables
local table c chain rest