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