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