3 ### Utility functions for firewall scripts
5 ### (c) 2008 Mark Wooding
8 ###----- Licensing notice ---------------------------------------------------
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.
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.
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.
25 ###--------------------------------------------------------------------------
26 ### Utility functions.
28 ## doit COMMAND ARGS...
30 ## If debugging, print the COMMAND and ARGS. If serious, execute them.
33 if [ "$FW_DEBUG" ]; then echo "* $*"; fi
34 if ! [ "$FW_NOACT" ]; then "$@"; fi
39 ## If debugging, print the MESSAGE.
42 if [ "$FW_DEBUG" ]; then echo "$*"; fi
45 ## defport NAME NUMBER
47 ## Define $port_NAME to be NUMBER.
50 eval port_$name=$number
53 ## defproto NAME NUMBER
55 ## Define $proto_NAME to be NUMBER.
58 eval proto_$name=$number
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.
71 *) eval "$var=\${$var:+\$val }\$word" ;;
76 ###--------------------------------------------------------------------------
77 ### Utility chains (used by function definitions).
80 ###--------------------------------------------------------------------------
81 ### Basic chain constructions.
83 ## ip46tables ARGS ...
85 ## Do the same thing for `iptables' and `ip6tables'.
92 ## clearchain CHAIN CHAIN ...
94 ## Ensure that the named chains exist and are empty.
99 *:*) table=${_chain%:*} _chain=${_chain#*:} ;;
102 run ip46tables -t $table -N $_chain 2>/dev/null || :
106 ## makeset SET TYPE [PARAMS]
108 ## Ensure that the named ipset exists. Don't clear it.
116 if ipset -nL | grep -q "^Name: $name\$"; then createp=nil; fi
119 if ipset -n -L | grep -q "^$name\$"; then createp=nil; fi
123 t) ipset -N "$name" "$@" ;;
127 ## errorchain CHAIN ACTION ARGS ...
129 ## Make a chain which logs a message and then invokes some other action,
130 ## typically REJECT. Log messages are prefixed by `fw: CHAIN'.
135 *:*) table=${chain%:*} chain=${chain#*:} ;;
138 clearchain $table:$chain
139 run ip46tables -t $table -A $chain -j LOG \
140 -m limit --limit 3/minute --limit-burst 10 \
141 --log-prefix "fw: $chain " --log-level notice || :
142 run ip46tables -t $table -A $chain -j "$@" \
143 -m limit --limit 20/second --limit-burst 100
144 run ip46tables -t $table -A $chain -j DROP
148 ###--------------------------------------------------------------------------
149 ### Basic option setting.
151 ## setopt OPTION VALUE
158 for ver in ipv4 ipv6; do
159 if [ -f /proc/sys/net/$ver/$opt ]; then
160 run sysctl -q net/$ver/$opt="$val"
165 nil) echo >&2 "$0: unknown IP option $opt"; exit 1 ;;
169 ## setdevopt OPTION VALUE [INTERFACES ...]
171 ## Set an IP interface-level sysctl.
174 opt=$1 val=$2; shift 2
179 for ver in ipv4 ipv6; do
180 cd /proc/sys/net/$ver/conf
182 [ -f $i/$opt ] || continue
183 case "$seen" in (*:$i:*) continue ;; esac
191 for ver in ipv4 ipv6; do
192 if [ -f /proc/sys/net/$ver/conf/$i/$opt ]; then
194 run sysctl -q net/$ver/conf/$i/$opt="$val"
198 nil) echo >&2 "$0: unknown device option $opt"; exit 1 ;;
204 ###--------------------------------------------------------------------------
205 ### Packet filter construction.
209 ## Add connection tracking to CHAIN, and allow obvious stuff.
213 run ip46tables -A $chain -p tcp -m state \
214 --state ESTABLISHED,RELATED -j ACCEPT
215 run ip46tables -A $chain -p tcp ! --syn -g bad-tcp
220 ## Add standard IP filtering rules to the CHAIN.
225 ## Pass fragments through, assuming that the eventual destination will sort
226 ## things out properly. Except for TCP, that is, which should never be
227 ## fragmented. This is an extra pain for ip6tables, which doesn't provide
228 ## a pleasant way to detect non-initial fragments.
229 run iptables -A $chain -p tcp -f -g tcp-fragment
230 run iptables -A $chain -f -j ACCEPT
231 run ip6tables -A $chain -p tcp -g tcp-fragment \
232 -m ipv6header --soft --header frag
233 run ip6tables -A $chain -j accept-non-init-frag
237 ## Accept a non-initial fragment. This is only needed by IPv6, to work
238 ## around a deficiency in the option parser.
239 run ip6tables -N accept-non-init-frag
240 run ip6tables -A accept-non-init-frag -j RETURN \
242 run ip6tables -A accept-non-init-frag -j ACCEPT \
243 -m ipv6header --header frag
246 ## allowservices CHAIN PROTO SERVICE ...
248 ## Add rules to allow the SERVICES on the CHAIN.
251 chain=$1 proto=$2; shift 2
258 left=${svc%:*} right=${svc#*:}
259 case $left in *[!0-9]*) eval left=\$port_$left ;; esac
260 case $right in *[!0-9]*) eval right=\$port_$right ;; esac
265 case $svc in *[!0-9]*) eval svc=\$port_$svc ;; esac
269 *: | :* | "" | *[!0-9:]*)
270 echo >&2 "Bad service name"
274 count=$(( $count + $n ))
275 if [ $count -gt 15 ]; then
276 run ip46tables -A $chain -p $proto -m multiport -j ACCEPT \
277 --destination-ports ${list#,}
286 run ip46tables -A $chain -p $proto -m multiport -j ACCEPT \
287 --destination-ports ${list#,}
290 run ip46tables -A $chain -p $proto -j ACCEPT \
291 --destination-port ${list#,}
296 ## ntpclient CHAIN NTPSERVER ...
298 ## Add rules to CHAIN to allow NTP with NTPSERVERs.
303 clearchain ntp-servers
304 for ntp; do run iptables -A ntp-servers -j ACCEPT -s $ntp; done
305 run iptables -A $ntpchain -j ntp-servers \
306 -p udp --source-port 123 --destination-port 123
311 ## Add rules to allow CHAIN to be a DNS resolver.
316 run ip46tables -A $chain -j ACCEPT \
317 -m state --state ESTABLISHED \
318 -p $p --source-port 53
324 ## Add rules to allow CHAIN to be a DNS server.
329 ## Allow TCP access. Hitting us with SYNs will make us deploy SYN cookies,
330 ## but that's tolerable.
331 run ip46tables -A $chain -j ACCEPT -p tcp --destination-port 53
333 ## Avoid being a DDoS amplifier by rate-limiting incoming DNS queries.
334 clearchain $chain-udp-dns
335 run ip46tables -A $chain-udp-dns -j ACCEPT \
336 -m limit --limit 20/second --limit-burst 300
337 run ip46tables -A $chain-udp-dns -g dns-rate-limit
338 run ip46tables -A $chain -j $chain-udp-dns \
339 -p udp --destination-port 53
342 ## openports CHAIN [MIN MAX]
344 ## Add rules to CHAIN to allow the open ports.
348 [ $# -eq 0 ] && set -- $open_port_min $open_port_max
349 run ip46tables -A $chain -p tcp -g interesting --destination-port $1:$2
350 run ip46tables -A $chain -p udp -g interesting --destination-port $1:$2
355 ipv=$1 ifname=$2; shift 2
356 ## Add rules for BCP38 egress filtering for IP version IPV (either 4 or 6).
357 ## IFNAME is the outgoing interface; the remaining arguments are network
360 ## Sort out which command we're using
364 *) echo >&2 "Unknown IP version $ipv"; exit 1 ;;
367 ## If we've not set up the error chain then do that.
370 errorchain bcp38 DROP
371 clearchain bcp38-check
372 ip46tables -A bcp38-check -g bcp38
376 ## Stitch our egress filter into the outbound chains if we haven't done
377 ## that yet. Do this for both IP versions: if we're only ever given
378 ## IPv6 addresses for a particular interface then we assume that IPv4
379 ## packets aren't allowed on it at all.
383 run ip46tables -A OUTPUT -j bcp38-check -o $ifname
385 1) run ip46tables -A FORWARD -j bcp38-check -o $ifname ;;
387 bcp38_setup=$bcp38_setup$ifname:
391 ## Finally, add in our allowed networks.
393 run $ipt -I bcp38-check -j RETURN -s $i
398 ###--------------------------------------------------------------------------
399 ### Packet classification.
401 ### See `classify.m4' for an explanation of how the firewall machinery for
402 ### packet classification works.
404 ### A list of all network names is kept in `allnets'. For each network NET,
405 ### shell variables are defined describing their properties.
407 ### net_class_NET The class of the network, as defined by
409 ### net_inet_NET List of IPv4 address ranges in the network.
410 ### net_inet6_NET List of IPv6 address ranges in the network.
411 ### net_via_NET List of other networks that this one forwards via.
412 ### net_hosts_NET List of hosts known to be in the network.
413 ### host_inet_HOST IPv4 address of the named HOST.
414 ### host_inet6_HOST IPv6 address of the named HOST.
416 ### Similarly, a list of hosts is kept in `allhosts', and for each host HOST,
417 ### a shell variables are defined:
419 ### host_ifaces_HOST List of interfaces for this host and the networks
420 ### they attach to, in the form IFACE=NET.
422 ## defbitfield NAME WIDTH
424 ## Defines MASK_NAME and BIT_NAME symbolic constants for dealing with
425 ## bitfields: x << BIT_NAME yields the value x in the correct position, and
426 ## ff & MASK_NAME extracts the corresponding value.
430 eval MASK_$name=$(( (1 << $width) - 1 << $bitindex ))
431 eval BIT_$name=$bitindex
432 bitindex=$(( $bitindex + $width ))
435 ## Define the layout of the bitfield.
441 ## defnetclass NAME FORWARD-TO...
443 ## Defines a netclass called NAME, which is allowed to forward to the
444 ## FORWARD-TO netclasses.
446 ## For each netclass, constants from_NAME and to_NAME are defined as the
447 ## appropriate values in the FROM and TO fields (i.e., not including any mask
450 ## This function also establishes mangle chains mark-from-NAME and
451 ## mark-to-NAME for applying the appropriate mark bits to the packet.
453 ## Because it needs to resolve forward references, netclasses must be defined
454 ## in a two-pass manner, using a loop of the form
456 ## for pass in 1 2; do netclassindex=0; ...; done
464 ## Pass 1. Establish the from_NAME and to_NAME constants, and the
465 ## netclass's mask bit.
466 trace "netclass $name = $netclassindex"
467 eval from_$name=$(( $netclassindex << $BIT_FROM ))
468 eval to_$name=$(( $netclassindex << $BIT_TO ))
469 eval fwd_$name=$(( 1 << ($netclassindex + $BIT_MASK) ))
474 ## Pass 2. Compute the actual from and to values. This is fiddly:
475 ## we want to preserve the other flags.
476 from=$(( ($netclassindex << $BIT_FROM) ))
477 frommask=$(( $MASK_FROM | $MASK_MASK ))
480 from=$(( $from + $bit ))
482 to=$(( ($netclassindex << $BIT_TO) ))
483 tomask=$(( $MASK_TO | $MASK_MASK ^ (1 << ($netclassindex + $BIT_MASK)) ))
484 trace "from $name --> set $(printf %08x/%08x $from $frommask)"
485 trace " to $name --> set $(printf %08x/%08x $to $tomask)"
487 ## Now establish the mark-from-NAME and mark-to-NAME chains.
488 clearchain mangle:mark-from-$name mangle:mark-to-$name
489 run ip46tables -t mangle -A mark-from-$name -j MARK \
490 --set-xmark $from/$frommask
491 run ip46tables -t mangle -A mark-to-$name -j MARK \
492 --set-xmark $to/$tomask
495 netclassindex=$(( $netclassindex + 1 ))
500 ## Define a network. Follow by calls to `addr', `via', etc. to define
501 ## properties of the network. Networks are processed in order, so if their
502 ## addresses overlap then the more specific addresses should be defined
507 eval net_class_$1=\$class
510 ## addr ADDRESS/LEN ...
512 ## Define addresses for the network being defined. ADDRESSes are in
513 ## colon-separated IPv6 or dotted-quad IPv4 form.
517 *:*) addword net_inet6_$net $i ;;
518 *) addword net_inet_$net $i ;;
525 ## Declare that packets from this network are forwarded to the other NETs.
527 eval "net_via_$net=\"$*\""
532 ## Declare that packets from this network must not be forwarded to the other
535 eval "net_noxit_$net=\"$*\""
538 ## host HOST ADDR ...
540 ## Define the address of an individual host on the current network. The
541 ## ADDRs may be full IPv4 or IPv6 addresses, or offsets from the containing
542 ## network address, which is a simple number for IPv4, or a suffix beginning
543 ## with `::' for IPv6. If an IPv6 base address is provided for the network
544 ## but not for the host then the host's IPv4 address is used as a suffix.
548 ## Work out which addresses we've actually been given.
551 case "$i" in ::*) a6=$i ;; *) a=$i ;; esac
555 *) echo >&2 "$0: no address for $name"; exit 1 ;;
557 case "${a6+t}" in t) ;; *) a6=::$a ;; esac
559 ## Work out the IPv4 address.
560 eval nn=\$net_inet_$net
565 case $a in *.*) aa=$a ;; *) aa=$base.$(( $offset + $a )) ;; esac
566 eval host_inet_$name=$aa
569 ## Work out the IPv6 address.
570 eval nn=\$net_inet6_$net
574 case $a6 in ::*) aa=$base$a6 ;; *) aa=$a6 ;; esac
575 eval host_inet6_$name=$aa
578 ## Remember the host in the list.
579 addword net_hosts_$net $name
584 ## Define a new host. Follow by calls to `iface' to define the host's
588 addword allhosts $host
589 eval host_type_$host=server
594 ## Declare the host to have the given type.
598 router | server | client) ;;
599 *) echo >&2 "$0: bad host type \`$type'"; exit 1 ;;
601 eval host_type_$host=$type
604 ## iface IFACE NET ...
606 ## Define a host's interfaces. Specifically, declares that the host has an
607 ## interface IFACE attached to the listed NETs.
611 addword host_ifaces_$host $name=$net
615 ## matchnets OPT WIN FLAGS PREPARE BASE SUFFIX NEXT NET [NET ...]
617 ## Build rules which match a particular collection of networks.
619 ## Specifically, use the address-comparison operator OPT (typically `-s' or
620 ## `-d') to match the addresses of each NET, writing the rules to the chain
621 ## BASESUFFIX. If we find a match, dispatch to WIN-CLASS, where CLASS is the
622 ## class of the matching network. In order to deal with networks containing
623 ## negative address ranges, more chains may need to be constructed; they will
624 ## be named BASE#Q for sequence numbers Q starting with NEXT. All of this
625 ## happens on the `mangle' table, and there isn't (currently) a way to tweak
628 ## The FLAGS gather additional interesting information about the job,
629 ## separated by colons. The only flag currently is :default: which means
630 ## that the default network was listed.
632 ## Finally, there is a hook PREPARE which is called just in advance of
633 ## processing the final network, passing it the argument FLAGS. (The PREPARE
634 ## string will be subjected to shell word-splitting, so it can provide some
635 ## arguments of its own if it wants.) It should set `mode' to indicate how
636 ## the chain should be finished.
638 ## goto If no networks matched, then issue a final `goto' to the
639 ## chain named by the variable `fail'.
641 ## call Run `$finish CHAIN' to write final rules to the named CHAIN
642 ## (which may be suffixed from the original BASE argument if
643 ## this was necessary). This function will arrange to call
644 ## these rules if no networks match.
646 ## ret If no network matches then return (maybe by falling off the
647 ## end of the chain).
649 local opt win flags prepare base suffix next net lose splitp
650 opt=$1 win=$2 flags=$3 prepare=$4 base=$5 suffix=$6 next=$7 net=$8
653 ## If this is the default network, then set the flag.
654 case "$net" in default) flags=${flags}default: ;; esac
656 ## Do an initial pass over the addresses to see whether there are any
657 ## negative ranges. If so, we'll need to split. See also the standard
660 eval "addrs=\"\$net_inet_$net \$net_inet6_$net\""
661 for a in $addrs; do case $a in !*) splitp=t; break ;; esac; done
663 trace "MATCHNETS [splitp $splitp] $opt $win $flags [$prepare] $base $suffix $next : $net $*"
665 ## Work out how to handle matches against negative address ranges. If this
666 ## is the last network, invoke the PREPARE hook to find out. Otherwise, if
667 ## we have to split the chain, recursively build the target here.
671 case $splitp,$mode in
679 clearchain mangle:$base#$next
680 lose="-g $base#$next"
687 clearchain mangle:$base#$next
688 matchnets $opt $win $flags "$prepare" \
689 $base \#$next $(( $next + 1 )) "$@"
690 lose="-g $base#$next" mode=goto
697 ## Populate the chain with rules to match the necessary networks.
698 eval addr=\$net_inet_$net addr6=\$net_inet6_$net class=\$net_class_$net
701 !*) run iptables -t mangle -A $base$suffix $lose $opt ${a#!} ;;
702 *) run iptables -t mangle -A $base$suffix -g $win-$class $opt $a ;;
707 !*) run ip6tables -t mangle -A $base$suffix $lose $opt ${a#!} ;;
708 *) run ip6tables -t mangle -A $base$suffix -g $win-$class $opt $a ;;
712 ## Wrap up the chain appropriately. If we didn't split and there are more
713 ## networks to handle then append the necessary rules now. (If we did
714 ## split, then we already wrote the rules for them above.) If there are no
715 ## more networks then consult the `mode' setting to find out what to do.
716 case $splitp,$#,$mode in
718 *,*,goto) run ip46tables -t mangle -A $base$suffix $lose ;;
719 t,0,call) $finish $base#$next ;;
720 nil,0,call) $finish $base$suffix ;;
722 matchnets $opt $win $flags "$prepare" $base "$suffix" $next "$@"
727 ## net_interfaces HOST NET
729 ## Determine the interfaces on which packets may plausibly arrive from the
730 ## named NET. Returns `-' if no such interface exists.
732 ## This algorithm is not very clever. It's just about barely good enough to
733 ## deduce transitivity through a simple routed network; with complicated
734 ## networks, it will undoubtedly give wrong answers. Check the results
735 ## carefully, and, if necessary, list the connectivity explicitly; use the
736 ## special interface `-' for networks you know shouldn't send packets to a
741 ## Determine the locally attached networks.
743 eval ii=\$host_ifaces_$host
744 for i in $ii; do targets=$targets$i:; done
746 ## Determine the transitivity.
751 ## First pass. Determine whether any of the networks we're considering
752 ## are in the target set. If they are, then return the corresponding
761 n=${tg%=$net:*}; tg=${n%:*}:; n=${n##*:}
766 case $any in nil) break ;; esac
769 case "$found" in ?*) echo $found; return ;; esac
771 ## No joy. Determine the set of networks which (a) these ones can
772 ## forward to, and (b) that we've not considered already. These are the
773 ## nets we'll consider next time around.
777 eval via=\$net_via_$net
779 case $seen in *":$n:"*) continue ;; esac
781 eval noxit=\$net_noxit_$n
782 case " $noxit " in *" $startnet "*) continue ;; esac
783 case " $nextnets " in
785 *) addword nextnets $n; any=t ;;
790 ## If we've run out of networks then there's no reachability. Return a
792 case $any in nil) echo -; return ;; esac
798 ###----- That's all, folks --------------------------------------------------