Overhaul address classification.
[firewall] / functions.m4
1 ### -*-sh-*-
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
24 m4_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.
31 run () {
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.
40 trace () {
41 set -e
42 if [ "$FW_DEBUG" ]; then echo "$*"; fi
43 }
44
45 ## defport NAME NUMBER
46 ##
47 ## Define $port_NAME to be NUMBER.
48 defport () {
49 name=$1 number=$2
50 eval port_$name=$number
51 }
52
53 ## defproto NAME NUMBER
54 ##
55 ## Define $proto_NAME to be NUMBER.
56 defproto () {
57 name=$1 number=$2
58 eval proto_$name=$number
59 }
60
61 ## addword VAR WORD
62 ##
63 ## Adds WORD to the value of the shell variable VAR, if it's not there
64 ## already. Words are separated by a single space; no leading or trailing
65 ## spaces are introduced.
66 addword () {
67 var=$1 word=$2
68 eval val=\$$var
69 case " $val " in
70 *" $word "*) ;;
71 *) eval "$var=\${$var:+\$val }\$word" ;;
72 esac
73 }
74
75 m4_divert(38)m4_dnl
76 ###--------------------------------------------------------------------------
77 ### Utility chains (used by function definitions).
78
79 m4_divert(20)m4_dnl
80 ###--------------------------------------------------------------------------
81 ### Basic chain constructions.
82
83 ## ip46tables ARGS ...
84 ##
85 ## Do the same thing for `iptables' and `ip6tables'.
86 ip46tables () {
87 set -e
88 iptables "$@"
89 ip6tables "$@"
90 }
91
92 ## clearchain CHAIN CHAIN ...
93 ##
94 ## Ensure that the named chains exist and are empty.
95 clearchain () {
96 set -e
97 for chain; do
98 case $chain in
99 *:*) table=${chain%:*} chain=${chain#*:} ;;
100 *) table=filter ;;
101 esac
102 run ip46tables -t $table -N $chain 2>/dev/null || :
103 done
104 }
105
106 ## makeset SET TYPE [PARAMS]
107 ##
108 ## Ensure that the named ipset exists. Don't clear it.
109 makeset () {
110 set -e
111 name=$1; shift
112 if ipset -nL | grep -q "^Name: $name$"; then
113 :
114 else
115 ipset -N "$name" "$@"
116 fi
117 }
118
119 ## errorchain CHAIN ACTION ARGS ...
120 ##
121 ## Make a chain which logs a message and then invokes some other action,
122 ## typically REJECT. Log messages are prefixed by `fw: CHAIN'.
123 errorchain () {
124 set -e
125 chain=$1; shift
126 case $chain in
127 *:*) table=${chain%:*} chain=${chain#*:} ;;
128 *) table=filter ;;
129 esac
130 clearchain $table:$chain
131 run ip46tables -t $table -A $chain -j LOG \
132 -m limit --limit 3/minute --limit-burst 10 \
133 --log-prefix "fw: $chain " --log-level notice
134 run ip46tables -t $table -A $chain -j "$@" \
135 -m limit --limit 20/second --limit-burst 100
136 run ip46tables -t $table -A $chain -j DROP
137 }
138
139 m4_divert(20)m4_dnl
140 ###--------------------------------------------------------------------------
141 ### Basic option setting.
142
143 ## setopt OPTION VALUE
144 ##
145 ## Set an IP sysctl.
146 setopt () {
147 set -e
148 opt=$1 val=$2
149 any=nil
150 for ver in ipv4 ipv6; do
151 if [ -f /proc/sys/net/$ver/$opt ]; then
152 run sysctl -q net/$ver/$opt="$val"
153 any=t
154 fi
155 done
156 case $any in
157 nil) echo >&2 "$0: unknown IP option $opt"; exit 1 ;;
158 esac
159 }
160
161 ## setdevopt OPTION VALUE [INTERFACES ...]
162 ##
163 ## Set an IP interface-level sysctl.
164 setdevopt () {
165 set -e
166 opt=$1 val=$2; shift 2
167 case "$#,$1" in
168 0, | 1,all)
169 set -- $(
170 seen=:
171 for ver in ipv4 ipv6; do
172 cd /proc/sys/net/$ver/conf
173 for i in *; do
174 [ -f $i/$opt ] || continue
175 case "$seen" in (*:$i:*) continue ;; esac
176 echo $i
177 done
178 done)
179 ;;
180 esac
181 for i in "$@"; do
182 any=nil
183 for ver in ipv4 ipv6; do
184 if [ -f /proc/sys/net/$ver/conf/$i/$opt ]; then
185 any=t
186 run sysctl -q net/ipv4/conf/$i/$opt="$val"
187 fi
188 done
189 case $any in
190 nil) echo >&2 "$0: unknown device option $opt"; exit 1 ;;
191 esac
192 done
193 }
194
195 m4_divert(20)m4_dnl
196 ###--------------------------------------------------------------------------
197 ### Packet filter construction.
198
199 ## conntrack CHAIN
200 ##
201 ## Add connection tracking to CHAIN, and allow obvious stuff.
202 conntrack () {
203 set -e
204 chain=$1
205 run ip46tables -A $chain -p tcp -m state \
206 --state ESTABLISHED,RELATED -j ACCEPT
207 run ip46tables -A $chain -p tcp ! --syn -g bad-tcp
208 }
209
210 ## commonrules CHAIN
211 ##
212 ## Add standard IP filtering rules to the CHAIN.
213 commonrules () {
214 set -e
215 chain=$1
216
217 ## Pass fragments through, assuming that the eventual destination will sort
218 ## things out properly. Except for TCP, that is, which should never be
219 ## fragmented. This is an extra pain for ip6tables, which doesn't provide
220 ## a pleasant way to detect non-initial fragments.
221 run iptables -A $chain -p tcp -f -g tcp-fragment
222 run iptables -A $chain -f -j ACCEPT
223 run ip6tables -A $chain -p tcp -g tcp-fragment \
224 -m ipv6header --soft --header frag
225 run ip6tables -A $chain -j accept-non-init-frag
226 }
227
228 m4_divert(38)m4_dnl
229 ## Accept a non-initial fragment. This is only needed by IPv6, to work
230 ## around a deficiency in the option parser.
231 run ip6tables -N accept-non-init-frag
232 run ip6tables -A accept-non-init-frag -j RETURN \
233 -m frag --fragfirst
234 run ip6tables -A accept-non-init-frag -j ACCEPT
235
236 m4_divert(20)m4_dnl
237 ## allowservices CHAIN PROTO SERVICE ...
238 ##
239 ## Add rules to allow the SERVICES on the CHAIN.
240 allowservices () {
241 set -e
242 chain=$1 proto=$2; shift 2
243 count=0
244 list=
245 for svc; do
246 case $svc in
247 *:*)
248 n=2
249 left=${svc%:*} right=${svc#*:}
250 case $left in *[!0-9]*) eval left=\$port_$left ;; esac
251 case $right in *[!0-9]*) eval right=\$port_$right ;; esac
252 svc=$left:$right
253 ;;
254 *)
255 n=1
256 case $svc in *[!0-9]*) eval svc=\$port_$svc ;; esac
257 ;;
258 esac
259 case $svc in
260 *: | :* | "" | *[!0-9:]*)
261 echo >&2 "Bad service name"
262 exit 1
263 ;;
264 esac
265 count=$(( $count + $n ))
266 if [ $count -gt 15 ]; then
267 run ip46tables -A $chain -p $proto -m multiport -j ACCEPT \
268 --destination-ports ${list#,}
269 list= count=$n
270 fi
271 list=$list,$svc
272 done
273 case $list in
274 "")
275 ;;
276 ,*,*)
277 run ip46tables -A $chain -p $proto -m multiport -j ACCEPT \
278 --destination-ports ${list#,}
279 ;;
280 *)
281 run ip46tables -A $chain -p $proto -j ACCEPT \
282 --destination-port ${list#,}
283 ;;
284 esac
285 }
286
287 ## ntpclient CHAIN NTPSERVER ...
288 ##
289 ## Add rules to CHAIN to allow NTP with NTPSERVERs.
290 ntpclient () {
291 set -e
292 chain=$1; shift
293 for ntp; do
294 run iptables -A $chain -s $ntp -j ACCEPT \
295 -p udp --source-port 123 --destination-port 123
296 done
297 }
298
299 ## dnsresolver CHAIN
300 ##
301 ## Add rules to allow CHAIN to be a DNS resolver.
302 dnsresolver () {
303 set -e
304 chain=$1
305 for p in tcp udp; do
306 run ip46tables -A $chain -j ACCEPT \
307 -m state --state ESTABLISHED \
308 -p $p --source-port 53
309 done
310 }
311
312 ## openports CHAIN [MIN MAX]
313 ##
314 ## Add rules to CHAIN to allow the open ports.
315 openports () {
316 set -e
317 chain=$1; shift
318 [ $# -eq 0 ] && set -- $open_port_min $open_port_max
319 run ip46tables -A $chain -p tcp -g interesting --destination-port $1:$2
320 run ip46tables -A $chain -p udp -g interesting --destination-port $1:$2
321 }
322
323 m4_divert(20)m4_dnl
324 ###--------------------------------------------------------------------------
325 ### Packet classification.
326 ###
327 ### See `classify.m4' for an explanation of how the firewall machinery for
328 ### packet classification works.
329 ###
330 ### A list of all network names is kept in `allnets'. For each network NET,
331 ### shell variables are defined describing their properties.
332 ###
333 ### net_class_NET The class of the network, as defined by
334 ### `defnetclass'.
335 ### net_inet_NET List of IPv4 address ranges in the network.
336 ### net_inet6_NET List of IPv6 address ranges in the network.
337 ### net_fwd_NET List of other networks that this one forwards to.
338 ### net_hosts_NET List of hosts known to be in the network.
339 ### host_inet_HOST IPv4 address of the named HOST.
340 ### host_inet6_HOST IPv6 address of the named HOST.
341 ###
342 ### Similarly, a list of hosts is kept in `allhosts', and for each host HOST,
343 ### a shell variables are defined:
344 ###
345 ### host_ifaces_HOST List of interfaces for this host and the networks
346 ### they attach to, in the form IFACE=NET.
347
348 ## defbitfield NAME WIDTH
349 ##
350 ## Defines MASK_NAME and BIT_NAME symbolic constants for dealing with
351 ## bitfields: x << BIT_NAME yields the value x in the correct position, and
352 ## ff & MASK_NAME extracts the corresponding value.
353 defbitfield () {
354 set -e
355 name=$1 width=$2
356 eval MASK_$name=$(( (1 << $width) - 1 << $bitindex ))
357 eval BIT_$name=$bitindex
358 bitindex=$(( $bitindex + $width ))
359 }
360
361 ## Define the layout of the bitfield.
362 bitindex=0
363 defbitfield MASK 16
364 defbitfield FROM 4
365 defbitfield TO 4
366
367 ## defnetclass NAME FORWARD-TO...
368 ##
369 ## Defines a netclass called NAME, which is allowed to forward to the
370 ## FORWARD-TO netclasses.
371 ##
372 ## For each netclass, constants from_NAME and to_NAME are defined as the
373 ## appropriate values in the FROM and TO fields (i.e., not including any mask
374 ## bits).
375 ##
376 ## This function also establishes mangle chains mark-from-NAME and
377 ## mark-to-NAME for applying the appropriate mark bits to the packet.
378 ##
379 ## Because it needs to resolve forward references, netclasses must be defined
380 ## in a two-pass manner, using a loop of the form
381 ##
382 ## for pass in 1 2; do netclassindex=0; ...; done
383 netclassess=
384 defnetclass () {
385 set -e
386 name=$1; shift
387 case $pass in
388 1)
389
390 ## Pass 1. Establish the from_NAME and to_NAME constants, and the
391 ## netclass's mask bit.
392 eval from_$name=$(( $netclassindex << $BIT_FROM ))
393 eval to_$name=$(( $netclassindex << $BIT_TO ))
394 eval _mask_$name=$(( 1 << ($netclassindex + $BIT_MASK) ))
395 nets="$nets $name"
396 ;;
397 2)
398
399 ## Pass 2. Compute the actual from and to values. We're a little bit
400 ## clever during source classification, and set the TO field to
401 ## all-bits-one, so that destination classification needs only a single
402 ## AND operation.
403 from=$(( ($netclassindex << $BIT_FROM) + (0xf << $BIT_TO) ))
404 for net; do
405 eval bit=\$_mask_$net
406 from=$(( $from + $bit ))
407 done
408 to=$(( ($netclassindex << $BIT_TO) + \
409 (0xf << $BIT_FROM) + \
410 (1 << ($netclassindex + $BIT_MASK)) ))
411 trace "from $name --> set $(printf %x $from)"
412 trace " to $name --> and $(printf %x $from)"
413
414 ## Now establish the mark-from-NAME and mark-to-NAME chains.
415 clearchain mangle:mark-from-$name mangle:mark-to-$name
416 run ip46tables -t mangle -A mark-from-$name -j MARK --set-mark $from
417 run ip46tables -t mangle -A mark-to-$name -j MARK --and-mark $to
418 ;;
419 esac
420 netclassindex=$(( $netclassindex + 1 ))
421 }
422
423 ## defnet NET CLASS
424 ##
425 ## Define a network. Follow by calls to `addr', `forwards', etc. to define
426 ## properties of the network. Networks are processed in order, so if their
427 ## addresses overlap then the more specific addresses should be defined
428 ## earlier.
429 defnet () {
430 net=$1 class=$2
431 addword allnets $net
432 eval net_class_$1=\$class
433 }
434
435 ## addr ADDRESS/LEN ...
436 ##
437 ## Define addresses for the network being defined. ADDRESSes are in
438 ## colon-separated IPv6 or dotted-quad IPv4 form.
439 addr () {
440 for i in "$@"; do
441 case "$i" in
442 *:*) addword net_inet6_$net $i ;;
443 *) addword net_inet_$net $i ;;
444 esac
445 done
446 }
447
448 ## forwards NET ...
449 ##
450 ## Declare that packets from this network are forwarded to the other NETs.
451 forwards () {
452 eval "net_fwd_$net=\"$*\""
453 }
454
455 ## noxit NET ...
456 ##
457 ## Declare that packets from this network must not be forwarded to the other
458 ## NETs.
459 noxit () {
460 eval "net_noxit_$net=\"$*\""
461 }
462
463 ## host HOST ADDR ...
464 ##
465 ## Define the address of an individual host on the current network. The
466 ## ADDRs may be full IPv4 or IPv6 addresses, or offsets from the containing
467 ## network address, which is a simple number for IPv4, or a suffix beginning
468 ## with `::' for IPv6. If an IPv6 base address is provided for the network
469 ## but not for the host then the host's IPv4 address is used as a suffix.
470 host () {
471 name=$1; shift
472
473 ## Work out which addresses we've actually been given.
474 unset a6
475 for i in "$@"; do
476 case "$i" in ::*) a6=$i ;; *) a=$i ;; esac
477 done
478 case "${a+t}" in
479 t) ;;
480 *) echo >&2 "$0: no address for $name"; exit 1 ;;
481 esac
482 case "${a6+t}" in t) ;; *) a6=::$a ;; esac
483
484 ## Work out the IPv4 address.
485 eval nn=\$net_inet_$net
486 for n in $nn; do
487 addr=${n%/*}
488 base=${addr%.*}
489 offset=${addr##*.}
490 case $a in *.*) aa=$a ;; *) aa=$base.$(( $offset + $a )) ;; esac
491 eval host_inet_$name=$aa
492 done
493
494 ## Work out the IPv6 address.
495 eval nn=\$net_inet6_$net
496 for n in $nn; do
497 addr=${n%/*}
498 base=${addr%::*}
499 case $a in ::*) aa=$addr$a ;; *) aa=$a ;; esac
500 eval host_inet6_$name=$aa
501 done
502
503 ## Remember the host in the list.
504 addword net_hosts_$net $name
505 }
506
507 ## defhost NAME
508 ##
509 ## Define a new host. Follow by calls to `iface' to define the host's
510 ## interfaces.
511 defhost () {
512 host=$1
513 addword allhosts $host
514 eval host_type_$host=endsys
515 }
516
517 ## router
518 ##
519 ## Declare the host to be a router, so it should forward packets and so on.
520 router () {
521 eval host_type_$host=router
522 }
523
524 ## iface IFACE NET ...
525 ##
526 ## Define a host's interfaces. Specifically, declares that the host has an
527 ## interface IFACE attached to the listed NETs.
528 iface () {
529 name=$1; shift
530 for net in "$@"; do
531 addword host_ifaces_$host $name=$net
532 done
533 }
534
535 ## net_interfaces HOST NET
536 ##
537 ## Determine the interfaces on which packets may plausibly arrive from the
538 ## named NET. Returns `-' if no such interface exists.
539 ##
540 ## This algorithm is not very clever. It's just about barely good enough to
541 ## deduce transitivity through a simple routed network; with complicated
542 ## networks, it will undoubtedly give wrong answers. Check the results
543 ## carefully, and, if necessary, list the connectivity explicitly; use the
544 ## special interface `-' for networks you know shouldn't send packets to a
545 ## host.
546 net_interfaces () {
547 host=$1 startnet=$2
548
549 ## Determine the locally attached networks.
550 targets=:
551 eval ii=\$host_ifaces_$host
552 for i in $ii; do targets=$targets$i:; done
553
554 ## Determine the transitivity.
555 seen=:
556 nets=$startnet
557 while :; do
558
559 ## First pass. Determine whether any of the networks we're considering
560 ## are in the target set. If they are, then return the corresponding
561 ## interfaces.
562 found=""
563 for net in $nets; do
564 tg=$targets
565 while :; do
566 any=nil
567 case $tg in
568 *"=$net:"*)
569 n=${tg%=$net:*}; tg=${n%:*}:; n=${n##*:}
570 addword found $n
571 any=t
572 ;;
573 esac
574 case $any in nil) break ;; esac
575 done
576 done
577 case "$found" in ?*) echo $found; return ;; esac
578
579 ## No joy. Determine the set of networks which (a) these ones can
580 ## forward to, and (b) that we've not considered already. These are the
581 ## nets we'll consider next time around.
582 nextnets=""
583 any=nil
584 for net in $nets; do
585 eval fwd=\$net_fwd_$net
586 for n in $fwd; do
587 case $seen in *":$n:"*) continue ;; esac
588 seen=$seen$n:
589 eval noxit=\$net_noxit_$n
590 case " $noxit " in *" $startnet "*) continue ;; esac
591 case " $nextnets " in
592 *" $n "*) ;;
593 *) addword nextnets $n; any=t ;;
594 esac
595 done
596 done
597
598 ## If we've run out of networks then there's no reachability. Return a
599 ## failure.
600 case $any in nil) echo -; return ;; esac
601 nets=$nextnets
602 done
603 }
604
605 m4_divert(-1)
606 ###----- That's all, folks --------------------------------------------------