#!/bin/sh 
#
#  This is automatically generated file. DO NOT MODIFY !
#
#  Firewall Builder  fwb_ipt v5.0.0.3547
#
#  Generated Fri Jun  3 17:29:40 2011 PDT by vadim
#
# files: * fw-A.fw /sw/FWbuilder/fw-A.fw
#
# Compiled for iptables 1.3.0
#

# fw-A:Routing:0: error: Object "gw_200" used as gateway in the routing rule 0 (main) is not reachable because it is not in any local network of the firewall
# fw-A:Routing:0: error: Object "gw_200" used as gateway in the routing rule 0 (main) is not in the same local network as interface eth3


FWBDEBUG=""

PATH="/sbin:/usr/sbin:/bin:/usr/bin:${PATH}"
export PATH



LSMOD="/sbin/lsmod"
MODPROBE="/sbin/modprobe"
IPTABLES="/sbin/iptables"
IP6TABLES="/sbin/ip6tables"
IPTABLES_RESTORE="/sbin/iptables-restore"
IP6TABLES_RESTORE="/sbin/ip6tables-restore"
IP="/sbin/ip"
IFCONFIG="/sbin/ifconfig"
VCONFIG="/sbin/vconfig"
BRCTL="/sbin/brctl"
IFENSLAVE="/sbin/ifenslave"
IPSET="/usr/sbin/ipset"
LOGGER="/usr/bin/logger"

log() {
    echo "$1"
    command -v "$LOGGER" >/dev/null 2>&1 && $LOGGER -p info "$1"
}

getInterfaceVarName() {
    echo $1 | sed 's/\./_/'
}

getaddr_internal() {
    dev=$1
    name=$2
    af=$3
    L=$($IP $af addr show dev $dev |  sed -n '/inet/{s!.*inet6* !!;s!/.*!!p}' | sed 's/peer.*//')
    test -z "$L" && { 
        eval "$name=''"
        return
    }
    eval "${name}_list=\"$L\"" 
}

getnet_internal() {
    dev=$1
    name=$2
    af=$3
    L=$($IP route list proto kernel | grep $dev | grep -v default |  sed 's! .*$!!')
    test -z "$L" && { 
        eval "$name=''"
        return
    }
    eval "${name}_list=\"$L\"" 
}


getaddr() {
    getaddr_internal $1 $2 "-4"
}

getaddr6() {
    getaddr_internal $1 $2 "-6"
}

getnet() {
    getnet_internal $1 $2 "-4"
}

getnet6() {
    getnet_internal $1 $2 "-6"
}

# function getinterfaces is used to process wildcard interfaces
getinterfaces() {
    NAME=$1
    $IP link show | grep ": $NAME" | while read L; do
        OIFS=$IFS
        IFS=" :"
        set $L
        IFS=$OIFS
        echo $2
    done
}

diff_intf() {
    func=$1
    list1=$2
    list2=$3
    cmd=$4
    for intf in $list1
    do
        echo $list2 | grep -q $intf || {
        # $vlan is absent in list 2
            $func $intf $cmd
        }
    done
}

find_program() {
  PGM=$1
  command -v $PGM >/dev/null 2>&1 || {
    echo "$PGM not found"
    exit 1
  }
}
check_tools() {
  find_program $IPTABLES 
 find_program $MODPROBE 
  find_program $IP 
  find_program $VCONFIG 
  find_program $IFENSLAVE 
}
reset_iptables_v4() {
  $IPTABLES -P OUTPUT  DROP
  $IPTABLES -P INPUT   DROP
  $IPTABLES -P FORWARD DROP

cat /proc/net/ip_tables_names | while read table; do
  $IPTABLES -t $table -L -n | while read c chain rest; do
      if test "X$c" = "XChain" ; then
        $IPTABLES -t $table -F $chain
      fi
  done
  $IPTABLES -t $table -X
done
}

reset_iptables_v6() {
  $IP6TABLES -P OUTPUT  DROP
  $IP6TABLES -P INPUT   DROP
  $IP6TABLES -P FORWARD DROP

cat /proc/net/ip6_tables_names | while read table; do
  $IP6TABLES -t $table -L -n | while read c chain rest; do
      if test "X$c" = "XChain" ; then
        $IP6TABLES -t $table -F $chain
      fi
  done
  $IP6TABLES -t $table -X
done
}


P2P_INTERFACE_WARNING=""

missing_address() {
    address=$1
    cmd=$2

    oldIFS=$IFS
    IFS="@"
    set $address
    addr=$1
    interface=$2
    IFS=$oldIFS



    $IP addr show dev $interface | grep -q POINTOPOINT && {
        test -z "$P2P_INTERFACE_WARNING" && echo "Warning: Can not update address of interface $interface. fwbuilder can not manage addresses of point-to-point interfaces yet"
        P2P_INTERFACE_WARNING="yes"
        return
    }

    test "$cmd" = "add" && {
      echo "# Adding ip address: $interface $addr"
      echo $addr | grep -q ':' && {
          $FWBDEBUG $IP addr $cmd $addr dev $interface
      } || {
          $FWBDEBUG $IP addr $cmd $addr broadcast + dev $interface
      }
    }

    test "$cmd" = "del" && {
      echo "# Removing ip address: $interface $addr"
      $FWBDEBUG $IP addr $cmd $addr dev $interface || exit 1
    }

    $FWBDEBUG $IP link set $interface up
}

list_addresses_by_scope() {
    interface=$1
    scope=$2
    ignore_list=$3
    $IP addr ls dev $interface | \
      awk -v IGNORED="$ignore_list" -v SCOPE="$scope" \
        'BEGIN {
           split(IGNORED,ignored_arr);
           for (a in ignored_arr) {ignored_dict[ignored_arr[a]]=1;}
         }
         (/inet |inet6 / && $0 ~ SCOPE && !($2 in ignored_dict)) {print $2;}' | \
        while read addr; do
          echo "${addr}@$interface"
	done | sort
}


update_addresses_of_interface() {
    ignore_list=$2
    set $1 
    interface=$1 
    shift

    FWB_ADDRS=$(
      for addr in $*; do
        echo "${addr}@$interface"
      done | sort
    )

    CURRENT_ADDRS_ALL_SCOPES=""
    CURRENT_ADDRS_GLOBAL_SCOPE=""

    $IP link show dev $interface >/dev/null 2>&1 && {
      CURRENT_ADDRS_ALL_SCOPES=$(list_addresses_by_scope $interface 'scope .*' "$ignore_list")
      CURRENT_ADDRS_GLOBAL_SCOPE=$(list_addresses_by_scope $interface 'scope global' "$ignore_list")
    } || {
      echo "# Interface $interface does not exist"
      # Stop the script if we are not in test mode
      test -z "$FWBDEBUG" && exit 1
    }

    diff_intf missing_address "$FWB_ADDRS" "$CURRENT_ADDRS_ALL_SCOPES" add
    diff_intf missing_address "$CURRENT_ADDRS_GLOBAL_SCOPE" "$FWB_ADDRS" del
}

clear_addresses_except_known_interfaces() {
    $IP link show | sed 's/://g' | awk -v IGNORED="$*" \
        'BEGIN {
           split(IGNORED,ignored_arr);
           for (a in ignored_arr) {ignored_dict[ignored_arr[a]]=1;}
         }
         (/state/ && !($2 in ignored_dict)) {print $2;}' | \
         while read intf; do
            echo "# Removing addresses not configured in fwbuilder from interface $intf"
            $FWBDEBUG $IP addr flush dev $intf scope global
            $FWBDEBUG $IP link set $intf down
         done
}
missing_vlan() {
    vlan=$1
    cmd=$2

    oldIFS=$IFS
    IFS="@"
    set $vlan
    subint=$1
    parent=$2
    IFS=$oldIFS

    vlan_id=$(echo $subint | sed -r 's/(vlan|[^.]*\.)//')
    test "$cmd" = "add" && {
        echo $subint | grep -q "vlan" && name_type="VLAN_PLUS_VID" || name_type="DEV_PLUS_VID"
        test "$vlan_id" \< "1" || name_type="${name_type}_NO_PAD"
        echo "# Adding VLAN interface $subint (parent: $parent)"
        $FWBDEBUG $VCONFIG set_name_type $name_type
        $FWBDEBUG $VCONFIG $cmd $parent $vlan_id
        $FWBDEBUG $IP link set $subint up
    }
    test "$cmd" = "rem" && {
        echo "# Removing VLAN interface $subint (parent: $parent)"
        $FWBDEBUG $VCONFIG $cmd $subint
    }
}

parse_fwb_vlans() {
    set $1 
    vlan_parent_interface=$1 
    shift

    FWB_VLANS=$(
      for subint in $*; do
        echo "${subint}@$vlan_parent_interface"
      done | sort
    )
    echo $FWB_VLANS
}

parse_current_vlans() {
    vlan_parent_interface=$1
    CURRENT_VLANS=""
    PROC_DIR="/proc/net/vlan/"
    test -d $PROC_DIR || $MODPROBE 8021q || {
        echo "$PROC_DIR does not exist. Vlan interfaces are not available."
        exit 1
    }

    test -f "/proc/net/vlan/config" && {
        CURRENT_VLANS=$(
            cat /proc/net/vlan/config | grep -v 'Dev name' | grep $vlan_parent_interface | \
                while read subint a vlan_id b parent; do
                echo "${subint}@$parent"
            done | sort
        )
    }
    echo $CURRENT_VLANS
}

update_vlans_of_interface() {
    args="$1"
    set $1 
    vlan_parent_interface=$1 

    FWB_VLANS=$(parse_fwb_vlans "$args")
    CURRENT_VLANS=$(parse_current_vlans $vlan_parent_interface)

    $IP link set $vlan_parent_interface up
    diff_intf missing_vlan "$FWB_VLANS" "$CURRENT_VLANS" add
    diff_intf missing_vlan "$CURRENT_VLANS" "$FWB_VLANS" rem
}

add_vlans() {
    args="$1"
    set $1 
    vlan_parent_interface=$1 

    FWB_VLANS=$(parse_fwb_vlans $args)
    CURRENT_VLANS=$(parse_current_vlans $vlan_parent_interface)

    $IP link set $vlan_parent_interface up
    diff_intf missing_vlan "$FWB_VLANS" "$CURRENT_VLANS" add
}

clear_vlans_except_known() {
    FWB_VLANS=$*
    CURRENT_VLANS=$(parse_current_vlans '|')

    diff_intf missing_vlan "$CURRENT_VLANS" "$FWB_VLANS" rem
}

missing_bond() {
    bond_intf=$1
    cmd=$2

    test "$cmd" = "down" && {
      echo "# Bring unconfigured bonding interface $bond_intf down"
      $FWBDEBUG $IP link set $bond_intf down
    }
}

missing_slave() {
    slave=$1
    cmd=$2

    oldIFS=$IFS
    IFS="@"
    set $slave
    intf=$1
    bond_interface=$2
    IFS=$oldIFS

    test "$cmd" = "-d" && {
      echo "# Delete bonding interface slave: $bond_interface $intf"
      $FWBDEBUG $IFENSLAVE -d $bond_interface $intf
    } || {
      echo "# Add bonding interface slave: $bond_interface $intf"
      $FWBDEBUG $IP link set $bond_interface up
      $FWBDEBUG $IFENSLAVE $bond_interface $intf
    }
}

load_bonding_module() {
    bonding_interfaces=$1
    shift
    module_parameters=$*

    PROC_DIR="/proc/net/bonding/"
    test -d $PROC_DIR || {
        cmd="$MODPROBE bonding $module_parameters"
        test -n "$FWBDEBUG" && echo "# $cmd" || $cmd || {
            # Module load failed.
            cat <<EOF

Could not load bonding interface module. Try to add 
module parameters to the file /etc/modprobe.conf or
/etc/modprobe.d/bond.conf and reboot
EOF
            # do not abort in test mode
            test -z "$FWBDEBUG" && exit 1
        }
    }
    ## test that we now have bonding interfaces that we need
    for bondint in $bonding_interfaces; do
        PROD_BOND_IFACE="${PROC_DIR}/$bondint"
        test -f $PROD_BOND_IFACE || {
            echo "Bonding interface $bondint does not exist"
            test -z "$FWBDEBUG" && exit 1
        }
    done
}

unload_bonding_module() {
    $MODPROBE -r bonding
}

update_bonding() {
    bond_interface=$1
    shift

    PROC_DIR="/proc/net/bonding/"
    PROD_BOND_IFACE="${PROC_DIR}/$bond_interface"
    test -f $PROD_BOND_IFACE && {

        FWB_SLAVES=""
        CURRENT_SLAVES=""

        FWB_SLAVES=$(
            for subint in $*; do
                echo "${subint}@$bond_interface"
            done | sort
        )

        CURRENT_SLAVES=$(
            cat $PROD_BOND_IFACE | grep 'Slave Interface:' | \
                while read a b slave; do
                    echo "${slave}@$bond_interface"
                done | sort
        )

        diff_intf missing_slave "$FWB_SLAVES" "$CURRENT_SLAVES" "  "
        diff_intf missing_slave "$CURRENT_SLAVES" "$FWB_SLAVES" "-d"
    }
}

clear_bonding_except_known() {
    PROC_DIR="/proc/net/bonding/"
    ls $PROC_DIR | awk -v IGNORED="$*" \
        'BEGIN {
           split(IGNORED,ignored_arr);
           for (a in ignored_arr) {ignored_dict[ignored_arr[a]]=1;}
         }
         (!($1 in ignored_dict)) {print $1;}' | \
         while read bond_intf; do
             PROD_BOND_IFACE="${PROC_DIR}/$bond_intf"
             slaves=$(cat $PROD_BOND_IFACE | awk '/[sS]lave [iI]nterface:/ { printf "%s ",$NF;}')
             test -n "$slaves" && {
                 echo "Removing slaves and bringing unconfigured bonding interface $bond_intf down"
                 $FWBDEBUG $IP link set $bond_intf up
                 $FWBDEBUG $IFENSLAVE  -d $bond_intf $slaves
                 $FWBDEBUG $IP link set $bond_intf down
             }
         done
}

check_file() {
    test -r "$2" || {
        echo "Can not find file $2 referenced by address table object $1"
        exit 1
    }
}

check_run_time_address_table_files() {
    :
    
}

load_modules() {
    :
    OPTS=$1
    MODULES_DIR="/lib/modules/`uname -r`/kernel/net/"
    MODULES=$(find $MODULES_DIR -name '*conntrack*' \! -name '*ipv6*'|sed  -e 's/^.*\///' -e 's/\([^\.]\)\..*/\1/')
    echo $OPTS | grep -q nat && {
        MODULES="$MODULES $(find $MODULES_DIR -name '*nat*'|sed  -e 's/^.*\///' -e 's/\([^\.]\)\..*/\1/')"
    }
    echo $OPTS | grep -q ipv6 && {
        MODULES="$MODULES $(find $MODULES_DIR -name nf_conntrack_ipv6|sed  -e 's/^.*\///' -e 's/\([^\.]\)\..*/\1/')"
    }
    for module in $MODULES; do 
        if $LSMOD | grep ${module} >/dev/null; then continue; fi
        $MODPROBE ${module} ||  exit 1 
    done
}

verify_interfaces() {
    :
    echo "Verifying interfaces: bond0 eth2 eth3 bond1 lo eth6 eth0 eth1 bond0.2 bond0.1 eth2.201 eth2.202 eth4 eth5"
    for i in bond0 eth2 eth3 bond1 lo eth6 eth0 eth1 bond0.2 bond0.1 eth2.201 eth2.202 eth4 eth5 ; do
        $IP link show "$i" > /dev/null 2>&1 || {
            log "Interface $i does not exist"
            exit 1
        }
    done
}

prolog_commands() {
    echo "Running prolog script"
    
}

epilog_commands() {
    echo "Running epilog script"
    
}

run_epilog_and_exit() {
    epilog_commands
    exit $1
}

configure_interfaces() {
    :
    # Configure interfaces
    load_bonding_module "bond0 bond1" max_bonds=2 mode=802.3ad xmit_hash_policy=layer2 miimon=100
    update_bonding bond0 eth0 eth1
    update_bonding bond1 eth4 eth5
    clear_bonding_except_known bond0 bond1
    update_vlans_of_interface "bond0 bond0.2 bond0.1"
    update_vlans_of_interface "eth2 eth2.201 eth2.202"
    clear_vlans_except_known bond0.2@bond0 bond0.1@bond0 eth2.201@eth2 eth2.202@eth2
    update_addresses_of_interface "eth3 192.0.2.11/24" ""
    update_addresses_of_interface "bond1 192.168.11.11/24" ""
    update_addresses_of_interface "lo 127.0.0.1/8" ""
    update_addresses_of_interface "eth6 192.168.6.11/24" ""
    update_addresses_of_interface "bond0.2 192.168.2.11/24" ""
    update_addresses_of_interface "bond0.1 192.168.1.11/24" ""
    update_addresses_of_interface "eth2.201 192.168.201.11/24" ""
    update_addresses_of_interface "eth2.202 192.168.202.11/24" ""
    clear_addresses_except_known_interfaces bond0 eth2 eth3 bond1 lo eth6 eth0 eth1 bond0.2 bond0.1 eth2.201 eth2.202 eth4 eth5
}

script_body() {
    echo 1 > /proc/sys/net/ipv4/ip_dynaddr 
     echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter 
     echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route 
     echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects 
     echo 1 > /proc/sys/net/ipv4/conf/all/log_martians 
     echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts 
     echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all 
     echo 0 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses 
     echo 1 > /proc/sys/net/ipv4/tcp_syncookies 
    echo 250000 > /proc/sys/net/ipv4/netfilter/ip_conntrack_max
    echo 250000 > /sys/module/ip_conntrack/parameters/hashsize
    echo 1 > /proc/sys/net/ipv4/netfilter/ip_conntrack_tcp_be_liberal 

    # ================ IPv4


    # ================ Table 'filter', automatic rules
    # accept established sessions
    $IPTABLES -A INPUT   -m state --state ESTABLISHED,RELATED -j ACCEPT 
    $IPTABLES -A OUTPUT  -m state --state ESTABLISHED,RELATED -j ACCEPT 
    $IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT 
    # drop packets that do not match any valid state and log them
    $IPTABLES -N drop_invalid
    $IPTABLES -A OUTPUT   -m state --state INVALID  -j drop_invalid 
    $IPTABLES -A INPUT    -m state --state INVALID  -j drop_invalid 
    $IPTABLES -A FORWARD  -m state --state INVALID  -j drop_invalid 
    $IPTABLES -A drop_invalid -j LOG --log-level debug --log-prefix "INVALID state -- DENY "
    $IPTABLES -A drop_invalid -j DROP















    # ============== ROUTING RULES ============== 

    TMPDIRNAME="/tmp/.fwbuilder.tempdir.$$"
    TMPFILENAME="$TMPDIRNAME/.fwbuilder.out"
    (umask 077 && mkdir $TMPDIRNAME) || exit 1

    #
    # This function stops stdout redirection
    # and sends previously saved output to terminal
    restore_script_output()
    {
      exec 1>&3 2>&1
      cat $TMPFILENAME
      rm -rf $TMPDIRNAME
    }

    # if any routing rule fails we do our best to prevent freezing the firewall
    route_command_error()
    {
      echo "Error: Routing rule $1 couldn't be activated"
      echo "Recovering previous routing configuration..."
      # delete current routing rules
      $IP route show | while read route ; do $IP route del $route ; done
      # restore old routing rules
      (IFS="
    "; for route in $oldRoutes; do (IFS=' '; $IP route add $route); done)
      echo "...done"
      restore_script_output
      epilog_commands
      exit 1
    }

    # redirect output to prevent ssh session from stalling
    exec 3>&1
    exec 1> $TMPFILENAME
    exec 2>&1

    # store previous routing configuration (sort: 'via' GW has to be
    # inserted after device routes)
    oldRoutes=$($IP route show | sort -k 2)

    echo "Deleting routing rules previously set by user space processes..."
    $IP route show | grep -v 'proto kernel' | \
        while read route ; do $IP route del $route ; done
        
    echo "Activating non-ecmp routing rules..."
    # 
    # Rule 0 (main)
    # 
    echo "Routing rule 0 (main)"
    # 
    # 
    # 
    # fw-A:Routing:0: error: Object "gw_200" used as gateway in the routing rule 0 (main) is not in the same local network as interface eth3
    # fw-A:Routing:0: error: Object "gw_200" used as gateway in the routing rule 0 (main) is not reachable because it is not in any local network of the firewall

    $IP route add default via 200.200.200.200 dev eth3 \
    || route_command_error "0 (main)"

    # 
    # Rule 1 (main)
    # 
    echo "Routing rule 1 (main)"
    # 
    # for 1410: gateway matches subnet of a vlan interface
    # 
    $IP route add 192.168.101.0/24 via 192.168.1.200 dev bond0.1 \
    || route_command_error "1 (main)"

    # 
    # Rule 2 (main)
    # 
    echo "Routing rule 2 (main)"
    # 
    # for 1410: gateway matches subnet of a vlan interface
    # 
    $IP route add 192.168.102.0/24 via 192.168.2.200 dev bond0.2 \
    || route_command_error "2 (main)"

    # 
    # Rule 3 (main)
    # 
    echo "Routing rule 3 (main)"
    # 
    # 
    # 
    $IP route add 192.168.111.0/24 via 192.168.11.200 dev bond1 \
    || route_command_error "3 (main)"

    # 
    # Rule 4 (main)
    # 
    echo "Routing rule 4 (main)"
    # 
    # for 1410: gateway matches subnet of a vlan interface
    # 
    $IP route add 192.168.211.0/24 via 192.168.201.200 dev eth2.201 \
    || route_command_error "4 (main)"

    # 
    # Rule 5 (main)
    # 
    echo "Routing rule 5 (main)"
    # 
    # for 1410: gateway matches subnet of a vlan interface
    # 
    $IP route add 192.168.212.0/24 via 192.168.202.200 dev eth2.202 \
    || route_command_error "5 (main)"


    restore_script_output
    echo "...done."
}

ip_forward() {
    :
    echo 1 > /proc/sys/net/ipv4/ip_forward
}

reset_all() {
    :
    reset_iptables_v4
}

block_action() {
    reset_all
}

stop_action() {
    reset_all
    $IPTABLES -P OUTPUT  ACCEPT
    $IPTABLES -P INPUT   ACCEPT
    $IPTABLES -P FORWARD ACCEPT
}

check_iptables() {
    IP_TABLES="$1"
    [ ! -e $IP_TABLES ] && return 151
    NF_TABLES=$(cat $IP_TABLES 2>/dev/null)
    [ -z "$NF_TABLES" ] && return 152
    return 0
}
status_action() {
    check_iptables "/proc/net/ip_tables_names"
    ret_ipv4=$?
    check_iptables "/proc/net/ip6_tables_names"
    ret_ipv6=$?
    [ $ret_ipv4 -eq 0 -o $ret_ipv6 -eq 0 ] && return 0
    [ $ret_ipv4 -eq 151 -o $ret_ipv6 -eq 151 ] && {
        echo "iptables modules are not loaded"
    }
    [ $ret_ipv4 -eq 152 -o $ret_ipv6 -eq 152 ] && {
        echo "Firewall is not configured"
    }
    exit 3
}

# See how we were called.
# For backwards compatibility missing argument is equivalent to 'start'

cmd=$1
test -z "$cmd" && {
    cmd="start"
}

case "$cmd" in
    start)
        log "Activating firewall script generated Fri Jun  3 17:29:40 2011 by vadim"
        check_tools
         prolog_commands 
        check_run_time_address_table_files
        
        load_modules " "
        configure_interfaces
        verify_interfaces
        
         reset_all 
        
        script_body
        ip_forward
        epilog_commands
        RETVAL=$?
        ;;

    stop)
        stop_action
        RETVAL=$?
        ;;

    status)
        status_action
        RETVAL=$?
        ;;

    block)
        block_action
        RETVAL=$?
        ;;

    reload)
        $0 stop
        $0 start
        RETVAL=$?
        ;;

    interfaces)
        configure_interfaces
        RETVAL=$?
        ;;

    test_interfaces)
        FWBDEBUG="echo"
        configure_interfaces
        RETVAL=$?
        ;;



    *)
        echo "Usage $0 [start|stop|status|block|reload|interfaces|test_interfaces]"
        ;;

esac

exit $RETVAL