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