functions.m4: Make clearchain tolerant of existing chains.
[firewall] / functions.m4
CommitLineData
775bd287 1### -*-sh-*-
bfdc045d
MW
2###
3### Utility functions for firewall scripts
4###
5### (c) 2008 Mark Wooding
6###
7
8###----- Licensing notice ---------------------------------------------------
9###
10### This program is free software; you can redistribute it and/or modify
11### it under the terms of the GNU General Public License as published by
12### the Free Software Foundation; either version 2 of the License, or
13### (at your option) any later version.
14###
15### This program is distributed in the hope that it will be useful,
16### but WITHOUT ANY WARRANTY; without even the implied warranty of
17### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18### GNU General Public License for more details.
19###
20### You should have received a copy of the GNU General Public License
21### along with this program; if not, write to the Free Software Foundation,
22### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
24m4_divert(20)m4_dnl
25###--------------------------------------------------------------------------
26### Utility functions.
27
28## doit COMMAND ARGS...
29##
30## If debugging, print the COMMAND and ARGS. If serious, execute them.
31run () {
32 set -e
33 if [ "$FW_DEBUG" ]; then echo "* $*"; fi
34 if ! [ "$FW_NOACT" ]; then "$@"; fi
35}
36
37## trace MESSAGE...
38##
39## If debugging, print the MESSAGE.
40trace () {
41 set -e
42 if [ "$FW_DEBUG" ]; then echo "$*"; fi
43}
44
45## defport NAME NUMBER
46##
47## Define $port_NAME to be NUMBER.
48defport () {
49 name=$1 number=$2
50 eval port_$name=$number
51}
52
ce79e94a
MW
53## defproto NAME NUMBER
54##
55## Define $proto_NAME to be NUMBER.
56defproto () {
57 name=$1 number=$2
58 eval proto_$name=$number
59}
60
c70bfbbb
MW
61m4_divert(38)m4_dnl
62###--------------------------------------------------------------------------
63### Utility chains (used by function definitions).
64
bfdc045d
MW
65m4_divert(22)m4_dnl
66###--------------------------------------------------------------------------
67### Basic chain constructions.
68
0291d6d5
MW
69## ip46tables ARGS ...
70##
71## Do the same thing for `iptables' and `ip6tables'.
72ip46tables () {
73 set -e
74 iptables "$@"
75 ip6tables "$@"
76}
77
bfdc045d
MW
78## clearchain CHAIN CHAIN ...
79##
80## Ensure that the named chains exist and are empty.
81clearchain () {
82 set -e
83 for chain; do
84 case $chain in
85 *:*) table=${chain%:*} chain=${chain#*:} ;;
86 *) table=filter ;;
87 esac
e91f4bbf 88 run ip46tables -t $table -N $chain 2>/dev/null || :
bfdc045d
MW
89 done
90}
91
92## errorchain CHAIN ACTION ARGS ...
93##
94## Make a chain which logs a message and then invokes some other action,
95## typically REJECT. Log messages are prefixed by `fw: CHAIN'.
96errorchain () {
97 set -e
98 chain=$1; shift
99 case $chain in
100 *:*) table=${chain%:*} chain=${chain#*:} ;;
101 *) table=filter ;;
102 esac
103 clearchain $table:$chain
0291d6d5 104 run ip46tables -t $table -A $chain -j LOG \
bfdc045d 105 -m limit --limit 3/minute --limit-burst 10 \
fc10e52b 106 --log-prefix "fw: $chain " --log-level notice
a188f549
MW
107 run ip46tables -t $table -A $chain -j "$@" \
108 -m limit --limit 20/second --limit-burst 100
109 run ip46tables -t $table -A $chain -j DROP
bfdc045d
MW
110}
111
112m4_divert(24)m4_dnl
113###--------------------------------------------------------------------------
114### Basic option setting.
115
116## setopt OPTION VALUE
117##
118## Set an IP sysctl.
119setopt () {
120 set -e
0f6364ac
MW
121 opt=$1 val=$2
122 any=nil
123 for ver in ipv4 ipv6; do
124 if [ -f /proc/sys/net/$ver/$opt ]; then
125 run sysctl -q net/$ver/$opt="$val"
126 any=t
127 fi
128 done
129 case $any in
130 nil) echo >&2 "$0: unknown IP option $opt"; exit 1 ;;
131 esac
bfdc045d
MW
132}
133
0f6364ac 134## setdevopt OPTION VALUE [INTERFACES ...]
bfdc045d
MW
135##
136## Set an IP interface-level sysctl.
137setdevopt () {
138 set -e
0f6364ac
MW
139 opt=$1 val=$2; shift 2
140 case "$#,$1" in
141 0, | 1,all)
142 set -- $(
143 seen=:
144 for ver in ipv4 ipv6; do
145 cd /proc/sys/net/$ver/conf
146 for i in *; do
147 [ -f $i/$opt ] || continue
148 case "$seen" in (*:$i:*) continue ;; esac
149 echo $i
150 done
151 done)
152 ;;
153 esac
154 for i in "$@"; do
155 any=nil
156 for ver in ipv4 ipv6; do
157 if [ -f /proc/sys/net/$ver/conf/$i/$opt ]; then
158 any=t
159 run sysctl -q net/ipv4/conf/$i/$opt="$val"
160 fi
161 done
162 case $any in
163 nil) echo >&2 "$0: unknown device option $opt"; exit 1 ;;
164 esac
bfdc045d
MW
165 done
166}
167
168m4_divert(26)m4_dnl
169###--------------------------------------------------------------------------
170### Packet filter construction.
171
172## conntrack CHAIN
173##
174## Add connection tracking to CHAIN, and allow obvious stuff.
175conntrack () {
176 set -e
177 chain=$1
0291d6d5 178 run ip46tables -A $chain -p tcp -m state \
bfdc045d 179 --state ESTABLISHED,RELATED -j ACCEPT
0291d6d5 180 run ip46tables -A $chain -p tcp ! --syn -g bad-tcp
bfdc045d
MW
181}
182
ecdca131
MW
183## commonrules CHAIN
184##
185## Add standard IP filtering rules to the CHAIN.
186commonrules () {
187 set -e
188 chain=$1
189
190 ## Pass fragments through, assuming that the eventual destination will sort
191 ## things out properly. Except for TCP, that is, which should never be
c70bfbbb
MW
192 ## fragmented. This is an extra pain for ip6tables, which doesn't provide
193 ## a pleasant way to detect non-initial fragments.
ecdca131
MW
194 run iptables -A $chain -p tcp -f -g tcp-fragment
195 run iptables -A $chain -f -j ACCEPT
0291d6d5
MW
196 run ip6tables -A $chain -p tcp -g tcp-fragment \
197 -m ipv6header --soft --header frag
c70bfbbb 198 run ip6tables -A $chain -j accept-non-init-frag
ecdca131
MW
199}
200
c70bfbbb
MW
201m4_divert(38)m4_dnl
202## Accept a non-initial fragment. This is only needed by IPv6, to work
203## around a deficiency in the option parser.
204run ip6tables -N accept-non-init-frag
205run ip6tables -A accept-non-init-frag -j RETURN \
206 -m frag --fragfirst
207run ip6tables -A accept-non-init-frag -j ACCEPT
208
209m4_divert(26)m4_dnl
bfdc045d
MW
210## allowservices CHAIN PROTO SERVICE ...
211##
212## Add rules to allow the SERVICES on the CHAIN.
213allowservices () {
214 set -e
215 chain=$1 proto=$2; shift 2
216 count=0
217 list=
218 for svc; do
219 case $svc in
220 *:*)
12ac65a1 221 n=2
bfdc045d
MW
222 left=${svc%:*} right=${svc#*:}
223 case $left in *[!0-9]*) eval left=\$port_$left ;; esac
224 case $right in *[!0-9]*) eval right=\$port_$right ;; esac
225 svc=$left:$right
226 ;;
227 *)
12ac65a1 228 n=1
bfdc045d
MW
229 case $svc in *[!0-9]*) eval svc=\$port_$svc ;; esac
230 ;;
231 esac
232 case $svc in
233 *: | :* | "" | *[!0-9:]*)
12ac65a1 234 echo >&2 "Bad service name"
bfdc045d
MW
235 exit 1
236 ;;
237 esac
238 count=$(( $count + $n ))
239 if [ $count -gt 15 ]; then
0291d6d5 240 run ip46tables -A $chain -p $proto -m multiport -j ACCEPT \
bfdc045d
MW
241 --destination-ports ${list#,}
242 list= count=$n
243 fi
244 list=$list,$svc
245 done
246 case $list in
247 "")
248 ;;
249 ,*,*)
0291d6d5 250 run ip46tables -A $chain -p $proto -m multiport -j ACCEPT \
bfdc045d
MW
251 --destination-ports ${list#,}
252 ;;
12ac65a1 253 *)
0291d6d5 254 run ip46tables -A $chain -p $proto -j ACCEPT \
bfdc045d
MW
255 --destination-port ${list#,}
256 ;;
257 esac
258}
259
260## ntpclient CHAIN NTPSERVER ...
261##
262## Add rules to CHAIN to allow NTP with NTPSERVERs.
263ntpclient () {
264 set -e
265 chain=$1; shift
266 for ntp; do
267 run iptables -A $chain -s $ntp -j ACCEPT \
268 -p udp --source-port 123 --destination-port 123
269 done
270}
271
272## dnsresolver CHAIN
273##
274## Add rules to allow CHAIN to be a DNS resolver.
275dnsresolver () {
276 set -e
277 chain=$1
278 for p in tcp udp; do
0291d6d5 279 run ip46tables -A $chain -j ACCEPT \
bfdc045d
MW
280 -m state --state ESTABLISHED \
281 -p $p --source-port 53
282 done
283}
284
285## openports CHAIN [MIN MAX]
286##
287## Add rules to CHAIN to allow the open ports.
288openports () {
289 set -e
290 chain=$1; shift
291 [ $# -eq 0 ] && set -- $open_port_min $open_port_max
0291d6d5
MW
292 run ip46tables -A $chain -p tcp -g interesting --destination-port $1:$2
293 run ip46tables -A $chain -p udp -g interesting --destination-port $1:$2
bfdc045d
MW
294}
295
296m4_divert(28)m4_dnl
297###--------------------------------------------------------------------------
298### Packet classification.
299
300## defbitfield NAME WIDTH
301##
302## Defines MASK_NAME and BIT_NAME symbolic constants for dealing with
303## bitfields: x << BIT_NAME yields the value x in the correct position, and
304## ff & MASK_NAME extracts the corresponding value.
305defbitfield () {
306 set -e
307 name=$1 width=$2
308 eval MASK_$name=$(( (1 << $width) - 1 << $bitindex ))
309 eval BIT_$name=$bitindex
310 bitindex=$(( $bitindex + $width ))
311}
312
313## Define the layout of the bitfield.
314bitindex=0
315defbitfield MASK 16
316defbitfield FROM 4
317defbitfield TO 4
318
319## defnetclass NAME FORWARD-TO...
320##
321## Defines a netclass called NAME, which is allowed to forward to the
322## FORWARD-TO netclasses.
323##
324## For each netclass, constants from_NAME and to_NAME are defined as the
325## appropriate values in the FROM and TO fields (i.e., not including any mask
326## bits).
327##
328## This function also establishes mangle chains mark-from-NAME and
329## mark-to-NAME for applying the appropriate mark bits to the packet.
330##
331## Because it needs to resolve forward references, netclasses must be defined
332## in a two-pass manner, using a loop of the form
333##
334## for pass in 1 2; do netclassindex=0; ...; done
335netclassess=
336defnetclass () {
337 set -e
338 name=$1; shift
339 case $pass in
340 1)
341
342 ## Pass 1. Establish the from_NAME and to_NAME constants, and the
343 ## netclass's mask bit.
344 eval from_$name=$(( $netclassindex << $BIT_FROM ))
345 eval to_$name=$(( $netclassindex << $BIT_TO ))
346 eval _mask_$name=$(( 1 << ($netclassindex + $BIT_MASK) ))
347 nets="$nets $name"
348 ;;
349 2)
350
351 ## Pass 2. Compute the actual from and to values. We're a little bit
352 ## clever during source classification, and set the TO field to
353 ## all-bits-one, so that destination classification needs only a single
354 ## AND operation.
355 from=$(( ($netclassindex << $BIT_FROM) + (0xf << $BIT_TO) ))
356 for net; do
357 eval bit=\$_mask_$net
358 from=$(( $from + $bit ))
359 done
360 to=$(( ($netclassindex << $BIT_TO) + \
12ac65a1 361 (0xf << $BIT_FROM) + \
bfdc045d
MW
362 (1 << ($netclassindex + $BIT_MASK)) ))
363 trace "from $name --> set $(printf %x $from)"
364 trace " to $name --> and $(printf %x $from)"
365
366 ## Now establish the mark-from-NAME and mark-to-NAME chains.
367 clearchain mangle:mark-from-$name mangle:mark-to-$name
0291d6d5
MW
368 run ip46tables -t mangle -A mark-from-$name -j MARK --set-mark $from
369 run ip46tables -t mangle -A mark-to-$name -j MARK --and-mark $to
bfdc045d
MW
370 ;;
371 esac
372 netclassindex=$(( $netclassindex + 1 ))
373}
374
46be9bde 375## defiface NAME[,NAME,...] NETCLASS:NETWORK/MASK...
bfdc045d 376##
46be9bde
MW
377## Declares network interfaces with the given NAMEs and associates with them
378## a number of reachable networks. During source classification, a packet
379## arriving on interface NAME from an address in NETWORK/MASK is classified
380## as coming from to NETCLASS. During destination classification, all
381## packets going to NETWORK/MASK are classified as going to NETCLASS,
382## regardless of interface (which is good, because the outgoing interface
383## hasn't been determined yet).
bfdc045d
MW
384##
385## As a special case, the NETWORK/MASK can be the string `default', which
386## indicates that all addresses not matched elsewhere should be considered.
387ifaces=:
3a68f688 388defaultifaces=""
0291d6d5 389allnets= allnets6=
bfdc045d
MW
390defiface () {
391 set -e
46be9bde
MW
392 names=$1; shift
393 seen=:
394 for name in $(echo $names | sed 'y/,/ /'); do
395 case $seen in *:"$name":*) continue ;; esac
396 seen=$seen$name:
397 case $ifaces in
398 *:"$name":*) ;;
bfdc045d 399 *)
46be9bde
MW
400 clearchain mangle:in-$name
401 run ip46tables -t mangle -A in-classify -i $name -g in-$name
bfdc045d
MW
402 ;;
403 esac
46be9bde
MW
404 ifaces=$ifaces$name:
405 for item; do
406 netclass=${item%:*} addr=${item#*:}
407 case $addr in
408 default)
3a68f688
MW
409 case "$defaultifaces,$defaultclass" in
410 ,* | *,$netclass)
411 defaultifaces="$defaultifaces $name"
412 defaultclass=$netclass
413 ;;
414 *)
415 echo >&2 "$0: inconsistent default netclasses"
416 exit 1
417 ;;
418 esac
46be9bde
MW
419 ;;
420 *:*)
421 run ip6tables -t mangle -A in-$name -g mark-from-$netclass \
422 -s $addr
423 run ip6tables -t mangle -A out-classify -g mark-to-$netclass \
424 -d $addr
425 allnets6="$allnets6 $name:$addr"
426 ;;
427 *)
428 run iptables -t mangle -A in-$name -g mark-from-$netclass \
429 -s $addr
430 run iptables -t mangle -A out-classify -g mark-to-$netclass \
431 -d $addr
432 allnets="$allnets $name:$addr"
433 ;;
434 esac
435 done
bfdc045d
MW
436 done
437}
438
439## defvpn IFACE CLASS NET HOST:ADDR ...
440##
441## Defines a VPN interface. If the interface has the form `ROOT+' (i.e., a
442## netfilter wildcard) then define a separate interface ROOTHOST routing to
443## ADDR; otherwise just write a blanket rule allowing the whole NET. All
444## addresses concerned are put in the named CLASS.
445defvpn () {
446 set -e
447 iface=$1 class=$2 net=$3; shift 3
448 case $iface in
449 *-+)
450 root=${iface%+}
451 for host; do
0291d6d5 452 name=${host%%:*} addr=${host#*:}
bfdc045d
MW
453 defiface $root$name $class:$addr
454 done
455 ;;
456 *)
457 defiface $iface $class:$net
458 ;;
459 esac
460}
461
462m4_divert(-1)
463###----- That's all, folks --------------------------------------------------