Iptables works with tables

Default: filter

Within tables there are:

  • Chaines
    • Input
    • Output
    • Forward
    • Pre route (before routing a packet)
    • Post route (after ...)

Within a chain there are:

  • Rules: what should happen to a packet

    • Ordering is important
    • If rule matches it will be applied and nothing more will be happend
    • the -j switch, specifies the target:
      • accept
      • drop
      • reject: sender will get an ICMP message that something went wrong
  • Policy

    • Policy is the default behavior
    • It's a good practice to have policy that drops everything that don't match a rule in a chain

basic syntax

In [ ]:
iptable -a CHAIN [-i/-o if] [-s/-d  source/dest addr]  -p (protocol) --sport/--dport NUM -j TARGET

-a : append to the end of a chain: INPUT/OUT/...
-i : income interface
-o : outgoing interface
-s : source address
-d : destination addresss
-p : protocol
--sport: source port
--dport: destination port
-j : target: accept, reject, drop

List everything that been currently used:

In [ ]:
iptables -L # List everything that been currently in use
In [ ]:
iptables -F # flush everything


In [ ]:
In [ ]:
iptables -P INPUT DROP
In [ ]:

Enable in/out on loopback

In [ ]:
iptables -A INPUT -j ACCEPT -i lo
In [ ]:
iptables -A OUTPUT -j ACCEPT -o lo

Allow ssh

In [ ]:
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
In [ ]:
iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT

Allow http

In [ ]:
iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT

Allow DNS

In [ ]:
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

Allow related traffic

In [ ]:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT


In [ ]:
iptables -A INPUT -j LOG
In [ ]:
iptables -A OUTOUT -j LOG

Save and restore sttings

In [ ]:
iptables-save > rules.txt
In [ ]:
iptables-restore < rules.txt


In [4]:
ufw status

Status: inactive

In [6]:
ufw --help | head
Usage: ufw COMMAND

 enable                          enables the firewall
 disable                         disables the firewall
 default ARG                     set default policy
 logging LEVEL                   set logging to LEVEL
 allow ARGS                      add allow rule
 deny ARGS                       add deny rule
In [ ]:
ufw enable
In [ ]:
ufw status

Status: active

In [ ]:
ufw allow ssh
In [7]:
grep ssh /etc/services
ssh		22/tcp				# SSH Remote Login Protocol
ssh		22/udp
In [ ]:
ufw reject out ssh
In [ ]:
ufw deny proto tcp from to any port 22
In [ ]:
ufw logging on
In [ ]: