Set up Ubuntu firewall

From ITGwiki
Jump to: navigation, search

These instructions will also work for Debian. This gives you a very restricted firewall. You will have to add exceptions to allow traffic individually. This is the most secure model.

Create your rules file

Just paste this into /etc/iptables.up.rules (you will probably have to create this file).

*filter
:INPUT DROP
:FORWARD DROP
:OUTPUT ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
-A INPUT -i lo -j ACCEPT 
-A INPUT -p icmp -j ACCEPT 
COMMIT

Automatically load rules on boot

Just paste this into /etc/network/if-pre-up.d/iptables (you will probably have to create this file).

#!/bin/sh
iptables-restore < /etc/iptables.up.rules

And make it executable so it can be run on boot

sudo chmod +x /etc/network/if-pre-up.d/iptables

Adding exceptions

Remember that rules are matched in order, so the rules that are likely to be matched more often (port 80 for a web server, port 22 for ssh access) should be closer to the top of your rules list, but below your loopback (-i lo) and state (-m state) rules.

Allow web traffic from anywhere

Add this line to your rules

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

Allow web traffic only from your local subnet

If your subnet is 192.168.0.0/24, add this line to your rules

-A INPUT -s 192.168.0.0/24 -p tcp -m tcp --dport 80 -j ACCEPT

Allow ssh traffic from a specific host

If you want to allow ssh traffic from 192.168.0.20, add this line to your rules

-A INPUT -s 192.168.0.20/32 -p tcp -m tcp --dport 22 -j ACCEPT

Manually saving and restoring rules

  • To manually save rules, run
    • sudo iptables-save > /etc/iptables.up.rules
  • To manually restore rules, run
    • sudo iptables-restore < /etc/iptables.up.rules

Sample rules

Here is a sample configuration that

  • Denies all incoming traffic by default
  • Does not forward traffic
  • Allows incoming traffic
    • Unrestricted if it comes from 192.168.1.0/24
    • To access SSH if it comes from 192.168.0.0/24
    • To access HTTP no matter where it comes from
    • If it's ICMP (ping requests)
*filter
:INPUT DROP
:FORWARD DROP
:OUTPUT ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
-A INPUT -i lo -j ACCEPT 
-A INPUT -s 192.168.1.0/24 -j ACCEPT
-A INPUT -s 192.168.0.0/24 -p tcp -m tcp --dport ssh -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p icmp -j ACCEPT 
COMMIT