create xenophobe chain in main firewall script
[firewall-squeep] / common.sh
1 #!/bin/sh
2
3 set -e
4
5 IPTABLES=$(which iptables)
6 IP6TABLES=$(which ip6tables)
7 IPSET=$(which ipset)
8
9 function decommentcat(){
10 sed 's/\s*#.*$//;/^\s*$/d' "$@"
11 }
12
13 function create_set(){
14 local set_name="$1"
15 shift
16 if ! $IPSET list "${set_name}" >/dev/null 2>&1
17 then
18 echo "creating set '${set_name}'"
19 $IPSET create "${set_name}" "$@"
20 fi
21 }
22
23 function create_drop_chain(){
24 local chain="$1"
25
26 if ! $IPTABLES -L "${chain}" >/dev/null 2>&1
27 then
28 echo "initializing chain '${chain}'"
29 $IPTABLES -N "${chain}" || $IPTABLES -F "${chain}"
30 $IPTABLES -A "${chain}" -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN
31 $IPTABLES -A "${chain}" -j REJECT --reject-with icmp-port-unreachable
32 $IPTABLES -v -L "${chain}"
33 fi
34
35 if ! $IP6TABLES -L "${chain}" >/dev/null 2>&1
36 then
37 echo "initializing chain '${chain}' ipv6"
38 $IP6TABLES -N "${chain}" || $IP6TABLES -F "${chain}"
39 $IP6TABLES -A "${chain}" -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN
40 $IP6TABLES -A "${chain}" -j REJECT --reject-with icmp6-port-unreachable
41 $IP6TABLES -v -L "${chain}"
42 fi
43 }
44
45 function insert_setmatch_rules(){
46 local single=0
47 if [ "x$1" = "x-single-set" ]
48 then
49 single=1
50 shift
51 fi
52 local ipt set_name="$1"
53 shift
54 for v in '' '6'
55 do
56 eval ipt="\$IP${v}TABLES"
57 if [ $single -eq 1 ]
58 then
59 v=''
60 fi
61 if ! $ipt -C INPUT -m set --match-set "${set_name}${v}" src "$@" >/dev/null 2>&1
62 then
63 echo "initializing rule '${set_name}${v}'"
64 $ipt -I INPUT -m set --match-set "${set_name}${v}" src "$@"
65 fi
66 done
67 }
68
69 function reload_cidr_sets(){
70 local set_name="$1"
71
72 # init new temporary sets
73 echo "updating set '${set_name}'"
74
75 create_set "${set_name}-tmp" hash:net
76 create_set "${set_name}6-tmp" hash:net family inet6
77
78 # populate them
79 for sfx in '' .$(hostname -s)
80 do
81 cidrfile="${set_name}.cidr${sfx}"
82 if [ -e "${cidrfile}" ]
83 then
84 for s in $(decommentcat "${cidrfile}")
85 do
86 case "${s}" in
87 *.*) table="${set_name}-tmp" ;;
88 *:*) table="${set_name}6-tmp" ;;
89 *)
90 echo "unknown entry '${s}' in '${cidrfile}'" 1>&2
91 continue
92 ;;
93 esac
94 $IPSET add "${table}" "${s}"
95 done
96 fi
97 done
98
99 # take new sets live
100 for v in '' 6
101 do
102 n="${set_name}${v}"
103 $IPSET swap "${n}-tmp" "${n}"
104 $IPSET destroy "${n}-tmp"
105 $IPSET list -t "${n}"
106 done
107 }
108
109 function add_service_entry(){
110 local port proto
111 port=$(echo "$1" | cut -d/ -f1)
112 proto=$(echo "$1" | cut -d/ -f2)
113 $IPSET -exist add allowed_${proto} ${port}
114 }
115
116 function allow_services(){
117 local s proto port
118 for s in "$@"
119 do
120 case "${s}" in
121 */*) add_service_entry "${s}"
122 ;;
123 *) for svc in $(getent services "${s}" | awk '{print $2}')
124 do
125 add_service_entry "${svc}"
126 done
127 ;;
128 esac
129 done
130 }
131