Project: IPFire
Code Location: git://git.ipfire.org/network.gitmaster
Browse
/
Download File
functions.firewall
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
#!/bin/bash
###############################################################################
#                                                                             #
# IPFire.org - A linux based firewall                                         #
# Copyright (C) 2012  IPFire Network Development Team                         #
#                                                                             #
# 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 3 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, see <http://www.gnu.org/licenses/>.       #
#                                                                             #
###############################################################################

# This function initializes all kernel parameters that need to be adjusted
# to run this firewall properly.
function firewall_kernel_init() {
	log INFO "Configuring kernel parameters..."
	local option

	# Enable conntrack accounting
	conntrack_set_accounting "true"

	# Adjust max. amount of simultaneous connections
	conntrack_set_max_connections "${CONNTRACK_MAX_CONNECTIONS}"

	# Increase UDP connection timeout (fixes DNS)
	conntrack_set_udp_timeout "${CONNTRACK_UDP_TIMEOUT}"

	# Disable sending redirects
	log INFO "Disabling sending redirects"
	sysctl_set_recursively "net.ipv6.conf" "send_redirects" 0
	sysctl_set_recursively "net.ipv4.conf" "send_redirects" 0

	# Enable source route protection
	log INFO "Enabling source route protection"
	sysctl_set_recursively "net.ipv6.conf" "accept_source_route" 0
	sysctl_set_recursively "net.ipv4.conf" "accept_source_route" 0

	# ICMP broadcast protection (smurf amplifier protection)
	log INFO "Enabling ICMP broadcast protection (smurf amplifier protection)"
	sysctl_set "net.ipv4.icmp_echo_ignore_broadcasts" 1

	# ICMP Dead Error Message protection
	log INFO "Enabling ICMP dead error message protection"
	sysctl_set "net.ipv4.icmp_ignore_bogus_error_responses" 0

	# Enable packet forwarding
	log INFO "Enabling packet forwarding"
	sysctl_set_recursively "net.ipv6.conf" "forwarding" 1
	sysctl_set_recursively "net.ipv4.conf" "forwarding" 1

	# Setting some kernel performance options
	log INFO "Setting some kernel performance options"
	for option in window_scaling timestamps sack dsack fack; do
		sysctl_set "net.ipv4.tcp_${option}" 1
	done
	sysctl_set "net.ipv4.tcp_low_latency" 0

	# Reduce DoS ability by reducing timeouts
	log INFO "Reducing DoS ability"
	sysctl_set "net.ipv4.tcp_fin_timeout" 30
	sysctl_set "net.ipv4.tcp_keepalive_time" 1800

	# Set number of times to retry SYN in a new connection
	sysctl_set "net.ipv4.tcp_syn_retries" 3

	# Set number of times to retry a SYN-ACK in a half-open new connection
	sysctl_set "net.ipv4.tcp_synack_retries" 2

	# Enable a fix for RFC1337 - time-wait assassination hazards in TCP
	sysctl_set "net.ipv4.tcp_rfc1337" 1

	# SYN-flood protection
	if enabled FIREWALL_SYN_COOKIES; then
		log INFO "Enabling SYN-flood protection via SYN-cookies"
		sysctl_set_bool "net.ipv4.tcp_syncookies" 1
	else
		log INFO "Disabling SYN-flood protection via SYN-cookies"
		sysctl_set_bool "net.ipv4.tcp_syncookies" 0
	fi

	# rp_filter
	if enabled FIREWALL_RP_FILTER; then
		log INFO "Enabling anti-spoof from non-routable IP addresses"
		sysctl_set_recursively "net.ipv4.conf" "rp_filter" 1
	else
		log INFO "Disabling anti-spoof from non-routable IP addresses"
		sysctl_set_recursively "net.ipv4.conf" "rp_filter" 0
	fi

	# Log martians
	if enabled FIREWALL_LOG_MARTIANS; then
		log INFO "Enabling the logging of martians"
		sysctl_set_recursively "net.ipv4.conf" "log_martians" 1
	else
		log INFO "Disabling the logging of martians"
		sysctl_set_recursively "net.ipv4.conf" "log_martians" 0
	fi

	# ICMP redirect messages
	if enabled FIREWALL_ACCEPT_ICMP_REDIRECTS; then
		log INFO "Enabling accepting ICMP-redirect messages"
		sysctl_set_recursively "net.ipv6.conf" "accept_redirects" 1
		sysctl_set_recursively "net.ipv4.conf" "accept_redirects" 1
	else
		log INFO "Disabling accepting ICMP-redirect messages"
		sysctl_set_recursively "net.ipv6.conf" "accept_redirects" 0
		sysctl_set_recursively "net.ipv4.conf" "accept_redirects" 0
	fi

	# Explicit Congestion Notification
	if enabled FIREWALL_USE_ECN; then
		log INFO "Enabling ECN (Explicit Congestion Notification)"
		sysctl_set "net.ipv4.tcp_ecn" 1
	else
		log INFO "Disabling ECN (Explicit Congestion Notification)"
		sysctl_set "net.ipv4.tcp_ecn" 2
	fi

	# Dynamic IP address hacking
	log INFO "Enabling kernel support for dynamic IP addresses"
	sysctl_set "net.ipv4.ip_dynaddr" 1

	if enabled FIREWALL_PMTU_DISCOVERY; then
		log INFO "Enabling PMTU discovery"
		sysctl_set "net.ipv4.ip_no_pmtu_disc" 0
	else
		log INFO "Disabling PMTU discovery"
		sysctl_set "net.ipv4.ip_no_pmtu_disc" 1
	fi

	# TTL
	if ipv4_ttl_valid "${FIREWALL_DEFAULT_TTL}"; then
		log INFO "Setting default TTL to ${FIREWALL_DEFAULT_TTL}"
		sysctl_set "net.ipv4.ip_default_ttl" "${FIREWALL_DEFAULT_TTL}"
	else
		log ERROR "Invalid value for default TTL '${FIREWALL_DEFAULT_TTL}'"
		log ERROR "  Must be between 10 and 255!"
	fi

	return ${EXIT_OK}
}

# High-level function which will create a ruleset for the current firewall
# configuration and load it into the kernel.
function firewall_start() {
	local protocol="${1}"
	assert isset protocol
	shift

	# Test mode.
	local test="false"

	while [ $# -gt 0 ]; do
		case "${1}" in
			--test)
				test="true"
				;;
			*)
				error "Unrecognized argument: ${1}"
				return ${EXIT_ERROR}
				;;
		esac
		shift
	done

	if enabled test; then
		log INFO "Test mode enabled."
		log INFO "The firewall ruleset will not be loaded."
	fi

	firewall_lock_acquire

	# Initialize an empty iptables ruleset.
	iptables_init "${protocol}" "DROP"

	# Add default chains.
	firewall_filter_rh0_headers "${protocol}"
	firewall_filter_icmp "${protocol}"
	firewall_filter_invalid_packets "${protocol}"
	firewall_custom_chains "${protocol}"
	firewall_connection_tracking "${protocol}"
	firewall_tcp_clamp_mss "${protocol}"

	# Add policies for every zone.
	firewall_localhost_create_chains "${protocol}"

	local zone
	for zone in $(zones_get_all); do
		# Create all needed chains for the zone.
		firewall_zone_create_chains "${protocol}" "${zone}"

		# After the chains that are always available have been
		# created, we will add a custom policy to every single
		# zone.

		policy_zone_add "${protocol}" "${zone}"
	done

	# Load the new ruleset.
	local args
	if enabled testmode; then
		list_append args "--test"
	fi
	iptables_commit "${protocol}" ${args}

	firewall_lock_release
}

function firewall_stop() {
	local protocol="${1}"
	assert isset protocol

	firewall_lock_acquire

	# Initialize an empty firewall ruleset
	# with default policy ACCEPT.
	iptables_init "${protocol}" ACCEPT

	# Load it.
	ipables_load "${protocol}"

	firewall_lock_release
}

function firewall_show() {
	local protocol="${1}"
	assert isset protocol

	# Shows the ruleset that is currently loaded.
	iptables_status "${protocol}"

	return ${EXIT_OK}
}

function firewall_panic() {
	local protocol="${1}"
	assert isset protocol
	shift

	local admin_hosts="$@"

	firewall_lock_acquire "${protocol}"

	# Drop all communications.
	iptables_init "${protocol}" DROP

	# If an admin host is provided, some administrative
	# things will be allowed from there.
	local admin_host
	for admin_host in ${admin_hosts}; do
		iptables "${protocol}" -A INPUT  -s "${admin_host}" -j ACCEPT
		iptables "${protocol}" -A OUTPUT -d "${admin_host}" -j ACCEPT
	done

	# Load it.
	iptables_commit "${protocol}"

	firewall_lock_release
}

function firewall_lock_acquire() {
	lock_acquire ${RUN_DIR}/.firewall_lock

	# Make sure the lock is released after the firewall
	# script has crashed or exited early.
	trap firewall_lock_release EXIT TERM KILL

	# Create a directory where we can put our
	# temporary data in the most secure way as possible.
	IPTABLES_TMPDIR=$(mktemp -d)
}

function firewall_lock_release() {
	if isset IPTABLES_TMPDIR; then
		# Remove all temporary data.
		rm -rf ${IPTABLES_TMPDIR}

		# Reset the tempdir variable.
		IPTABLES_TMPDIR=
	fi

	# Reset the trap.
	trap true EXIT TERM KILL

	lock_release ${RUN_DIR}/.firewall_lock
}

function firewall_custom_chains() {
	local protocol="${1}"
	assert isset protocol

	log INFO "Creating CUSTOM* chains..."

	# These chains are intened to be filled with
	# rules by the user. They are processed at the very
	# beginning so it is possible to overwrite everything.

	iptables_chain_create "${protocol}" CUSTOMINPUT
	iptables "${protocol}" -A INPUT -j CUSTOMINPUT

	iptables_chain_create "${protocol}" CUSTOMFORWARD
	iptables "${protocol}" -A FORWARD -j CUSTOMFORWARD

	iptables_chain_create "${protocol}" CUSTOMOUTPUT
	iptables "${protocol}" -A OUTPUT -j CUSTOMOUTPUT

	iptables_chain_create "${protocol}" -t nat CUSTOMPREROUTING
	iptables "${protocol}" -t nat -A PREROUTING -j CUSTOMPREROUTING

	iptables_chain_create "${protocol}" -t nat CUSTOMPOSTROUTING
	iptables "${protocol}" -t nat -A POSTROUTING -j CUSTOMPOSTROUTING

	iptables_chain_create "${protocol}" -t nat CUSTOMOUTPUT
	iptables "${protocol}" -t nat -A OUTPUT -j CUSTOMOUTPUT
}

function firewall_filter_invalid_packets() {
	local protocol="${1}"
	assert isset protocol

	local log_limit="-m limit --limit 5/m --limit-burst 10"

	# Create a chain
	iptables_chain_create "${protocol}" FILTER_INVALID
	iptables "${protocol}" -A INPUT   -j FILTER_INVALID
	iptables "${protocol}" -A OUTPUT  -j FILTER_INVALID
	iptables "${protocol}" -A FORWARD -j FILTER_INVALID

	# Create a chain where only TCP packets go
	iptables_chain_create "${protocol}" FILTER_INVALID_TCP
	iptables "${protocol}" -A FILTER_INVALID -p tcp -j FILTER_INVALID_TCP

	# Create a chain where only UDP packets go
	iptables_chain_create "${protocol}" FILTER_INVALID_UDP
	iptables "${protocol}" -A FILTER_INVALID -p udp -j FILTER_INVALID_UDP

	# Create a chain where only ICMP packets go
	iptables_chain_create "${protocol}" FILTER_INVALID_ICMP
	iptables "${protocol}" -A FILTER_INVALID -p icmp -j FILTER_INVALID_ICMP


	# Optionally log all port scans

	if enabled FIREWALL_LOG_STEALTH_SCANS; then
		log INFO "Logging of stealth scans enabled"

		# NMAP FIN/URG/PSH - XMAS scan
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL FIN,URG,PSH \
			"${log_limit}" -j "$(iptables_LOG "Stealth XMAS scan")"

		# SYN/RST/ACK/FIN/URG
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG \
			"${log_limit}" -j "$(iptables_LOG "Stealth XMAS-PSH scan")"

		# ALL/ALL
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL ALL \
			"${log_limit}" -j "$(iptables_LOG "Stealth XMAS-ALL scan")"

		# NMAP FIN Stealth
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL FIN \
			"${log_limit}" -j "$(iptables_LOG "Stealth FIN scan")"

		# SYN/RST
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags SYN,RST SYN,RST \
			"${log_limit}" -j "$(iptables_LOG "Stealth SYN/RST scan")"

		# SYN/FIN
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags SYN,FIN SYN,FIN \
			"${log_limit}" -j "$(iptables_LOG "Stealth SYN/FIN scan")"

		# Null scan
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL NONE \
			"${log_limit}" -j "$(iptables_LOG "Stealth NULL scan")"
	else
		log INFO "Logging of stealth scans disabled"
	fi


	# Drop scan packets

	# NMAP FIN/URG/PSH
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP

	# SYN/RST/ACK/FIN/URG
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP

	# ALL/ALL
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL ALL -j DROP

	# NMAP FIN Stealth
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL FIN -j DROP

	# SYN/RST
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags SYN,RST SYN,RST -j DROP

	# SYN/FIN
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP

	# Null scan
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-flags ALL NONE -j DROP


	# Log packets with bad flags

	if enabled FIREWALL_LOG_BAD_TCP_FLAGS; then
		log INFO "Logging of packets with bad TCP flags enabled"

		# Option 64
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-option 64 \
			"${log_limit}" -j "$(iptables_LOG "Bad TCP flag(64)")"

		# Option 128
		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-option 128 \
			"${log_limit}" -j "$(iptables_LOG "Bad TCP flag(128)")"
	else
		log INFO "Logging of packets with bad TCP flags disabled"
	fi

	# Drop packets with bad flags

	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-option 64 -j DROP
	iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp --tcp-option 128 -j DROP


	# Log invalid packets

	if enabled FIREWALL_LOG_INVALID_TCP; then
		log INFO "Logging of INVALID TCP packets enabled"

		iptables "${protocol}" -A FILTER_INVALID_TCP -p tcp -m conntrack --ctstate INVALID \
			"${log_limit}" -j "$(iptables_LOG "INVALID TCP")"
	else
		log INFO "Logging of INVALID TCP packets disabled"
	fi

	if enabled FIREWALL_LOG_INVALID_UDP; then
		log INFO "Logging of INVALID UDP packets enabled"

		iptables "${protocol}" -A FILTER_INVALID_UDP -p udp -m conntrack --ctstate INVALID \
			"${log_limit}" -j "$(iptables_LOG "INVALID UDP")"
	else
		log INFO "Logging of INVALID UDP packets disabled"
	fi

	if enabled FIREWALL_LOG_INVALID_ICMP; then
		log INFO "Logging of INVALID ICMP packets enabled"

		iptables "${protocol}" -A FILTER_INVALID_ICMP -p icmp -m conntrack --ctstate INVALID \
			"${log_limit}" -j "$(iptables_LOG "INVALID ICMP")"
	else
		log INFO "Logging of INVALID ICMP packets disabled"
	fi

	# Drop all INVALID packets
	iptables "${protocol}" -A FILTER_INVALID -m conntrack --ctstate INVALID -j DROP
}

function firewall_tcp_clamp_mss() {
	# Do nothing if this has been disabled.
	enabled FIREWALL_CLAMP_PATH_MTU || return ${EXIT_OK}

	local protocol="${1}"
	assert isset protocol

	log DEBUG "Adding rules to clamp MSS to path MTU..."

	iptables "${protocol}" -t mangle -A FORWARD \
		-p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
}

function firewall_connection_tracking() {
	local protocol="${1}"
	assert isset protocol

	log INFO "Creating Connection Tracking chain..."

	iptables_chain_create "${protocol}" CONNTRACK
	iptables "${protocol}" -A CONNTRACK -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
	iptables "${protocol}" -A CONNTRACK -m conntrack --ctstate INVALID -j "$(iptables_LOG "INVALID packet: ")"
	iptables "${protocol}" -A CONNTRACK -m conntrack --ctstate INVALID -j DROP

	iptables "${protocol}" -A INPUT   -j CONNTRACK
	iptables "${protocol}" -A OUTPUT  -j CONNTRACK
	iptables "${protocol}" -A FORWARD -j CONNTRACK
}

function firewall_localhost_create_chains() {
	local protocol="${1}"
	assert isset protocol

	log DEBUG "Creating firewall chains for localhost..."

	# Accept everything on lo
	iptables "${protocol}" -A INPUT  -i lo -j ACCEPT
	iptables "${protocol}" -A OUTPUT -o lo -j ACCEPT
}

function firewall_filter_rh0_headers() {
	local protocol="${1}"
	assert isset protocol

	# Only IPv6.
	[ "${protocol}" = "ipv6" ] || return ${EXIT_OK}

	# Filter all packets that have RH0 headers
	# http://www.ietf.org/rfc/rfc5095.txt
	iptables_chain_create "${protocol}" FILTER_RH0
	iptables "${protocol}" -A FILTER_RH0 -m rt --rt-type 0 -j DROP

	iptables "${protocol}" -A INPUT   -j FILTER_RH0
	iptables "${protocol}" -A FORWARD -j FILTER_RH0
	iptables "${protocol}" -A OUTPUT  -j FILTER_RH0
}

function firewall_filter_icmp() {
	local protocol="${1}"
	assert isset protocol

	# Only IPv6.
	[ "${protocol}" = "ipv6" ] || return ${EXIT_OK}

	local chain="FILTER_ICMPV6"

	# Create an extra chain for handling ICMP packets.
	iptables_chain_create "${protocol}" "${chain}_COMMON"

	local suffix
	for suffix in INC FWD OUT; do
		iptables_chain_create "${protocol}" "${chain}_${suffix}"
		iptables "${protocol}" -A "${chain}_${suffix}" -j "${chain}_COMMON"
	done
	iptables "${protocol}" -A INPUT   -p icmpv6 -j "${chain}_INC"
	iptables "${protocol}" -A FORWARD -p icmpv6 -j "${chain}_FWD"
	iptables "${protocol}" -A OUTPUT  -p icmpv6 -j "${chain}_OUT"

	# Packets that must always pass the firewall.
	# Type 4: Parameter Problem
	local type
	for type in ttl-zero-during-reassembly bad-header; do
		iptables "${protocol}" -A "${chain}_COMMON" \
			-p icmpv6 --icmpv6-type "${type}" -j ACCEPT
	done

	# Packets that are accepted if they belong to an existing connection.
	for type in echo-reply destination-unreachable packet-too-big \
			unknown-header-type unknown-option; do
		iptables "${protocol}" -A "${chain}_COMMON" \
			-m conntrack --ctstate ESTABLISHED,RELATED \
			-p icmpv6 --icmpv6-type "${type}" -j ACCEPT
	done

	# Packets that are always discarded.
	# Type 100, 101, 200, 201: Private Experimentation
	for type in 100 101 200 201; do
		iptables "${protocol}" -A "${chain}_COMMON" \
			-p icmpv6 --icmpv6-type "${type}" -j DROP
	done

	# Discard packets from local networks with hop limit smaller than $hoplimit.
	# Type 148: Path solicitation
	# Type 149: Path advertisement
	local hoplimit=255
	for type in {router,neighbour}-{advertisement,solicitation} 148 149; do
		iptables "${protocol}" -A "${chain}_INC" \
			-p icmpv6 --icmpv6-type "${type}" \
			-m hl --hl-lt "${hoplimit}" -j DROP
	done

	# The firewall is always allowed to send ICMP echo requests.
	iptables "${protocol}" -A "${chain}_OUT" \
		-p icmpv6 --icmpv6-type echo-request -j ACCEPT

	return ${EXIT_OK}
}

function firewall_zone_create_chains() {
	local protocol="${1}"
	assert isset protocol

	local zone="${2}"
	assert isset zone

	log DEBUG "Creating firewall chains for zone '${zone}'."

	local chain_prefix="ZONE_${zone^^}"

	# Create filter chains.
	iptables_chain_create "${protocol}" "${chain_prefix}_INPUT"
	iptables "${protocol}" -A INPUT   -i ${zone} -j "${chain_prefix}_INPUT"

	iptables_chain_create "${protocol}" "${chain_prefix}_OUTPUT"
	iptables "${protocol}" -A OUTPUT  -o ${zone} -j "${chain_prefix}_OUTPUT"

	# Custom rules.
	iptables_chain_create "${protocol}" "${chain_prefix}_CUSTOM"

	# Intrusion Prevention System.
	iptables_chain_create "${protocol}" "${chain_prefix}_IPS"

	# Create a chain for each other zone.
	# This leaves us with n^2 chains. Duh.

	local other_zone other_chain_prefix
	for other_zone in $(zones_get_all); do
		other_chain_prefix="${chain_prefix}_${other_zone^^}"
		iptables_chain_create "${protocol}" "${other_chain_prefix}"

		# Connect the chain with the FORWARD chain.
		iptables "${protocol}" -A FORWARD -i "${zone}" -o "${other_zone}" \
			-j "${other_chain_prefix}"

		# Handle custom rules.
		iptables "${protocol}" -A "${other_chain_prefix}" -j "${chain_prefix}_CUSTOM"

		# Link IPS.
		iptables "${protocol}" -A "${other_chain_prefix}" -j "${chain_prefix}_IPS"

		# Rules.
		iptables_chain_create "${protocol}" "${other_chain_prefix}_RULES"
		iptables "${protocol}" -A "${other_chain_prefix}" -j "${other_chain_prefix}_RULES"

		# Policy.
		iptables_chain_create "${protocol}" "${other_chain_prefix}_POLICY"
		iptables "${protocol}" -A "${other_chain_prefix}" -j "${other_chain_prefix}_POLICY"
	done

	## Create mangle chain.
	#iptables_chain_create "${protocol}" -t mangle "${chain_prefix}"
	#iptables "${protocol}" -t mangle -A PREROUTING  -i "${zone}" -j "${chain_prefix}"
	#iptables "${protocol}" -t mangle -A POSTROUTING -o "${zone}" -j "${chain_prefix}"

	## Quality of Service
	#iptables_chain_create "${protocol}" -t mangle "${chain_prefix}_QOS_INC"
	#iptables "${protocol}" -t mangle -A "${chain_prefix}" -i "${zone}" -j "${chain_prefix}_QOS_INC"
	#iptables_chain_create "${protocol}" -t mangle "${chain_prefix}_QOS_OUT"
	#iptables "${protocol}" -t mangle -A "${chain_prefix}" -o "${zone}" -j "${chain_prefix}_QOS_OUT"

	# Create NAT chain.
	iptables_chain_create "${protocol}" -t nat "${chain_prefix}"
	iptables "${protocol}" -t nat -A PREROUTING  -i "${zone}" -j "${chain_prefix}"
	iptables "${protocol}" -t nat -A POSTROUTING -o "${zone}" -j "${chain_prefix}"

	# Network Address Translation
	iptables_chain_create "${protocol}" -t nat "${chain_prefix}_DNAT"
	iptables "${protocol}" -t nat -A PREROUTING  -i "${zone}" -j "${chain_prefix}_DNAT"
	iptables_chain_create "${protocol}" -t nat "${chain_prefix}_SNAT"
	iptables "${protocol}" -t nat -A POSTROUTING -o "${zone}" -j "${chain_prefix}_SNAT"

	# UPnP
	iptables_chain_create "${protocol}" -t nat "${chain_prefix}_UPNP"
	iptables "${protocol}" -t nat -A "${chain_prefix}" -j "${chain_prefix}_UPNP"

	return ${EXIT_OK}
}

function firewall_parse_rules() {
	local file=${1}
	assert isset file
	shift

	# End if no rule file exists.
	[ -r "${file}" ] || return ${EXIT_OK}

	local cmd

	local ${FIREWALL_RULES_CONFIG_PARAMS}
	local line
	while read -r line; do
		# Skip empty lines.
		[ -n "${line}" ] || continue

		# Skip commented lines.
		[ "${line:0:1}" = "#" ] && continue

		# Parse the rule.
		_firewall_parse_rule_line ${line}
		if [ $? -ne ${EXIT_OK} ]; then
			log WARNING "Skipping invalid line: ${line}"
			continue
		fi

		cmd="iptables $@"

		# Source IP address/net.
		if isset src; then
			list_append cmd "-s ${src}"
		fi

		# Destination IP address/net.
		if isset dst; then
			list_append cmd "-d ${dst}"
		fi

		# Protocol.
		if isset proto; then
			list_append cmd "-p ${proto}"

			if list_match ${proto} ${FIREWALL_PROTOCOLS_SUPPORTING_PORTS}; then
				if isset sport; then
					list_append cmd "--sport ${sport}"
				fi

				if isset dport; then
					list_append cmd "--dport ${dport}"
				fi
			fi
		fi

		# Always append the action.
		list_append cmd "-j ${action}"

		# Execute command.
		${cmd}
	done < ${file}
}

function _firewall_parse_rule_line() {
	local arg

	# Clear all values.
	for arg in ${FIREWALL_RULES_CONFIG_PARAMS}; do
		assign "${arg}" ""
	done

	local key val
	while read -r arg; do
		key=$(cli_get_key ${arg})

		if ! listmatch "${key}" ${FIREWALL_RULES_CONFIG_PARAMS}; then
			log WARNING "Unrecognized argument: ${arg}"
			return ${EXIT_ERROR}
		fi

		val=$(cli_get_val ${arg})
		assign "${key}" "${val}"
	done <<< "$(args $@)"

	# action must always be set.
	if ! isset action; then
		log WARNING "'action' is not set: $@"
		return ${EXIT_ERROR}
	fi

	for arg in src dst; do
		isset ${arg} || continue

		# Check for valid IP addresses.
		if ! ip_is_valid ${!arg}; then
			log WARNING "Invalid IP address for '${arg}=${!arg}': $@"
			return ${EXIT_ERROR}
		fi
	done

	if isset proto; then
		# Make lowercase.
		proto=${proto,,}

		if ! list_match "${proto}" ${FIREWALL_SUPPORTED_PROTOCOLS}; then
			log WARNING "Unsupported protocol type 'proto=${proto}': $@"
			return ${EXIT_ERROR}
		fi
	fi

	for arg in sport dport; do
		isset ${arg} || continue

		# Check if port is valid.
		if ! isinteger ${arg}; then
			log WARNING "Invalid port '${arg}=${!arg}': $@"
			return ${EXIT_ERROR}
		fi
	done

	return ${EXIT_OK}
}