#!/usr/bin/env bash


# -------------
# - Settings
# -------------

ipt_conf_dir="/etc/ipt-firewall"

inc_functions_file="${ipt_conf_dir}/include_functions.conf"

load_modules_file=${ipt_conf_dir}/load_modules_ipv6.conf

conf_logging=${ipt_conf_dir}/logging_ipv6.conf
conf_interfaces=${ipt_conf_dir}/interfaces_ipv6.conf
conf_default_settings=${ipt_conf_dir}/default_settings.conf
conf_main=${ipt_conf_dir}/main_ipv6.conf
conf_post_declarations=${ipt_conf_dir}/post_declarations.conf
conf_ban_ipv6_list="${ipt_conf_dir}/ban_ipv6.list"


ip6t="$(command -v ip6tables 2>/dev/null)"

if [[ -z "$ip6t" ]] ; then
   echo ""
   echo -e "\tip6tables was not found on this server!"
   echo
   echo -e "\tFirewall Script was stopped!"
   echo
   exit 1
fi


# -------------
# - Load Default Settings and Functions
# -------------

if [[ ! -f "$conf_default_settings" ]]; then
   fatal "Missing configuration for default_settings - file '$conf_default_settings'"
else
   source $conf_default_settings
fi

if [[ ! -f "$inc_functions_file" ]] ; then
   echo ""
   echo -e "\tMissing include file '$inc_functions_file'"
   echo
   echo -e "\tFirewall Script was stopped!"
   echo
   exit 1
else
   source $inc_functions_file
fi


# -------------
# - Some checks and preloads..
# -------------

# Check IPv6 presence
if detect_ipv6; then
  IPV6_ACTIVE=1
  if has_ipv6_addr; then
   info "IPv6 enabled (global address present)."
  else
    warn "IPv6 enabled but no global address configured yet."
  fi
else
  IPV6_ACTIVE=0
  warn "IPv6 disabled via sysctl."
fi

# Fail if ip6tables points to legacy (helps avoid surprises on dual-stack hosts / fail2ban)
if command -v ip6tables >/dev/null 2>&1; then
   if ! ip6tables --version 2>/dev/null | grep -q "nf_tables"; then
      echo ""
      echo "ERROR: ip6tables is NOT using nf_tables backend (ip6tables-nft)."
      echo "Fix (on the host, as root):"
      echo "  update-alternatives --set ip6tables /usr/sbin/ip6tables-nft"
      echo ""
      echo "Current: $(ip6tables --version 2>/dev/null || echo 'unknown')"
      exit 1
   fi
fi


# -------------
# --- Ensure required modules for this script (best effort; host-side in containers)
# -------------


echo
echononl "\tEnsure required modules are loaded.."
if is_container ; then
   echo_skipped
else

   ensure_mod nf_conntrack
   ensure_mod nf_nat
   ensure_mod nf_conntrack_ftp
   ensure_mod nf_nat_ftp
   ensure_mod xt_recent
   ensure_mod xt_hashlimit
   ensure_mod xt_connlimit
   ensure_mod xt_owner
   ensure_mod xt_helper
   ensure_mod br_netfilter

   echo_done
fi


# Disable automatic conntrack helper assignment (keep explicit CT --helper rules)
if ! is_container; then
   sysctl -w net.netfilter.nf_conntrack_helper=0 >/dev/null 2>&1 || true
fi

if [[ ! -f "$conf_logging" ]]; then
   fatal "Missing configuration for logging - file '$conf_logging'"
else
   source $conf_logging
fi

if [[ ! -f "$conf_interfaces" ]]; then
   fatal "Missing interface configurations  - file '$conf_interfaces'"
else
   source $conf_interfaces
fi

if [[ ! -f "$conf_main" ]]; then
   fatal "Missing main configurations  - file '$conf_main'"
else
   source $conf_main
fi

if [[ ! -f "$conf_post_declarations" ]]; then
   fatal "Missing post declarations  - file '$conf_post_declarations'"
else
   source $conf_post_declarations
fi



echo
echo -e "\033[37m\033[1m\tStarting firewall iptables (IPv6)..\033[m"
echo


# -------------
# --- Activate IP Forwarding
# -------------

if ! is_container ; then

   # ---
   # - Disable ip forwarding between interfaces
   # ---
   if $kernel_forward_between_interfaces ; then
      echononl "\tActivate Forwarding.."
      echo 1 > /proc/sys/net/ipv6/conf/all/forwarding
   else
      echononl "\t\033[33m\033[1mDisable Forwarding..\033[m"
      echo 0 > /proc/sys/net/ipv6/conf/all/forwarding
   fi

   echo_done

fi

# -------------
# --- Adjust Kernel Parameters (Security/Tuning)
# -------------

echononl "\tAdjust Kernel Parameters (Security/Tuning).."

if ! is_container ; then

   # ---
   # - Deactivate Source Routed Packets
   # ---
   for asr in /proc/sys/net/ipv6/conf/*/accept_source_route; do
      if $kernel_deactivate_source_route ; then
         echo 0 > $asr
      fi
   done


   # ---
   # -  Deactivate sending ICMP redirects
   # ---
   if $kernel_dont_accept_redirects ; then
      echo "0" > /proc/sys/net/ipv6/conf/all/accept_redirects
   fi

   echo_done # Adjust Kernel Parameters (Security/Tuning)
else
   echo_skipped

fi # if ! is_container



# -------------
# --- Prevent bridged traffic getting pushed through the host's iptables rules
# -------------

echo
echononl "\tDo not firewall bridged / LX Gust System traffic"

if ${do_not_firewall_bridged_traffic} || ${do_not_firewall_lx_guest_systems} ; then

   if ! is_container; then

      _done=false

      for _dev in ${ext_if_arr[@]} ; do

         # Try to detect  virtual interfaces (veth*)) and the master interface 
         # of the given bridge  dynamically
         #
         #     ports="$(get_bridge_ports "$br")"
         #
         # or directly here:
         #
         # ports="$(ip -o link show master "${_dev}" 2>/dev/null | awk -F': ' '{print $2}')"
         #
         #     ports="$(ip -o link show master "${_dev}" 2>/dev/null | awk -F': ' '{print $2}')"
         #
         ports="$(ip -o link show master "${_dev}" 2>/dev/null | awk -F': ' '{print $2}')"

         for _port in $ports ; do
            $ip6t -A FORWARD -i "${_port}" -j ACCEPT
            $ip6t -A FORWARD -o "${_port}" -j ACCEPT
            _done=true
         done

      done

      if ! ${_done} ; then
         $ip6t -A FORWARD -i veth+ -j ACCEPT
         $ip6t -A FORWARD -o veth+ -j ACCEPT
      fi

      echo_done
   else
      echo_skipped
   fi
else
   echo_skipped
fi


echononl "\tTake care 'net.bridge.bridge-nf-call-ip6tables' is set to '1'.."
if ${do_not_firewall_bridged_traffic} || ${do_not_firewall_lx_guest_systems} ; then

   if ! is_container; then

      _bridge_sysctl_ok=true

      # IPv6: keep bridge netfilter on, but bypass host filtering for container ports
      # (do NOT set bridge-nf-call-ip6tables=0)
      sysctl -w net.bridge.bridge-nf-call-ip6tables=1 >/dev/null 2>&1 || _bridge_sysctl_ok=false

      if ${_bridge_sysctl_ok} ; then
         echo_done
      else
         echo_failed
      fi

   else
      echo_skipped
   fi
fi



# ------------- Fail2ban handling (do not stop/start; keep bans stable) -------------
#
echo
echononl "\tCheck presence and configuration of Fail2ban .."
echo_done
if ! has_fail2ban ; then
   warn "Fail2ban is not installed.."
elif ! fail2ban_running ; then
   warn "Fail2ban is installed but not running.."
else
   CURRENT_BANACTION=$(grep -E '^\s*banaction\s*=' "$FAIL2BAN_CONFIG_FILE" | head -1 | tr -d ' ' | cut -d'=' -f2)
   if [[ -n ${CURRENT_BANACTION} ]] ; then
      if [ "$CURRENT_BANACTION" = "nftables" ]; then
         info "Fail2ban is running, banaction is et to nftables."
      else
         warn "Change banaction from ${CURRENT_BANACTION} to \033[1mbanaction=nftables\033[m"
      fi
   else
      warn "banaction seems not to be configured. Take care that \033[1mbanaction=nftables\033[m"
   fi
   FAIL2BAN_WAS_RUNNING=true
fi
#
# ------------- Ende: Fail2ban handling (do not stop/start; keep bans stable) -------------


# -------------
# --- Set default policies / Flush Rules
# -------------


echo
echononl "\tFlushing firewall iptable (IPv6).."

# - default policies
# -
$ip6t -P INPUT ACCEPT
$ip6t -P OUTPUT ACCEPT
$ip6t -P FORWARD ACCEPT

## - flush chains
## -
$ip6t -F
$ip6t -F INPUT
$ip6t -F OUTPUT
$ip6t -F FORWARD
$ip6t -F -t mangle
$ip6t -F -t nat
$ip6t -F -t raw
$ip6t -X
$ip6t -Z

echo_done # Flushing firewall iptable (IPv6)..
echo


echononl "\tMasquerade (NAT) interfaces.."
if [[ ${#nat_device_arr[@]} -gt 0 ]] && $kernel_activate_forwarding ; then
   for _dev in ${nat_device_arr[@]} ; do
      $ip6t -t nat -A POSTROUTING -o $_dev -j MASQUERADE
   done
   echo_done
else
   echo_skipped
fi
echo

# -------------
# ---- Log given IP Addresses
# -------------

echononl "\tLog given IPv6 Addresses"
if [[ ${#log_ip_arr[@]} -gt 0 ]]; then
   for _ip in ${log_ip_arr[@]} ; do
      $ip6t -A INPUT -s $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix $_ip IN: "
      $ip6t -A OUTPUT -d $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix $_ip OUT: "
      $ip6t -A FORWARD -s $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix $_ip FORWARD FROM: "
      $ip6t -A FORWARD -d $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix $_ip FORWARD TO: "
   done

   echo_done
else
   echo_skipped
fi



# -------------
# ------------ Stopping firewall if only flushing was requested (parameter flush)
# -------------

case $1 in
   flush)
      echo
      echo -e "\t\033[37m\033[1mFlushing firewall was requested. No more rules..\033[m"
      echo
      exit 0;;
esac


# ---
# - Permit all traffic through WireGuard lines
# ---
echononl "\tPermit all traffic through WireGuard lines.."
for _wg_if in ${wg_if_arr[@]} ; do
   $ip6t -A INPUT -i $_wg_if -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -i $_wg_if -j ACCEPT
   fi
done
echo_done


# ---
# - Permit all traffic through VPN lines
# ---
echononl "\tPermit all traffic through VPN lines.."
for _vpn_if in ${vpn_if_arr[@]} ; do
   $ip6t -A INPUT -i $_vpn_if -m conntrack --ctstate NEW -j ACCEPT
   $ip6t -A OUTPUT -o $_vpn_if -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -i $_vpn_if -m conntrack --ctstate NEW -j ACCEPT
      $ip6t -A FORWARD -o $_vpn_if -m conntrack --ctstate NEW -j ACCEPT
   fi
done
echo_done



# -------------
# --- Pass through Devices Interfaces (not firewalled)
# -------------

echononl "\tPass through Devices (not firewalled)"
if [[ ${#unprotected_if_arr[@]} -gt 0 ]]; then
   for _dev in ${unprotected_if_arr[@]} ; do
      if $log_unprotected || $log_all ; then
         $ip6t -t mangle -A PREROUTING -i $_dev -j $LOG_TARGET $tag_log_prefix "$log_prefix Not firewalled ${_dev}: "
         $ip6t -A OUTPUT -o $_dev -j $LOG_TARGET $tag_log_prefix "$log_prefix Not firewalled ${_dev}: "
         $ip6t -A INPUT -i $_dev -j $LOG_TARGET $tag_log_prefix "$log_prefix Not firewalled ${_dev}: "
         $ip6t -A FORWARD -o $_dev -j $LOG_TARGET $tag_log_prefix "$log_prefix Not firewalled ${_dev}: "
      fi
      $ip6t -t mangle -A PREROUTING -i $_dev -j ACCEPT
      $ip6t -A OUTPUT -o $_dev -j ACCEPT
      $ip6t -A INPUT -i $_dev -j ACCEPT
      $ip6t -A FORWARD -o $_dev -j ACCEPT
   done
   echo_done
else
   echo_skipped
fi


# ---
# - Allow Forwarding certain private Addresses
# ---

echononl "\tAllow forwarding (private) IPs / IP-Ranges.."
if [[ ${#forward_private_ip_arr[@]} -gt 0 ]] ; then
   for _ip in ${forward_private_ip_arr[@]}; do
      if $log_forwarding_priv_ip || $log_all ; then
         $ip6t -t mangle -A PREROUTING -d $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix Accept priv ip $_ip: "
         $ip6t -t mangle -A PREROUTING-s $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix Accept priv ip $_ip: "
      fi
      $ip6t -t mangle -A PREROUTING -d $_ip -j ACCEPT
      $ip6t -t mangle -A PREROUTING-s $_ip -j ACCEPT
   done
   echo_done
else
   echo_skipped
fi



# -------------
# --- Block IPs / Networks / Interfaces
# -------------
echononl "\tBlock IPs / Networks / Interfaces.."


# ---
# - Block IPs
# ---

for _ip in $blocked_ips ; do
   for _dev in ${ext_if_arr[@]} ; do
      if $log_blocked_ip || $log_all ; then
         $ip6t -A INPUT -i $_dev -s $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked ${_ip}: "
         if $kernel_forward_between_interfaces ; then
            $ip6t -A FORWARD -i $_dev -s $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked ${_ip}: "
         fi
      fi
      $ip6t -A INPUT -i $_dev -s $_ip -j DROP
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -i $_dev -s $_ip -j DROP
      fi
   done
done


# ---
# - Block Interfaces
# ---

for _if in ${blocked_if_arr[@]} ; do
   if $log_blocked_if || $log_all ; then
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -i $_if -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked IF ${_if}: "
         $ip6t -A FORWARD -o $_if -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked IF ${_if}: "
      fi
      $ip6t -A INPUT -i $_if -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked IF ${_if}: "
      $ip6t -A OUTPUT -o $_if -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked IF ${_if}: "
   fi
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -i $_if -j DROP
      $ip6t -A FORWARD -o $_if -j DROP
   fi
   $ip6t -A INPUT -i $_if -j DROP
   $ip6t -A OUTPUT -o $_if -j DROP
done

echo_done # Block IPs / Networks / Interfaces..



# ---
# - Block IPs/Netwoks reading from file 'ban_ipv6.list'"
# ---

echononl "\tBlock IPs/Netwoks reading from file 'ban_ipv6.list' .."

if [[ -f "$conf_ban_ipv6_list" ]] ; then

	declare -a ban_ipv6_arr=()
   declare -a no_valid_ipv6=()

	# Regex valid ipv6 address
	#
	_regex_ipv6='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$'

   while IFS='' read -r _line || [[ -n $_line ]] ; do

		is_valid_ipv6=false
		is_valid_mask=false
      ipv6=""
      mask=""

      # Ignore comment lines
      #
      [[ $_line =~ ^[[:space:]]{0,}# ]] && continue

      # Ignore blank lines
      #
      [[ $_line =~ ^[[:space:]]*$ ]] && continue

      # Remove leading whitespace characters
      #
      _line="${_line#"${_line%%[![:space:]]*}"}"


      # Catch ipv6 Address
      #
      given_ipv6="$(echo  $_line | cut -d ' ' -f1)"


      # Splitt ipv6 address from possible given CIDR number
      #
      IFS='/' read -ra _addr <<< "$given_ipv6"
      ipv6="${_addr[0]}"

		# Test mask if given
		#
      if [[ -n "${_addr[1]}" ]] ; then
         mask="${_addr[1]}"

         # Is 'mask' a valid CIDR number? If not, test agains a valid netmask
         #
         if $(test -z "${mask##*[!0-9]*}" > /dev/null 2>&1) ; then

            # Its not a vaild mask number, but naybe a valit netmask.
            #
				no_valid_ipv6_arr+=("$given_ipv6")

         else
            if [[ $mask -gt 128 ]]; then

               # Its not a vaild cidr number, but naybe a valit netmask.
               #
					no_valid_ipv6_arr+=("$given_ipv6")
				else
					is_valid_mask=true
            fi
         fi
      else
         mask=64
			is_valid_mask=true
      fi

		# Check if given ipv6 address is valif
		if [[ "$ipv6" =~ ${_regex_ipv6} ]]; then
			is_valid_ipv6=true
		fi


		if $is_valid_ipv6 && $is_valid_mask; then

         _ip="${ipv6}/${mask}"

			if containsElement "$_ip"  "${ban_ipv6_arr[@]}" ; then
				continue
			fi

         for _dev in ${ext_if_arr[@]} ; do
            if $log_blocked_ip || $log_all ; then
               $ip6t -A INPUT -i $_dev -s $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked by ban_ipv6.list: "
               if $kernel_forward_between_interfaces ; then
                  $ip6t -A FORWARD -i $_dev -s $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix Blocked by ban_ipv6.list: "
               fi
            fi

            $ip6t -A INPUT -i $_dev -s $_ip -j DROP
            if $kernel_forward_between_interfaces ; then
               $ip6t -A FORWARD -i $_dev -s $_ip -j DROP
            fi
         done

			ban_ipv6_arr+=("$_ip")

      else
			if ! containsElement "$given_ipv6"  "${no_valid_ipv6_arr[@]}" ; then
         	no_valid_ipv6_arr+=("$given_ipv6")
			fi
      fi

   done < "$conf_ban_ipv6_list"
   echo_done

   if [[ ${#no_valid_ipv6_arr[@]} -gt 0  ]]; then
      warn "Ignored: ${no_valid_ipv6_arr[@]}"
   fi
else
   echo_skipped
fi



# -------------
# --- Protections against several attacks / unwanted packages
# -------------
echo
echo -e "\t\033[37m\033[1mProtections against several attacks / unwanted packages..\033[m"


# ---
# - Drop invalid packets
# ---
echononl "\tDrop invalid packets"

# ---
# Ersatzlos gestrichen
# ---
echo_skipped

#if $log_invalid_packets || $log_all ; then
#   $ip6t -t mangle -A PREROUTING -m conntrack --ctstate INVALID -j  $LOG_TARGET $tag_log_prefix "$log_prefix Invalid packets:"
#fi
#$ip6t -t mangle -A PREROUTING -m conntrack --ctstate INVALID -j DROP
#echo_done


# ---
# Drop TCP packets that are new and are not SYN
# ---

echononl "\tDrop TCP packets that are new and are not SYN"
if $log_new_not_sync || $log_all  ; then
   $ip6t -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j $LOG_TARGET $tag_log_prefix "$log_prefix New but not SYN:"
fi
$ip6t -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j DROP
echo_done


# ---
# - Drop SYN packets with suspicious MSS value
# ---

echononl "\tDrop SYN packets with suspicious MSS value"
if $log_syn_with_suspicious_mss || $log_all  ; then
   $ip6t -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j $LOG_TARGET $tag_log_prefix "$log_prefix suspicious MSS:"
fi
$ip6t -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP
echo_done


# ---
# - Block packets with bogus TCP flags
# ---

echononl "\tBlock packets with bogus TCP flags"
if $log_invalid_flags || $log_all ; then
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
   $ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j $LOG_TARGET $tag_log_prefix "$log_prefix Invalid flags:"
fi
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP
$ip6t -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP
echo_done


# ---
# - Block spoofed (own ip) packets
# ---

echononl "\tBlock spoofed (own ip) packets"
if $log_spoofed || $log_all ; then
   for _ip in ${ext_ip_arr[@]} ; do
      $ip6t -t mangle -A PREROUTING -s $_ip -d $_ip -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofed (own ip): "
   done
fi
for _ip in ${ext_ip_arr[@]} ; do
   $ip6t -t mangle -A PREROUTING -s $_ip -d $_ip -j DROP
done
echo_done


# ---
# - Block spoofed (private/reserved) packets
# ---

echononl "\tBlock spoofed (private/reserved) packets"
for _dev in ${ext_if_arr[@]} ; do
   if $log_spoofed || $log_all ; then
      $ip6t -t mangle -A PREROUTING -i $_dev -s $ula_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Private (ula_block): "
      #$ip6t -t mangle -A PREROUTING -i $_dev -s $link_local_unicast_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Private (Link Local Unicast): "
      $ip6t -t mangle -A PREROUTING -i $_dev -s $multicast_ipv6 -j $LOG_TARGET $tag_log_prefix "$log_prefix Multicast: "
   fi
done

if $log_spoofed || $log_all ; then
   $ip6t -t mangle -A PREROUTING -s $loopback_ipv6 ! -i lo -j $LOG_TARGET $tag_log_prefix "$log_prefix Loopback: "
fi

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -t mangle -A PREROUTING -i $_dev -s $ula_block -j DROP

   # !! Does NOT work !!
   #
   #$ip6t -t mangle -A PREROUTING -i $_dev -s $link_local_unicast_block -j DROP

   $ip6t -t mangle -A PREROUTING -i $_dev -s $multicast_ipv6 -j DROP
done
$ip6t -t mangle -A PREROUTING -s $loopback_ipv6 ! -i lo -j DROP
echo_done


# ---
# - Drop ICMP all ICMP traffic (you usually don't need this protocol)
# ---

echononl "\tDrop all ICMP traffic.."
echo_skipped

if [[ -n "$drop_icmp" ]] && $drop_icmp ; then

   warn " No ICMPv6 packets were dropped - they are essential."

fi


# -------------
# --- Drop Mikrotik RouterOS Neighbor Discovery Protocol (MNDP) Traffic
# --- Drop Tinc VPN Traffic
# -------------

[ "${drop_mndp,,}" == "yes" ] && drop_mndp=true
[ "${drop_mndp,,}" == "no" ] && drop_mndp=false

echononl "\tDrop Tinc VPN / Mikrotik RouterOS Neighbor Discovery Traffic"
if [[ -n "$drop_mndp" ]] && $drop_mndp ; then
   for _dev in ${ext_if_arr[@]} ; do

      if $log_mndp || $log_all ; then
         $ip6t -A OUTPUT -o $_dev -p udp --dport $standard_mndp_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MNDP Out: "
         $ip6t -A INPUT -i $_dev -p udp --dport $standard_mndp_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MNDP IN: "
         if $kernel_forward_between_interfaces ; then
            $ip6t -A FORWARD -o $_dev -p udp --dport $standard_mndp_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MNDP fwd Out: "
            $ip6t -A FORWARD -i $_dev -p udp --dport $standard_mndp_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MNDP fwd In: "
         fi
      fi

      $ip6t -A OUTPUT -o $_dev -p udp --dport $standard_mndp_port -j DROP
      $ip6t -A INPUT -i $_dev -p udp --dport $standard_mndp_port -j DROP
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -o $_dev -p udp --dport $standard_mndp_port -j DROP
         $ip6t -A FORWARD -i $_dev -p udp --dport $standard_mndp_port -j DROP
      fi

   done
   echo_done
else
   echo_skipped
fi


# -------------
# --- Drop Multicast DNS Traffic
# -------------

[ "${drop_mdns,,}" == "yes" ] && drop_mdns=true
[ "${drop_mdns,,}" == "no" ] && drop_mdns=false

echononl "\tDrop Multicast DNS Traffic"
if [[ -n "$drop_mdns" ]] && ${drop_mdns} ; then
   for _dev in ${ext_if_arr[@]} ; do

      if $log_mdns || $log_all ; then
         $ip6t -A OUTPUT -o $_dev -p udp --dport $standard_mdns_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MDNS Out: "
         $ip6t -A INPUT -i $_dev -p udp --dport $standard_mdns_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MDNS IN: "
         if $kernel_forward_between_interfaces ; then
            $ip6t -A FORWARD -o $_dev -p udp --dport $standard_mdns_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MDNS fwd Out: "
            $ip6t -A FORWARD -i $_dev -p udp --dport $standard_mdns_port -j $LOG_TARGET $tag_log_prefix "$log_prefix MDNS fwd In: "
         fi
      fi

      $ip6t -A OUTPUT -o $_dev -p udp --dport $standard_mdns_port -j DROP
      $ip6t -A INPUT -i $_dev -p udp --dport $standard_mdns_port -j DROP
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -o $_dev -p udp --dport $standard_mdns_port -j DROP
         $ip6t -A FORWARD -i $_dev -p udp --dport $standard_mdns_port -j DROP
      fi

   done
   echo_done
else
   echo_skipped
fi


# ---
# - Don't allow spoofing out from this server
# ---

echo ""
echononl "\tDon't allow spoofing out from this server"
if $log_spoofed_out || $log_all ; then
   for _dev in ${ext_if_arr[@]} ; do
      $ip6t -A OUTPUT -o $_dev -s $ula_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
      #$ip6t -A OUTPUT -o $_dev -s $link_local_unicast_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
      $ip6t -A OUTPUT -o $_dev -s $multicast_ipv6 -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
      $ip6t -A OUTPUT -o $_dev -s $loopback_ipv6 -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -o $_dev -s $ula_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
         #$ip6t -A FORWARD -o $_dev -s $link_local_unicast_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
         $ip6t -A FORWARD -o $_dev -s $multicast_ipv6 -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
         $ip6t -A FORWARD -o $_dev -s $loopback_ipv6 -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
      fi
   done
fi

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -s $ula_block -j DROP
   #$ip6t -A OUTPUT -o $_dev -s $link_local_unicast_block -j DROP
   $ip6t -A OUTPUT -o $_dev -s $multicast_ipv6 -j DROP
   $ip6t -A OUTPUT -o $_dev -s $loopback_ipv6 -j DROP
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -s $ula_block -j DROP
      #$ip6t -A FORWARD -o $_dev -s $link_local_unicast_block -j DROP
      $ip6t -A FORWARD -o $_dev -s $multicast_ipv6 -j DROP
      $ip6t -A FORWARD -o $_dev -s $loopback_ipv6 -j DROP
   fi
done
echo_done


# -------------
# --- Traffic generally allowed
# -------------

echo
echononl "\tLoopback device generally allowed.."

# ---
# - Loopback device
# ---

$ip6t -A INPUT -i lo -j ACCEPT
$ip6t -A OUTPUT -o lo -j ACCEPT

echo_done


# ---
# - Already established connections
# ---

echononl "\tAccept already established connections.."

$ip6t -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ip6t -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

$ip6t -A INPUT -m conntrack --ctstate INVALID -j DROP

if $kernel_forward_between_interfaces ; then
   $ip6t -A FORWARD  -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
fi

echo_done

echononl "\tICMPv6 - mandatory for IPv6 to work correctly!"

# ICMPv6 essentials (numbers to be compatible with ip6tables-nft)
# 1  = destination-unreachable
# 2  = packet-too-big
# 3  = time-exceeded
# 4  = parameter-problem
# 128= echo-request
# 129= echo-reply
# 133= router-solicitation
# 134= router-advertisement
# 135= neighbor-solicitation
# 136= neighbor-advertisement
for t in 1 2 3 4 128 129 133 134 135 136; do
   $ip6t -A INPUT  -p ipv6-icmp --icmpv6-type $t -j ACCEPT
   $ip6t -A OUTPUT -p ipv6-icmp --icmpv6-type $t -j ACCEPT

   # Normaly, 'do_not_firewall_bridged_traffic' and 'do_not_firewall_lx_guest_systems' must
   # not be part of the if-clause, but in SINMA systems, this is needed for LX Container to
   # work
   #
   if ${kernel_forward_between_interfaces} \
      || ${do_not_firewall_bridged_traffic} \
      || ${do_not_firewall_lx_guest_systems} ; then

      $ip6t -A FORWARD -p  ipv6-icmp --icmpv6-type "$t" -j ACCEPT
   fi
done

echo_done

# ---
# - Protection against syn-flooding
# ---

echo
echononl "\tProtection against syn-flooding"
if $protection_against_syn_flooding ; then
   $ip6t -N syn-flood
   $ip6t -A syn-flood -m limit --limit 1/second --limit-burst 3 -j RETURN
   if $log_syn_flood || $log_all ; then
      $ip6t -A syn-flood -j $LOG_TARGET $tag_log_prefix "$log_prefix SYN flood: "
   fi
   $ip6t -A syn-flood -j DROP
   echo_done
else
   echo_skipped
fi


# ---
# - Protection against port scanning
# ---

echononl "\tProtection against port scanning"
if $protection_against_port_scanning ; then
   $ip6t -N port-scanning
   $ip6t -A port-scanning -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s --limit-burst 2 -j RETURN
   if $log_port_scanning || $log_all ; then
      $ip6t -A port-scanning -j $LOG_TARGET $tag_log_prefix "$log_prefix Port Scan:"
   fi
   $ip6t -A port-scanning -j DROP
   echo_done
else
   echo_skipped
fi


# ---
# - Protection against SSH brute-force attacks
# ---

echononl "\tProtection against SSH brute-force attacks"
if $protection_against_ssh_brute_force_attacks ; then
   $ip6t -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --set
   if $log_ssh_brute_force || $log_all ; then
      $ip6t -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j $LOG_TARGET $tag_log_prefix "$log_prefix SSH brute-force:"
   fi
   $ip6t -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP
   echo_done
else
   echo_skipped
fi


# ---
# - Limit connections per source IP
# ---

echononl "\tLimit connections per source IP"
if $limit_connections_per_source_IP ; then

   if ! is_number $per_IP_connection_limit ; then
      per_IP_connection_limit=$default_per_IP_connection_limit
   fi

   if $log_rejected || $log_all ; then

   $ip6t -A INPUT -p tcp --syn \
      -m connlimit --connlimit-above $per_IP_connection_limit --connlimit-mask 128 --connlimit-saddr \
      -j $LOG_TARGET $tag_log_prefix "$log_prefix CONN limit per IP:"

   fi

   $ip6t -A INPUT -p tcp --syn \
      -m connlimit --connlimit-above $per_IP_connection_limit --connlimit-mask 128 --connlimit-saddr \
      -j REJECT --reject-with tcp-reset

   echo_done
else
   echo_skipped
fi


# ---
# - Limit RST packets
# ---

echononl "\tLimit RST packets"

# ---
# Ersatzlos gestrichen
# ---
echo_skipped

#if $limit_rst_packets ; then
#   $ip6t -A INPUT -p tcp --tcp-flags RST RST -m limit --limit 2/s --limit-burst 2 -j ACCEPT
#   if $log_rejected || $log_all ; then
#      $ip6t -A INPUT -p tcp --tcp-flags RST RST -j $LOG_TARGET $tag_log_prefix "$log_prefix Limit RST packets: "
#   fi
#   $ip6t -A INPUT -p tcp --tcp-flags RST RST -j DROP
#   echo_done
#else
#   echo_skipped
#fi


# ---
# - Limit new TCP connections per second per source IP
# ---

echononl "\tLimit new (syn) TCP connections per second per source IP (multiport)"

if $limit_new_tcp_connections_per_seconds_per_source_IP \
      && [[ ${#limit_new_tcp_connections_per_seconds_ports} -gt 0 ]]; then

   #$ip6t -A INPUT -p tcp -m conntrack --ctstate NEW -m limit --limit 60/s --limit-burst 20 -j ACCEPT

   # Rate-Limit für neue SYNs auf 443 pro IP
   $ip6t -A INPUT -p tcp --syn \
      -m multiport --dports $limit_new_tcp_connections_per_seconds_ports \
      -m hashlimit --hashlimit-name syn_multi_v4 \
      --hashlimit 30/second --hashlimit-burst 60 \
      --hashlimit-mode srcip --hashlimit-srcmask 32 \
      -j ACCEPT

   if $log_rejected || $log_all ; then

      #$ip6t -A INPUT -p tcp -m conntrack --ctstate NEW -j $LOG_TARGET $tag_log_prefix "$log_prefix Limit new TCP conn's: "

      #  rate-limited logging für Überschreiter
      $ip6t -A INPUT -p tcp --syn \
         -m multiport --dports $limit_new_tcp_connections_per_seconds_ports \
         -m hashlimit --hashlimit-name syn_multi_v4_log  \
         --hashlimit 2/second --hashlimit-burst 10 \
         --hashlimit-mode srcip --hashlimit-srcmask 32 \
         -j $LOG_TARGET $tag_log_prefix "$log_prefix SYN over limit (multiport):"
   fi
   $ip6t -A INPUT -p tcp -m conntrack --ctstate NEW -j DROP
   echo_done
else
   echo_skipped
fi


# ---
# - Use SYNPROXY on all ports (disables connection limiting rule)
# ---

#echononl "\tUse SYNPROXY on all ports (disables connection limiting rule)"
#$ip6t -t raw -A PREROUTING -p tcp -m tcp --syn -j CT --notrack
#$ip6t -A INPUT -p tcp -m tcp -m conntrack --ctstate INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460
#$ip6t -A INPUT -m conntrack --ctstate INVALID -j DROP
#echo_done



# -------------
# ------------- Stopping firewall here if requested (parameter stop)
# -------------

case $1 in
   sto*)
      #echononl "Stopping firewall iptable (IPv6).."
      echo
      echo -e "\t\033[37m\033[1mStop was requested. No more rules..\033[m"
      echo
      exit 0;;
esac


echo

# -------------
# --- Traffic Counter (used by munin)
# -------------

echononl "\tCreate Traffic Counter (used by munin)"
if $create_traffic_counter ; then
   for _ip in ${ext_ip_arr[@]} ; do
      $ip6t -A INPUT -d $_ip
      $ip6t -A INPUT -s $_ip
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -d $_ip
         $ip6t -A FORWARD -s $_ip
      fi
   done
   echo_done
else
   echo_skipped
fi


# -------------
# --- iPerf
# -------------

# iPerf is a tool for active measurements of the maximum achievable bandwidth on IP networks.
# It supports tuning of various parameters related to timing, buffers and protocols (TCP, UDP,
# SCTP with IPv4 and IPv6). For each test it reports the bandwidth, loss, and other parameters.

echononl "\tCreate \"iPerf\" rules.."
if $create_iperf_rules ; then
   $ip6t -A INPUT -p tcp --dport 5001 -j ACCEPT
   $ip6t -A INPUT -p tcp --sport 5001 -j ACCEPT
   #
   $ip6t -A OUTPUT -p tcp --dport 5001 -j ACCEPT
   $ip6t -A OUTPUT -p tcp --sport 5001 -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -p tcp --dport 5001 -j ACCEPT
      $ip6t -A FORWARD -p tcp --sport 5001 -j ACCEPT
   fi
   echo_done
else
   echo_skipped
fi


# -------------
# --- Generally prohibited
# -------------

echononl "\tGenerally prohibited traffic.."

for _dev in ${ext_if_arr[@]} ; do
   if $log_prohibited || $log_all ; then
      for _port in ${block_tcp_port_arr[@]} ; do
         $ip6t -A INPUT -p tcp -i $_dev --dport $_port -j $LOG_TARGET $tag_log_prefix "$log_prefix gen. prohibited: "
      done
      for _port in ${block_udp_port_arr[@]} ; do
         $ip6t -A INPUT -p udp -i $_dev --dport $_port -j $LOG_TARGET $tag_log_prefix "$log_prefix gen. prohibited: "
      done
      if $kernel_forward_between_interfaces ; then
         for _port in ${block_tcp_port_arr[@]} ; do
            $ip6t -A FORWARD -p tcp -i $_dev --dport $_port -j $LOG_TARGET $tag_log_prefix "$log_prefix gen. prohibited: "
         done
         for _port in ${block_udp_port_arr[@]} ; do
            $ip6t -A FORWARD -p udp -i $_dev --dport $_port -j $LOG_TARGET $tag_log_prefix "$log_prefix gen. prohibited: "
         done
      fi
   fi
   for _port in ${block_tcp_port_arr[@]} ; do
      $ip6t -A INPUT -p tcp -i $_dev --dport $_port -j DROP
   done
   for _port in ${block_udp_port_arr[@]} ; do
      $ip6t -A INPUT -p udp -i $_dev --dport $_port -j DROP
   done
   if $kernel_forward_between_interfaces ; then
      for _port in ${block_tcp_port_arr[@]} ; do
         $ip6t -A FORWARD -p tcp -i $_dev --dport $_port -j DROP
      done
      for _port in ${block_udp_port_arr[@]} ; do
         $ip6t -A FORWARD -p udp -i $_dev --dport $_port -j DROP
      done
   fi
done

echo_done
echo


# -------------
# ---- Restrict local Servive to given (extern) IP-Address/Network
# -------------

echononl "\tRestrict local Servive to given (extern) IP-Address/Network"
if [[ ${#restrict_local_service_to_net_arr[@]} -gt 0 ]] ; then

   _deny_service_arr=()

   for _val in "${restrict_local_service_to_net_arr[@]}" ; do
      IFS=',' read -a _val_arr <<< "${_val}"

      for _dev in ${ext_if_arr[@]} ; do
         $ip6t -A INPUT -i $_dev -p ${_val_arr[3]} -s ${_val_arr[0]} -d ${_val_arr[1]} --dport ${_val_arr[2]} -j ACCEPT

         if ! containsElement "${_dev},${_val_arr[1]},${_val_arr[2]},${_val_arr[3]}" "${_deny_service_arr[@]}" ; then
            _deny_service_arr+=("${_dev},${_val_arr[1]},${_val_arr[2]},${_val_arr[3]}")
         fi
      done

   done

   for _val in "${_deny_service_arr[@]}" ; do
      IFS=',' read -a _val_arr <<< "${_val}"
      $ip6t -A INPUT -i ${_val_arr[0]} -p ${_val_arr[3]} -d ${_val_arr[1]} --dport ${_val_arr[2]} -j DROP
   done

   echo_done
else
   echo_skipped
fi


# -------------
# ---- Restrict local Network to given extern IP-Address/Network
# -------------

echononl "\tRestrict local Address/Network to given extern Address/Network"
if [[ ${#restrict_local_net_to_net_arr[@]} -gt 0 ]] ; then

   _deny_net_arr=()

   for _val in "${restrict_local_net_to_net_arr[@]}" ; do
      IFS=',' read -a _val_arr <<< "${_val}"
      for _dev in ${ext_if_arr[@]} ; do
         $ip6t -A INPUT -i $_dev -s ${_val_arr[0]} -d ${_val_arr[1]} -j ACCEPT

         if ! containsElement "${_dev},${_val_arr[1]}" "${_deny_net_arr[@]}" ; then
            _deny_net_arr+=("${_dev},${_val_arr[1]}")
         fi
      done

   done

   for _val in "${_deny_net_arr[@]}" ; do
      IFS=',' read -a _val_arr <<< "${_val}"
      $ip6t -A INPUT -i ${_val_arr[0]} -d ${_val_arr[1]} -j DROP
   done

   echo_done
else
   echo_skipped
fi

echo


# ---
# - LOG CGI script Traffic out
# ---

echo
echononl "\tLOG CGI/PHP traffic out."

if $log_cgi_traffic_out && [[ ${#cgi_script_user_arr[@]} -gt 0 ]] ; then
   for _dev in ${ext_if_arr[@]} ; do
      for _user in ${cgi_script_user_arr[@]} ; do
         $ip6t -A OUTPUT -o $_dev -m owner --uid-owner $_user -j $LOG_TARGET $tag_log_prefix "$log_prefix $_user PHP-OUT: "
      done
   done
   echo_done
else
   echo_skipped
fi
echo


# -------------
# --- Allow all outgoing traffic
# -------------
echononl "\tAllow all outgoing traffic.."
if [[ -n "$allow_all_outgoing_traffic" ]] && $allow_all_outgoing_traffic ; then
   for _dev in ${ext_if_arr[@]} ; do
      $ip6t -A OUTPUT -o $_dev -p ALL -m conntrack --ctstate NEW -j ACCEPT
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -o $_dev -p ALL -m conntrack --ctstate NEW -j ACCEPT
      fi
   done
   echo_done
else
   echo_skipped
fi


# ---
# - Don't allow traffik into Unique local network (ULA)
# ---

echo ""
echononl "\tDon't allow traffic into Unique local network (ULA)"
if $log_private_network_out || $log_all ; then
   for _dev in ${ext_if_arr[@]} ; do
      $ip6t -A OUTPUT -o $_dev -d $ula_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -o $_dev -d $ula_block -j $LOG_TARGET $tag_log_prefix "$log_prefix Spoofing Out: "
      fi
   done
fi

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -d $ula_block -j DROP
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -d $ula_block -j DROP
   fi
done
echo_done


# -------------
# --- Services
# -------------

echo
echo -e "\t\033[37m\033[1mAdd Rules for Services..\033[m"
echo


# -------------
# ---- Allow extern Service
# -------------

echononl "\t\tAllow extern Service"

if [[ ${#allow_ext_service_arr[@]} -gt 0 ]] ; then
   for _dev in "${ext_if_arr[@]}" ; do
      for _val in "${allow_ext_service_arr[@]}" ; do
         IFS=',' read -a _val_arr <<< "${_val}"
         $ip6t -A OUTPUT -o $_dev -p ${_val_arr[2]} -d ${_val_arr[0]} --dport ${_val_arr[1]} -m conntrack --ctstate NEW -j ACCEPT
      done
   done
   echo_done
else
   echo_skipped
fi


# -------------
# ---- Allow extern IP-Address/Network
# -------------

echononl "\t\tAllow extern IP-Address/Network"

if [[ ${#allow_ext_net_arr[@]} -gt 0 ]] ; then
   for _dev in "${ext_if_arr[@]}" ; do
      for _net in "${allow_ext_net_arr[@]}" ; do
         $ip6t -A OUTPUT -o $_dev -p all -d $_net -m conntrack --ctstate NEW -j ACCEPT
      done
   done
   echo_done
else
   echo_skipped
fi

echo


# -------------
# ---- Allow (non-standard) local Services
# -------------

echononl "\t\tAllow (non-standard) local Services"

if [[ ${#allow_local_service_arr[@]} -gt 0 ]] ; then
   for _dev in "${ext_if_arr[@]}" ; do
      for _val in "${allow_local_service_arr[@]}" ; do
         IFS=',' read -a _val_arr <<< "${_val}"
         $ip6t -A INPUT -i $_dev -p ${_val_arr[1]} --dport ${_val_arr[0]} -m conntrack --ctstate NEW -j ACCEPT
      done
   done
   echo_done
else
   echo_skipped
fi


# -------------
# ---- Allow local Services from given (extern) network
# -------------

echononl "\t\tAllow local Services from given (extern) network"

if [[ ${#allow_local_service_from_network_arr[@]} -gt 0 ]] ; then
   for _dev in "${ext_if_arr[@]}" ; do
      for _val in "${allow_local_service_from_network_arr[@]}" ; do
         IFS=',' read -a _val_arr <<< "${_val}"
         $ip6t -A INPUT -i $_dev -p ${_val_arr[2]} -s ${_val_arr[0]} --dport ${_val_arr[1]} -m conntrack --ctstate NEW -j ACCEPT
      done
   done
   echo_done
else
   echo_skipped
fi

echo


# ---
# - DHCP
# ---

echononl "\t\tDHCP Clients"

if [[ ${#dhcp_client_if_arr[@]} -gt 0 ]] ; then
   for _dev in ${dhcp_if_arr[@]} ; do
      # - out
      $ip6t -A OUTPUT -p udp -o $_dev --dport 67 -d ::/0 --sport 1024:65535 -j ACCEPT
      # - in
      $ipt -A INPUT -p udp -i $_dev --sport 67 -d ::/0 --dport 68 -j ACCEPT
   done
   echo_done
else
   echo_skipped
fi

echononl "\t\tDHCP Server"

if [[ ${#dhcp_server_if_arr[@]} -gt 0 ]] ; then
   for _dev in ${dhcp_server_if_arr[@]} ; do
      # - in
      $ip6t -A INPUT -p udp -i $_dev -s ::/0 --sport 68 --dport 67 -j ACCEPT
      # - out
      $ip6t -A OUTPUT -p udp -o $_dev --sport 67 -d ::/0 --dport 68 -j ACCEPT
   done
   echo_done
else
   echo_skipped
fi



# ---
# - DNS out only
# ---

echononl "\t\tDNS out only"

# - Nameservers on the INET must be reachable for the local recursiv nameserver
# - but also for all others
# -
for _dev in ${ext_if_arr[@]} ; do
   # - out from local and virtual mashine(s)
   $ip6t -A OUTPUT -o $_dev -p udp --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT

   # - Only useful (needed) if kernel forwarding is activated (kernel_forward_between_interfaces=true)
   if $kernel_forward_between_interfaces ; then
      # - forward from virtual mashine(s)
      $ip6t -A FORWARD -o $_dev -p udp --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done



# ---
# - DNS Service
# ---

echononl "\t\tDNS Service"

if [[ ${#dns_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_dns_server_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#dns_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${dns_server_ips[@]} ; do
         # dns requests
         #
         # Note:
         #    If the total size of the DNS record is larger than 512 bytes,
         #    it will be sent over TCP, not UDP.
         #
         $ip6t -A INPUT -p udp -d $_ip --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A INPUT -p tcp -d $_ip --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
         # Zonetransfer
         $ip6t -A OUTPUT -p tcp -s $_ip --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   if [[ ${#forward_dns_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_dns_server_ip_arr[@]} ; do
         # dns requests
         #
         # Note:
         #    If the total size of the DNS record is larger than 512 bytes,
         #    it will be sent over TCP, not UDP.
         #
         $ip6t -A FORWARD -p udp -d $_ip --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A FORWARD -p tcp -d $_ip --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
         # Zonetransfer
         $ip6t -A FORWARD -p tcp -s $_ip --dport $standard_dns_port -m conntrack --ctstate NEW -j ACCEPT
      done
   fi
   echo_done
else
   echo_skipped
fi


# ---
# - local Resolver"
# ---

echononl "\t\tlocal Resolver"
if [[ -n "$local_resolver_service" ]] && $local_resolver_service  ; then
   if [[ ${#resolver_allowed_network_arr[@]} -gt 0 ]] ; then
      for _net in ${resolver_allowed_network_arr[@]} ; do
         $ip6t -A INPUT -p udp -s $_net --dport $resolver_port -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A INPUT -p tcp -s $_net --dport $resolver_port -m conntrack --ctstate NEW -j ACCEPT
      done
      echo_done
   else
      echo_failed
   fi
else
   echo_skipped
fi


# ---
# - SSH out only
# ---

echononl "\t\tSSH out only"

# ausgehende Anfragen
for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_ssh_port -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_ssh_port -m conntrack --ctstate NEW -j ACCEPT
   fi

   if [[ ${#ssh_port_arr[@]} -gt 0 ]] ; then
      for _port in ${ssh_port_arr[@]} ; do

         [[ "$_port" = "$standard_ssh_port" ]] && continue

         $ip6t -A OUTPUT -o $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT

         if $kernel_forward_between_interfaces ; then
            $ip6t -A FORWARD -o $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         fi

      done
   fi

done

if [[ ${#local_if_arr[@]}  -gt 0 ]] ; then
   for _dev in ${local_if_arr[@]} ; do
      $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_ssh_port -m conntrack --ctstate NEW -j ACCEPT

         if [[ ${#ssh_port_arr[@]} -gt 0 ]] ; then
            for _port in ${ssh_port_arr[@]} ; do

               [[ "$_port" = "$standard_ssh_port" ]] && continue

               $ip6t -A OUTPUT -o $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT

               if $kernel_forward_between_interfaces ; then
                  $ip6t -A FORWARD -i $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT
               fi
            done
         fi
   done
fi

echo_done


# ---
# - SSH Service
# ---

echononl "\t\tSSH Service"

if [[ ${#ssh_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_ssh_server_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#ssh_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${ssh_server_ip_arr[@]} ; do
         for _port in ${ssh_port_arr[@]} ; do
            $ip6t -A INPUT -p tcp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   if [[ ${#forward_ssh_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_ssh_server_ip_arr[@]} ; do
         for _port in ${ssh_port_arr[@]} ; do
            $ip6t -A FORWARD -p tcp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - VPN
# ---

echononl "\t\tVPN Service only out"
if [[ ${#vpn_port_arr[@]} -gt 0 ]] ; then

   for _dev in ${ext_if_arr[@]} ; do
      for _port in ${vpn_port_arr[@]} ; do
         $ip6t -A OUTPUT -o $_dev -p udp --dport $_port  -m conntrack --ctstate NEW -j ACCEPT
      done
   done

   echo_done
else
   echo_skipped
fi

echononl "\t\tVPN Services.."
if [[ ${#vpn_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_vpn_server_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#vpn_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${vpn_server_ip_arr[@]} ; do
         for _port in ${vpn_port_arr[@]} ; do
            $ip6t -A INPUT -p udp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   if [[ ${#forward_vpn_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_vpn_server_ip_arr[@]} ; do
         $ip6t -A FORWARD -p udp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Wireguard
# ---

echononl "\t\tWireguard Service only out"
if [[ ${#wireguard_out_port_port_arr[@]} -gt 0 ]] ; then

   for _dev in ${ext_if_arr[@]} ; do
      for _port in ${wireguard_out_port_port_arr[@]} ; do
         $ip6t -A OUTPUT -o $_dev -p udp --dport $_port  -m conntrack --ctstate NEW -j ACCEPT
      done
   done

   echo_done
else
   echo_skipped
fi

echononl "\t\tWireguard Services.."
if [[ ${#wireguard_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_wireguard_server_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#wireguard_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${wireguard_server_ip_arr[@]} ; do
         for _port in ${wireguard_server_port_arr[@]} ; do
            $ip6t -A INPUT -p udp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   if [[ ${#forward_wireguard_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_wireguard_server_ip_arr[@]} ; do
         $ip6t -A FORWARD -p udp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Rsync Out
# ---

echononl "\t\tRsync (only OUT)"

if [[ ${#rsync_out_ip_arr[@]} -gt 0 ]] || [[ ${#forward_rsync_out_ip_arr[@]} -gt 0 ]] ; then

   if [[ ${#rsync_out_ip_arr[@]} -gt 0 ]] ; then
      for _port in ${rsync_port_arr[@]} ; do

         for _ip in ${rsync_out_ip_arr[@]} ; do
            $ip6t -A OUTPUT -p tcp -s $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done

      done
   fi

   if [[ ${#forward_rsync_out_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _port in ${rsync_port_arr[@]} ; do

         for _ip in ${forward_rsync_out_ip_arr[@]} ; do
            $ip6t -A FORWARD -p tcp -s $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done

      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Telnet
# ---

echononl "\t\tTelnet (only OUT)"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_telnet_port -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_telnet_port -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - MySQL
# ---

echononl "\t\tMySQL (only OUT)"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_mysql_port -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_mysql_port -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - Prometheus Monitoring - local Server
# ---

echononl "\t\tLocal Prometheus Service"

if [[ ${#prometheus_local_server_ip_arr[@]} -gt 0 ]] ; then
   for _ip in ${prometheus_local_server_ip_arr[@]} ; do
      $ip6t -A OUTPUT -p tcp -s $_ip -m multiport --dports $prometheus_remote_client_ports -m conntrack --ctstate NEW -j ACCEPT
   done
   echo_done
else
   echo_skipped
fi


# ---
# - Prometheus Monitoring - local client
# ---

echononl "\t\tLocal Prometheus Client"

if [[ ${#prometheus_local_client_ip_arr[@]} -gt 0 ]] && [[ ${#prometheus_remote_server_ip_arr[@]} -gt 0 ]]; then
   for _ip in ${prometheus_local_client_ip_arr[@]} ; do
      for _ip in ${prometheus_remote_server_ip_arr[@]} ; do
          $ip6t -A INPUT -p tcp -d $_ip -m multiport --dports $prometheus_local_client_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   done
   echo_done
else
   echo_skipped
fi
      

# ---
# - Munin remote service
# ---

echononl "\t\tMunin remote service"

if [ "X$munin_remote_ip" != "X" ]; then
   for _dev in ${ext_if_arr[@]} ; do
      $ip6t -A INPUT -i $_dev -p tcp --syn -s $munin_remote_ip --dport $munin_local_port -m conntrack --ctstate NEW -j ACCEPT
      if $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -i $_dev -p tcp --syn -s $munin_remote_ip --dport $munin_local_port -m conntrack --ctstate NEW -j ACCEPT
      fi
   done
   echo_done
else
   echo_skipped
fi


# ---
# - Munin local service
# ---

echononl "\t\tMunin local service"


if [[ ${#munin_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_munin_server_ip_arr[@]} -gt 0 ]] ; then

   if [[ ${#munin_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${munin_server_ip_arr[@]} ; do
         $ip6t -A OUTPUT -p tcp -s $_ip --dport $munin_remote_port -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   if [[ ${#forward_munin_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_munin_server_ip_arr[@]} ; do
         $ip6t -A FORWARD -p tcp -s $_ip --dport $munin_remote_port -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Mail (SMTP OUT)
# ---

echononl "\t\tMail (SMTP OUT)"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_smtp_port -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_smtp_port -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - Mail (additional smtp ports OUT)
# ---

echononl "\t\tMail (additional smtp ports OUT)"

if [[ ${#smtpd_additional_outgoung_port_arr[@]} -gt 0 ]] ; then

   for _port in ${smtpd_additional_outgoung_port_arr[@]} ; do
      for _dev in ${ext_if_arr[@]} ; do
         $ip6t -A OUTPUT -o $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         if $kernel_forward_between_interfaces ; then
            $ip6t -A FORWARD -o $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         fi
      done
   done

   echo_done
else
   echo_skipped
fi


# ---
# - Mail SMTP Server (Port 25) including Spam Control
# ---

echononl "\t\tMail SMTP Server (Port 25) including Spam Control"

if [[ ${#smtpd_ips_arr[@]} -gt 0 ]] || [[ ${#forward_smtpd_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#smtpd_ips_arr[@]} > 0 ]] ; then

      for _ip in ${smtpd_ips_arr[@]} ; do
         $ip6t -A INPUT -p tcp -d $_ip --dport $standard_smtp_port -m conntrack --ctstate NEW -j ACCEPT
         #
         # Razor2  (TCP Port 2703)
         $ip6t -A OUTPUT -p tcp -s $_ip --dport 2703 -m conntrack --ctstate NEW -j ACCEPT
         # DEPRECATED: TCP Port 7 (echo)
         $ip6t -A OUTPUT -p tcp -s $_ip --dport 7 -m conntrack --ctstate NEW -j ACCEPT
         #
         # Pyzor (UDP Port 24441 or  TCP Port 24441 or both ?)
         $ip6t -A OUTPUT -p udp -s $_ip --dport 24441 -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A OUTPUT -p tcp -s $_ip --dport 24441 -m conntrack --ctstate NEW -j ACCEPT
         #
         # - DCC  (port udp:6277)
         $ip6t -A OUTPUT -s $_ip -p udp -m udp --dport 6277  -m conntrack --ctstate NEW  -j ACCEPT
         # if DCC Server is running (port tcp:6277)
         $ip6t -A INPUT -p tcp -d $_ip --dport 6277 -j ACCEPT
         $ip6t -A OUTPUT -p tcp -s $_ip --dport 6277 -j ACCEPT
      done
   fi

   if [[ ${#forward_smtpd_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_smtpd_ip_arr[@]} ; do
         $ip6t -A FORWARD -p tcp -d $_ip --dport $standard_smtp_port -m conntrack --ctstate NEW -j ACCEPT
         #
         # Razor2  (TCP Port 2703)
         $ip6t -A FORWARD -p tcp -s $_ip --dport 2703 -m conntrack --ctstate NEW -j ACCEPT
         # DEPRECATED: TCP Port 7 (echo)
         $ip6t -A FORWARD -p tcp -s $_ip --dport 7 -m conntrack --ctstate NEW -j ACCEPT
         #
         # Pyzor (UDP Port 24441 or  TCP Port 24441 or both ?)
         $ip6t -A FORWARD -p udp -s $_ip --dport 24441 -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A FORWARD -p tcp -s $_ip --dport 24441 -m conntrack --ctstate NEW -j ACCEPT
         #
         # DCC  (port udp:6277)
         $ip6t -A FORWARD -s $_ip -p udp -m udp --dport 6277  -m conntrack --ctstate NEW  -j ACCEPT
         # if DCC Server is running (port tcp:6277)
         $ip6t -A FORWARD -p tcp -d $_ip --dport 6277 -j ACCEPT
         $ip6t -A FORWARD -p tcp -s $_ip --dport 6277 -j ACCEPT
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Mail (additional smtp ports IN)
# ---

echononl "\t\tMail (additional smtp ports IN)"

if [[ ${#smtpd_additional_listen_port_arr[@]} -gt 0 ]] ; then

   for _port in ${smtpd_additional_listen_port_arr[@]} ; do
      for _dev in ${ext_if_arr[@]} ; do
         $ip6t -A INPUT -i $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         if $kernel_forward_between_interfaces ; then
            $ip6t -A FORWARD -i $_dev -p tcp --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         fi
      done
   done

   echo_done
else
   echo_skipped
fi


# ---
# -  Mailservice (Submission/SMTPS/POP/IMAP Server)
# ---

echononl "\t\tMailservice (Submission/SMTPS/POP/IMAP Server)"

if [[ ${#mail_server_ips_arr[@]} -gt 0 ]] || [[ ${#forward_mail_server_ip_arr[@]} -gt 0 ]] ; then

   if [[ ${#mail_server_ips_arr[@]} -gt 0 ]] ; then
      for _ip in ${mail_server_ips_arr[@]} ; do
         # mail ports
         #
         $ip6t -A INPUT -p tcp -d $_ip -m multiport --dports $mail_user_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi # if [[ ${#mail_server_ips_arr[@]} -gt 0 ]]

   if [[ ${#forward_mail_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_mail_server_ip_arr[@]} ; do
         # mail ports
         #
         $ip6t -A FORWARD -p tcp -d $_ip -m multiport --dports $mail_user_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi # if [[ ${#forward_mail_server_ip_arr[@]} -gt 0 ]] ; then

   echo_done
else
   echo_skipped
fi


# ---
# - (local) Dovecot auth service
# ---

echononl "\t\t(local) Dovecot auth service"

if [[ -n "$dovecot_auth_service" ]] && $dovecot_auth_service ; then

   if [[ ${#dovecot_auth_allowed_network_arr[@]} -gt 0 ]] && [[ -n "$dovecot_auth_port" ]]; then
      for _ip in ${dovecot_auth_allowed_network_arr[@]} ; do
         $ip6t -A INPUT -p tcp -s $_ip --dport $dovecot_auth_port -m conntrack --ctstate NEW -j ACCEPT
      done
      echo_done
   else
      echo_failed
   fi
else
   echo_skipped
fi


# ---
# - Mail Client (Submission/SMTPS/POPS/IMAPS) out only
# ---

echononl "\t\tMail Client (Submission/SMTPS/POPS/IMAPS) out only"

if [[ ${#mail_client_ips_arr[@]} -gt 0 ]] || [[ ${#forward_mail_client_ip_arr[@]} -gt 0 ]] ; then

   if [[ ${#mail_client_ips_arr[@]} -gt 0 ]] ; then
      for _ip in ${mail_client_ips_arr[@]} ; do
         # mail ports
         #
         $ip6t -A OUTPUT -p tcp -s $_ip -m multiport --dports $mail_user_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi # if [[ ${#mail_client_ips_arr[@]} -gt 0 ]]

   if [[ ${#forward_mail_client_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_mail_client_ip_arr[@]} ; do
         # mail ports
         #
         $ip6t -A FORWARD -p tcp -s $_ip -m multiport --dports $mail_user_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi # if [[ ${#forward_mail_client_ip_arr[@]} -gt 0 ]] ; then

   echo_done
else
   echo_skipped
fi


# ---
# - HTTP(S) OUT
# ---

echononl "\t\tHTTP(S) out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp -m multiport --dports $standard_http_ports -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp -m multiport --dports $standard_http_ports -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - HTTP(S) (local) Webserver
# ---

echononl "\t\tHTTP(S) (local) Webserver"

if [[ ${#http_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_http_server_ip_arr[@]} -gt 0 ]]  ; then

   if [[ ${#http_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${http_server_ip_arr[@]} ; do
         $ip6t -A INPUT -p tcp -d $_ip -m multiport --dports $http_ports -m conntrack --ctstate NEW -j ACCEPT
      done

      if  [[ ${#forward_http_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
         for _ip in ${forward_http_server_ip_arr[@]} ; do
            $ip6t -A FORWARD -p tcp -d $_ip -m multiport --dports $http_ports -m conntrack --ctstate NEW -j ACCEPT
         done
      fi
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Mattermost Service
# ---

echononl "\t\tMattermost (MM) Service"
if [[ ${#mm_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_mm_server_ip_arr[@]} -gt 0 ]]  ; then

   if [[ ${#mm_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${mm_server_ip_arr[@]} ; do
         $ip6t -A INPUT -p udp -d $_ip -m multiport --dports $mm_udp_ports_in -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A OUTPUT -p udp -s $_ip -m multiport --dports $mm_udp_ports_out -m conntrack --ctstate NEW -j ACCEPT
      done

      if  [[ ${#forward_mm_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
         for _ip in ${forward_mm_server_ip_arr[@]} ; do
            $ip6t -A FORWARD -p udp -d $_ip -m multiport --dports $mm_udp_ports_in -m conntrack --ctstate NEW -j ACCEPT
            $ip6t -A FORWARD -p udp -s $_ip -m multiport --dports $mm_udp_ports_out -m conntrack --ctstate NEW -j ACCEPT
         done
      fi
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - FTP out only"
# ---

echononl "\t\tFTP out only (using CT target)"

# - (Re)define helper
# -
$ip6t -A OUTPUT -t raw -p tcp --dport $standard_ftp_port -j CT --helper ftp

# - Used for different ftpdata recent lists 'ftp6data_out_$j'
# -
declare -i j=1

for _dev in ${ext_if_arr[@]} ; do

   # - (1)
   # -
   # - Open FTP connection and add the destination ip (--rdest) to ftpdata recent list 'ftpdata_out_$j'.
   # -
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_ftp_port -m conntrack --ctstate NEW \
      -m recent --name ftp6data_out_$j --rdest --set -j ACCEPT

	# - (2)
	# -    - Accept packets if the destination ip-address (--rdest) is in the 'ftpdata_$i' list (--update)
	# -      and the destination ip-address was seen within the last 1800 seconds (--seconds 1800).
	# -
	# -    - If matched, the "last seen" timestamp of the destination address will be updated (--update).
	# -
	# -    - Entries in the ftpdata list not seen in the last 1800 will be removed (--reap).
	# -
	$ip6t -A OUTPUT -o $_dev -p tcp -m conntrack --ctstate NEW --dport 1024: \
		-m recent --name ftp6data_out_$j --rdest --update --seconds 1800 --reap -j ACCEPT

	((j++))

   # - Accept (helper ftp) related connections
   # -
   $ip6t -A OUTPUT -m conntrack --ctstate RELATED -m helper --helper ftp -o $_dev -p tcp --dport 1024: -j ACCEPT

done

echo_done


#echononl "\t\tFTP out only"
#
#for _dev in ${ext_if_arr[@]} ; do
#   # (Datenkanal aktiv)
#   $ip6t -A INPUT -i $_dev -p tcp --sport $standard_ftp_data_port -m conntrack --ctstate NEW -j ACCEPT
#   # (Datenkanal passiv)
#   $ip6t -A OUTPUT -o $_dev -p tcp --sport $unprivports --dport $unprivports -m conntrack --ctstate NEW -j ACCEPT
#   # (Kontrollverbindung)
#   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_ftp_port -m conntrack --ctstate NEW -j ACCEPT
#   if $kernel_forward_between_interfaces ; then
#      # (Datenkanal aktiv)
#      $ip6t -A FORWARD -i $_dev -p tcp --sport $standard_ftp_data_port -m conntrack --ctstate NEW -j ACCEPT
#      # (Datenkanal passiv)
#      $ip6t -A FORWARD -o $_dev -p tcp --sport $unprivports --dport $unprivports -m conntrack --ctstate NEW -j ACCEPT
#      # (Kontrollverbindung)
#      $ip6t -A FORWARD -o $_dev -p tcp  --dport $standard_ftp_port -m conntrack --ctstate NEW -j ACCEPT
#   fi
#done
#
#echo_done


# ---
# - FTP Server"
# ---

echononl "\t\tFTP Server (using CT target)"

if [[ ${#ftp_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_ftp_server_ip_arr[@]} -gt 0 ]]  ; then

   # - Used for different ftpdata recent lists 'ftpdata_$i'
   # -
   declare -i i=1

   # - (Re)define helper
   # -
   # - !! Note: !!
   # -    for both, local FTP server (ftp_server_ip_arr)
   # -    and forward to FTP server (forward_ftp_server_ip_arr)
   # -
   $ip6t -A PREROUTING -t raw -p tcp --dport $standard_ftp_port -j CT --helper ftp

   if [[ ${#ftp_server_ip_arr[@]} -gt 0 ]] ; then

      for _ip in ${ftp_server_ip_arr[@]} ; do

         # =====
         # -
         # - ip_conntrack_ftp cannot see the TLS-encrypted traffic
         # - ======================================================
         # -
         # - Workaround:
         # -    (1) add source ip to a 'recent list' named 'ftpdata_$i!  if ftp control connections appear
         # -    (2) accept packets of the formaly created recent list 'ftpdata_$i!
         # -
         # =====

         # - (1)
         # -
         # - Accept initial FTP connection and add the source ip to ftpdata recent list 'ftpdata_$i'.
         # -
         $ip6t -A INPUT -p tcp -m conntrack --ctstate NEW -d $_ip --dport 21 -m recent --name ftpdata_$i --set -j ACCEPT

         # - (2)
         # -    - Accept packets if the source ip-address is in the 'ftpdata_$i' list (--update) and the
         # -      source ip-address was seen within the last 1800 seconds (--seconds 1800).
         # -
         # -    - If matched, the "last seen" timestamp of the source address will be updated (--update).
         # -
         # -    - Entries in the ftpdata list not seen in the last 1800 will be removed (--reap).
         # -
         $ip6t -A INPUT -p tcp -m conntrack --ctstate NEW --sport 1024: -d $_ip --dport $ftp_passive_port_range \
            -m recent --name ftpdata_$i --update --seconds 1800 --reap -j ACCEPT

         # - Accept (helper ftp) related connections
         # -
         $ip6t -A INPUT -m conntrack --ctstate RELATED -m helper --helper ftp -d $_ip -p tcp --dport 1024: -j ACCEPT

         ((i++))

      done
   fi

   if [[ ${#forward_ftp_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then

      for _ip in ${forward_ftp_server_ip_arr[@]} ; do

         # =====
         # -
         # - ip_conntrack_ftp cannot see the TLS-encrypted traffic
         # - ======================================================
         # -
         # - Workaround:
         # -    (1) add source ip to a 'recent list' named 'ftpdata_$i!  if ftp control connections appear
         # -    (2) accept packets of the formaly created recent list 'ftpdata_$i!
         # -
         # =====

         # - (1)
         # -
         # - Accept initial FTP connection and add the source ip to ftpdata recent list 'ftpdata_$i'.
         # -
         $ip6t -A FORWARD -p tcp -m conntrack --ctstate NEW -d $_ip --dport $standard_ftp_port -m recent --name ftpdata_$i --set -j ACCEPT

         # - (2)
         # -    - Accept packets if the source ip-address is in the 'ftpdata_$i' list (--update) and the
         # -      source ip-address was seen within the last 1800 seconds (--seconds 1800).
         # -
         # -    - If matched, the "last seen" timestamp of the source address will be updated (--update).
         # -
         # -    - Entries in the ftpdata list not seen in the last 1800 will be removed (--reap).
         # -
         $ip6t -A FORWARD -p tcp -m conntrack --ctstate NEW --sport 1024: -d $_ip --dport $ftp_passive_port_range \
            -m recent --name ftpdata_$i --update --seconds 1800 --reap -j ACCEPT
         $ip6t -A FORWARD -p tcp -m conntrack --ctstate NEW --dport 1024: -s $_ip --sport $ftp_passive_port_range \
            -m recent --name ftpdata_$i --update --seconds 1800 --reap -j ACCEPT

         # - Accept (helper ftp) related connections
         # -
         $ip6t -A FORWARD -m conntrack --ctstate RELATED -m helper --helper ftp -d $_ip -p tcp --dport 1024: -j ACCEPT
         $ip6t -A FORWARD -m conntrack --ctstate RELATED -m helper --helper ftp -s $_ip -p tcp --sport 1024: -j ACCEPT

         ((i++))

      done
   fi

   echo_done
else
   echo_skipped
fi


#echononl "\t\tFTP Server"
#
#if [[ ${#ftp_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_ftp_server_ip_arr[@]} -gt 0 ]]  ; then
#   if [[ ${#ftp_server_ip_arr[@]} -gt 0 ]] ; then
#      for _ip in ${ftp_server_ip_arr[@]} ; do
#            # (Datenkanal aktiv)
#            $ip6t -A OUTPUT -p tcp -s $_ip --sport $standard_ftp_data_port -m conntrack --ctstate NEW -j ACCEPT
#            # Datenkanal (passiver modus)
#            $ip6t -A INPUT -p tcp -d $_ip --dport $unprivports --sport $unprivports -m conntrack --ctstate NEW -j ACCEPT
#            # - Kontrollverbindung
#            $ip6t -A INPUT -p tcp -d $_ip --dport $standard_ftp_port --sport $unprivports -m conntrack --ctstate NEW -j ACCEPT
#      done
#   fi
#
#   if [[ ${#forward_ftp_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
#      for _ip in ${forward_ftp_server_ip_arr[@]} ; do
#         # (Datenkanal aktiv)
#         $ip6t -A FORWARD -p tcp -s $_ip --sport $standard_ftp_data_port -m conntrack --ctstate NEW -j ACCEPT
#         # Datenkanal (passiver modus)
#         $ip6t -A FORWARD -p tcp -d $_ip --dport $unprivports --sport $unprivports -m conntrack --ctstate NEW -j ACCEPT
#         # - Kontrollverbindung
#         $ip6t -A FORWARD -p tcp -d $_ip --dport $standard_ftp_port --sport $unprivports -m conntrack --ctstate NEW -j ACCEPT
#      done
#   fi
#
#   echo_done
#else
#   echo_skipped
#fi


# ---
# - XMPP Service (Jabber)
# ---

echononl "\t\tXMPP Service"

if [[ ${#xmpp_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_xmpp_server_ip_arr[@]} -gt 0 ]]  ; then

   if [[ ${#xmpp_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${xmpp_server_ip_arr[@]} ; do
         for _port in ${xmmp_tcp_in_port_arr[@]} ; do
            $ip6t -A INPUT -p tcp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done

         for _port in ${xmmp_tcp_out_port_arr[@]} ; do
            $ip6t -A OUTPUT -p tcp -s $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi


   if  [[ ${#forward_xmpp_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_xmpp_server_ip_arr[@]} ; do
         for _port in ${xmmp_tcp_in_port_arr[@]} ; do
            $ip6t -A FORWARD -p tcp -d $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done

         for _port in ${xmmp_tcp_out_port_arr[@]} ; do
            $ip6t -A FORWARD -p tcp -s $_ip --dport $_port -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# -  XMPP Remote Dovecote Out Service
# ---

echononl "\t\tXMPP Remote Dovecote Out Service"

if [[ ${#xmmp_remote_out_service_arr[@]} -gt 0 ]] ; then
   for _dev in "${ext_if_arr[@]}" ; do
      for _val in "${xmmp_remote_out_service_arr[@]}" ; do
         IFS=',' read -a _val_arr <<< "${_val}"
         $ip6t -A OUTPUT -o $_dev -p tcp -d ${_val_arr[0]} --dport ${_val_arr[1]} -m conntrack --ctstate NEW -j ACCEPT
      done
   done
   echo_done
else
   echo_skipped
fi


# ---
# - Mumble Service
# ---

echononl "\t\tMumble Service"


if [[ ${#mumble_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_mumble_server_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#mumble_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${mumble_server_ip_arr[@]} ; do
         $ip6t -A INPUT -p tcp -d $_ip -m multiport --dports $mumble_ports -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A INPUT -p udp -d $_ip -m multiport --dports $mumble_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   if [[ ${#forward_mumble_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_mumble_server_ip_arr[@]} ; do
         $ip6t -A FORWARD -p tcp -d $_ip -m multiport --dports $mumble_ports -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A FORWARD -p udp -d $_ip -m multiport --dports $mumble_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Jitsi Video Conferencing Service
# ---

echononl "\t\tJitsi Meet Video Conferencing Service Incoming Ports"


if [[ ${#jitsi_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_jitsi_server_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#jitsi_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${jitsi_server_ip_arr[@]} ; do
         if ! containsElement "$_ip" "${http_server_ip_arr[@]}" || [[ "$jitsi_tcp_ports" != "$standard_http_ports" ]] ; then
            $ip6t -A INPUT -p tcp -d $_ip -m multiport --dports $jitsi_tcp_ports -m conntrack --ctstate NEW -j ACCEPT
         fi
         $ip6t -A INPUT -p udp -d $_ip -m multiport --dports $jitsi_udp_port_range -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   if [[ ${#forward_jitsi_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_jitsi_server_ip_arr[@]} ; do
         if ! containsElement "$_ip" "${http_server_ip_arr[@]}" || [[ "$jitsi_tcp_ports" != "$standard_http_ports" ]] ; then
            $ip6t -A FORWARD -p tcp -d $_ip -m multiport --dports $jitsi_tcp_ports -m conntrack --ctstate NEW -j ACCEPT
         fi
         $ip6t -A FORWARD -p udp -d $_ip -m multiport --dports $jitsi_udp_port_range -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   echo_done
else
   echo_skipped
fi

echononl "\t\tJitsi Meet Video Conferencing Service Outgoing Ports"
if [[ ${#jitsi_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_jitsi_server_ip_arr[@]} -gt 0 ]] ; then
   if [[ ${#jitsi_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${jitsi_server_ip_arr[@]} ; do
         $ip6t -A OUTPUT -p tcp -s $_ip -m multiport --dports $jitsi_tcp_ports_out -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A OUTPUT -p udp -s $_ip -m multiport --dports $jitsi_udp_ports_out -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   if [[ ${#forward_jitsi_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_jitsi_server_ip_arr[@]} ; do
         $ip6t -A FORWARD -p tcp -s $_ip -m multiport --dports $jitsi_tcp_ports_out -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A FORWARD -p udp -s $_ip -m multiport --dports $jitsi_udp_ports_out -m conntrack --ctstate NEW -j ACCEPT
      done
   fi
   echo_done
else
   echo_skipped
fi

echononl "\t\tJitsi Meet Dovecot Authentication"
if [[ ${#jitsi_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_jitsi_server_ip_arr[@]} -gt 0 ]] ; then
   if $jitsi_dovecot_auth && [[ -n "$jitsi_dovecot_host" ]] && [[ -n "$jitsi_dovecot_port" ]] ; then
      if [[ ${#jitsi_server_ip_arr[@]} -gt 0 ]] ; then
         $ip6t -A OUTPUT -p tcp -d $jitsi_dovecot_host --dport $jitsi_dovecot_port -m conntrack --ctstate NEW -j ACCEPT
      fi

      if [[ ${#forward_jitsi_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
         $ip6t -A FORWARD -p tcp -d $jitsi_dovecot_host --dport $jitsi_dovecot_port -m conntrack --ctstate NEW -j ACCEPT
      fi
      echo_done
   else
      echo_skipped
   fi
else
   echo_skipped
fi

echononl "\t\tJitsi Remote Jibri Client"
if [[ ${#jitsi_server_ip_arr[@]} -gt 0 ]] \
      && $jitsi_jibri_remote_auth \
      && [[ ${#jitsi_jibri_remote_ip_arr[@]} -gt 0 ]] ; then
   for _ip in ${jitsi_jibri_remote_ip_arr[@]} ; do
      $ip6t -A INPUT -p tcp -s  $_ip --dport $jitsi_jibri_remote_auth_port -m conntrack --ctstate NEW -j ACCEPT
   done

   echo_done
else
   echo_skipped
fi


# ---
# - Jibri Recording / Streaming Service
# ---

echononl "\t\tJibri Recording / Streaming Service"
if [[ ${#jibri_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_jibri_server_ip_arr[@]} -gt 0 ]]; then

   if [[ -z "$jibri_remote_jitsi_server" ]]; then
      echo_skipped
   else
      if [[ ${#jibri_server_ip_arr[@]} -gt 0 ]] ; then
         for _ip in ${jibri_server_ip_arr[@]} ; do
            $ip6t -A OUTPUT -p tcp -s $_ip -d $jibri_remote_jitsi_server --dport $jibri_remote_auth_port -m conntrack --ctstate NEW -j ACCEPT
            $ip6t -A OUTPUT -p udp -s $_ip -d $jibri_remote_jitsi_server -m multiport --dports $standard_jitsi_udp_port_range  -m conntrack --ctstate NEW -j ACCEPT
            $ip6t -A OUTPUT -p udp -s $_ip -m multiport --dports $default_outbound_streaming_tcp_ports  -m conntrack --ctstate NEW -j ACCEPT
         done
      fi

      if [[ ${#forward_jibri_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
         for _ip in ${forward_jibri_server_ip_arr[@]} ; do
            $ip6t -A FORWARD -p tcp -s $_ip -d $jibri_remote_jitsi_server --dport $jibri_remote_auth_port -m conntrack --ctstate NEW -j ACCEPT
            $ip6t -A FORWARD -p udp -s $_ip -d $jibri_remote_jitsi_server -m multiport --dports $standard_jitsi_udp_port_range  -m conntrack --ctstate NEW -j ACCEPT
            $ip6t -A FORWARD -p udp -s $_ip -m multiport --dports $default_outbound_streaming_tcp_ports  -m conntrack --ctstate NEW -j ACCEPT
         done
      fi

      echo_done
   fi
else
   echo_skipped
fi


# ---
# - TURN Service (for NC Talk App)
# ---

echononl "\t\tTURN Service (for NC Talk App) both: udp and tcp"

if [[ ${#nc_turn_server_ip_arr[@]} -gt 0 ]] || [[ ${#forward_nc_turn_server_ip_arr[@]} -gt 0 ]]  ; then

   if [[ ${#nc_turn_server_ip_arr[@]} -gt 0 ]] ; then
      for _ip in ${nc_turn_server_ip_arr[@]} ; do
         $ip6t -A INPUT -p tcp -d $_ip -m multiport --dports $nc_turn_ports -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A INPUT -p udp -d $_ip -m multiport --dports $nc_turn_ports -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A INPUT -p udp -d $_ip -m multiport --dports $nc_turn_udp_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi

   if  [[ ${#forward_nc_turn_server_ip_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _ip in ${forward_nc_turn_server_ip_arr[@]} ; do
         $ip6t -A FORWARD -p tcp -d $_ip -m multiport --dports $nc_turn_ports -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A FORWARD -p udp -d $_ip -m multiport --dports $nc_turn_ports -m conntrack --ctstate NEW -j ACCEPT
         $ip6t -A FORWARD -p udp -d $_ip -m multiport --dports $nc_turn_udp_ports -m conntrack --ctstate NEW -j ACCEPT
      done
   fi


   echo_done
else
   echo_skipped
fi


# ---
# - Timeserver (Port 37 NOT NTP!)"
# ---

echononl "\t\tTimeserver (Port 37 NOT NTP!) out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_timeserver_port  -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_timeserver_port  -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - NTP out only"
# ---

echononl "\t\tNTP out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_ntp_port  -m conntrack --ctstate NEW -j ACCEPT
   $ip6t -A OUTPUT -o $_dev -p udp --dport $standard_ntp_port  -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_ntp_port  -m conntrack --ctstate NEW -j ACCEPT
      $ip6t -A FORWARD -o $_dev -p udp --dport $standard_ntp_port  -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - NTP local Service"
# ---

echononl "\t\tNTP local Service"
if [[ -n "$local_ntp_service" ]] && $local_ntp_service  ; then
   if [[ -z "$ntp_allowed_net" ]] ; then
      echo_failed
   else
      $ip6t -A OUTPUT -p udp -d $ntp_allowed_net --dport $ntp_port -m conntrack --ctstate NEW -j ACCEPT
      $ip6t -A INPUT -p udp -s $ntp_allowed_net --dport $ntp_port -m conntrack --ctstate NEW -j ACCEPT
      echo_done
   fi
else
   echo_skipped
fi


# ---
# - LDAP out only
# ---

echononl "\t\tLDAP out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_ldap_port  -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_ldap_port  -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - LDAPS out only
# ---

echononl "\t\tLDAPS out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_ldaps_port  -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_ldaps_port  -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - Whois out only
# ---

echononl "\t\tWhois out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_whois_port  -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_whois_port  -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - PGP Keyserver  out only
# ---

echononl "\t\tPGP/GPG Key server - out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_pgp_keyserver_port  -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_pgp_keyserver_port  -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done


# ---
# - GIT out only
# ---

echononl "\t\tGIT out only"

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p tcp --dport $standard_git_port  -m conntrack --ctstate NEW -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p tcp --dport $standard_git_port  -m conntrack --ctstate NEW -j ACCEPT
   fi
done

echo_done
echo


# ---
# - Special TCP Ports OUT
# ---

echononl "\t\tSpecial TCP Ports OUT"

if [[ ${#tcp_out_port_arr[@]} -gt 0 ]] || [[ ${#forward_tcp_out_port_arr[@]} -gt 0 ]] ; then

   if [[ ${#tcp_out_port_arr[@]} -gt 0 ]] ; then

      for _dev in ${ext_if_arr[@]} ; do
         for _port in ${tcp_out_port_arr[@]} ; do
            $ip6t -A OUTPUT -o $_dev -p tcp --dport $_port  -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   if [[ ${#forward_tcp_out_port_arr[@]} -gt 0 ]] && $kernel_forward_between_interfaces ; then
      for _dev in ${ext_if_arr[@]} ; do
         for _port in ${tcp_out_port_arr[@]} ; do
            $ip6t -A FORWARD -o $_dev -p tcp --dport $_port  -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   echo_done
else
   echo_skipped
fi


# ---
# - Special UDP Ports OUT
# ---

echononl "\t\tSpecial UDP Ports OUT"

if [[ ${#udp_out_port_arr[@]} -gt 0 ]] || [[ ${#forward_udp_out_port_arr[@]} -gt 0 ]] ; then
   if [[ ${#udp_out_port_arr[@]} -gt 0 ]] ; then
      for _dev in ${ext_if_arr[@]} ; do
         for _port in ${udp_out_port_arr[@]} ; do
            $ip6t -A OUTPUT -o $_dev -p udp --dport $_port  -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   if [[ ${#forward_udp_out_port_arr[@]} -gt 0 ]] ; then
      for _dev in ${ext_if_arr[@]} ; do
         for _port in ${forward_udp_out_port_arr[@]} ; do
            $ip6t -A FORWARD -o $_dev -p udp --dport $_port  -m conntrack --ctstate NEW -j ACCEPT
         done
      done
   fi

   echo_done
else
   echo_skipped
fi

echo

# -------------
# --- Portforwarding
# -------------

# ---
# - Portforwarding TCP
# ---

echononl "\t\tPortforwarding TCP"

if [[ ${#portforward_tcp_arr[@]} -gt 0 ]] ; then
   for _val in "${portforward_tcp_arr[@]}" ; do

      # - Split value
      # -
      IFS=',' read -a _val_arr <<< "${_val}"

      # - Allow Packets IN
      # -
      $ip6t -A INPUT -i ${_val_arr[0]} -p tcp -d ${_val_arr[1]} --dport ${_val_arr[2]} -m conntrack --ctstate NEW -j ACCEPT

      # - Allow Packets FORWARD
      # -
      $ip6t -A FORWARD -i ${_val_arr[0]} -p tcp -d ${_val_arr[3]} --dport ${_val_arr[4]} -m conntrack --ctstate NEW -j ACCEPT

      _job_id="$(ps ax | grep "TCP6-LISTEN:${_val_arr[2]},fork,bind=\[${_val_arr[1]}\]" | grep -v grep  | awk '{print$1}')"
      if [[ -n "$_job_id" ]]; then
         kill ${_job_id} > /dev/null 2>&1
      fi

      socat TCP6-LISTEN:${_val_arr[2]},fork,bind=[${_val_arr[1]}] TCP:[${_val_arr[3]}]:${_val_arr[4]} &

   done
   echo_done
else
   echo_skipped
fi


# ---
# - Portforwarding UDP
# ---

echononl "\t\tPortforwarding UDP"

if [[ ${#portforward_udp_arr[@]} -gt 0 ]] ; then
   for _val in "${portforward_udp_arr[@]}" ; do

      # - Split value
      # -
      IFS=',' read -a _val_arr <<< "${_val}"

      # - Allow Packets IN
      # -
      $ip6t -A INPUT -i ${_val_arr[0]} -p udp -d ${_val_arr[1]} --dport ${_val_arr[2]} -m conntrack --ctstate NEW -j ACCEPT

      # - Allow Packets FORWARD
      # -
      $ip6t -A FORWARD -i ${_val_arr[0]} -p udp -d ${_val_arr[3]} --dport ${_val_arr[4]} -m conntrack --ctstate NEW -j ACCEPT

      _job_id="$(ps ax | grep "UDP6-LISTEN:${_val_arr[2]},fork,bind=\[${_val_arr[1]}\]" | grep -v grep  | awk '{print$1}')"
      if [[ -n "$_job_id" ]]; then
         kill ${_job_id} > /dev/null 2>&1
      fi

      socat UDP6-LISTEN:${_val_arr[2]},fork,bind=[${_val_arr[1]}] UDP:[${_val_arr[3]}]:${_val_arr[4]} &

   done
   echo_done
else
   echo_skipped
fi


echo

# ---
# - UNIX Traceroute
# ---

echononl "\t\tUNIX Traceroute"

#   versendet udp packete im gegensatz zu tracert von windows
#   der icmp-echo-request pakete versendet
#   einige implementierungen von traceroute (linux) erm�lichens
#   die option -I und versenden dann ebenfalls icmp-echo-request pakete

for _dev in ${ext_if_arr[@]} ; do
   $ip6t -A OUTPUT -o $_dev -p udp -m conntrack --ctstate NEW --dport 33434:33530 -j ACCEPT
   $ip6t -A INPUT -i $_dev -p udp -m conntrack --ctstate NEW --dport 33434:33530 -j ACCEPT
   if $kernel_forward_between_interfaces ; then
      $ip6t -A FORWARD -o $_dev -p udp -m conntrack --ctstate NEW --dport 33434:33530 -j ACCEPT
      $ip6t -A FORWARD -i $_dev -p udp -m conntrack --ctstate NEW --dport 33434:33530 -j ACCEPT
   fi
done

echo_done


# ---
# - Ping
# ---

echononl "\t\tPing"

$ip6t -A INPUT -p ipv6-icmp -j ACCEPT
$ip6t -A OUTPUT -p ipv6-icmp -j ACCEPT
if $kernel_forward_between_interfaces ; then
   $ip6t -A FORWARD -p ipv6-icmp -j ACCEPT
fi

#for _dev in ${ext_if_arr[@]} ; do
#   $ip6t -A INPUT -i $_dev -p ipv6-icmp -j ACCEPT
#   $ip6t -A OUTPUT -o $_dev -p ipv6-icmp -j ACCEPT
#   if $kernel_forward_between_interfaces ; then
#      $ip6t -A FORWARD -i $_dev -p ipv6-icmp -j ACCEPT
#      $ip6t -A FORWARD -o $_dev -p ipv6-icmp -j ACCEPT
#   fi
#done
#for _dev in ${local_if_arr[@]} ; do
#   $ip6t -A INPUT -i $_dev -p ipv6-icmp -j ACCEPT
#   $ip6t -A OUTPUT -o $_dev -p ipv6-icmp -j ACCEPT
#   if $kernel_forward_between_interfaces ; then
#      $ip6t -A FORWARD -i $_dev -p ipv6-icmp -j ACCEPT
#      $ip6t -A FORWARD -o $_dev -p ipv6-icmp -j ACCEPT
#   fi
#done

echo_done


# ---
# - log all rejected traffic
# ---

echo
echononl "\tLogging all rejected traffic"

if $log_rejected || $log_all ; then

   $ip6t -A OUTPUT -m limit --limit-burst 5 -p tcp ! --tcp-flags ACK,FIN ACK,FIN -j $LOG_TARGET $tag_log_prefix "$log_prefix Rejected (end of firewall): "
   $ip6t -A OUTPUT -m limit --limit-burst 5 -p udp -j $LOG_TARGET $tag_log_prefix "$log_prefix Rejected (end of firewall): "
   $ip6t -A INPUT -m limit --limit-burst 5 -j $LOG_TARGET $tag_log_prefix "$log_prefix Rejected (end of firewall): "

   if $kernel_forward_between_interfaces ; then
      #$ip6t -A FORWARD -j $LOG_TARGET $tag_log_prefix "$log_prefix Rejected: "
      $ip6t -A FORWARD -m limit --limit-burst 5 -j $LOG_TARGET $tag_log_prefix "$log_prefix Rejected (end of firewall): "
   fi
   echo_done
else
   echo_skipped
fi


# ---
# - Drop all other
# ---

echo
echononl "\tDrop all other on all interfaces"

$ip6t -A INPUT -j DROP
$ip6t -A OUTPUT -j DROP

# Normaly FORWARD pakages shoul be dropped fpr all packages. but on sinma systems it is needed
# to question also 'do_not_firewall_bridged_traffic' and 'do_not_firewall_lx_guest_systems'. 
# Otherwise, LX Container won't work on SINMA systems.
#
if ${do_not_firewall_bridged_traffic} \
   || ${do_not_firewall_lx_guest_systems} ; then
   $ip6t -A FORWARD -j ACCEPT
else
   $ip6t -A FORWARD -j DROP
fi

echo_done



# -------------
# ------------- Reload Fail2Ban if installed
# -------------

if ${FAIL2BAN_WAS_RUNNING}; then
   echo
   echononl "\tReloading fail2ban.."
   $fail2ban_client reload > /dev/null 2>&1
   if [ "$?" = "0" ]; then
      echo_done
   else
      # Fallback: reload + restart jails if needed
      $fail2ban_client reload --restart > /dev/null 2>&1
      if [ "$?" = "0" ]; then
         echo_done
      else
         echo_skipped
         warn "Fail2ban reload failed. Leaving fail2ban unchanged. Check: fail2ban-client -d and /var/log/fail2ban.log"
      fi
   fi
else
   # fail2ban not running before; do not start it here
   :
fi


echo
exit 0

