ipturntables.sh 48.2 KB
Newer Older
1
2
3
4
5
6
7
#!/bin/bash

# trying to simplify iptables usage

printAbout()
{
	printf "Usage: $0
8
 -4=IPv4*|-6=IPv6|-d=dry-run
9
10
 [KERNEL_PARAMS param1,param2,...,paramN]
 [PROBE_KERNEL_MODS mod1,mod2,...,modN]
11
 [RESET [default_policy=ACCEPT|DROP|REJECT]]
12
 [BASE_RULE_SET]
13
 [ALLOW_DHCP on_link]
14
15
 [ALLOW_SUBNETS on_link]
 [ALLOW_LINK_LOCAL on_link]
16
 [ALLOW_MULTICAST_ADDRS ]
17
 [ALLOW_SERVICE_DISCOVERY on_link]
18
 [ALLOW_STATEFUL_PACKETS ip|link]
19
 [ALLOW_TUNNEL mode on_link from_address]
20
 [ALLOW_PORT|ALLOW_SERVICE port[,port,port,...] ip|link [tcp|udp]]
21
22
 [FORWARD_SUBNET from_subnet/mask to_link]
 [FORWARD_SUBNET_PROTECTIVE from_subnet/mask to_link]
23
 [FORWARD_PORT|FORWARD_ROUTING ip|link port(s) to_address[:to_port] [tcp|udp]]
24
 [MAC_FILTER chain mac_address]
25
 [POSTROUTING_MASQUERADE subnet/mask on_link]
26
 [DEBUG_CHAIN chain_name]
27
28
29
30
 [REMOVE rule_regex_pattern]
 [LIST [CHAIN]]
 [LOG*|NFLOG]
                     *=Default if omitted
31
32
33
34
35
36

Written by Branko Mikic in Nov 2ol4
All copyrights reserved. Free use of this software is granted under the terms of the GNU General Public License (GPLv3).

See man page (ipturntables.8) for a detailed documentation.

37
" >&2
38
39
40
41
42
	exit 5
}

msg()
{
43
44
	echo "" >&2
	echo "${0##*/}: $1" >&2
45
46
47
48
49
50
51
52
53
}

error()
{
	msg "(ERROR $1) >> $2"
	kill $$
    exit $1
}

54
# some helpers
55

56
57
58
function isNaturalNumber() { [[ ${1} =~ ^[0-9]+$ ]]; }
function isInteger() { [[ ${1} == ?(-)+([0-9]) ]]; }
function isFloat() { [[ ${1} == ?(-)@(+([0-9]).*([0-9])|*([0-9]).+([0-9]))?(E?(-|+)+([0-9])) ]]; }
59
function isNumber() { isNaturalNumber $1 || isInteger $1 || isFloat $1; }
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
###
### $1: A list of kernel module names to probe for.
###
probeKernelModules()
{
 local sz;

	printf "# Kernel modules probed:\n#   "

	$DEPMOD -a
	for sz in $1; do
		printf " %s" $sz
		$MODPROBE $sz
		(( $? != 0 )) && error 100 "Kernel module '$sz' no available."
	done
	echo ""
}

###
### $1: Mode must be an integer value of 4 or 6 (4=inet|6=inet6)
### $2: Desired kernel param below /proc/sys/net/ipv$(MODE)/conf
###     eg: autoconf or eth2/redirect
###
printKernelParams()
{
 local i; local sz; local sy;

	[ $1 -ne 4 ] && [ $1 -ne 6 ] &&	error 1001 "printKernelParams(): Mode must be an integer of 4 or 6."

	(( i=0 ));
	sz="/proc/sys/net/ipv$1"

	[ -f "$sz/conf/default/$2" ] && sz="$sz/conf" && sy="*/$2"
	[ -f "$sz/conf/$2" ] && sz="$sz/conf" && sy="$2"
Branko Mikić's avatar
Branko Mikić committed
95
	[ -d "$sz/conf/$2" ] && sz="$sz/conf/$2" && sy="*" && printf "#\n# $2:\n"
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
	[ -f "$sz/$2" ] && sy="$2"
	[ -z "$sy" ] && error 27 "Kernel param: '$2' not found!"

	pushd $sz 1>/dev/nul 2>/dev/nul
	for sz in $sy ; do
		(( i==0 )) && printf "#"
		printf "%36s=%-12s" $sz $(cat $sz);
		(( i++ ))
		if (( i == 2 )); then
			printf "\n"
			(( i=0 ))
		else
			printf "\t"
		fi
	done;
	popd 1>/dev/nul 2>/dev/nul
	(( i == 1 )) && printf "\n"
}

###
### Checks network devices for existence
###
### $1: A list of network devices
###
### Return code is (0: Given devices exist | 1: One of the devices not existing)
###
checkLink()
{
 local sz; local i;

126
	(( ${#@} == 0 )) && error 1202 "checkDevice(): device or device list argument is mandatory."
127
128
129
130
131
132
133
134
135
136

	(( i=0 ))
	for sz in $@; do
		$IP link show $sz 1>/dev/nul 2>/dev/nul
		(( i+=$? ))
	done
	return $i
}

###
137
### $1: an interface (eg: eth0 or eth1, ...)
138
###
139
140
141
142
143
144
### Returns an unique hex ID derived from the MAC address.
### Virtual network devices return a special hash value since
### they usally don't have a MAC address.
### 
getLinkID()
{
145
 local i; local p;
146
147
148

	[ -z "$1" ] && error 1203 "getLinkID(): device argument is mandatory."

149
150
	p=$(cat /sys/class/net/$1/addr_len 2>/dev/null) || p=0;
	if [ $p -gt 0 ]; then
151
152
153
154
155
156
157
158
159
160
		printf "0x%s" $(cat /sys/class/net/$1/address | sed "s/://g")
	else
		printf "0x"
		for (( i=0; i<${#1}; i++ )); do
			printf '%02X' "'${1:$i:1}"
		done
	fi
}

###
161
### $1: an interface (eg: eth0 or eth1, ...)
162
163
164
###
### Returns the MAC address of the desired network interface
###
165
166
getLinkMAC()
{
167
168
169
170
	[ -z "$1" ] && error 1204 "getLinkMAC(): device argument is mandatory."

#	printf "%s" $($IP link show $1 | grep -o -P "(?<=link/ether ).*(?=\sbrd)")
	printf "%s" $(cat /sys/class/net/$1/address)
171

172
173
		# tricky! regardless wether it's true or false >> just return the return code
	[ $(cat /sys/class/net/eth2/addr_len) -gt 0 ] ; return $?
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
}

###
### $1: Mode must be an integer value of 4 or 6 (4=inet|6=inet6)
### $2: Scope to obtain addresses from (eg: host|link|global|all)
### $3: list of devices (separated by spaces) to obtain ip's for.
###
### Prints a list of corresponding ip addresses
###
obtainIPs()
{
 local sz;

	[ $1 -ne 4 ] && [ $1 -ne 6 ] &&	error 1001 "obtainIPs(): Mode must be an integer of 4 or 6."
	[[ $2 =~ host|link|global|all ]] || error 1002 "obtainIPs(): Scope argument must be either host, link, global or all"
	[ -z "$3" ] && error 1002 "obtainIPs(): No list of devices given."

	for sz in $3; do
		sz=$(ip \-$1 addr show dev $sz scope $2 | grep -P -o "[\w|\.|\:]+(?=\/\d+)")
		printf " $sz"
	done
}

###
198
### $1: Some IP of a local net
199
###
200
obtainRouteToIP()
201
{
202
	printf "%s" $($IP -o route get $1 | grep -o -P "(?<=src\s)(\d+\.){3}\d+")
203
204
205
}

###
206
### $1: Desired IP address to obtain corresponding net prefix
207
###
208
### Returns a subnet prefix
209
###
210
obtainNetPrefix()
211
{
212
 local i;
213

214
215
216
217
218
	[ $ENVID -eq 4 ] &&	\
		printf "%s" $(ip -4 r l match $1 | grep -v ^default | grep -m1 -oP "^(\d+\.){3}+\d+\/\d+")
	[ $ENVID -eq 6 ] && \
		printf "%s" $(ip -6 r l match $1 | grep -oP "^[^\s]*")
	echo ;
219
220
}

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#obtainNetPrefixOBSOLETE()
#{
# local i;
#
#	if [ $ENVID -eq 4 ]; then
#			# obtain ip of this host from given ip
#		if ! $IP addr show $1 &> /dev/null ; then
#			i=$(obtainRouteToIP $1)
#		else
#			i=$1
#		fi
#		printf "%s" $($IP -o route list | grep -oP "(\d+\.){3}+\d+\/\d+(?=.* src $i)")
#	fi
#	[ $ENVID -eq 6 ] && printf "%s" $($IP -o route list | grep -oP "${1%::*}::\/\d* (?=dev $2)")
#}

237
238
239
240
241
242
243
244
245
246
###
### $1: a net prefix (eg: 192.168.0.0/16)
###
### Prints the related device from the route table
### Return code != 0 indicating an error.
###
obtainLinkFromSubnetPrefix()
{
 local sz;

247
	sz=$($IP -o route list | grep -P "^$1" | grep -o -P "(?<= dev )\w*")
248
249
250
251
	(( $? == 0 )) && printf "%s" $sz && return 0
	return 1
}

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
###
### $1: a MAC address (eg; 06:00:17:d3:97:b4)
###
### Return code == 0: Argument has MAC format
###             != 0: Argument is not in MAC format
###
checkMACArgFormat()
{
	echo "$1" | grep -q -oE "^(\w+{2}:){5}\w{2}$"
}

###
### $1: IP address with optional port assignment (eg: 192.168.1.1:80) or a device node
###
### Returns TRUE if $1 is an IPv4 or IPv6 address otherwise FALSE 
###
checkIPArgFormat()
{
 local sz;

	[ $ENVID -eq 4 ] && sz="(\d+\.){3}\d+((\:)+(\d)+)*$"
		# TODO: check for IPv6 address! Format is untested and likely to fail
274
275
#	[ $ENVID -eq 6 ] && sz="^([\da-fA-F]+:)+(:[\da-fA-F]+)+$"
	[ $ENVID -eq 6 ] && sz="^([\da-fA-F]*:+)*:*[\da-fA-F]+$"
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290

	echo "$1" | grep -q -P "$sz" 1>/dev/nul 2>/dev/nul
	return $?
}

###
### $1: A subnet/mask argument
###
### Returns 0 if argument has a subnet/mask format otherwise 1
###
checkSubnetArgFormat()
{
 local sz;

	[ $ENVID -eq 4 ] && sz="(\d+\.){3}+\d+\/\d+"
291
	[ $ENVID -eq 6 ] && sz="^([\da-fA-F]+:)+(:\/\d+)+$"
292
293
294
295
296

	echo "$1" | grep -q -P "$sz" 1>/dev/nul 2>/dev/nul
	return $?
}

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
###
### $1: Either tcp or udp
###
### Returns a string either 'tcp', 'udp'
### or 'any' if none of the other
###
checkProtocol()
{
	echo $1 | grep -iP "(tcp|udp)" 1>/dev/nul 2>/dev/nul
	if (($? == 0)); then
		printf $1
	else
		printf "any"
	fi
}

313
314
315
316
317
318
319
320
321
322
323
###
### $1: chain to search for device occurence in any rule
###
### Returns the # of rules in a chain
###
returnRuleCount()
{
 local sz;

	[ -z $1 ] && error 1 "returnRuleCount(): chain argument is mandatory."

324
	let sz=$($IPTABLES --line-numbers -nL $1 | grep -P -c ^[0-9]+)
325
	return $sz
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
}

###
### Checks if iptables contains any rules
###
### Returns rule count of INPUT, OUTPUT & FORWARD or 0 if empty
###
IsEmpty()
{
 local n;

	(( n=0 ))
	returnRuleCount INPUT
	(( n=n+$? ))
	returnRuleCount OUTPUT
	(( n=n+$? ))
	returnRuleCount FORWARD
	(( n=n+$? ))
	return $n
}

###
### $1: chain to search in (eg: INPUT or -t nat POSTROUTING)
### $2: string pattern to look for
###
### Prints a list of rule indices in which the pattern occurs
###
obtainRuleIndices()
{
 local sz; local sy;

	if [[ $1 =~ -t ]]; then
		[ -z $2 ] && error 70 "obtainRuleIndices() expects a tablename after optional -t argument."
		sy="$1 $2"
		shift; shift;
	fi
	[ -z "$1" ] && error 71 "obtainRuleIndices(): chain argument is mandatory."
	[ -z "$2" ] && error 72 "obtainRuleIndices(): string pattern argument is mandatory."

365
	sz=$($IPTABLES --line-numbers $sy -vnL $1 | grep -P -o "^[0-9]*(?=.*$2)")
366
367
368
369
370
371
372
	printf "%s " $sz
}

###
### $1: chain to delete rules by pattern in (eg: INPUT or -t nat POSTROUTING)
### $2: string pattern to look for
###
373
374
### Deletes any rule in chain $1 containing the pattern $2
### Return code == Number of successfully removed rules
375
376
377
378
###
deleteRules()
{
 local i; local ia;
379
 local sz; local n;
380
381
382
383
384
385
386
387

	if [[ $1 =~ -t ]]; then
		[ -z $2 ] && error 70 "deleteRules() expects a tablename after optional -t argument."
		sz="$1 $2"
		shift; shift;
	fi
		# putting it in brackets returns it as an array
	ia=($(obtainRuleIndices $sz $1 "$2"))
388
	(( n=0 ))
389
	for (( i=${#ia[@]}-1; i>=0; i-- )); do
390
			# delete rule
391
		$IPTABLES $sz -D $1 ${ia[$i]}
392
		(( $? == 0 )) && (( n++ ))
393
	done
394
	return $n
395
396
397
398
399
400
401
}

###
### $1: One or multiple desired chains to probe for existence
###
probeChains()
{
402
403
404
405
406
407
408
409
410
411
412
413
 local sz; local t;

	[ -z $1 ] && error 10 "probeChain(NULL): chain argument is mandatory."

	while (( ${#@} > 0 )); do
		[[ $1 =~ -t ]] && {
			t=$1; shift;
			(( ${#t} <= 2 )) && {
				t+=$1; shift;
			}
		}
		$IPTABLES $t -nvL $1 1>/dev/nul 2>/dev/nul
414
		(( $? != 0 )) && return 1
415
		shift;
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
	done
	return 0
}

###
### $1: Desired name of chain to alloc (only for user-defined chains!)
###     Attention!
###     if that chain already exists it will be zero'ed & flushed (!)
###
allocChain()
{
	[ -z $1 ] && error 10 "allocChain(NULL): chain argument is mandatory."
	[[ $1 =~ INPUT|FORWARD|OUTPUT ]] && error 11 "allocChain($1): Built-in chains are hardwired! Only user-defined chains can be allocated."

	$IPTABLES -nvL $1 1>/dev/nul 2>/dev/nul
	if (( $? == 0 )); then
432
		$IPTABLES --zero $1;
433
434
435
436
437
438
439
440
		$IPTABLES --flush $1
	else
		$IPTABLES -N $1
	fi
	return 0
}

###
441
### $1: Desired name of chain to dealloc (only for user-defined chains!)
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
###
deallocChain()
{
	[ -z $1 ] && error 10 "deallocChain(NULL): chain argument is mandatory."
	[[ $1 =~ INPUT|FORWARD|OUTPUT ]] && error 11 "deallocChain($1): Built-in chains are hardwired! Only user-defined chains can be allocated."

	$IPTABLES -nvL $1 1>/dev/nul 2>/dev/nul
	(( $? != 0 )) && echo "INFO >> deallocChain($1): Given chain doesn't exist." && return 1
	$IPTABLES --zero $1
	$IPTABLES --flush $1
	$IPTABLES --delete-chain $1
}

###
### $1: A subnet (eg: 192.168.0.0/16)
###
### Prints a hexadecimal representation (eg: 0xC0A8000010)
###
460
formatAsHexID() {
461
462
463
464
465
466
467
468
469
470
471
472
 local sz; local sy;
								# sed using bash! ${1//REPLACE_ME/WITH_THIS}
	if [ $ENVID -eq 4 ]; then
		sz=${1//\./ }
		sz=${sz//\// }
		for sy in $sz; do
			printf "%02X" $sy
		done
	fi

	if [ $ENVID -eq 6 ]; then
		sz=${1%/*}
473
474
		printf ${sz//\:/}
		[[ $1 =~ '/' ]] && printf "%02X" ${1#*/}
475
476
477
478
479
480
481
482
483
	fi
}

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~ main script starts here
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	(( ${#@} == 0 )) && printAbout

484
485
486
487
488
489
490
491
492
493
	DEPMOD=$(which depmod)
	[ -z "$DEPMOD" ] && error 2 "Can't use depmod command. Please install missing command."

	MODPROBE=$(which modprobe)
	[ -z "$MODPROBE" ] && error 3 "Can't use modprobe command. Please install missing command."

	IP=$(which ip)
	(( $? != 0 )) && error 4 "Can't use ip command. Please install missing command."

	# we are a user of 'netdev' group or root?
494
	$(groups $USER | grep netdev) >/dev/null
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
	[ "$USER" != "root" ] && (( $? == 1 )) && \
		error 5 "Superuser priviledges needed. This script makes heavy use of 'iptables' command which is only allowed to be used by root or a user being a member of 'netdev' group."

	sz=$(echo "$@" | grep -ioP "(LOG|NFLOG)");
	(( $? != 0 )) \
		&& { [ -v NFLOG ] && sz="NFLOG" || sz="LOG"; } \
		|| sz=${sz^^};
	[ "$sz" == LOG ] && TO_LOG="-j LOG --log-prefix";
	[ "$sz" == NFLOG ] && TO_LOG="-j NFLOG --nflog-group 32 --nflog-prefix";
	[ -z "$TO_LOG" ] && error 6 "Malformed log argument: Must be either 'LOG' or 'NFLOG'.";
	printf "# iptables log statement: '%s'\n" "$TO_LOG";

	sz=$(echo "$@" | grep -oP "\-(4|6)+")
	sz=${sz//-/}
	(( ${#sz} == 0 )) && { sz=4; printf >&2 "WARNING! Protocol version not specified. Using: IPv%s\n" $sz; };
	(( ${#sz} != 1 )) && error 7 "Malformed protocol version. Specify either -4 or -6 once!";
	if [ $sz -eq 4 ]; then
		IPTABLES=$(which iptables)
		(( $? != 0 )) && error 8 "Can't use iptables command. Please install missing command."
	fi
	if [ $sz -eq 6 ]; then
		IP+=" -6"
		IPTABLES=$(which ip6tables)
		(( $? != 0 )) && error 9 "Can't use ip6tables command. Please install missing command."
	fi
	ENVID=$sz

	sz=$(echo "$@" | grep -oP "\-(d|D)+")
	sz=${sz//-/}
	if [ "${sz^^}" == 'D' ]; then
		unset sz;
		[ $ENVID -eq 6 ] && sz=$ENVID
		IPTABLES="echo -e \nip${sz}tables"
		printf "Using dry-run, executing echo instead of iptables command.\n"
529
	fi
530
531
532
533
534
535
536
537
538
539
540
541
542
543

		# define dhcp ports depending on wether 4 or 6 is used
	[ $ENVID -eq 4 ] && {
		LLsubnet="169.254.0.0/16";
		dhcp_client=68;  dhcp_server=67;
	}
	[ $ENVID -eq 6 ] && {
		LLsubnet="fe80::/10";
		dhcp_client=546; dhcp_server=547;
	}

	DHCP_CLIENT_MARK=1;
	DHCP_SERVER_MARK=2;
	((DHCP_BOTH_MARK = DHCP_CLIENT_MARK + DHCP_SERVER_MARK ));
544
545
546
547
548

	while (( ${#@} >= 1 )); do
		arg=${1^^}
		shift
		case $arg in
549
550
551
552
			-4|-6|-d|-D|LOG|NFLOG)
				# simply ignore
				;;

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
			KERNEL_PARAMS)
				printf "#\n# /proc/sys/net/ipv$ENVID:\n"
				for sz in $(echo $1 | sed "s/,/ /g"); do
					printKernelParams $ENVID $sz
				done
				echo "#"
				shift
				;;

			PROBE_KERNEL_MODS)
				sz=$(echo $1 | sed "s/,/ /g")
				probeKernelModules "$sz"
				echo "#"
				shift
				;;

			RESET)
				echo "# reseting ruleset ($IPTABLES)"

				sz=${1^^}
				if [[ $sz =~ ACCEPT|DROP|REJECT ]]; then
					shift
				else
					sz="ACCEPT"
				fi

				$IPTABLES -t nat -nvL 1>/dev/nul 2>/dev/nul
				(( $? == 0 )) && $IPTABLES -t nat -F

				$IPTABLES -t mangle -nvL 1>/dev/nul 2>/dev/nul
				(( $? == 0 )) && $IPTABLES -t mangle -F

				$IPTABLES -F
					# set policy (default: accept)
				$IPTABLES -P INPUT $sz
				$IPTABLES -P OUTPUT $sz
				$IPTABLES -P FORWARD $sz
					# delete all user-specified chains
				$IPTABLES -X
592
593
				$IPTABLES -t nat -X
				$IPTABLES -t mangle -X
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
					# reset all counters
				$IPTABLES -Z

				unset sz
				;;

			BASE_RULE_SET)
				IsEmpty; (( $? != 0 )) && error 32 "iptables contains rules. Prepend RESET before BASE_RULE_SET argument."

				echo "# setting up base ruleset"

					# default policy is to drop anything on builtin chains
				$IPTABLES -P INPUT DROP
				$IPTABLES -P FORWARD DROP
				$IPTABLES -P OUTPUT DROP

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
					# DHCP
				$IPTABLES -t mangle -N DHCP
				$IPTABLES -t mangle -A DHCP -p udp \
							-m addrtype --src-type LOCAL --limit-iface-out \
							-m udp --sport $dhcp_client --dport $dhcp_server \
							-m mark --mark $DHCP_CLIENT_MARK/$DHCP_CLIENT_MARK \
							-j MARK --set-mark 0xff \
							-m comment --comment "sending request from local interface";
				$IPTABLES -t mangle -A DHCP -p udp \
							-m udp --sport $dhcp_server --dport $dhcp_client \
							-m mark ! --mark 0/$DHCP_BOTH_MARK \
							-j MARK --set-mark 0xff \
							-m comment --comment "request/discover/reply from server";
				[ $ENVID == "6" ] && {
					$IPTABLES -t mangle -A DHCP -p udp \
								-s $LLsubnet \
								-m addrtype --dst-type MULTICAST \
								-m udp --sport $dhcp_client --dport $dhcp_server \
								-m mark --mark $DHCP_SERVER_MARK/$DHCP_SERVER_MARK \
								-j MARK --set-mark 0xff \
								-m comment --comment "receiving requests via link-local (IPv6 only)";
	 			}
				$IPTABLES -t mangle -A DHCP -m mark --mark 0xff -j RETURN;
				$IPTABLES -t mangle -A DHCP $TO_LOG "[BLOCK] (DHCP) ";
				$IPTABLES -t mangle -A DHCP -j DROP;
					# mark incoming dhcp packets very early
				$IPTABLES -t mangle -I PREROUTING -p udp -m multiport --port ${dhcp_client},${dhcp_server} \
							-j DHCP -m comment --comment "dhcp in"
					# mark follow up dhcp packets leaving
				$IPTABLES -t mangle -I OUTPUT -p udp -m multiport --port ${dhcp_client},${dhcp_server} \
							-j DHCP -m comment --comment "dhcp out"

# for everyone wondering why a DHCP request via broadcast like
# 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP ... is never seen by
# netfilter on any outgoing chain on any table that's because most
# dhcp daemons are using PF_PACKET sockets for the _first_, _initial_
# request which bypasses the whole netfilter.
# To keep things more confusing this doesn't apply for any 'ordinary'
# follow up dhcp packet (only the first one!)
# https://unix.stackexchange.com/questions/447440/ufw-iptables-not-blocking-dhcp-udp-port-67
650

651
652
653
654
					# create an ANTI-FLOOD protection chain. Maximises the rate of incoming connections. 
					# Used for protection against SYN or PING_OF_DEATH flooding
				$IPTABLES -N ANTI-FLOOD
				$IPTABLES -A ANTI-FLOOD -m limit --limit 3/s -j RETURN
655
656
				$IPTABLES -A ANTI-FLOOD $TO_LOG "[BLOCK] (ANTI-FLOOD) "
				$IPTABLES -A ANTI-FLOOD -j DROP
657
658
659
660

					# limits the connection attempts
				$IPTABLES -N LIMITER
				$IPTABLES -A LIMITER -m state ! --state NEW -j RETURN
661
662
663
664
665
666
667
668
669
670
				$IPTABLES -A LIMITER --match hashlimit --hashlimit-name LIMITER \
									--hashlimit-mode srcip --hashlimit-upto 3/hour --hashlimit-burst 3 \
									--hashlimit-htable-size 256 --hashlimit-htable-max 1024 -j RETURN
				$IPTABLES -A LIMITER --match hashlimit --hashlimit-name DROP_SILENTLY \
									--hashlimit-mode srcip --hashlimit-srcmask 16 \
									--hashlimit-above 16/day -j DROP
				$IPTABLES -A LIMITER $TO_LOG "[BLOCK] (LIMITER) "
				$IPTABLES -A LIMITER -j DROP

					# Will be used in INPUT & OUTPUT to add allowed subnets on local links
671
				$IPTABLES -N LOCAL
672
673
674
675
676
					# DHCPv4 packets pass wondrously but DHCPv6 needs explicit permission
				[ $ENVID == "6" ] && {
					$IPTABLES -A LOCAL -p udp -m multiport --port ${dhcp_client},${dhcp_server} -m mark --mark 0xff \
								-j ACCEPT -m comment --comment "allow our marked dhcp packets from prerouting";
				}
677
678
679
680
681

					# will be used in INPUT, OUTPUT & FORWARD
					# this chain should return always! (don't place DROP rules on specific ICMPs here!)
				$IPTABLES -N ICMP

682
					# place your custom rules in these chains used in INPUT & OUTPUT
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
				$IPTABLES -N USER-IN
				$IPTABLES -N USER-OUT

					# allow local loopback in & out
				$IPTABLES -A INPUT -i lo -j ACCEPT
				$IPTABLES -A OUTPUT -o lo -j ACCEPT

				# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IPv4
				if [ $ENVID == "4" ]; then

						# ICMPs allowed (nearly all as most others are depricated)
					$IPTABLES -A ICMP -p icmp -m icmp --icmp-type 3 -j ACCEPT -m comment --comment "destination-unreachable"
					$IPTABLES -A ICMP -p icmp -m icmp --icmp-type 4 -j ACCEPT -m comment --comment "source-quench"
					$IPTABLES -A ICMP -p icmp -m icmp --icmp-type 8 -j ANTI-FLOOD -m comment --comment "echo-request: Ping of death"
					$IPTABLES -A ICMP -p icmp -m icmp --icmp-type 8 -j ACCEPT -m comment --comment "echo-request"
					$IPTABLES -A ICMP -p icmp -m icmp --icmp-type 11 -j ACCEPT -m comment --comment "time-exceeded"
					$IPTABLES -A ICMP -p icmp -m icmp --icmp-type 12 -j ACCEPT -m comment --comment "parameter-problem"

						# handle ICMP protocol
					$IPTABLES -A INPUT -p icmp -j ICMP

704
705
						# intercept all the TCP handshakes and correct on-the-fly the wrong
						# MSS value requested by internal hosts in magle tables of FORWARD chain
706
707
708
709
710
711
					$IPTABLES -A FORWARD -t mangle -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
	 			fi

				# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IPv6
				if [ $ENVID == "6" ]; then

712
713
714
715
716
717
718
719
						# filter all packets that have RH0 headers:
					#$IPTABLES -A INPUT -m rt --rt-type 0 --rt-segsleft 0 -j DROP
					#$IPTABLES -A OUTPUT -m rt --rt-type 0 --rt-segsleft 0 -j DROP
					#$IPTABLES -A FORWARD -m rt --rt-type 0 --rt-segsleft 0 -j DROP
						# explicit rules for RH0 is many years obsolete and no longer necessary on modern Linux systems!
						# https://serverfault.com/questions/410321/debian-ip6tables-rules-setup-for-ipv6/527334

						# echo reply allow explicitly on link local 
720
					$IPTABLES -A ICMP -p ipv6-icmp -m icmp6 --icmpv6-type 129 -s $LLsubnet -j ACCEPT -m comment --comment "echo-reply allowed on link local"
721
						# accept harmless ICMP requests
722
723
724
725
726
727
728
					$IPTABLES -A ICMP -p ipv6-icmp -m icmp6 --icmpv6-type 1 -j ACCEPT -m comment --comment "destination unreachable"
					$IPTABLES -A ICMP -p ipv6-icmp -m icmp6 --icmpv6-type 2 -j ACCEPT -m comment --comment "packet too big"
					$IPTABLES -A ICMP -p ipv6-icmp -m icmp6 --icmpv6-type 3 -j ACCEPT -m comment --comment "time exceeded"
					$IPTABLES -A ICMP -p ipv6-icmp -m icmp6 --icmpv6-type 4 -j ACCEPT -m comment --comment "parameter problem"
					$IPTABLES -A ICMP -p ipv6-icmp -m icmp6 --icmpv6-type 128 -j ANTI-FLOOD -m comment --comment "echo-request: Ping of death"
					$IPTABLES -A ICMP -p ipv6-icmp -m icmp6 --icmpv6-type 128 -j ACCEPT  -m comment --comment "echo-request"

729
730
						# ICMP: handling of router|neighbor solicitation|advertisments
						# with special hop limits for traffic in and out
731
732
733
734
					$IPTABLES -A INPUT -p ipv6-icmp -m icmp6 --icmpv6-type 133 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "multicast listener done"
					$IPTABLES -A INPUT -p ipv6-icmp -m icmp6 --icmpv6-type 134 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "router advertisement"
					$IPTABLES -A INPUT -p ipv6-icmp -m icmp6 --icmpv6-type 135 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "neighbor solicitation"
					$IPTABLES -A INPUT -p ipv6-icmp -m icmp6 --icmpv6-type 136 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "neighbor advertisement"
735
					$IPTABLES -A OUTPUT -p ipv6-icmp -m icmp6 --icmpv6-type 133 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "multicast listener done"
736
737
#TODO: RAs out on specific interface
#ip6tables -I OUTPUT 3 -o ppp0 -p ipv6-icmp -m icmp6 --icmpv6-type 134 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "router advertisement"
738
739
740
					$IPTABLES -A OUTPUT -p ipv6-icmp -m icmp6 --icmpv6-type 135 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "neighbor solicitation"
					$IPTABLES -A OUTPUT -p ipv6-icmp -m icmp6 --icmpv6-type 136 -m hl --hl-eq 255 -j ACCEPT -m comment --comment "neighbor advertisement"
					$IPTABLES -A OUTPUT -p ipv6-icmp -m icmp6 --icmpv6-type 143 -m hl --hl-eq 1 -j ACCEPT -m comment --comment "V2 multicast listener report"
741
742
743

						# handle ICMP protocol
					$IPTABLES -A INPUT -p ipv6-icmp -j ICMP
744
				fi
745

746
				# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for both IPv(4|6)
747

748
					# only routable internal subnets allowed
749
				$IPTABLES -A INPUT -j LOCAL
750
751
					# only routable subnets allowed
				$IPTABLES -A OUTPUT -j LOCAL
752

753
754
				$IPTABLES -A INPUT -m state --state INVALID $TO_LOG "[BLOCK] (INVALID) "
				$IPTABLES -A INPUT -m state --state INVALID -j DROP
755

756
757
					# syn-flood protection
				$IPTABLES -A INPUT -p tcp --syn -j ANTI-FLOOD
758

759
760
					# furtive port scanner
				$IPTABLES -A INPUT -p tcp --tcp-flags SYN,ACK,FIN,RST RST -j ANTI-FLOOD
761

762
763
					# allow some safe ports (but use a limiter especially for ssh port)
				$IPTABLES -A INPUT -p tcp -m tcp --dport 22 -j LIMITER -m comment --comment "avoid bashing on ssh port"
764
				$IPTABLES -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT -m comment --comment "ssh"
765

766
767
768
769
770
771
				# ~~~ any of the default chains should end with this!

					# user customized rules for traffic coming in & going out
				$IPTABLES -A INPUT -j USER-IN -m comment --comment "add your custom INPUT rules in the USER-IN chain!"
				$IPTABLES -A OUTPUT -j USER-OUT -m comment --comment "add your custom OUTPUT rules in the USER-OUT chain!"

772
773
774
775
776
777
778
779
780
781
782
					# stateful packets intiated by ourself coming back
					# but only of it's destined to a local address, no (multi|broad)cast!
				#$IPTABLES -A INPUT -m addrtype --dst-type LOCAL --limit-iface-in \
				#					-m state --state RELATED,ESTABLISHED -j ACCEPT

					# stateful packets intiated by ourself going out
					# but only for traffic coming from a local address.
					# (multi|broad)casts need to be allowed explicitly!
				$IPTABLES -A OUTPUT -m addrtype --src-type LOCAL --limit-iface-out \
									-m state --state RELATED,ESTABLISHED -j ACCEPT

783
					# default log rules
784
785
786
				$IPTABLES -A INPUT -m limit --limit 8/min --limit-burst 16 $TO_LOG "[IN$ENVID-DROP] "
				$IPTABLES -A OUTPUT -m limit --limit 8/min --limit-burst 16 $TO_LOG "[OU$ENVID-DROP] "
				$IPTABLES -A FORWARD -m limit --limit 8/min --limit-burst 16 $TO_LOG "[FW$ENVID-DROP] "
787
788
				;;

789
790
791
792
			ALLOW_DHCP)
				probeChains -tmangle DHCP
				(( $? != 0 )) && \
					error 42 "The 'DHCP' chain is missing. Setup a new base firewall with BASE_RULE_SET first."
793

794
795
796
				checkLink $1;
				(( $? != 0 )) && \
					printf >&2 "WARNING! '$1' is currently not available. Maybe invoked later?\n" ;
797

798
799
					# $2 = dhcp mode
				unset sz;
800

801
802
803
				sz=${2,,};
				[ -z "$sz" ] && \
					error 43 "ALLOW_DHCP expects a dhcp mode (eg. client|server|both)";
804

805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
				[ $sz == "client" ] && sz=$DHCP_CLIENT_MARK;
				[ $sz == "server" ] && sz=$DHCP_SERVER_MARK;
				[ $sz == "both" ] && sz=$DHCP_BOTH_MARK;

				printf "# allowing DHCP (IPv%s) client requests on '%s'.\n" $ENVID $1;
				[ $ENVID == 6 ] && \
					printf >&2 "ATTENTION! DHCPv6 allows implicit link local traffic on corresponding ports only.\n";

				ID="ALLOW_DHCP_$(getLinkID $1)";
				deleteRules -t mangle DHCP "$ID";

				$IPTABLES -t mangle -I DHCP -i $1 -j MARK --set-mark $sz -m comment --comment "$ID";
				$IPTABLES -t mangle -I DHCP -o $1 -j MARK --set-mark $sz -m comment --comment "$ID";

				shift; shift;
820
821
				;;

822
			ALLOW_SUBNETS)
823
824
				probeChains LOCAL
				(( $? != 0 )) && error 42 "The 'LOCAL' chain is missing. Setup a new base firewall with BASE_RULE_SET first."
825

826
827
828
				checkLink $1
				(( $? != 0 )) && error 41 "ALLOW_SUBNETS expects an interface argument (eg: eth0)"

829
830
				ID="ALLOW_SUBNETS_$(getLinkID $1)"
				deleteRules LOCAL "$ID"
831
832
833

				printf "# allowing subnets on $1 link:"

834
835
836
837
				# exclude 'manually' configured link-local addresses (for whatever reason)
				p=$LLsubnet
				for addr in $(obtainIPs $ENVID global $1); do
					subnet=$(obtainNetPrefix $addr)
838
839
840
841
842

						# omit a subnet when it has been processed already!
					echo "$p" | grep "$subnet" 1>/dev/nul 2>/dev/nul
					(( $? == 0 )) && continue

843
844
845
					printf " %s" $addr

					$IPTABLES -I LOCAL 1 -i $1 -s $subnet -d $addr -j ACCEPT -m comment --comment "$ID"
846
					$IPTABLES -I LOCAL 1 -o $1 -s $addr -d $subnet -j ACCEPT -m comment --comment "$ID"
847
848
849
850

					p+=" $subnet"
				done

851
				printf " (broadcast)"
852
853
				$IPTABLES -I LOCAL 1 -i $1 -m pkttype --pkt-type broadcast -j ACCEPT -m comment --comment "$ID (broadcast in)"
				$IPTABLES -I LOCAL 1 -o $1 -m pkttype --pkt-type broadcast -j ACCEPT -m comment --comment "$ID (broadcast out)"
854

855
# not sure about implicitly allowing link local since this is called alllow_subnets
856
					# for IPv6 on this link
857
858
859
860
861
862
#				[ $ENVID -eq 6 ] && {
#					printf " %s" $LLsubnet;
#					$IPTABLES -I LOCAL 1 -o $1 -s $LLsubnet \
#								-m addrtype --src-type LOCAL --limit-iface-out \
#								-j ACCEPT -m comment --comment "$ID (link-local out)";
#				};
863
864
865
866
867
868

				echo ""
				shift
				unset addr; unset subnet; unset p
				;;

869
			ALLOW_STATIC_SUBNETS)
870
				probeChains LOCAL
871
872
				(( $? != 0 )) && error 42 "The 'LOCAL' chain is missing. Setup a new base firewall with BASE_RULE_SET first."

873
874
875
876
877
878
879
880
				[ -z "$1" ] && error 44 "ALLOW_STATIC_SUBNETS expects an interface argument (eg: eth0)"
				[ -z "$2" ] && error 45 "ALLOW_STATIC_SUBNETS expects a comma separated list of subnets to allow (eg: 192.168.0.0/16)"

				subnets=${2//,/ };
				for s in $subnets; do
					checkSubnetArgFormat $s;
					(( $? != 0 )) && error 46 "ALLOW_STATIC_SUBNETS can't handle malformed subnet argument: $s";
				done;
881

882
				ID="ALLOW_SUBNETS_$(getLinkID $1)"
883
				deleteRules LOCAL "$ID"
884

885
				printf "# allowing subnets on $1 link: $subnets"
886

887
888
889
890
891
				unset s;
				for s in $subnets; do
					$IPTABLES -I LOCAL 1 -i $1 -s $s -m addrtype --dst-type LOCAL -j ACCEPT -m comment --comment "$ID"
					$IPTABLES -I LOCAL 1 -o $1 -m addrtype --src-type LOCAL -d $s -j ACCEPT -m comment --comment "$ID"
				done
892

893

894
895
896
897
				echo ""
				shift; shift;
				unset addr; unset subnet; unset p
				;;
898

899
900
901
			ALLOW_LINK_LOCAL)
				probeChains LOCAL
				(( $? != 0 )) && error 42 "The 'LOCAL' chain is missing. Setup a new base firewall with BASE_RULE_SET first."
902

903
904
905
906
907
908
909
910
911
912
913
914
915
				checkLink $1
				(( $? != 0 )) && error 41 "ALLOW_LINK_LOCAL expects an interface argument (eg: eth0)"

				ID="ALLOW_LINK_LOCAL_$(getLinkID $1)"
				deleteRules LOCAL "$ID"

				printf "# allowing link local (%s) on %s\n" $LLsubnet $1

#TODO: allowing link local this way allows implicitly sending RAs which should only be allowed explicitly
				$IPTABLES -I LOCAL 1 -i $1 -d $LLsubnet -j ACCEPT -m comment --comment "$ID"
				$IPTABLES -I LOCAL 1 -o $1 -s $LLsubnet \
							-m addrtype --src-type LOCAL --limit-iface-out \
							-j ACCEPT -m comment --comment "$ID";
916
917
918
				shift
				;;

919
920
			ALLOW_LAYER2_MULTICAST)

921
922
923
#				#-A INPUT -m pkttype --pkt-type multicast -j ACCEPT
#				iptables -I LOCAL 1 -m pkttype --pkt-type multicast -i macvlan0 -s 10.1.0.0/16 -j ACCEPT
#				iptables -O LOCAL 1 -m pkttype --pkt-type multicast -o macvlan0 -d 10.1.0.0/16 -j ACCEPT
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
			ALLOW_MULTICAST_ADDRS)
				checkLink $1;
				(( $? != 0 )) && \
					printf "WARNING! interface '%s' currently not available. Maybe invoked later?\n" $1;

					# UDP port or ports
				unset ports; unset dports;
					# all numbers concatenated must be still a number?!
				sz=${2//,/};
				[ -n "$sz" ] && {
					isNaturalNumber $sz;
					(( $? != 0 )) && \
						error 51 "ALLOW_MULTICAST_ADDRS expects a whitespace-less, comma separated list of destination UDP ports. (eg: 80,443)\nArgument is malformed.";
					ports="-m multiport --ports $2";
					dports="-m multiport --dports $2";
				};

				probeChains LOCAL;
				(( $? != 0 )) && error 37 "The 'LOCAL' chain is missing. Setup a new base firewall with BASE_RULE_SET first."

				sz='.';
				[ -n "$ports$dports" ] && sz=" on UDP ports: $2.";
				printf "# allowing multicast addresses on '$1'$sz\n";

				ID="ALLOW_MULTICAST_ADDRS_$(getLinkID $1)" 
				deleteRules LOCAL "$ID"

				$IPTABLES -I LOCAL 1 -p udp -i $1 \
							-m addrtype --dst-type MULTICAST \
							$dports \
							-j ACCEPT -m comment --comment "${ID}_in";

					# for outgoing traffic on LOCAL & MULTICAST it's
					# sufficient if the ports may be source, dest or even both
				$IPTABLES -I LOCAL 1 -p udp -o $1 \
							-m addrtype --src-type LOCAL --limit-iface-out \
							-m addrtype --dst-type MULTICAST \
							$ports \
							-j ACCEPT -m comment --comment "${ID}_out";

				[ -n "$2" ] && shift;
				shift;
				;;
969

970
971
			ALLOW_SERVICE_DISCOVERY)
				checkLink $1
972
				(( $? != 0 )) && error 36 "ALLOW_SERVICE_DISCOVERY expects an interface argument (eg: eth0)"
973

974
				probeChains LOCAL
975
				(( $? != 0 )) && error 37 "The 'LOCAL' chain is missing. Setup a new base firewall with BASE_RULE_SET first."
976
977
978

				printf "# allowing service discovery on %s link.\n" $1

979
				ID="ALLOW_SERVICE_DISCOVERY on $(getLinkID $1)" 
980
				deleteRules LOCAL "$ID"
981
982

				if [ $ENVID -eq 4 ]; then
983
					$IPTABLES -I LOCAL 1 -d 224.0.0.251/32 -p udp -m udp -i $1 --dport 5353 -j ACCEPT -m comment --comment "$ID (multicast mDNS)"
984
985
					$IPTABLES -I LOCAL 1 -d 224.0.0.252/32 -p udp -m udp -i $1 --dport 5355 -j ACCEPT -m comment --comment "$ID (multicast LLMNR)"
 
986
987
988
989
					$IPTABLES -I LOCAL 1 -d 239.255.255.250/32 -p udp -m udp -i $1 --dport 1900 -j ACCEPT -m comment --comment "$ID (multicast UPnP/SSDP: site-local)"

					$IPTABLES -I LOCAL 1 -d 239.255.255.250/32 -p udp -m udp -i $1 --dport 3702 -j ACCEPT -m comment --comment "$ID (multicast WSD)"

990
991
				fi
				if [ $ENVID -eq 6 ]; then
992
					$IPTABLES -I LOCAL 1 -d ff02::fb/128 -p udp -m udp -i $1 --dport 5353 -j ACCEPT -m comment --comment "$ID (multicast mDNS)"
993
994
					$IPTABLES -I LOCAL 1 -d ff02::1:3/128 -p udp -m udp -i $1 --dport 5355 -j ACCEPT -m comment --comment "$ID (multicast LLMNR)"

995
996
997
998
999
1000
1001
1002
1003
1004
						# https://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol
					$IPTABLES -I LOCAL 1 -d ff02::c/128 -p udp -m udp -i $1 --dport 1900 -j ACCEPT -m comment --comment "$ID (multicast UPnP/SSDP: link-local)"
					$IPTABLES -I LOCAL 1 -d ff05::c/128 -p udp -m udp -i $1 --dport 1900 -j ACCEPT -m comment --comment "$ID (multicast UPnP/SSDP: site-local)"
					$IPTABLES -I LOCAL 1 -d ff08::c/128 -p udp -m udp -i $1 --dport 1900 -j ACCEPT -m comment --comment "$ID (multicast UPnP/SSDP: org-local)"
					$IPTABLES -I LOCAL 1 -d ff0e::c/128 -p udp -m udp -i $1 --dport 1900 -j ACCEPT -m comment --comment "$ID (multicast UPnP/SSDP: global)"

					$IPTABLES -I LOCAL 1 -d ff02::c/128 -p udp -m udp -i $1 --dport 3702 -j ACCEPT -m comment --comment "$ID (multicast WSD)"

					# exotic multicast from Canon printers
					#$IPTABLES -I LOCAL 1 -d ff02::1/128 -p udp -m udp -i $1 --dport 8612 -j ACCEPT -m comment --comment "$ID (multicast BJNP)"
1005
1006
1007
1008
1009
				fi

				shift;
				;;

1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
			ALLOW_STATEFUL_PACKETS)
				unset sz
				probeChains USER-IN USER-OUT
				(( $? != 0 )) && error 42 "ALLOW_STATEFUL_PACKETS needs 'USER-*' chains. Setup a new base firewall with BASE_RULE_SET first."

					# $1 == device node or IP address?
				checkIPArgFormat "$1"
				if (( $? != 0 )); then

					checkLink $1
					(( $? != 0 )) && \
						printf >&2 "WARNING! '$1' currently not available. Maybe invoked later?\n"

					by[0]="-i $1 -m addrtype --dst-type LOCAL --limit-iface-in";
					by[1]="-o $1 -m addrtype --src-type LOCAL --limit-iface-out";
					printf "# allowing stateful packets on '%s'.\n" $1
					sz=$(getLinkID $1);
				else
					[ -z "$(obtainNetPrefix $1)" ] && \
						printf >&2 "WARNING! no route to '$1' or argument has malformed IP format"

					by[0]="-d $1 -m addrtype ! --src-type LOCAL";
					by[1]="-s $1";
					printf "# allowing stateful packets on any interface when sending from '%s'.\n" $1
					sz=$(formatAsHexID $1);
				fi

				ID="ALLOW_STATEFUL_PACKETS_$sz"
				deleteRules USER-IN "$ID"
				deleteRules USER-OUT "$ID"

					# stateful packets intiated by ourself coming back
					# but only of it's destined to a given interface, no (multi|broad)cast!
				$IPTABLES -A USER-IN ${by[0]} \
							-m state --state RELATED,ESTABLISHED \
							-j ACCEPT -m comment --comment "$ID"

					# stateful packets allowing only new packets out
				$IPTABLES -A USER-OUT ${by[1]} \
							-m state --state NEW \
							-j ACCEPT -m comment --comment "$ID";
				shift;
				;;

1054
			ALLOW_TUNNEL)
1055
1056
				[ $ENVID -eq 6 ] && error 90 "Only useful with IPv4."

1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
				probeChains USER-IN
				(( $? != 0 )) && error 37 "The 'USER-IN' chain is missing. Setup a new base firewall with BASE_RULE_SET first."
				probeChains USER-OUT
				(( $? != 0 )) && error 37 "The 'USER-OUT' chain is missing. Setup a new base firewall with BASE_RULE_SET first."

					# convert mode to lower case
				sz=${1,,}
				[ $sz == "ipip" ] && sz=94
				[ $sz == "gre" ] && sz=47
				[ $sz == "sit" ] && sz=41
				isNaturalNumber $sz
				(( $? != 0 )) && error 37 "ALLOW_TUNNEL expects a tunnel mode (eg: ipip, gre or sit)"

				checkLink $2
				(( $? != 0 )) && error 38 "ALLOW_TUNNEL expects an incoming interface to allow tunnel traffic from (eg: eth0)"

				checkIPArgFormat $3
				(( $? != 0 )) && error 39 "ALLOW_TUNNEL expects a source IP address to allow tunnel traffic from (eg: 192.168.1.1)"

				printf "# allowing '%s' tunnel on %s link from %s.\n" ${1^^} $2 $3

				ID="ALLOW_TUNNEL_${1^^}_$(getLinkID $2)_$3"
				deleteRules USER-IN "$ID"
				deleteRules USER-OUT "$ID"

				$IPTABLES -A USER-IN -i $2 -p $sz -s $3 -j ACCEPT -m comment --comment "$ID"
				$IPTABLES -A USER-OUT -o $2 -p $sz -d $3 -j ACCEPT -m comment --comment "$ID"

				shift; shift; shift;
				;;

1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
			6TO4)
				[ $ENVID -eq 6 ] && error 90 "Only useful with IPv4."

				checkIPArgFormat "$1"
				(( $? != 0 )) && error 91 "6to4 expects a public, routable IPv4 wan address."

				checkLink $2
				(( $? == 0 )) && error 92 "Tunnel name '$2' already in use.\n"

				sz=$(printf "2002:%02x%02x:%02x%02x:e0::1" ${1//./ })
				ip tunnel add $2 mode sit local $1 remote 192.88.99.1 ttl 125 dev eth2
				ip -6 address add $sz dev $2
				ip link set $2 up
				ip -6 route add 2000::/3 dev $2 metric 1

				#ip6tables -I FORWARD 1 -s 2002::/16 -o sit2 -j ACCEPT
				shift; shift;
				;;

			ALLOW_PORT|ALLOW_SERVICE)
					# $1 == port or ports
				ay=${1//,/}
				for sz in $ay; do
					isNaturalNumber $sz
					(( $? != 0 )) && error 70 "ALLOW_PORT expects a destination port or ports argument (eg: 80,443)"
				done

1115
1116
1117
					# $3 == protocol?
				PROTO=$(checkProtocol $3)

1118
1119
1120
1121
					# $2 == device node or IP address?
				checkIPArgFormat "$2"
				if (( $? != 0 )); then

1122
1123
1124
1125
1126
					[[ $2 =~ [:alnum:]+ ]] || error 71 "ALLOW_PORT expects either an IP or interface argument."

					checkLink $2;
					(( $? != 0 )) && \
						printf >&2 "WARNING! '$2' currently not available. Maybe invoked later?\n";
1127

1128
1129
1130
					FILTER_BY="-i $2";
					printf "# allow port(s): %s (%s) to reach %s\n" $1 $PROTO $2;
					printf >&2 "ATTENTION! Ports reachable for any address configured on this device! Maybe unintended?\n";
1131
					sz="$2"
1132
1133
				else
					sz=$(obtainNetPrefix $2)
1134
1135
1136
1137
1138
1139
1140
1141
					[ -z $sz ] && {
						printf >&2 "WARNING! No route to '$2'\n";
						unset sz;
					} || \
						sz=" on $(obtainLinkFromSubnetPrefix $sz)";

					FILTER_BY="-d $2";
					printf "# allow port(s): %s (%s) to reach %s%s.\n" $1 $PROTO $2 "$sz"
1142
					sz="$(formatAsHexID $2)"
1143
1144
				fi

1145
				ID="ALLOW_PORT_$1_$sz"
1146
1147
				deleteRules USER-IN "$ID"

1148
1149
1150
1151
1152
1153
1154
				if [[ $PROTO =~ any ]]; then
					$IPTABLES -A USER-IN $FILTER_BY -p tcp -m multiport --ports $1 -j ACCEPT -m comment --comment "$ID"
					$IPTABLES -A USER-IN $FILTER_BY -p udp -m multiport --ports $1 -j ACCEPT -m comment --comment "$ID"
				else
					$IPTABLES -A USER-IN $FILTER_BY -p $PROTO -m multiport --ports $1 -j ACCEPT -m comment --comment "$ID"
					shift;
				fi
1155
1156

				shift; shift;
1157
				unset FILTER_BY; unset PROTO; unset ay; unset ID;
1158
1159
				;;

1160
1161
1162
1163
1164
1165
1166
1167
1168

# undocumented ugly hack:
# optional source interface in front of subnet arg
			FORWARD_SUBNET_FROM)
				unset DEV;
				DEV=$1;
				shift;
				;&

1169
			FORWARD_SUBNET)
1170
				unset sz;
1171
1172
1173
1174
1175
				[ $ENVID -eq 4 ] && sz=" (eg: 192.168.0.0/16)"
				[ $ENVID -eq 6 ] && sz=" (eg: 2001:DB8::/32)"
				checkSubnetArgFormat $1
				(( $? != 0 )) && error 51 "FORWARD_SUBNET expects a subnet/mask argument$sz and a (internal!) LAN device."

1176
1177
1178
1179
				[ -z $DEV ] && {
					DEV=$(obtainLinkFromSubnetPrefix $1)
					(( $? != 0 )) && error 52 " A route to '$1' doesn't exist. Forwarding without a route?"
				}
1180
1181
1182
1183

				checkLink $2
				(( $? != 0 )) && error 53 " No '$2' device found."

1184
				printf "# forwarding %s (%s) to %s.\n" $1 $DEV $2
1185

1186
				ID="FORWARD_SUBNET_$(getLinkID $DEV)_$(formatAsHexID $1)_$2"
1187
1188
				deleteRules FORWARD "$ID"

1189
1190
1191
					# get index position for placing subchains in FORWARD chain
				returnRuleCount FORWARD
				n=$?
1192

1193
1194
1195
				$IPTABLES -I FORWARD $n -i $DEV -o $2 -s $1 -j ACCEPT -m comment --comment "$ID"
				$IPTABLES -I FORWARD $n -i $2 -o $DEV -d $1 -m state --state RELATED,ESTABLISHED -j ACCEPT -m comment --comment "$ID"
				$IPTABLES -I FORWARD $n -i $2 -o $DEV -d $1 -m state --state NEW -j ACCEPT -m comment --comment "$ID"
1196
1197

				unset n
1198
1199
1200
1201
				shift; shift
				;;

			FORWARD_SUBNET_PROTECTIVE)
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
				unset DEV;
# undocumented ugly hack:
# optional source interface in front of subnet arg
# {
				checkLink $1
				(( $? == 0 )) && {
					DEV=$1;
					shift;
				};
# }
1212
				checkSubnetArgFormat $1
1213
1214
1215
1216
1217
				(( $? != 0 )) && {
					[ $ENVID -eq 4 ] && sz=" (eg: 192.168.0.0/16)"
					[ $ENVID -eq 6 ] && sz=" (eg: 2001:DB8::/32)"
					error 51 "FORWARD_SUBNET_PROTECTIVE expects a subnet/mask argument$sz and a WAN device (eg: ppp0)"
				}
1218

1219
1220
1221
1222
				[ -z $DEV ] && {
					DEV=$(obtainLinkFromSubnetPrefix $1)
					(( $? != 0 )) && error 52 "A route to '$1' doesn't exist. Forwarding without a route?"
				}
1223
1224
1225
1226
1227
1228

				probeChains ICMP
				(( $? != 0 )) && error 53 "The 'ICMP' chain is missing. Setup a new base firewall with BASE_RULE_SET first."

				sz=""
				checkLink $2
1229
1230
1231
1232
				(( $? != 0 )) && \
					printf >&2 "WARNING! '$2' currently not available. Maybe invoked later?)\n";

				printf "# forwarding protectively %s (%s) to %s.\n" $1 $DEV $2
1233

1234
				ID=$(printf "FORWARD_SUBNET_PROTECTIVE_%s_%s_%s" $DEV $(formatAsHexID "$1") $2)
1235
1236
				deleteRules FORWARD "$ID"

1237
1238
					# for IPv6 subnets the max chain name length can
					# be easily exceeded so we need a shorter name
1239
				#CHAIN=$(printf "%s-%s-%s" $(formatAsHexID "$1") $2 $DEV)
1240
				CHAIN=$(printf "%X-IN" $(cksum <<<"$ID" | grep -oP "^\d*"))
1241
1242
				allocChain $CHAIN

1243
1244
1245
1246
					# get index position for placing subchains in FORWARD chain
				returnRuleCount FORWARD
				n=$?

1247
1248
1249
1250
1251
1252
					# allow ICMP requests from the inner
				[ $ENVID -eq 4 ] && sz="icmp"
				[ $ENVID -eq 6 ] && sz="ipv6-icmp"
				$IPTABLES -A $CHAIN -p $sz -j ICMP

					# drop invalid packets
1253
1254
				$IPTABLES -A $CHAIN -m state --state INVALID $TO_LOG "[BLOCK] (INVALID) "
				$IPTABLES -A $CHAIN -m state --state INVALID -j DROP
1255
1256

					# syn-flood protection
1257
				$IPTABLES -A $CHAIN -p tcp -d $1 --syn -j ANTI-FLOOD
1258
					# furtive port scanner
1259
				$IPTABLES -A $CHAIN -p tcp -d $1 --tcp-flags SYN,ACK,FIN,RST RST -j ANTI-FLOOD
1260
1261

					# allow safe ports for inbound traffic
1262
				$IPTABLES -A $CHAIN -p tcp -m tcp -m multiport --sports 80,443 -j ACCEPT 
1263
1264
1265

					# forward to the inside for related or established traffic only!
				$IPTABLES -A $CHAIN -m state --state RELATED,ESTABLISHED -j ACCEPT
1266

1267
				$IPTABLES -I FORWARD $n -i $2 -o $DEV -d $1 -j $CHAIN -m comment --comment "$ID"
1268

1269
				CHAIN=$(printf "%X-OUT" $(cksum <<<"$ID" | grep -oP "^\d*"))
1270
1271
				allocChain $CHAIN

1272
					# forward new, related & established traffic outside
1273
1274
1275
1276
1277
1278
				$IPTABLES -A $CHAIN -m state --state RELATED,ESTABLISHED -j ACCEPT
				$IPTABLES -A $CHAIN -m state --state NEW -j ACCEPT

					# allow safe ports for outbound traffic
				$IPTABLES -A $CHAIN -p tcp -m tcp -m multiport --dports 80,443 -j ACCEPT 

1279
				$IPTABLES -I FORWARD $n -i $DEV -o $2 -s $1 -j $CHAIN -m comment --comment "$ID"
1280

1281
				unset sz; unset DEV; unset CHAIN; unset n
1282
1283
1284
				shift; shift
				;;

1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
			FORWARD_PORT|FORWARD_ROUTING)
				ay=${2//,/}		# check given port list
				for sz in $ay; do
					isNaturalNumber $sz
					(( $? != 0 )) && error 70 "FORWARD_ROUTING expects a destination port argument (eg: 80,443)"
				done

				checkIPArgFormat "$3"
				(( $? != 0 )) && error 71 "FORWARD_ROUTING expects a destination IP to your internal host and an optional destination port (eg: 192.168.1.1[:80])"

					# $1 == device node or IP address?
				checkIPArgFormat "$1"
				if (( $? != 0 )); then
					[[ ! $1 =~ [A-Za-z]{3}[0-9]+ ]] && error 72 "FORWARD_ROUTING expects '$1' to be a device node or an IP address."

					checkLink $1
1301
1302
					(( $? != 0 )) && \
						printf >&2 "WARNING! '$1' currently not available. Maybe invoked later?\n"
1303

1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
					FILTER_BY="-i $1"
				else
					sz=$(obtainNetPrefix $1)
					[ -z $sz ] && error 73 "FORWARD_ROUTING has no route to '$1' or a malformed IP format (eg: 192.168.1.1)"

					FILTER_BY="-i $(obtainLinkFromSubnetPrefix $sz) -d $1"
				fi
					# create a mark ID (cksum)
				MARK_ID=$(printf "0x%x" $(cksum <<<"$1$2$3" | grep -oP "^\d*"))

1314
1315
1316
1317
1318
					# $4 == protocol (tcp|udp) with 'tcp' as default when not specified
				PROTO=$(checkProtocol $4)
				[[ $PROTO =~ any ]] && PROTO=tcp

				printf "# prerouting port fowarding from %s:%s to %s (ID: %s)\n" $1 $2 $3 $MARK_ID
1319
1320

				ID="FORWARD_ROUTING $MARK_ID"
1321
				deleteRules FORWARD "$ID"
1322
1323
				deleteRules -t nat PREROUTING "$ID"
				deleteRules -t nat POSTROUTING "$ID"
1324

1325
1326
1327
1328
1329
						# We mark traffic originating from someone to our receiver IP|device on the
						# specified port only.
						# This may look complicated but makes absolutely sense since our POSTROUTING
						# needs to distinguish from traffic carrying our MARK_ID _and_ traffic on the 
						# corresponding port returned from the forwarded host.
1330
1331
				$IPTABLES -t nat -A PREROUTING $FILTER_BY -p $PROTO -m multiport --dports $2 -j MARK --set-mark $MARK_ID -m comment --comment "$ID"
				$IPTABLES -t nat -A PREROUTING -m mark --mark $MARK_ID -p $PROTO -j DNAT --to $3 -m comment --comment "$ID"
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341

						# prerouting rewrites destination address for marked packets therefore these
						# go through the FORWARD chain instead of INPUT, to avoid having other rules
						# (eg: FORWARD_SUBNET_PROTECTIVE) blocking our marked packets accidentially
						# we allow them to be forwarded explicitly
				$IPTABLES -I FORWARD 1 -m mark --mark $MARK_ID -j ACCEPT -m comment --comment "$ID"

						# allow packets back & forth from the forwarded host
						# Attention! >> These response packets are _not_ carrying our MARK_ID
						# therefore these rules are all inserted at index 1 so order matters!
1342
1343
1344
				[[ $3 =~ : ]] && sz=${3#*:} || sz=$2
				$IPTABLES -I FORWARD 1 -p $PROTO -s ${3%:*}/32 -m multiport --sports $sz -j ACCEPT -m comment --comment "$ID"
				$IPTABLES -I FORWARD 1 -p $PROTO -d ${3%:*}/32 -m multiport --dports $sz -j ACCEPT -m comment --comment "$ID"
1345
1346
1347
1348
1349

						# Masquerade only those carrying our MARK_ID!
				$IPTABLES -t nat -I POSTROUTING 1 -m mark --mark $MARK_ID -d ${3%:*}/32 -j MASQUERADE -m comment --comment "$ID"

				shift; shift; shift;
1350
1351
				[[ $(checkProtocol $4) =~ any ]] && shift
				unset FILTER_BY; unset PROTO; unset MARK_ID;
1352
				unset ID;
1353
1354
				;;

1355
1356
1357
1358
1359
1360
1361
			MAC_FILTER)
				sz=$($IPTABLES -nvL | grep -oP "(?<=Chain\s)\S+" | grep ${1^^})
				[ -z $sz ] && error 90 "MAC_FILTER expects a chain name to place filter in (eg: INPUT, FORWARD, ...)"

				checkMACArgFormat "$2"
				(( $? != 0 )) && error 91 "MAC_FILTER expects an ether address (MAC) (eg: 06:00:17:d3:97:b4)"

1362
1363
1364
1365
1366
				printf "# filtering '%s' MAC address in %s chain.\n" $2 $sz;

				#$IP n | grep "$2" >/dev/nul && \
				[[ $($IP n) =~ $2 ]] && \
					printf "WARNING! Mac address appears to be a host of the local network.\n"
1367

1368
1369
1370
				sy=${2//:/}
				sy=${sy,,}
				ID=$(printf "MAC_FILTER_%s_%s" $sz $sy)
1371
				deleteRules $sz "$ID"
1372

1373
1374
				$IPTABLES -I $sz 1 -m mac --mac-source $2 -j DROP -m comment --comment "$ID"

1375
				unset sz; unset sy;
1376
				shift; shift
1377
1378
1379
1380
1381
1382
1383
1384
				;;

			TRANSPARENT_PROXY)
				#$IPTABLES -t nat -A PREROUTING -i $LAN -p tcp --dport 80 -j DNAT --to $SQUID_SERVER:$SQUID_PORT
				#$IPTABLES -t nat -A PREROUTING -i $WAN -p tcp --dport 80 -j REDIRECT --to-port $SQUID_PORT
				;;

			POSTROUTING_MASQUERADE)
1385
				[ $ENVID -ne 4 ] && printf "# Masquerading (NAT) is only useful for IPv4!\n"
1386
1387
1388
1389
1390
1391

				checkSubnetArgFormat $1
				(( $? != 0 )) && error 61 "POSTROUTING_MASQUERADE expects a subnet/mask on an outgoing device argument (eg: 192.168.0.0/16 ppp0)"

				sz=""
				checkLink $2
1392
1393
1394
1395
				(( $? != 0 )) && \
					printf >&2 "WARNING! '$2' currently not available. Maybe invoked later?\n" 

				printf "# masquerading %s when leaving through %s.\n" $1 $2
1396

1397
				ID=$(printf "POSTROUTING_MASQUERADE %s_%s_%s" $(obtainLinkFromSubnetPrefix $1) $(formatAsHexID "$1") $2)
1398
1399
1400
1401
1402
1403
1404
1405
				deleteRules -t nat POSTROUTING "$ID"

				$IPTABLES -t nat -A POSTROUTING -s $1 -o $2 -j MASQUERADE -m comment --comment "$ID"

				shift; shift;
				unset ID;
				;;

1406
1407
1408
			PORT_KNOCKING)
				# http://stackoverflow.com/questions/15451009/port-knocking-using-iptables
				;;
1409

1410
1411
1412
1413
1414
1415
1416
			DEBUG_CHAIN)
				$IPTABLES -nvL $1 1>/dev/nul 2>/dev/nul
				(( $? != 0 )) && error 83 "DEBUG_CHAIN expects a chain name argument. A chain called '$1' was not found."

				ID="DEBUG_CHAIN $1" 
				deleteRules $1 "$ID"

1417
1418
1419
1420
1421
1422
1423
				$IPTABLES -A $1 -p all $TO_LOG "[${1%${1#??}}$ENVID-DEBUG] " -m comment --comment "$ID"
				shift;
				unset ID;
				;;

			LIST)
				$IPTABLES --line-numbers -nvL $1
1424
1425
1426
				shift;
				;;

1427
			REMOVE)
1428
1429
1430
1431
1432
				printf "# Removing rules containing '$1' in:"
				for sz in $($IPTABLES -nvL | grep -o -P "(?<=Chain\s)\S+"); do
					$IPTABLES -nvL $sz | grep "$1" 1>/dev/nul 2>/dev/nul
					if (( $? == 0 )); then
						deleteRules $sz "$1"
1433
						(( $? != 0 )) && printf " $sz"
1434
1435
1436
1437
1438
1439
					fi
				done
				for sz in $($IPTABLES -t nat -nvL | grep -o -P "(?<=Chain\s)\S+"); do
					$IPTABLES -t nat -nvL $sz | grep "$1" 1>/dev/nul 2>/dev/nul
					if (( $? == 0 )); then
						deleteRules -t nat $sz "$1"
1440
						(( $? != 0 )) && printf " $sz"
1441
1442
					fi
				done
1443
1444
1445
1446
1447
1448
1449
				for sz in $($IPTABLES -t mangle -nvL | grep -o -P "(?<=Chain\s)\S+"); do
					$IPTABLES -t mangle -nvL $sz | grep "$1" 1>/dev/nul 2>/dev/nul
					if (( $? == 0 )); then
						deleteRules -t mangle $sz "$1"
						(( $? != 0 )) && printf " $sz"
					fi
				done
1450
				echo " ... done"
1451

1452
1453
1454
				printf "# Deallocating orphaned chains:"
				for sz in $($IPTABLES -nvL | grep -o -P "(?<=Chain\s)\S+(?=\s\(0 ref)"); do
					printf " $sz"
1455
					sleep 1;
1456
1457
1458
					deallocChain $sz
				done
				echo " ... done"
1459

1460
1461
				unset sz;
				shift;
1462
1463
				;;

1464
1465
1466
1467
			VERBOSE|LIST_RULES|SHOW_RULES)
				$IPTABLES-save
				;;