Downtown Doug Brown Wiki

Thoughts from a combined Apple/Linux/Windows geek

User Tools

Site Tools


ubuntu:iptables_rules

iptables rules

Here's how I set up a firewall on a server. This is confirmed to work in Ubuntu 10.04, 12.04, and 14.04.

First of all, sudo iptables -L -n -v will probably show no rules. Right?

Let's create some rules, starting with this template:

*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -s 12.34.56.78/32 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -s 12.34.56.78/32 -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
COMMIT
*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT

Customize this to your heart's content. In this example I'm allowing HTTP access on port 80, restricting SSH access on port 22 so it's only accepted from a particular sample IP (12.34.56.78), and only allowing ICMP traffic from the same sample IP. I'm also adding rules so that loopback and established connections will work correctly. All other traffic is blocked.

Put your final rules into the file /etc/iptables.rules.

Next, ensure it all works:

sudo iptables-restore < /etc/iptables.rules

Make sure you haven't locked yourself out of your server. It's happened to us all, I'm sure. As long as nothing breaks and the rules seem to behave correctly, set it up to automatically apply these rules when the network interface comes up:

sudo vi /etc/network/if-pre-up.d/iptables

Put the following into it (replace eth0 with the name of your network interface):

#!/bin/sh
if [ "${IFACE}" = eth0 ]; then
    /sbin/iptables-restore < /etc/iptables.rules
fi

Make it executable:

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

That should do the trick! Confirm that your firewall rules come up correctly on boot.

ubuntu/iptables_rules.txt · Last modified: 2019/05/27 13:31 by doug