fancier services
[firewall-squeep] / common.sh
index 4bb66ff664b0a8be18b419a9eda030f0abc78680..f8860fcb1adf50868d549a147cfeb5f57ef23ea9 100644 (file)
--- a/common.sh
+++ b/common.sh
@@ -20,3 +20,90 @@ function create_set(){
        fi
 }
 
+function insert_setmatch_rules(){
+       local single=0
+       if [ "x$1" = "x-single-set" ]
+       then
+               single=1
+               shift
+       fi
+       local ipt set_name="$1"
+       shift
+       for v in '' '6'
+       do
+               eval ipt="\$IP${v}TABLES"
+               if [ $single -eq 1 ]
+               then
+                       v=''
+               fi
+               if ! $ipt -C INPUT -m set --match-set "${set_name}${v}" src "$@" >/dev/null 2>&1
+               then
+                       echo "initializing rule '${set_name}${v}'"
+                       $ipt -I INPUT -m set --match-set "${set_name}${v}" src "$@"
+               fi
+       done
+}
+
+function reload_cidr_sets(){
+       local set_name="$1"
+
+       # init new temporary sets
+       echo "updating set '${set_name}'"
+
+       create_set "${set_name}-tmp" hash:net
+       create_set "${set_name}6-tmp" hash:net family inet6
+
+       # populate them
+       for sfx in '' .$(hostname -s)
+       do
+               cidrfile="${set_name}.cidr${sfx}"
+               if [ -e "${cidrfile}" ]
+               then
+                       for s in $(decommentcat "${cidrfile}")
+                       do
+                               case "${s}" in
+                                       *.*) table="${set_name}-tmp" ;;
+                                       *:*) table="${set_name}6-tmp" ;;
+                                       *)
+                                               echo "unknown entry '${s}' in '${cidrfile}'" 1>&2
+                                               continue
+                                       ;;
+                               esac
+                               $IPSET add "${table}" "${s}"
+                       done
+               fi
+       done
+
+       # take new sets live
+       for v in '' 6
+       do
+               n="${set_name}${v}"
+               $IPSET swap "${n}-tmp" "${n}"
+               $IPSET destroy "${n}-tmp"
+               $IPSET list -t "${n}"
+       done
+}
+
+function add_service_entry(){
+       local port/proto
+       port=$(echo "${s}" | cut -d/ -f1)
+       proto=$(echo "${s}" | cut -d/ -f2)
+       $IPSET -exist add allowed_${proto} ${port}
+}
+
+function allow_services(){
+       local s proto port
+       for s in "$@"
+       do
+               case "${s}" in
+               */*)    add_service_entry "${s}"
+                       ;;
+               *)      for svc in $(getent services "${s}" | awk '{print $2}')
+                       do
+                               add_service_entry "${svc}"
+                       done
+                       ;;
+               esac
+       done
+}
+