Subversion Repositories ALCASAR

Rev

Rev 3170 | Rev 3190 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log

#!/bin/bash
# $Id: alcasar-iptables.sh 3177 2024-03-01 18:32:19Z rexy $
# Script de mise en place des regles du parefeu d'Alcasar (mode normal)
# This script writes the netfilter rules for ALCASAR
# Rexy - 3abtux - CPN
#
# Reminders
# There are four channels for log :
#       1 tracability of the consultation equipment with The 'Netflow' kernel module (iptables target = NETFLOW);
#       2 protection of ALCASAR with the Ulog group 1 (default group)
#       3 SSH on ALCASAR with the Ulog group 2;
#       4 extern access attempts on ALCASAR with the Ulog group 3.
# The bootps/dhcp (67) port is always open on tun0/INTIF by coova
CONF_FILE="/usr/local/etc/alcasar.conf"
EXTIF=`grep ^EXTIF= $CONF_FILE|cut -d"=" -f2`                           # EXTernal InterFace
INTIF=`grep ^INTIF= $CONF_FILE|cut -d"=" -f2`                           # INTernal InterFace
TUNIF="tun0"                                                            # listen device for chilli daemon
private_ip_mask=`grep ^PRIVATE_IP= $CONF_FILE|cut -d"=" -f2`
private_ip_mask=${private_ip_mask:=192.168.182.1/24}
PRIVATE_IP=`echo $private_ip_mask | cut -d"/" -f1`                      # ALCASAR LAN IP address
private_network=`/bin/ipcalc -n $private_ip_mask|cut -d"=" -f2`         # LAN IP address (ie.: 192.168.182.0)
private_prefix=`/bin/ipcalc -p $private_ip_mask|cut -d"=" -f2`          # LAN prefix (ie. 24)
PRIVATE_NETWORK_MASK=$private_network/$private_prefix                   # LAN IP address + prefix (192.168.182.0/24)
public_ip_mask=`grep ^PUBLIC_IP= $CONF_FILE|cut -d"=" -f2`              # ALCASAR WAN IP address
dhcp_on_extif="off"
if [[ "$public_ip_mask" == "dhcp" ]]
then
        dhcp_on_extif="on"
        PTN="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([012]?[0-9]|3[0-2])\b"
        public_ip_mask=`ip addr show $EXTIF | egrep -o $PTN`
fi
PUBLIC_IP=`echo $public_ip_mask | cut -d"/" -f1`
dns1=`grep ^DNS1= $CONF_FILE|cut -d"=" -f2`
dns2=`grep ^DNS2= $CONF_FILE|cut -d"=" -f2`
dns1=${dns1:=208.67.220.220}
dns2=${dns2:=208.67.222.222}
DNSSERVERS="$dns1,$dns2"                                                # first and second public DNS servers
INT_DNS_IP=`grep INT_DNS_IP $CONF_FILE|cut -d"=" -f2`                   # Adresse du serveur DNS interne
INT_DNS_ACTIVE=`grep INT_DNS_ACTIVE $CONF_FILE|cut -d"=" -f2`   # Activation de la redirection DNS interne
BL_IP_CAT="/usr/local/share/iptables-bl-enabled"                        # categories files of the BlackListed IP
WL_IP_CAT="/usr/local/share/iptables-wl-enabled"                        # categories files of the WhiteListed IP
TMP_users_set_save="/tmp/users_set_save"                                # tmp file for backup users set
TMP_set_save="/tmp/ipset_save"                                          # tmp file for blacklist and whitelist creation
TMP_ip_gw_save="/tmp/ipset_ip_gw_save"                          # tmp file for already connected ips
SSH_LAN=`grep ^SSH_LAN= $CONF_FILE|cut -d"=" -f2`                       # SSH LAN port
SSH_LAN=${SSH_LAN:=0}
SSH_WAN=`grep ^SSH_WAN= $CONF_FILE|cut -d"=" -f2`               # SSH WAN port
SSH_WAN=${SSH_WAN:=0}
SSH_WAN_ADMIN_FROM=`grep ^SSH_ADMIN_FROM= $CONF_FILE|cut -d"=" -f2|cut -d"/" -f2`
SSH_WAN_ADMIN_FROM=${SSH_WAN_ADMIN_FROM:="0.0.0.0"}
SSH_WAN_ADMIN_FROM=$([ "$SSH_WAN_ADMIN_FROM" == "0.0.0.0" ] && echo "0.0.0.0/0" || echo "$SSH_WAN_ADMIN_FROM" )
SSH_LAN_ADMIN_FROM=`grep ^SSH_ADMIN_FROM= $CONF_FILE|cut -d"=" -f2|cut -d"/" -f1`
SSH_LAN_ADMIN_FROM=${SSH_LAN_ADMIN_FROM:="0.0.0.0"}
SSH_LAN_ADMIN_FROM=$([ "$SSH_LAN_ADMIN_FROM" == "0.0.0.0" ] && echo "$PRIVATE_NETWORK_MASK" || echo "$SSH_LAN_ADMIN_FROM" )
IPTABLES="/sbin/iptables"
REHABILITED_IP="/etc/e2guardian/lists/exceptioniplist"
ALLOWED_SITES="/usr/local/etc/alcasar-site-direct"                      # WEB Sites allowed for all (no av and no filtering for av_bl users)
MULTIWAN=`grep ^MULTIWAN $CONF_FILE|cut -d"=" -f2`
PROXY=`grep ^PROXY= $CONF_FILE|cut -d"=" -f2`
PROXY_IP=`grep ^PROXY_IP= $CONF_FILE|cut -d"=" -f2`
nb_gw=`grep ^WAN $CONF_FILE|wc -l`
interlan=`grep ^INTERLAN= $CONF_FILE|cut -d"=" -f2`
interlan=${interlan:=off}

# Allow requests to internal DNS if activated
if [ "$INT_DNS_ACTIVE" = "on" ]
then
        DNSSERVERS="$DNSSERVERS,$INT_DNS_IP"
fi

#ipset name list for load_balancing
gw_list="gw0"
if [ "$MULTIWAN" == "on" ] || [ "$MULTIWAN" == "On" ]; then
        for ((i=1 ; i<=$nb_gw ; i++)); do
                gw_list="${gw_list} gw$i"
        done
fi

# Sauvegarde des SET des utilisateurs connectés si ils existent
# Saving SET of connected users if it exists
ipset list not_filtered 1>/dev/null 2>&1
if [ $? -eq 0 ];
then
        ipset save not_filtered > $TMP_users_set_save
        ipset save av >> $TMP_users_set_save
        ipset save av_bl >> $TMP_users_set_save
        ipset save av_wl >> $TMP_users_set_save
        ipset save proto_0 >> $TMP_users_set_save
        ipset save proto_1 >> $TMP_users_set_save
        ipset save proto_2 >> $TMP_users_set_save
        ipset save proto_3 >> $TMP_users_set_save
fi

# Sauvegarde de la liste de toutes les IP déjà connectées pour les réintégrer dans le load balancing
# Saving all of the already connected IP in order to put them back in the load balancing after
if [ ! -f $TMP_ip_gw_save ];then
        # Save only if alcasar-network.sh --save has not been executed before
        for i in $gw_list;do
                ipset list $i 1>/dev/null 2>&1
                if [ $? -eq 0 ]
                then
                        # the cut -d":" -f5 deletes all the lines with a :, i.e all the lines execpt the members
                        ipset list $i | cut -d":" -f5 | sed '/^[[:space:]]*$/d' >> $TMP_ip_gw_save
                fi
        done
fi

# Chargement de la sonde NetFlow (module noyau ipt_NETFLOW)
# loading of NetFlow probe (ipt_NETFLOW kernel module)
modprobe ipt_NETFLOW destination=127.0.0.1:2055

# Effacement des règles existantes
# Flush all existing rules
$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -t mangle -F
$IPTABLES -F INPUT
$IPTABLES -F FORWARD
$IPTABLES -F OUTPUT

# Suppression des chaines utilisateurs sur les tables filter et nat
# Flush non default rules on filter and nat tables
$IPTABLES -X
$IPTABLES -t nat -X

# Stratégies par défaut
# Default policies
$IPTABLES -P INPUT DROP
$IPTABLES -P FORWARD DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -t nat -P PREROUTING ACCEPT
$IPTABLES -t nat -P POSTROUTING ACCEPT
$IPTABLES -t nat -P OUTPUT ACCEPT

#############################
#          IPSET            #
#############################
# destruction de tous les SET
# destroy all SET
ipset flush
ipset destroy

###### BL set  ###########
# Calcul de la taille / Compute the length
bl_set_length=$(wc -l $BL_IP_CAT/* | awk '{print $1}' | tail -n 1)
# Chargement / loading
echo "create bl_ip_blocked hash:net family inet hashsize 1024 maxelem $bl_set_length" > $TMP_set_save
for category in `ls -1 $BL_IP_CAT | cut -d '@' -f1`
do
        cat $BL_IP_CAT/$category >> $TMP_set_save
done
ipset -! restore < $TMP_set_save
rm -f $TMP_set_save
# Suppression des ip réhabilitées / Removing of rehabilitated ip
for ip in $(cat $REHABILITED_IP)
do
        ipset -q del bl_ip_blocked $ip
done

# ipset for exception web sites (usefull for filtered users = av_bl)
ipset create site_direct hash:net hashsize 1024
for site in $(cat $ALLOWED_SITES)
do
    ipset add site_direct $site
done

###### WL set  ###########
# taille fixe, car peuplé par unbound / fixe length due to unbound dynamic loading
wl_set_length=65536
# Chargement Loading
echo "create wl_ip_allowed hash:net family inet hashsize 1024 maxelem $wl_set_length" > $TMP_set_save
#get ip-wl files from ACC
for category in `ls -1 $WL_IP_CAT |cut -d '@' -f1`
do
        cat $WL_IP_CAT/$category >> $TMP_set_save
done
ipset -! restore < $TMP_set_save
rm -f $TMP_set_save

# Restoration des SET des utilisateurs connectés si ils existent sinon création des SET
# Restoring the connected users SETs if available, otherwise creating SETs
if [ -e $TMP_users_set_save ];
then
        ipset -! restore < $TMP_users_set_save
        rm -f $TMP_users_set_save
else
        ipset create not_filtered hash:ip hashsize 1024
        ipset create av hash:ip hashsize 1024
        ipset create av_bl hash:ip hashsize 1024
        ipset create av_wl hash:ip hashsize 1024
        # pour les filtrages de protocole par utilisateur / For network protocols filtering by user
        ipset create proto_0 hash:ip hashsize 1024
        ipset create proto_1 hash:ip hashsize 1024
        ipset create proto_2 hash:ip hashsize 1024
        ipset create proto_3 hash:ip hashsize 1024
fi

#ipsets for load balancing
for i in $gw_list; do
        ipset create $i hash:ip
done
cat $TMP_ip_gw_save | while read ip; do
        gw_min="gw0"
        weight=`grep ^PUBLIC_WEIGHT= $CONF_FILE | cut -d"=" -f2`
        already=`ipset list $gw_min | grep Number\ of\ entries: | cut -d":" -f2`
        #The *1000 is here to avoid working on floats in bash
        gw_min_value=$((1000 * $already / $weight))
        i=1
        for gw in $gw_list;do
                if [ "$gw" != "gw0" ]; then
                        weight=`grep ^WAN$i= $CONF_FILE | awk -F'"' '{ print $2 }' | awk -F ',' '{ print $2 }'`
                        already=`ipset list $gw | grep Number\ of\ entries: | cut -d":" -f2`
                        value=$((1000 * $already / $weight))
                        if [ $value -lt $gw_min_value ]
                        then
                                gw_min_value=$value
                                gw_min=$gw
                        fi
                        i=$(($i+1))
                fi
        done
        ipset add $gw_min $ip
done
rm -f $TMP_ip_gw_save

#############################
#       PREROUTING          #
#############################
# Marquage (et journalisation) des paquets qui tentent d'accéder directement aux ports d'écoute du proxy HTTP/HTTPS (E2Guardian) pour pouvoir les rejeter en INPUT
# Mark (and log) the direct attempts to E2guardian listen ports in order to REJECT them in INPUT rules
# 8080 = ipset av_bl
$IPTABLES -A PREROUTING -t nat -i $TUNIF -p tcp -d $PRIVATE_IP -m tcp --dport 8080 -j NFLOG --nflog-group 1 --nflog-prefix "RULE direct-proxy -- DENY "
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp -m tcp --dport 8080 -j MARK --set-mark 1
# 8090 = ipset av_wl + av
$IPTABLES -A PREROUTING -t nat -i $TUNIF -p tcp -d $PRIVATE_IP -m tcp --dport 8090 -j NFLOG --nflog-group 1 --nflog-prefix "RULE direct-proxy -- DENY "
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp -m tcp --dport 8090 -j MARK --set-mark 2
# 8443 = tranparent HTTPS for ipsets av_bl + av_wl + av (future version)
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -p tcp -d $PRIVATE_IP -m tcp --dport 8443 -j NFLOG --nflog-group 1 --nflog-prefix "RULE direct-proxy -- DENY "
#$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp -m tcp --dport 8443 -j MARK --set-mark 6

# Marquage des paquets qui tentent d'accéder directement aux ports d'écoute DNS (UNBOUND) pour pouvoir les rejeter en INPUT
# Mark the direct attempts to DNS ports (UNBOUND) in order to REJECT them in INPUT rules
# 54 = ipset av_bl
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp --dport 54 -j MARK --set-mark 3
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p udp --dport 54 -j MARK --set-mark 3
# 55 = ipset av_wl
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp --dport 55 -j MARK --set-mark 4
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p udp --dport 55 -j MARK --set-mark 4
# 56 = blackall
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p tcp --dport 56 -j MARK --set-mark 5
$IPTABLES -A PREROUTING -t mangle -i $TUNIF -d $PRIVATE_IP -p udp --dport 56 -j MARK --set-mark 5

# redirection DNS des usagers
# users DNS redirection
# 54 = ipset av_bl
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -p udp --dport domain -j REDIRECT --to-port 54
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -p tcp --dport domain -j REDIRECT --to-port 54
# 55 = ipset av_wl
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -p udp --dport domain -j REDIRECT --to-port 55
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -p tcp --dport domain -j REDIRECT --to-port 55
# 53 = all other users
$IPTABLES -A PREROUTING -t nat -i $TUNIF ! -d $PRIVATE_IP -p udp --dport domain -j REDIRECT --to-port 53
$IPTABLES -A PREROUTING -t nat -i $TUNIF ! -d $PRIVATE_IP -p tcp --dport domain -j REDIRECT --to-port 53

# Redirection HTTP des usagers 'av_bl' cherchant à joindre les IP de la blacklist vers ALCASAR (page 'accès interdit')
# Redirect HTTP of 'av_bl' users who want blacklist IP to ALCASAR ('access denied' page)
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p tcp --dport http -j REDIRECT --to-port 80

# Redirection HTTP des usagers 'av_wl' cherchant à joindre les IP qui ne sont pas dans la WL vers ALCASAR (page 'accès interdit')
# Redirect HTTP of 'av_wl' users who want IP not in the WL to ALCASAR ('access denied' page)
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -m set ! --match-set wl_ip_allowed dst -p tcp --dport http -j REDIRECT --to-port 80

# Journalisation des usagers "av_bl + av_wl + av" (paquets SYN uniquement). Les autres protocoles sont journalisés en FORWARD par netflow.
# accounting of "av_bl + av_wl + av"  users (only syn packets). Other protocols are logged in FORWARD by netflow
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src ! -d $PRIVATE_IP -p tcp --dport http -m conntrack --ctstate NEW -j NFLOG --nflog-group 1 --nflog-prefix "RULE F_http -- ACCEPT "
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src ! -d $PRIVATE_IP -p tcp --dport http -m conntrack --ctstate NEW -j NFLOG --nflog-group 1 --nflog-prefix "RULE F_http -- ACCEPT "
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av src ! -d $PRIVATE_IP -p tcp --dport http -m conntrack --ctstate NEW -j NFLOG --nflog-group 1 --nflog-prefix "RULE F_http -- ACCEPT "

# Redirection des requêtes HTTP des usagers "av_bl + av_wl + av" vers E2guardian
# Redirect outbound "av_bl + av_wl +av" users HTTP requests to E2guardian
# 8080 = ipset av_bl
#$IPTABLES -A PREROUTING -t mangle -i $TUNIF -m set --match-set av_bl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP  -p tcp --dport http -j MARK --set-mark 200
$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP  -p tcp --dport http -j REDIRECT --to-port 8080
# 8090 = ipset av_wl & av
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src ! -d $PRIVATE_IP -p tcp --dport http -j REDIRECT --to-port 8090
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av src ! -d $PRIVATE_IP -p tcp --dport http -j REDIRECT --to-port 8090

# Redirection des requêtes HTTPS sortantes des usagers av_bl + av_wl + av vers E2Guardian (in a future version - don't forget to set E2guardian as a tranparent HTTPS proxy)
# Redirect outbound HTTPS requests of av_bl + av_wl + av users to E2Guardian
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_bl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP  -p tcp --dport https -j REDIRECT --to-port 8443
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av_wl src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP  -p tcp --dport https -j REDIRECT --to-port 8443
#$IPTABLES -A PREROUTING -t nat -i $TUNIF -m set --match-set av src -m set ! --match-set site_direct dst ! -d $PRIVATE_IP  -p tcp --dport https -j REDIRECT --to-port 8443

# Redirection des requêtes NTP vers le serveur NTP local
# Redirect NTP request in local NTP server
$IPTABLES -A PREROUTING -t nat -i $TUNIF -s $PRIVATE_NETWORK_MASK ! -d $PRIVATE_IP -p udp --dport ntp -j REDIRECT --to-port 123

#Récupération de la marque associée à une gw pour chaque connection
$IPTABLES -A PREROUTING -t mangle -j CONNMARK --restore-mark

if [ "$PROXY" == "on" ] || [ "$PROXY" == "On" ];then
        $IPTABLES -A PREROUTING -t nat -i $TUNIF ! -d $PRIVATE_IP -p tcp -m multiport --dports http,https -j DNAT --to-destination $PROXY_IP
fi

#Marquage pour le load balancing
if [ "$MULTIWAN" == "on" ] || [ "$MULTIWAN" == "On" ]; then
        temp_index=200
        for i in $gw_list; do
                $IPTABLES -A PREROUTING -t mangle -i $TUNIF -m set --match-set $i src -j MARK --set-mark $temp_index
                temp_index=$(($temp_index+1))
        done
fi

#############################
#         INPUT             #
#############################
# Tout passe sur loopback
# accept all on loopback
$IPTABLES -A INPUT -i lo -j ACCEPT
$IPTABLES -A OUTPUT -o lo -j ACCEPT

# Rejet des demandes de connexions non conformes (FIN-URG-PUSH, XMAS, NullScan, SYN-RST et NEW not SYN)
# Drop non standard connexions (FIN-URG-PUSH, XMAS, NullScan, SYN-RST and NEW not SYN)
$IPTABLES -A INPUT -p tcp --tcp-flags FIN,URG,PSH FIN,URG,PSH -j DROP
$IPTABLES -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
$IPTABLES -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
$IPTABLES -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
$IPTABLES -A INPUT -p tcp -m tcp ! --syn -m conntrack --ctstate NEW -j DROP

# Si configuré, on autorise les réponses DHCP sur EXTIF
# If configured, DHCP responses are allowed on EXTIF
if [[ "$dhcp_on_extif" == "on" ]]
then
        $IPTABLES -A INPUT -i $EXTIF -p tcp --dport 68 -j ACCEPT
        $IPTABLES -A INPUT -i $EXTIF -p udp --dport 68 -j ACCEPT
fi

# On rejette les trame en broadcast et en multicast sur EXTIF (évite leur journalisation)
# Drop broadcast & multicast on EXTIF to avoid log
$IPTABLES -A INPUT -m addrtype --dst-type BROADCAST,MULTICAST -j DROP

# On autorise les retours de connexions légitimes par INPUT
# Conntrack on INPUT
$IPTABLES -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# On interdit les connexions directes aux ports d'écoute d'E2Guardian. Les packets concernés ont été marqués et loggués dans la table mangle (PREROUTING)
# Deny direct connections on E2Guardian listen ports. The concerned paquets have been marked and logged in mangle table (PREROUTING)
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 8080 -m mark --mark 1 -j REJECT --reject-with tcp-reset # av_bl
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 8090 -m mark --mark 2 -j REJECT --reject-with tcp-reset # av_wl + av
#$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 8443 -m mark --mark 6 -j REJECT --reject-with tcp-reset # av_bl + av_wl + av (future version)

# On autorise les connexions HTTP/HTTPS légitimes vers E2Guardian
# Allow HTTP connections to E2Guardian
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -p tcp --dport 8080 -m conntrack --ctstate NEW --syn -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -p tcp --dport 8090 -m conntrack --ctstate NEW --syn -j ACCEPT
#$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -p tcp --dport 8443 -m conntrack --ctstate NEW --syn -j ACCEPT # (future version)

# On interdit les connexions directes aux ports d'écoupe DNS (UNBOUND). Les packets concernés ont été marqués dans la table mangle (PREROUTING)
# Deny direct connections to DNS ports (UNBOUND). The concerned paquets are marked in mangle table (PREROUTING)
$IPTABLES -A INPUT -i $TUNIF -p udp --dport 54 -m mark --mark 3 -j REJECT --reject-with icmp-port-unreachable
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 54 -m mark --mark 3 -j REJECT --reject-with tcp-reset
$IPTABLES -A INPUT -i $TUNIF -p udp --dport 55 -m mark --mark 4 -j REJECT --reject-with icmp-port-unreachable
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 55 -m mark --mark 4 -j REJECT --reject-with tcp-reset
$IPTABLES -A INPUT -i $TUNIF -p udp --dport 56 -m mark --mark 5 -j REJECT --reject-with icmp-port-unreachable
$IPTABLES -A INPUT -i $TUNIF -p tcp --dport 56 -m mark --mark 5 -j REJECT --reject-with tcp-reset

# On autorise les connexion DNS légitime
# Allow DNS connections
# ipset = av_bl
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport 54 -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 54 -j ACCEPT
# ipset = av_wl
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport 55 -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 55 -j ACCEPT
# blackall
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport 56 -j ACCEPT
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 56 -j ACCEPT

# On accepte l'accès aux services internes
# Internal services access
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport domain -j ACCEPT    # DNS
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport domain -j ACCEPT    # DNS
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p icmp --icmp-type 8 -j ACCEPT    # Réponse ping # ping responce
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p icmp --icmp-type 0 -j ACCEPT    # Requête  ping # ping request
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport https -j ACCEPT     # Pages d'authentification et MCC # authentication pages and MCC
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport http -j ACCEPT      # Page d'avertissement filtrage # Filtering warning pages
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p tcp --dport 3990:3991 -j ACCEPT # Requêtes de deconnexion usagers # Users logout requests
$IPTABLES -A INPUT -i $TUNIF -s $PRIVATE_NETWORK_MASK -d $PRIVATE_IP -p udp --dport ntp -j ACCEPT       # Serveur local de temps # local time server

# Accès au serveur SSHD si activé en LAN et WAN
# SSHD server access in LAN and WAN if enabled
if [ $SSH_LAN -gt 0 ]
        then
        $IPTABLES -A INPUT -i $TUNIF -s $SSH_LAN_ADMIN_FROM -d $PRIVATE_IP -p tcp --dport $SSH_LAN -m conntrack --ctstate NEW -j NFLOG --nflog-group 2 --nflog-prefix "RULE ssh-from-LAN -- ACCEPT"
        $IPTABLES -A INPUT -i $TUNIF -s $SSH_LAN_ADMIN_FROM -d $PRIVATE_IP -p tcp --dport $SSH_LAN -j ACCEPT
fi
if [ $SSH_WAN -gt 0 ]
        then
        $IPTABLES -A INPUT -i $EXTIF -s $SSH_WAN_ADMIN_FROM -d $PUBLIC_IP -p tcp --dport $SSH_WAN -m conntrack --ctstate NEW --syn -j NFLOG --nflog-group 2 --nflog-prefix "RULE ssh-from-WAN -- ACCEPT"
        $IPTABLES -A INPUT -i $EXTIF -s $SSH_WAN_ADMIN_FROM -d $PUBLIC_IP -p tcp --dport $SSH_WAN -j ACCEPT
fi

# Insertion de règles locales
# Here, we add local rules (i.e. VPN from Internet)
if [ -f /usr/local/etc/alcasar-iptables-local.sh ]; then
        . /usr/local/etc/alcasar-iptables-local.sh
fi

# Journalisation et rejet des connexions (autres que celles autorisées) effectuées depuis le LAN
# Deny and log on INPUT from the LAN
$IPTABLES -A INPUT -i $TUNIF -m conntrack --ctstate NEW -j NFLOG --nflog-group 3 --nflog-prefix "RULE rej-int -- REJECT "
$IPTABLES -A INPUT -i $TUNIF -p tcp -j REJECT --reject-with tcp-reset
$IPTABLES -A INPUT -i $TUNIF -p udp -j REJECT --reject-with icmp-port-unreachable

# Interdiction d'accès à INTIF (n'est utile que lorsque chilli est arrêté).
# Reject INTIF access (only when chilli is down)
$IPTABLES -A INPUT -i $INTIF -j NFLOG --nflog-group 3 --nflog-prefix "RULE Protect1 -- REJECT "
$IPTABLES -A INPUT -i $INTIF -j REJECT

# Journalisation et rejet des connexions initiées depuis le réseau extérieur (test des effets du paramètre --limit en cours)
# On EXTIF, the access attempts are log in channel 2 (we should test --limit option to avoid deny of service)
$IPTABLES -A INPUT -i $EXTIF -m conntrack --ctstate NEW -j NFLOG --nflog-group 3 --nflog-threshold 10 --nflog-prefix "RULE rej-ext -- DROP"

#############################
#        FORWARD            #
#############################

# Blocage des IPs du SET bl_ip_blocked pour le SET av_bl
# Deny IPs of the SET bl_ip_blocked for the set av_bl
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p icmp -j REJECT --reject-with icmp-host-prohibited
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p udp -j REJECT --reject-with icmp-host-prohibited
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_bl src -m set --match-set bl_ip_blocked dst -p tcp -j REJECT --reject-with tcp-reset

# Active le suivi de session
# Allow Conntrack
$IPTABLES -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Compute uamallowed IP (ie : IP address of equipments connected between ALCASAR and router like DMZ, own servers, etc.)
nb_uamallowed=`wc -l /usr/local/etc/alcasar-uamallowed | cut -d" "  -f1`
if [ $nb_uamallowed != "0" ]
then
        while read ip_allowed_line
        do
                ip_allowed=`echo $ip_allowed_line|cut -d"\"" -f2`
                $IPTABLES -A FORWARD -i $TUNIF -d $ip_allowed -m conntrack --ctstate NEW -j NETFLOW
                $IPTABLES -A FORWARD -i $TUNIF -d $ip_allowed -m conntrack --ctstate NEW -j ACCEPT
        done < /usr/local/etc/alcasar-uamallowed
fi

# filtrage protocole par utilisateur (profile 1 : http, https)
# protocols filtering for users (profil 1 : http, https)
        $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_1 src -s $PRIVATE_NETWORK_MASK -p tcp -m multiport ! --dports http,https -m conntrack --ctstate NEW -j REJECT --reject-with tcp-reset
        $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_1 src -s $PRIVATE_NETWORK_MASK -p udp -m multiport ! --dports http,https -m conntrack --ctstate NEW -j REJECT --reject-with icmp-port-unreachable

# filtrage protocole par utilisateur (profile 2 : http https smtp pop3 pop3s imap imaps ftp sftp ssh)
# protocols filtering for users (profil 2 : http https smtp pop3 pop3s imap imaps ftp sftp ssh)

        $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_2 src -s $PRIVATE_NETWORK_MASK -p tcp -m multiport ! --dports smtp,http,https,pop3,pop3s,imap,imaps,ftp,ftp-data,sftp,ssh -m conntrack --ctstate NEW -j REJECT --reject-with tcp-reset
        $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_2 src -s $PRIVATE_NETWORK_MASK -p udp -m multiport ! --dports smtp,http,https,pop3,pop3s,imap,imaps,ftp,ftp-data,sftp,ssh -m conntrack --ctstate NEW -j REJECT --reject-with icmp-port-unreachable

# filtrage protocole par utilisateur (profile 3 : personnalisable via l'ACC)
# protocols filtering for users (profil 3 : customized with ACC)
custom_tcp_protocols_list='';custom_udp_protocols_list=''
while read svc_line
do
        svc_on=`echo $svc_line|cut -b1`
        if [ $svc_on != "#" ]
        then
                svc_name=`echo $svc_line|cut -d" " -f1`
                svc_port=`echo $svc_line|cut -d" " -f2`
                if [ $svc_name = "icmp" ]
                then
                        svc_icmp="on"
                else
                        if [ "$custom_tcp_protocols_list" == "" ]
                        then
                                custom_tcp_protocols_list=$svc_port
                        else
                                custom_tcp_protocols_list=`echo $custom_tcp_protocols_list","$svc_port`
                        fi
                        udp_svc=`egrep "[[:space:]]$svc_port/udp" /etc/services|wc -l`
                        if [ $udp_svc = "1" ] # udp service exist
                        then
                                if [ "$custom_udp_protocols_list" == "" ]
                                then
                                        custom_udp_protocols_list=$svc_port
                                else
                                        custom_udp_protocols_list=`echo $custom_udp_protocols_list","$svc_port`
                                fi
                        fi
                fi
        fi
done < /usr/local/etc/alcasar-services
        if [ "$custom_tcp_protocols_list" == "" ]
        then
                $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -j REJECT
        else
                if [ "$svc_icmp" != "on" ]
                then
                        $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -p icmp -j REJECT --reject-with icmp-proto-unreachable
                fi
                $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -p tcp -m multiport ! --dports $custom_tcp_protocols_list -m conntrack --ctstate NEW -j REJECT --reject-with tcp-reset
                $IPTABLES -A FORWARD -i $TUNIF -m set --match-set proto_3 src -s $PRIVATE_NETWORK_MASK -p udp -m multiport ! --dports $custom_udp_protocols_list -m conntrack --ctstate NEW -j REJECT --reject-with icmp-port-unreachable
        fi

# On autorise (ou pas) les utilisateurs à accéder au réseau situé entre ALCASAR et le routeur Internet
# Users are allowed (or not allowed) to access the network between ALCASAR and the Internet router
if [ "$interlan" != "on" ]
then
        $IPTABLES -A FORWARD -i $TUNIF -d $public_ip_mask -j DROP
fi

# Blocage des usagers 'av_wl' cherchant à joindre les IP qui ne sont pas dans la WL
# Block 'av_wl' users who want IP not in the WL
$IPTABLES -A FORWARD -i $TUNIF -m set --match-set av_wl src -m set ! --match-set wl_ip_allowed dst -j DROP

# journalisation et autorisation des connections sortant du LAN
# Allow forward connections with log
$IPTABLES -A FORWARD -i $TUNIF -s $PRIVATE_NETWORK_MASK -m conntrack --ctstate NEW -j NETFLOW
$IPTABLES -A FORWARD -i $TUNIF -s $PRIVATE_NETWORK_MASK -m conntrack --ctstate NEW -j ACCEPT

#############################
#         OUTPUT            #
#############################
# On laisse tout sortir sur la carte interne (voir les règles suivantes pour la carte externe)
# We let everything out on INTIF (see following rules for the EXTIF)
$IPTABLES -A OUTPUT ! -o $EXTIF -j ACCEPT

# Si configuré, on autorise les requêtes DHCP sur EXTIF
# Allow DHCP requests on EXTIF if configured
if [[ "$dhcp_on_extif" == "on" ]]
then
        $IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport 67 -j ACCEPT
        $IPTABLES -A OUTPUT -o $EXTIF -p udp --dport 67 -j ACCEPT
fi

# On autorise les requêtes DNS vers les serveurs DNS identifiés
# Allow DNS requests to identified DNS servers
$IPTABLES -A OUTPUT -o $EXTIF -d $DNSSERVERS -p udp --dport domain -m conntrack --ctstate NEW -j ACCEPT

# On autorise les requêtes HTTP et HTTPS avec log Netflow (en provenance de E2guardian)
# HTTP & HTTPS requests are allowed with netflow log (from E2guardian)
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport http -j NETFLOW
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport http -j ACCEPT
#$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport https -j NETFLOW # When E2guardian will be in HTTPS transparent proxy)
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport https -j ACCEPT

# On autorise les requêtes RSYNC sortantes (maj BL de Toulouse)
# RSYNC requests are allowed (update of Toulouse BL)
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport rsync -j ACCEPT

# On autorise les requêtes FTP
# FTP requests are allowed
# modprobe nf_conntrack_ftp # no more needed with kernel > 5.15.85
# $IPTABLES -t raw -A OUTPUT -p tcp --dport ftp -j CT --helper ftp # no more needed with kernel > 5.15.85
$IPTABLES -A OUTPUT -o $EXTIF -p tcp --dport ftp -j ACCEPT
$IPTABLES -A OUTPUT -o $EXTIF -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# On autorise les requêtes NTP
# NTP requests are allowed
$IPTABLES -A OUTPUT -o $EXTIF -p udp --dport ntp -j ACCEPT

# On autorise les requêtes ICMP (ping)
# ICMP (ping) requests are allowed
$IPTABLES -A OUTPUT -o $EXTIF -p icmp --icmp-type 8 -j ACCEPT

# On autorise les requêtes LDAP
# LDAP requests are allowed
$IPTABLES -A OUTPUT -o $EXTIF -p tcp -m multiport --dports ldap,ldaps -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
$IPTABLES -A OUTPUT -o $EXTIF -p udp -m multiport --dports ldap,ldaps -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT

#############################
#       POSTROUTING         #
#############################
# Traduction dynamique d'adresse en sortie
# Dynamic NAT on EXTIF
$IPTABLES -A POSTROUTING -t nat -o $EXTIF -j MASQUERADE

#Sauvegarde de la marque associée à la connexion pour le load balancing
$IPTABLES -A POSTROUTING -t mangle -j CONNMARK --save-mark

#############################
#          FAIL2BAN         #
#############################
# Reload Fail2Ban
if systemctl -q is-active fail2ban; then
        /usr/bin/fail2ban-client ping &>/dev/null && /usr/bin/fail2ban-client -q reload &>/dev/null
fi