simple statefull firewall with iptables

Today, I was very very nervous ! Believe ! I’m ! So, I decided paste this simple script that I did a long time ago, but BELIEVE ! WORK and  is EFFECTIVE !

Brief resume, of why I’m posting this script:
frw~ # iptables -nvL

Chain INPUT (policy ACCEPT 215K packets, 38M bytes)
Chain FORWARD (policy ACCEPT 4848K packets, 3768M bytes)
Chain OUTPUT (policy ACCEPT 78397 packets, 11M bytes)

This is what really import at this moment ! Rules of the INPUT and FORWARD CHAIN, I not will show, because the target of rule is ACCEPT and  the POLICY of CHAIN IS ACCEPT too , thus,  WHY RULES WITH ACCEPT !???? make no sense !

Alright, a simple script …

# cat

# Simple firewall

ipt=$(which iptables)
# Set yours ifaces here

# Clear all rulez at tables FILTER and NAT ( -F ) and delete chains predeffined by user (-X) and set POLICY ACCEPT

defaccept() {

$ipt -F
$ipt -X
$ipt -t nat -F
$ipt -t nat -X

# Default Policy 😉 ( firewall begins here 😉 )

defdrop() {


# Allowing local traffic at loopback interface ( and doing statefullllllll

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

$ipt -A INPUT -i $iface -m state –state RELATED,ESTABLISHED -j ACCEPT
$ipt -A OUTPUT -o $iface -p tcp –dport 53 -j ACCEPT
$ipt -A OUTPUT -o $iface -p udp –dport 53 -j ACCEPT
$ipt -A OUTPUT -o $iface -p tcp –syn -m state –state NEW -j ACCEPT
$ipt -A OUTPUT -o $iface -p icmp –icmp-type echo-request -j ACCEPT
$ipt -A OUTPUT -o $iface -m state –state RELATED,ESTABLISHED -j ACCEPT

# Allowing necessary services

dispserv() {

$ipt -A INPUT -i $iface -p tcp -m multiport –dport 22 -j ACCEPT
$ipt -A INPUT -i $iface -p udp -m multiport –dport 5000,8000:9000 -j ACCEPT

case $1 in
start) defdrop && dispserv ;;
stop) defaccept ;;
reload) defaccept && defdrop && dispserv ;;
statefull) defaccept && defdrop ;;
test) defdrop && dispserv && sleep 40 && defaccept ;;
*) echo “Uso: “$0″ start, stop, reload, statefull, test” ;;

This firewall is very very simple, and is designed to allow only running services, in this example, asterisk and ssh.
Permit DNS searches and ping ( echo request ) .
Statefull is Accept connections only generated by firewall

Adjust to yours purposes and execute it

#  chmod +x
# ./ start

# iptables -nvL

See by you the diference.





This entry was posted in Network and tagged , . Bookmark the permalink.