Saturday, July 5, 2008

IpChains

Task

Write a iptables script that blocks everything except ping (icmp) and ssh (port 22), http (80) and https (443).

Solution
  #!/bin/bash
export ipt=/sbin/iptables
$ipt -F #Flush all the rules one by one
$ipt -X #Zero all standard chains and statistic counters
$ipt -Z #Erase all user created chains
#Three commands above anything that might have existed prior to running the script to make sure there is a clean slate.
$ipt -P INPUT ACCEPT #Create a behavior for INPUT policy, which is to accept
$ipt -P OUTPUT ACCEPT #Create a behavior for OUTPUT policy, which is to accept
$ipt -P FORWARD ACCEPT # Create a behavior for FORWARD policy, which is to accept

#We call iptables and tell it to Append to the INPUT policy.
#This line allows traffic to go through port 22
$ipt -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
$ipt -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
$ipt -A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
$ipt -A INPUT -m state --state NEW -m tcp -p tcp -j DROP

#Allow pings
#Ping requires the ability to accept packets and send packet back out.
#Ping is a layer 3,ICMP operation.
#In order to allow it our protocol now becomes icmp instead of tcp. We do not need any modules.
#Ping packets are able to be received.
$ipt -A INPUT -p icmp -j ACCEPT

#Ping packets are able to be sent
$ipt -A OUTPUT -p icmp -j ACCEPT
-m says load a module state which allows access to the connection tracking state of the packets
--state precedes a comma separated list of the connection states to match. In this case it's NEW.
NEW the packet has started a new connection or a connection that has not seen packets going in both directions
-m tcp load the tcp module (just like we loaded the state module) this module allows us extra functionality with tcp
-p tcp specifies protocol, in my case TCP
--dport 22 feature provided by the -m tcp module, in this case I want the rule to be applicable to port 22 (ssh).
-j ACCEPT means the results of this chain is to accept the packets. (-j specifies the target of the rule if the packet matches the rule. If I said -j DROP we would block all traffic to port 22).

No comments: