#!/bin/bash

MYSELF=$( basename $0 )

script_help() {
    cat <<EOF
${MYSELF} help:

This script initializes iptables

Usage: ${MYSELF} -s <SYSTEM>

where:
    SYSTEM ... dev (development) | dep (deploy)

EOF
}

if [[ $# -lt 2 ]]
then
    script_help
    exit 1
fi

while getopts "s:" option
do
    case ${option} in
    s)  SYSTEM=$OPTARG
        ;;
    *)  script_help
        exit 2
        ;;
    esac
done

if [[ $UID -gt 0 ]]
then
    echo "$MYSELF needs to be run as superuser. You are $USER."
    exit 3
fi

IPT="/sbin/iptables"
PUB_IF="eth0"
DHCP_IF="eth1"
VPN_IF="tun0"
LH_NET="127.0.0.0/8"
AIRPOINTER_NET="172.19.0.0/16"
HEADQUARTERS_NET="10.10.1.0/24"
OPENVPN_NET="172.17.20.0/24"
DHCP_NET="172.17.2.0/24"
VPN_NET="10.88.0.0/16"
RECORDUM_WIRE_WAN="88.116.128.194"
RECORDUM_LTE_WAN="178.115.237.41"

# the flush removes the fail2ban rule(s) - these will be re-added upon reboot/fail2ban restart
echo "Flush iptable rules"
${IPT} -F
${IPT} -X
${IPT} -t nat -F
${IPT} -t nat -X
${IPT} -t mangle -F
${IPT} -t mangle -X

# Create separate chains for TCP and UDP to traverse
echo "Create our user chains for access port handling and throttling"
${IPT} -N TCP_TRAFFIC
${IPT} -N UDP_TRAFFIC
${IPT} -N ICMP_TRAFFIC
${IPT} -N IN_HTTP
${IPT} -N IN_HTTP_SSL
${IPT} -N IN_SSH
if [[ -n "$SYSTEM" ]] && [[ "$SYSTEM" == "dev" ]]
then
    ${IPT} -N REST_HTTP_SSL
fi

echo "Set default policy"
${IPT} -P INPUT   DROP
${IPT} -P FORWARD DROP
${IPT} -P OUTPUT  ACCEPT

# samba and postgresql via openvpn for development machines
if [[ -n "$SYSTEM" ]] && [[ "$SYSTEM" == "dev" ]]
then
    echo "Activate ports (Samba, Postgresql, REST) for development systems"
fi

# allow traffic that belongs to established connections, or new valid traffic
# that is related to these connections
echo "allow traffic that belongs to established connections"
${IPT} -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

echo "Allow all on localhost"
# Allows all loopback (lo) traffic and drop all traffic to 127.0.0.0/8 that doesn't use lo
${IPT} -A INPUT -i lo -j ACCEPT
${IPT} -A INPUT ! -i lo -d ${LH_NET} -j REJECT
echo "Allow all on vpn tunnel"
# Allows all tunnel (tun0) traffic
#${IPT} -A INPUT -i ${VPN_IF} -j ACCEPT
# Drop all traffic to 10.88.0.0/16 that doesn't use tun0
${IPT} -A INPUT ! -i ${VPN_IF} -d ${VPN_NET} -j REJECT

# Protection against spoofing attacks
# Blocking reserved local addresses incoming from the internet or local network is normally done through
# setting rp_filter (Reverse Path Filter) in sysctl to 1. To do so, add the following line to your
# /etc/sysctl.d/local.conf file (see sysctl for details) to enable source address verification which is
# built into Linux kernel itself. The verification by the kernel will handle spoofing better than individual
# iptables rules for each case.
#
# net.ipv4.conf.all.rp_filter=1

echo "Drop invalid traffic"
# ICMPv6 Neighbor Discovery packets remain untracked, and will always be classified "INVALID" though
# they are not corrupted or the like. Keep this in mind, and accept them before the INVALID DROP.
${IPT} -A INPUT -p 41 -j ACCEPT
# This rule will drop all packets with invalid headers or checksums, invalid TCP flags, invalid ICMP messages
# (such as a port unreachable when we did not send anything to the host), and out of sequence packets which 
# can be caused by sequence prediction or other similar attacks.
# The "DROP" target will drop a packet without any response, contrary to REJECT which politely refuses
# the packet. We use DROP because there is no proper "REJECT" response to packets that are INVALID, and we
# do not want to acknowledge that we received these packets.
${IPT} -A INPUT -m conntrack --ctstate INVALID -j DROP

# Now we attach the TCP and UDP chains to the INPUT chain to handle all new incoming connections.
# Once a connection is accepted by either TCP or UDP chain, it is handled by the RELATED/ESTABLISHED
# traffic rule. The TCP and UDP chains will either accept new incoming connections, or politely reject
# them. New TCP connections must be started with SYN packets.
#
# NEW but not SYN is the only invalid TCP flag not covered by the INVALID state. The reason is because
# they are rarely malicious packets, and they should not just be dropped. Instead, we simply do not
# accept them, so they are rejected with a TCP RST by the next rule.
echo "Attach our private traffic chains"
# allow ports only with throttling
${IPT} -A INPUT -p tcp --dport  22 -m conntrack --ctstate NEW -j IN_SSH
${IPT} -A INPUT -p tcp --dport  80 -m conntrack --ctstate NEW -j IN_HTTP
${IPT} -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -j IN_HTTP_SSL
if [[ -n "$SYSTEM" ]] && [[ "$SYSTEM" == "dev" ]]
then
    ${IPT} -A INPUT -p tcp --dport 18181 -m conntrack --ctstate NEW -j REST_HTTP_SSL
fi
# optional: all http(s) access on all interfaces except the public interface
# this forces the usage of the openvpn connection and our secure server (recordum.net)
#${IPT} -A INPUT -p tcp --dport  80 -m conntrack ! -i ${PUB_IF} --ctstate NEW -j IN_HTTP
#${IPT} -A INPUT -p tcp --dport 443 -m conntrack ! -i ${PUB_IF} --ctstate NEW -j IN_HTTP_SSL
# split traffic by protocol
${IPT} -A INPUT -p tcp --syn -m conntrack --ctstate NEW -j TCP_TRAFFIC
${IPT} -A INPUT -p udp -m conntrack --ctstate NEW -j UDP_TRAFFIC
${IPT} -A INPUT -p icmp -m conntrack --ctstate NEW -j ICMP_TRAFFIC

echo "Deny the rest but be polite about it"
# We reject TCP connections with TCP RST packets and UDP streams with ICMP port unreachable messages
# if the ports are not opened. This imitates default Linux behavior (RFC compliant), and it allows
# the sender to quickly close the connection and clean up. Also add hosts with rejected packets to
# the TCP-PORTSCAN list.
${IPT} -A INPUT -p tcp -m recent --set --name TCP-PORTSCAN -j REJECT --reject-with tcp-rst
${IPT} -A INPUT -p udp -m recent --set --name UDP-PORTSCAN -j REJECT --reject-with icmp-port-unreachable
# For other protocols, we add a final rule to the INPUT chain to reject all remaining incoming traffic
# with icmp protocol unreachable messages. This imitates Linux's default behavior.
${IPT} -A INPUT -j REJECT --reject-with icmp-proto-unreachable

# add allowed traffic ports to the TCP_TRAFFIC/UDP_TRAFFIC chains
echo "Fill the private traffic chains"
### TCP_TRAFFIC ###
# First, insert a rule at the top of the TCP_TRAFFIC chain. This rule responds with a TCP RST to any host
# that got onto the TCP-PORTSCAN list in the past sixty seconds. The --update switch causes the recent list
# to be updated, meaning the 60 second counter is reset.
${IPT} -I TCP_TRAFFIC -p tcp -m recent --update --seconds 60 --name TCP-PORTSCAN -j REJECT --reject-with tcp-rst
# glibc CVE-2015-7547 fix; and be rude about it -> DROP
echo "glibc CVE-2015-7547 fix"
${IPT} -A TCP_TRAFFIC -p tcp -m tcp --sport 53 -m length --length 2048:65535 -j DROP
# open general ports
echo "Allow incoming tcp connections to modbus (502, 1502) and linout (21562)"
${IPT} -A TCP_TRAFFIC -p tcp -m multiport --dports 502,1502,21562 -j ACCEPT
# now open network only ports
echo "Allow incoming connections for ${DHCP_NET} to postgresql"
${IPT} -A TCP_TRAFFIC -p tcp -i ${DHCP_IF} -s ${DHCP_NET} --dport 5432 -j ACCEPT
echo "Allow incoming connections for ${AIRPOINTER_NET} to postgresql"
${IPT} -A TCP_TRAFFIC -p tcp -i ${PUB_IF} -s ${AIRPOINTER_NET} --dport 5432 -j ACCEPT
echo "Allow incoming connections for ${HEADQUARTERS_NET} to postgresql"
${IPT} -A TCP_TRAFFIC -p tcp -i ${PUB_IF} -s ${HEADQUARTERS_NET} --dport 5432 -j ACCEPT
if [[ -n "$SYSTEM" ]] && [[ "$SYSTEM" == "dev" ]]
then
    ${IPT} -A TCP_TRAFFIC -p tcp -i ${PUB_IF} -s ${AIRPOINTER_NET} -m multiport --dports 139,445 -j ACCEPT
    echo "Allow incoming connections for ${OPENVPN_NET} to postgresql"
    ${IPT} -A TCP_TRAFFIC -p tcp -i ${PUB_IF} -s ${OPENVPN_NET} --dport 5432 -j ACCEPT
fi

### UDP_TRAFFIC ###
# First, add a rule to reject packets from hosts on the UDP-PORTSCAN list to the top of the UDP chain. 
${IPT} -I UDP_TRAFFIC -p udp -m recent --update --seconds 60 --name UDP-PORTSCAN -j REJECT --reject-with icmp-port-unreachable
# glibc CVE-2015-7547 fix; and be rude about it -> DROP
echo "glibc CVE-2015-7547 fix"
${IPT} -A UDP_TRAFFIC -p udp -m udp --sport 53 -m length --length 2048:65535 -j DROP
echo "Allow incoming udp connections to port: AIP (20010, 20070), Horiba (56790)"
${IPT} -A UDP_TRAFFIC -p udp -m multiport --dports 20010,20070,56790 -j ACCEPT
${IPT} -A UDP_TRAFFIC -p udp -i ${PUB_IF} -m multiport --dports 137,138 -j ACCEPT
# now open interface only ports
echo "Allow incoming DHCP requests"
${IPT} -A UDP_TRAFFIC -p udp -i ${DHCP_IF} --dport 67:68 --sport 67:68 -j ACCEPT
echo "Allow incoming connections for ${DHCP_NET} to port 123 (ntp syncs)"
${IPT} -A UDP_TRAFFIC -p udp -i ${DHCP_IF} -s ${DHCP_NET} -m multiport --dports 123 -j ACCEPT

### ICMP_TRAFFIC ###
# Accept all new incoming ICMP request, as blocking creates more heartburn than good
echo "Allow icmp traffic"
# Drop deprecated "Source Quench" type: 4; the one "bad" icmp type
${IPT} -A ICMP_TRAFFIC -p icmp --icmp-type 4 -j DROP
# throttle the rest
${IPT} -A ICMP_TRAFFIC -m recent --name ICMP-THROTTLE --rttl --rcheck --hitcount 10 --seconds 1 -j DROP
${IPT} -A ICMP_TRAFFIC -m recent --name ICMP-THROTTLE --set -j ACCEPT

### TCP THROTTLE ###
# now open ssh, http(s) with throttling
echo "Throttle incoming http traffic"
${IPT} -A IN_HTTP -m recent --name HTTP-THROTTLE --rttl --rcheck --hitcount 20 --seconds 2 -j LOG --log-prefix "RATELIMIT HTTP: "
${IPT} -A IN_HTTP -m recent --name HTTP-THROTTLE --rttl --rcheck --hitcount 20 --seconds 2 -j DROP
${IPT} -A IN_HTTP -m recent --name HTTP-THROTTLE --set -j ACCEPT
echo "Throttle incoming https traffic"
${IPT} -A IN_HTTP_SSL -m recent --name HTTP-SSL-THROTTLE --rttl --rcheck --hitcount 20 --seconds 2 -j LOG --log-prefix "RATELIMIT HTTPS: "
${IPT} -A IN_HTTP_SSL -m recent --name HTTP-SSL-THROTTLE --rttl --rcheck --hitcount 20 --seconds 2 -j DROP
${IPT} -A IN_HTTP_SSL -m recent --name HTTP-SSL-THROTTLE --set -j ACCEPT
echo "Throttle incoming ssh traffic"
${IPT} -A IN_SSH -s ${RECORDUM_WIRE_WAN} -j ACCEPT
${IPT} -A IN_SSH -s ${RECORDUM_LTE_WAN} -j ACCEPT
${IPT} -A IN_SSH -m recent --name SSH-THROTTLE --rttl --rcheck --hitcount 3 --seconds 10 -j LOG --log-prefix "RATELIMIT SSH: "
${IPT} -A IN_SSH -m recent --name SSH-THROTTLE --rttl --rcheck --hitcount 3 --seconds 10 -j DROP
${IPT} -A IN_SSH -m recent --name SSH-THROTTLE --set -j ACCEPT
if [[ -n "$SYSTEM" ]] && [[ "$SYSTEM" == "dev" ]]
then
    echo "Throttle incoming REST traffic"
    ${IPT} -A REST_HTTP_SSL -m recent --name REST-THROTTLE --rttl --rcheck --hitcount 20 --seconds 2 -j LOG --log-prefix "RATELIMIT REST: "
    ${IPT} -A REST_HTTP_SSL -m recent --name REST-THROTTLE --rttl --rcheck --hitcount 20 --seconds 2 -j DROP
    ${IPT} -A REST_HTTP_SSL -m recent --name REST-THROTTLE --set -j ACCEPT
fi

exit 0
