Sunday, June 26, 2016

iptables: Setting Up iptables: Accept Only Output and Reject Input

Command (Checking current settings for iptables):

$ sudo iptables -L -v
[sudo] password for username:

Result:

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination      

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination      

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination


Command (Create a script):

$ cat ~/bin/set_firewall

Result:

#!/bin/bash

#Deleting every configurations
iptables -F
iptables -X

#Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

#Accept ping
iptables -A INPUT -p icmp -j ACCEPT

#Accept loopback
iptables -A INPUT -i lo -j ACCEPT

#Open using ports
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

#After session is established, let packets through
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#Save the configurations
iptables-save


Command (Add execution mode):

$ sudo chmod +x ./set_firewall 


Command (Execute the script):

$ sudo ./set_firewall 

Result:

# Generated by iptables-save v1.6.0 on Sun Jun 26 11:24:41 2016
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
COMMIT
# Completed on Sun Jun 26 11:24:41 2016


Command (Checking current settings for iptables):

$ sudo iptables -L -v
[sudo] password for username:

Result:

Chain INPUT (policy DROP 376K packets, 21M bytes)
 pkts bytes target     prot opt in     out     source               destination        
  262 15437 ACCEPT     icmp --  any    any     anywhere             anywhere          
    0     0 ACCEPT     all  --  lo     any     anywhere             anywhere          
  637 35360 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:http
17217 2332K ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:ssh
    0     0 ACCEPT     all  --  any    any     anywhere             anywhere             state RELATED,ESTABLISHED

Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination        

Chain OUTPUT (policy ACCEPT 17561 packets, 3529K bytes)
 pkts bytes target     prot opt in     out     source               destination