# # Shorewall 4.5 -- /usr/share/shorewall/lib.common. # # This program is under GPL [http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt] # # (c) 2010-2012 - Tom Eastep (teastep@shorewall.net) # # Complete documentation is available at http://shorewall.net # # This program is free software; you can redistribute it and/or modify # it under the terms of Version 2 of the GNU General Public License # as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # The purpose of this library is to hold those functions used by both the CLI and by the # generated firewall scripts. To avoid versioning issues, it is copied into generated # scripts rather than loaded at run-time. # ######################################################################################### # # Conditionally produce message # progress_message() # $* = Message { local timestamp timestamp= if [ $VERBOSITY -gt 1 ]; then [ -n "$g_timestamp" ] && timestamp="$(date +%H:%M:%S) " echo "${timestamp}$@" fi if [ $LOG_VERBOSITY -gt 1 ]; then timestamp="$(date +'%b %_d %T') " echo "${timestamp}$@" >> $STARTUP_LOG fi } progress_message2() # $* = Message { local timestamp timestamp= if [ $VERBOSITY -gt 0 ]; then [ -n "$g_timestamp" ] && timestamp="$(date +%H:%M:%S) " echo "${timestamp}$@" fi if [ $LOG_VERBOSITY -gt 0 ]; then timestamp="$(date +'%b %_d %T') " echo "${timestamp}$@" >> $STARTUP_LOG fi } progress_message3() # $* = Message { local timestamp timestamp= if [ $VERBOSITY -ge 0 ]; then [ -n "$g_timestamp" ] && timestamp="$(date +%H:%M:%S) " echo "${timestamp}$@" fi if [ $LOG_VERBOSITY -ge 0 ]; then timestamp="$(date +'%b %_d %T') " echo "${timestamp}$@" >> $STARTUP_LOG fi } # # Set a standard chain's policy # setpolicy() # $1 = name of chain, $2 = policy { run_iptables -P $1 $2 } # # Generate a list of all network interfaces on the system # find_all_interfaces() { ${IP:-ip} link list | egrep '^[[:digit:]]+:' | cut -d ' ' -f2 | sed -r 's/(@.*)?:$//' } # # Generate a list of all network interfaces on the system that have an ipv4 address # find_all_interfaces1() { ${IP:-ip} -$g_family addr list | egrep '^[[:digit:]]+:' | cut -d ' ' -f2 | sed -r 's/(@.*)?:$//' } # # Find the value 'dev' in the passed arguments then echo the next value # find_device() { while [ $# -gt 1 ]; do [ "x$1" = xdev ] && echo $2 && return shift done } # # Find the value 'via' in the passed arguments then echo the next value # find_gateway() { while [ $# -gt 1 ]; do [ "x$1" = xvia ] && echo $2 && return shift done } # # Find the value 'mtu' in the passed arguments then echo the next value # find_mtu() { while [ $# -gt 1 ]; do [ "x$1" = xmtu ] && echo $2 && return shift done } # # Find the value 'peer' in the passed arguments then echo the next value up to # "/" # find_peer() { while [ $# -gt 1 ]; do [ "x$1" = xpeer ] && echo ${2%/*} && return shift done } # # Try to find the gateway through an interface looking for 'nexthop' find_nexthop() # $1 = interface { echo $(find_gateway `$IP -$g_family route list | grep "[[:space:]]nexthop.* $1"`) } # # Find the default route's interface # find_default_interface() { $IP -$g_family route list | while read first rest; do [ "$first" = default ] && echo $(find_device $rest) && return done } # # Determine if Interface is up # interface_is_up() { [ -n "$($IP -$g_family link list dev $1 2> /dev/null | grep -e '[<,]UP[,>]')" ] } # # Determine if interface is usable from a Netfilter prespective # interface_is_usable() # $1 = interface { [ "$1" = lo ] && return 0 interface_is_up $1 && [ "$(find_first_interface_address_if_any $1)" != :: ] && run_isusable_exit $1 } # # Find interface addresses--returns the set of addresses assigned to the passed # device # find_interface_addresses() # $1 = interface { if [ $g_family -eq 4 ]; then $IP -f inet addr show $1 2> /dev/null | grep inet\ | sed 's/\s*inet //;s/\/.*//;s/ peer.*//' else $IP -f inet6 addr show $1 2> /dev/null | grep 'inet6 2' | sed 's/\s*inet6 //;s/\/.*//;s/ peer.*//' fi } # # echo the list of networks routed out of a given interface # get_routed_networks() # $1 = interface name, $2-n = Fatal error message { local address local rest $IP -$g_family route show dev $1 2> /dev/null | while read address rest; do case "$address" in default) if [ $# -gt 1 ]; then shift fatal_error "$@" else echo "WARNING: default route ignored on interface $1" >&2 fi ;; multicast|broadcast|prohibit|nat|throw|nexthop) ;; [2-9]*) [ "$address" = "${address%/*}" ] && address="${address}/128" echo $address ;; *) if [ $g_family -eq 4 ]; then [ "$address" = "${address%/*}" ] && address="${address}/128" echo $address fi ;; esac done } # # Clear the current traffic shaping configuration # delete_tc1() { clear_one_tc() { $TC qdisc del dev $1 root 2> /dev/null $TC qdisc del dev $1 ingress 2> /dev/null } run_tcclear_exit run_ip link list | \ while read inx interface details; do case $inx in [0-9]*) clear_one_tc ${interface%:} ;; *) ;; esac done } # # Detect a device's MTU -- echos the passed device's MTU # get_device_mtu() # $1 = device { local output output="$($IP link list dev $1 2> /dev/null)" # quotes required for /bin/ash if [ -n "$output" ]; then echo $(find_mtu $output) else echo 1500 fi } # # Version of the above that doesn't generate any output for MTU 1500. # Generates 'mtu ' otherwise, where is the device's MTU + 100 # get_device_mtu1() # $1 = device { local output output="$($IP link list dev $1 2> /dev/null)" # quotes required for /bin/ash local mtu if [ -n "$output" ]; then mtu=$(find_mtu $output) if [ -n "$mtu" ]; then [ $mtu = 1500 ] || echo mtu $(($mtu + 100)) fi fi } # # Undo changes to routing # undo_routing() { local undofiles local f if [ -z "$g_noroutes" ]; then # # Restore rt_tables database # if [ -f ${VARDIR}/rt_tables ]; then [ -w /etc/iproute2/rt_table -a -z "$KEEP_RT_TABLES" ] && cp -f ${VARDIR}/rt_tables /etc/iproute2/ && progress_message "/etc/iproute2/rt_tables database restored" rm -f ${VARDIR}/rt_tables fi # # Restore the rest of the routing table # undofiles="$(ls ${VARDIR}/undo_*routing 2> /dev/null)" if [ -n "$undofiles" ]; then for f in $undofiles; do . $f done rm -f $undofiles progress_message "Shorewall-generated routing tables and routing rules removed" fi fi } # # Save the default route # save_default_route() { awk \ 'BEGIN {defroute=0;}; /^default / {defroute=1; print; next}; /nexthop/ {if (defroute == 1 ) {print ; next} }; { defroute=0; };' } # # Restore the default route that was in place before the initial 'shorewall start' # replace_default_route() # $1 = USE_DEFAULT_RT { # # default_route and result are inherited from the caller # if [ -n "$default_route" ]; then case "$default_route" in *metric*) # # Don't restore a default route with a metric unless USE_DEFAULT_RT=Yes. Otherwise, we only replace the one with metric 0 # [ -n "$1" ] && qt $IP -$g_family route replace $default_route && progress_message "Default Route (${default_route# }) restored" default_route= ;; *) qt $IP -$g_family route replace $default_route && progress_message "Default Route (${default_route# }) restored" result=0 default_route= ;; esac fi } restore_default_route() # $1 = USE_DEFAULT_RT { local result result=1 if [ -z "$g_noroutes" -a -f ${VARDIR}/default_route ]; then local default_route default_route= local route while read route ; do case $route in default*) replace_default_route $1 default_route="$default_route $route" ;; *) default_route="$default_route $route" ;; esac done < ${VARDIR}/default_route replace_default_route $1 if [ $result = 1 ]; then # # We didn't restore a default route with metric 0 # if $IP -$g_family -o route list 2> /dev/null | fgrep default | fgrep -qv metric; then # # But we added a default route with metric 0 # qt $IP -$g_family route del default metric 0 && progress_message "Default route with metric 0 deleted" fi fi rm -f ${VARDIR}/default_route fi return $result } # # Flush the conntrack table if $g_purge is non-empty # conditionally_flush_conntrack() { if [ -n "$g_purge" ]; then if [ -n $(mywhich conntrack) ]; then conntrack -f ipv$_family -F else error_message "WARNING: The '-p' option requires the conntrack utility which does not appear to be installed on this system" fi fi } # # Issue a message and stop/restore the firewall # fatal_error() { echo " ERROR: $@" >&2 if [ $LOG_VERBOSITY -ge 0 ]; then timestamp="$(date +'%_b %d %T') " echo "${timestamp} ERROR: $@" >> $STARTUP_LOG fi stop_firewall [ -n "$TEMPFILE" ] && rm -f $TEMPFILE exit 2 } # # Issue a message and stop # startup_error() # $* = Error Message { echo " ERROR: $@: Firewall state not changed" >&2 if [ $LOG_VERBOSITY -ge 0 ]; then timestamp="$(date +'%_b %d %T') " echo "${timestamp} ERROR: $@" >> $STARTUP_LOG fi case $COMMAND in start) logger -p kern.err "ERROR:$g_product start failed:Firewall state not changed" ;; restart) logger -p kern.err "ERROR:$g_product restart failed:Firewall state not changed" ;; restore) logger -p kern.err "ERROR:$g_product restore failed:Firewall state not changed" ;; esac if [ $LOG_VERBOSITY -ge 0 ]; then timestamp="$(date +'%_b %d %T') " case $COMMAND in start) echo "${timestamp} ERROR:$g_product start failed:Firewall state not changed" >> $STARTUP_LOG ;; restart) echo "${timestamp} ERROR:$g_product restart failed:Firewall state not changed" >> $STARTUP_LOG ;; restore) echo "${timestamp} ERROR:$g_product restore failed:Firewall state not changed" >> $STARTUP_LOG ;; esac fi kill $$ exit 2 } # # Run iptables and if an error occurs, stop/restore the firewall # run_iptables() { local status while [ 1 ]; do $g_tool $@ status=$? [ $status -ne 4 ] && break done if [ $status -ne 0 ]; then error_message "ERROR: Command \"$g_tool $@\" Failed" stop_firewall exit 2 fi } # # Run iptables retrying exit status 4 # do_iptables() { local status while [ 1 ]; do $g_tool $@ status=$? [ $status -ne 4 ] && return $status; done } # # Run iptables and if an error occurs, stop/restore the firewall # run_ip() { if ! $IP -$g_family $@; then error_message "ERROR: Command \"$IP -$g_family $@\" Failed" stop_firewall exit 2 fi } # # Run tc and if an error occurs, stop/restore the firewall # run_tc() { if ! $TC $@ ; then error_message "ERROR: Command \"$TC $@\" Failed" stop_firewall exit 2 fi } # # Get the Shorewall version of the passed script # get_script_version() { # $1 = script local temp local version local ifs local digits local verbosity verbosity="$VERBOSITY" VERBOSITY=0 temp=$( $SHOREWALL_SHELL $1 version | sed 's/-.*//' ) if [ $? -ne 0 ]; then version=0 else ifs=$IFS IFS=. temp=$(echo $temp) IFS=$ifs digits=0 for temp in $temp; do version=${version}$(printf '%02d' $temp) digits=$(($digits + 1)) [ $digits -eq 3 ] && break done fi echo $version VERBOSITY="$verbosity" } # # Do required exports or create the required option string and run the passed script using # $SHOREWALL_SHELL # run_it() { local script local options local version export VARDIR script=$1 shift version=$(get_script_version $script) if [ $version -lt 040408 ]; then # # Old script that doesn't understand 4.4.8 script options # export RESTOREFILE export VERBOSITY export NOROUTES=$g_noroutes export PURGE=$g_purge export TIMESTAMP=$g_timestamp export RECOVERING=$g_recovering case "$g_program" in *-lite) # # Shorewall Lite # export LOGFORMAT export IPTABLES ;; esac else # # 4.4.8 or later -- no additional exports required # if [ x$1 = xtrace -o x$1 = xdebug ]; then options="$1 -" shift; else options='-' fi [ -n "$g_noroutes" ] && options=${options}n [ -n "$g_timestamp" ] && options=${options}t [ -n "$g_purge" ] && options=${options}p [ -n "$g_recovering" ] && options=${options}r options="${options}V $VERBOSITY" [ -n "$RESTOREFILE" ] && options="${options} -R $RESTOREFILE" fi $SHOREWALL_SHELL $script $options $@ } # # Message to stderr # error_message() # $* = Error Message { echo " $@" >&2 } # # Undo the effect of 'split()' # join() { local f local o o= for f in $* ; do o="${o:+$o:}$f" done echo $o } # # Return the number of elements in a list # list_count() # $* = list { return $# } # # Split a colon-separated list into a space-separated list # split() { local ifs ifs=$IFS IFS=: echo $* IFS=$ifs } # # Search a list looking for a match -- returns zero if a match found # 1 otherwise # list_search() # $1 = element to search for , $2-$n = list { local e e=$1 while [ $# -gt 1 ]; do shift [ "x$e" = "x$1" ] && return 0 done return 1 } # # Suppress all output for a command # qt() { "$@" >/dev/null 2>&1 } # # Suppress all output and input - mainly for preventing leaked file descriptors # to avoid SELinux denials # qtnoin() { "$@" /dev/null 2>&1 } qt1() { local status while [ 1 ]; do "$@" /dev/null 2>&1 status=$? [ $status -ne 4 ] && return $status done } # # Determine if Shorewall[6] is "running" # product_is_started() { qt1 $g_tool -L shorewall -n } shorewall_is_started() { qt1 $IPTABLES -L shorewall -n } shorewall6_is_started() { qt1 $IP6TABLES -L shorewall -n } # # Echos the fully-qualified name of the calling shell program # my_pathname() { cd $(dirname $0) echo $PWD/$(basename $0) } # # Source a user exit file if it exists # run_user_exit() # $1 = file name { local user_exit user_exit=$(find_file $1) if [ -f $user_exit ]; then progress_message "Processing $user_exit ..." . $user_exit fi } # # Load a Kernel Module -- assumes that the variable 'moduledirectories' contains # a space-separated list of directories to search for # the module and that 'moduleloader' contains the # module loader command. # loadmodule() # $1 = module name, $2 - * arguments { local modulename modulename=$1 local modulefile local suffix if [ -d /sys/module/ ]; then if ! list_search $modulename $DONT_LOAD; then if [ ! -d /sys/module/$modulename ]; then shift for suffix in $MODULE_SUFFIX ; do for directory in $moduledirectories; do modulefile=$directory/${modulename}.${suffix} if [ -f $modulefile ]; then case $moduleloader in insmod) insmod $modulefile $* ;; *) modprobe $modulename $* ;; esac break 2 fi done done fi fi elif ! list_search $modulename $DONT_LOAD $MODULES; then shift for suffix in $MODULE_SUFFIX ; do for directory in $moduledirectories; do modulefile=$directory/${modulename}.${suffix} if [ -f $modulefile ]; then case $moduleloader in insmod) insmod $modulefile $* ;; *) modprobe $modulename $* ;; esac break 2 fi done done fi } # # Reload the Modules # reload_kernel_modules() { local save_modules_dir save_modules_dir=$MODULESDIR local directory local moduledirectories moduledirectories= local moduleloader moduleloader=modprobe local uname if ! qt mywhich modprobe; then moduleloader=insmod fi [ -n "${MODULE_SUFFIX:=ko ko.gz o o.gz gz}" ] [ -z "$MODULESDIR" ] && \ uname=$(uname -r) && \ MODULESDIR=/lib/modules/$uname/kernel/net/ipv${g_family}/netfilter:/lib/modules/$uname/kernel/net/netfilter:/lib/modules/$uname/kernel/net/sched:/lib/modules/$uname/extra:/lib/modules/$uname/extra/ipset [ -d /sys/module/ ] || MODULES=$(lsmod | cut -d ' ' -f1) for directory in $(split $MODULESDIR); do [ -d $directory ] && moduledirectories="$moduledirectories $directory" done [ -n "$moduledirectories" ] && while read command; do eval $command done MODULESDIR=$save_modules_dir } # # Load kernel modules required for Shorewall # load_kernel_modules() # $1 = Yes, if we are to save moduleinfo in $VARDIR { local save_modules_dir save_modules_dir=$MODULESDIR local directory local moduledirectories moduledirectories= local moduleloader moduleloader=modprobe local savemoduleinfo savemoduleinfo=${1:-Yes} # So old compiled scripts still work local uname if ! qt mywhich modprobe; then moduleloader=insmod fi [ -n "${MODULE_SUFFIX:=o gz ko o.gz ko.gz}" ] [ -z "$MODULESDIR" ] && \ uname=$(uname -r) && \ MODULESDIR=/lib/modules/$uname/kernel/net/ipv${g_family}/netfilter:/lib/modules/$uname/kernel/net/netfilter:/lib/modules/$uname/kernel/net/sched:/lib/modules/$uname/extra:/lib/modules/$uname/extra/ipset for directory in $(split $MODULESDIR); do [ -d $directory ] && moduledirectories="$moduledirectories $directory" done [ -n "$LOAD_HELPERS_ONLY" ] && modules=$(find_file helpers) || modules=$(find_file modules) if [ -f $modules -a -n "$moduledirectories" ]; then [ -d /sys/module/ ] || MODULES=$(lsmod | cut -d ' ' -f1) progress_message "Loading Modules..." . $modules if [ $savemoduleinfo = Yes ]; then [ -d ${VARDIR} ] || mkdir -p ${VARDIR} echo MODULESDIR="$MODULESDIR" > ${VARDIR}/.modulesdir cp -f $modules ${VARDIR}/.modules fi elif [ $savemoduleinfo = Yes ]; then [ -d ${VARDIR} ] || mkdir -p ${VARDIR} > ${VARDIR}/.modulesdir > ${VARDIR}/.modules fi MODULESDIR=$save_modules_dir } # # Note: The following set of IP address manipulation functions have anomalous # behavior when the shell only supports 32-bit signed arithmetic and # the IP address is 128.0.0.0 or 128.0.0.1. # LEFTSHIFT='<<' # # Convert an IP address in dot quad format to an integer # decodeaddr() { local x local temp temp=0 local ifs ifs=$IFS IFS=. for x in $1; do temp=$(( $(( $temp $LEFTSHIFT 8 )) | $x )) done echo $temp IFS=$ifs } # # convert an integer to dot quad format # encodeaddr() { addr=$1 local x local y y=$(($addr & 255)) for x in 1 2 3 ; do addr=$(($addr >> 8)) y=$(($addr & 255)).$y done echo $y } # # Netmask from CIDR # ip_netmask() { local vlsm vlsm=${1#*/} [ $vlsm -eq 0 ] && echo 0 || echo $(( -1 $LEFTSHIFT $(( 32 - $vlsm )) )) } # # Network address from CIDR # ip_network() { local decodedaddr decodedaddr=$(decodeaddr ${1%/*}) local netmask netmask=$(ip_netmask $1) echo $(encodeaddr $(($decodedaddr & $netmask))) } # # The following hack is supplied to compensate for the fact that many of # the popular light-weight Bourne shell derivatives don't support XOR ("^"). # ip_broadcast() { local x x=$(( 32 - ${1#*/} )) [ $x -eq 32 ] && echo -1 || echo $(( $(( 1 $LEFTSHIFT $x )) - 1 )) } # # Calculate broadcast address from CIDR # broadcastaddress() { local decodedaddr decodedaddr=$(decodeaddr ${1%/*}) local netmask netmask=$(ip_netmask $1) local broadcast broadcast=$(ip_broadcast $1) echo $(encodeaddr $(( $(($decodedaddr & $netmask)) | $broadcast ))) } # # Test for network membership # in_network() # $1 = IP address, $2 = CIDR network { local netmask netmask=$(ip_netmask $2) # # Use string comparison to work around a broken BusyBox ash in OpenWRT # test $(( $(decodeaddr $1) & $netmask)) = $(( $(decodeaddr ${2%/*}) & $netmask )) } # # Query NetFilter about the existence of a filter chain # chain_exists() # $1 = chain name { qt1 $g_tool -L $1 -n } # # Find the interface with the passed MAC address # find_interface_by_mac() { local mac mac=$1 local first local second local rest local dev $IP link list | while read first second rest; do case $first in *:) dev=$second ;; *) if [ "$second" = $mac ]; then echo ${dev%:} return fi esac done } # # Find interface address--returns the first IP address assigned to the passed # device # find_first_interface_address() # $1 = interface { if [ $g_family -eq 4 ]; then # # get the line of output containing the first IP address # addr=$(${IP:-ip} -$g_family addr show $1 2> /dev/null | grep 'inet .* global' | head -n1) # # If there wasn't one, bail out now # [ -n "$addr" ] || startup_error "Can't determine the IP address of $1" # # Strip off the trailing VLSM mask (or the peer IP in case of a P-t-P link) # along with everything else on the line # echo $addr | sed 's/\s*inet //;s/\/.*//;s/ peer.*//' else # # get the line of output containing the first IP address # addr=$(${IP:-ip} -f inet6 addr show dev $1 2> /dev/null | fgrep 'inet6 ' | fgrep -v 'scope link' | head -n1) # # If there wasn't one, bail out now # [ -n "$addr" ] || startup_error "Can't determine the IPv6 address of $1" # # Strip off the trailing VLSM mask (or the peer IP in case of a P-t-P link) # along with everything else on the line # echo $addr | sed 's/\s*inet6 //;s/\/.*//;s/ peer.*//' fi } find_first_interface_address_if_any() # $1 = interface { if [ $g_family -eq 4 ]; then # # get the line of output containing the first IP address # addr=$(${IP:-ip} -f inet addr show $1 2> /dev/null | grep 'inet .* global' | head -n1) # # Strip off the trailing VLSM mask (or the peer IP in case of a P-t-P link) # along with everything else on the line # [ -n "$addr" ] && echo $addr | sed 's/\s*inet //;s/\/.*//;s/ peer.*//' || echo 0.0.0.0 else # # get the line of output containing the first IP address # addr=$(${IP:-ip} -f inet6 addr show dev $1 2> /dev/null | fgrep 'inet6 ' | fgrep -v 'scope link' | head -n1) # # Strip off the trailing VLSM mask (or the peer IP in case of a P-t-P link) # along with everything else on the line # [ -n "$addr" ] && echo $addr | sed 's/\s*inet6 //;s/\/.*//;s/ peer.*//' || echo :: fi } # # Internal version of 'which' # mywhich() { local dir for dir in $(split $PATH); do if [ -x $dir/$1 ]; then echo $dir/$1 return 0 fi done return 2 } # # Find a File -- For relative file name, look in each ${CONFIG_PATH} then ${CONFDIR} # find_file() { local saveifs saveifs= local directory case $1 in /*) echo $1 ;; *) for directory in $(split $CONFIG_PATH); do if [ -f $directory/$1 ]; then echo $directory/$1 return fi done echo ${CONFDIR}/$1 ;; esac } # # Set the Shorewall state # set_state () # $1 = state { if [ $# -gt 1 ]; then echo "$1 ($(date)) from $2" > ${VARDIR}/state else echo "$1 ($(date))" > ${VARDIR}/state fi } # # Perform variable substitution on the passed argument and echo the result # expand() # $@ = contents of variable which may be the name of another variable { eval echo \"$@\" } # # Function for including one file into another # INCLUDE() { . $(find_file $(expand $@)) } # Function to truncate a string -- It uses 'cut -b -' # rather than ${v:first:last} because light-weight shells like ash and # dash do not support that form of expansion. # truncate() # $1 = length { cut -b -${1} }