5 IPTABLES
=$(which iptables)
6 IP6TABLES
=$(which ip6tables)
21 function decommentcat
(){
22 cat "$@" | sed 's/\s*#.*$//;/^\s*$/d'
25 function create_set
(){
28 if ! $IPSET list
"${set_name}" >/dev
/null
2>&1
30 echo "creating set '${set_name}'"
31 $IPSET create
"${set_name}" "$@"
35 function create_drop_chain
(){
38 if ! $IPTABLES -L "${chain}" >/dev
/null
2>&1
40 echo "initializing chain '${chain}'"
41 $IPTABLES -N "${chain}" || $IPTABLES -F "${chain}"
42 $IPTABLES -A "${chain}" -m conntrack
--ctstate ESTABLISHED
,RELATED
-j RETURN
43 $IPTABLES -A "${chain}" -j REJECT
--reject-with icmp
-port-unreachable
44 $IPTABLES -v -L "${chain}"
47 if ! $IP6TABLES -L "${chain}" >/dev
/null
2>&1
49 echo "initializing chain '${chain}' ipv6"
50 $IP6TABLES -N "${chain}" || $IP6TABLES -F "${chain}"
51 $IP6TABLES -A "${chain}" -m conntrack
--ctstate ESTABLISHED
,RELATED
-j RETURN
52 $IP6TABLES -A "${chain}" -j REJECT
--reject-with icmp6
-port-unreachable
53 $IP6TABLES -v -L "${chain}"
57 function insert_setmatch_rules
(){
59 if [ "x$1" = "x-single-set" ]
64 local ipt set_name
="$1"
68 eval ipt
="\$IP${v}TABLES"
73 if ! $ipt -C INPUT
-m set --match-set "${set_name}${v}" src
"$@" >/dev
/null
2>&1
75 echo "initializing rule '${set_name}${v}'"
76 $ipt -I INPUT
-m set --match-set "${set_name}${v}" src
"$@"
81 # try to recreate sets faster than one-at-a-time by generating restore rules
82 function ipset_restore_from_cidr
(){
92 # extract existing set configuration to create temporary set
93 (set -o pipefail
; $IPSET save
"${set_name}${v}" 2>/dev
/null
| grep -m 1 '^create ' | sed "s/\(create ${set_name}${v}\)/\1-tmp/") || continue
94 # populate with new data
95 decommentcat
"${set_name}.cidr" "${set_name}.cidr.$(hostname -s)" 2>/dev
/null
| sed -n 's/\(.*'"${vmatch}"'.*\)/add '"${set_name}${v}-tmp"' \1/p'
99 function reload_cidr_sets
(){
103 ipset_restore_from_cidr
"${set_name}" | ipset restore
107 $IPSET swap
"${n}-tmp" "${n}"
108 $IPSET destroy
"${n}-tmp"
109 $IPSET list
-t "${n}"
113 function _old_reload_cidr_sets
(){
118 # init new temporary sets
119 echo "updating set '${set_name}'"
121 create_set
"${set_name}-tmp" hash:net
"$@"
122 create_set
"${set_name}6-tmp" hash:net
"$@" family inet6
125 for sfx
in '' .
$(hostname -s)
127 cidrfile
="${set_name}.cidr${sfx}"
128 if [ -e "${cidrfile}" ]
130 for s
in $(decommentcat "${cidrfile}")
133 *.
*) table
="${set_name}-tmp" ;;
134 *:*) table
="${set_name}6-tmp" ;;
136 echo "unknown entry '${s}' in '${cidrfile}'" 1>&2
140 $IPSET add
"${table}" "${s}"
149 $IPSET swap
"${n}-tmp" "${n}"
150 $IPSET destroy
"${n}-tmp"
151 $IPSET list
-t "${n}"
155 function add_service_entry
(){
157 port
=$(echo "$1" | cut -d/ -f1)
158 proto
=$(echo "$1" | cut -d/ -f2)
159 $IPSET -exist add allowed_
${proto} ${port}
162 function allow_services
(){
167 */*) add_service_entry
"${s}"
169 *) for svc
in $(egrep "^${s}\s+" /etc/services | decommentcat | awk '{print $2}')
171 add_service_entry
"${svc}"