#!/bin/sh

# check iptables rule specification is exist,
# if not add it
check_and_add_iptables()
{
    iptables -C "$@" > /dev/null 2>&1
    EXIST=$?
    if [ $EXIST -ne 0 ]; then
        iptables -A "$@"
    fi
}

add_input_tcp_filter() {
    check_and_add_iptables INPUT -p tcp -m tcp --dport "$1" -m comment --comment "$2" -j ACCEPT
}

# allow basic services
add_input_tcp_filter 22 SSH
add_input_tcp_filter 2263 SSH
add_input_tcp_filter 80 HTTP
add_input_tcp_filter 443 HTTPS

# allow DNS
check_and_add_iptables INPUT -p tcp --dport 53 -j ACCEPT -m comment --comment "DNS"
check_and_add_iptables INPUT -p udp --dport 53 -j ACCEPT -m comment --comment "DNS"

# allow internal network
check_and_add_iptables INPUT -s 127.0.0.0/24 -m comment --comment "Internal Network" -j ACCEPT
# allow ping
check_and_add_iptables INPUT -p icmp -m comment --comment ping -j ACCEPT
# allow all established and related connections
check_and_add_iptables INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# allow loopback
check_and_add_iptables INPUT -i lo -j ACCEPT
# dropped for INPUT by default
iptables -P INPUT DROP
