#!/bin/sh
#
# Basic Firewall script
#
# Debian System
#
# Author: Rafal Rajs <elessar1@poczta.wp.pl>
#
############################################################################################
#path to the defs file
. /etc/scripts/globals

#
############################################################################################

#default POLICY  

$IPTABLES -P INPUT DROP
$IPTABLES -P FORWARD DROP
$IPTABLES -P OUTPUT ACCEPT

#
############################################################################################


########
## To avoid this entry in the error log: kernel: ipt_connlimit: Oops: invalid ct state ?, use this rule:

$IPTABLES -A FORWARD -p tcp -m conntrack --ctstate INVALID -j DROP

############################################################################################


############################################################################################
# connlimits

j=1

while [ $j -lt $L_USERS ]
do
	$IPTABLES -A FORWARD -s ${USER_IP[${j}]} -p tcp -m connlimit --connlimit-above $MAX_CONNS -j REJECT --reject-with tcp-reset
	j=$[$j+1]
done;


# LIMIT server traffic, excluding 22 (ssh) access
$IPTABLES -A OUTPUT -o $ZEW -s ${USER_IP[${L_USERS}]} -p tcp --sport ! 22 -m connlimit --connlimit-above $MAX_CONNS -j REJECT --reject-with tcp-reset


## allow only defined IP Addresses

j=1

while [ $j -lt $L_USERS ]
do
	$IPTABLES -A FORWARD -s ${USER_IP[${j}]} -j ACCEPT
	$IPTABLES -A FORWARD -d ${USER_IP[${j}]} -j ACCEPT
	j=$[$j+1]
done;

## allow loopback
$IPTABLES -A INPUT -i lo -j ACCEPT

## allow access to the server from internal network
$IPTABLES -A INPUT -i $WEW -j ACCEPT

###limits on the external interface

# allow established connections
$IPTABLES -A INPUT -i $ZEW -m state --state ESTABLISHED,RELATED -j ACCEPT

####custom services
## SSH
$IPTABLES -A INPUT -i $ZEW -p tcp --dport 22 -m state --state NEW -j ACCEPT
 
##pings
$IPTABLES -A INPUT -i $ZEW -p icmp --icmp-type echo-request -j ACCEPT

