Tutorial

How To Set Up a Firewall Using Iptables on Ubuntu 12.04

Published on August 3, 2012
How To Set Up a Firewall Using Iptables on Ubuntu 12.04
Not using Ubuntu 12.04?Choose a different version or distribution.
Ubuntu 12.04

Status: Deprecated

This article covers a version of Ubuntu that is no longer supported. If you are currently operate a server running Ubuntu 12.04, we highly recommend upgrading or migrating to a supported version of Ubuntu:

Reason: Ubuntu 12.04 reached end of life (EOL) on April 28, 2017 and no longer receives security patches or updates. This guide is no longer maintained.

See Instead:
This guide might still be useful as a reference, but may not work on other Ubuntu releases. If available, we strongly recommend using a guide written for the version of Ubuntu you are using. You can use the search functionality at the top of the page to find a more recent version.

About Iptables

In order to make a server more secure after the initial set up, Ubuntu ships with iptables which is the distribution’s default firewall. At the outset, although the Ubuntu firewall is configured, it is set up to allow all incoming and outgoing traffic on a virtual private server. To enable some stronger protection on the server, we can add some basic iptables rules.

The iptables rules come from a series of options that can be combined to create each specific process. Each packet that crossing the firewall is checked by each rule in order. As soon as it matches a rule, the packet follows the associated action, otherwise it proceeds down the line.

Note: This tutorial covers IPv4 security. In Linux, IPv6 security is maintained separately from IPv4. For example, "iptables" only maintains firewall rules for IPv4 addresses but it has an IPv6 counterpart called "ip6tables", which can be used to maintain firewall rules for IPv6 network addresses.

If your VPS is configured for IPv6, please remember to secure both your IPv4 and IPv6 network interfaces with the appropriate tools. For more information about IPv6 tools, refer to this guide: How To Configure Tools to Use IPv6 on a Linux VPS

Iptables Commands

Although this tutorial will go over a limited amount of commands that would provide a server with some basic security, there are a variety of nuanced and specific cases that can be developed for iptables. Below are some of the most useful commands for developing a firewall for your VPS, but keep in mind that this is a short list and there are a variety of other options.

-A: (Append), adds a rule to iptables
-L:  (List), shows the current rules
-m conntrack: allows rules to be based on the current connection state, elaborated in the the --cstate command.
--cstate: explains the states that connections can be in, there are 4: New, Related, Established, and Invalid
-p: (protocol), refers to the the protocol of the rule or of the packet to check.The specified protocol can be one of tcp, udp, udplite, icmp, esp, ah, sctp or the special keyword "all".
--dport: (port), refers to the the port through which the machine connects
-j: (jump), this command refers to the action that needs to be taken if something matches a  rule perfectly. It translates to one of four possibilities:
	-ACCEPT: the packet is accepted, and no further rules are processed
	-REJECT: the packet is rejected, and the 	sender is notified, and no further rules are processed
	-DROP: the packet is rejected, but the 	sender is not notified, and no further rules are processed
	-LOG: the packet is accepted but logged, and the following rules are processed 
-I: (Insert), adds a rule between two previous ones
-I INPUT 3: inserts a rule to make it the third in the list
-v: (verbose), offers more details about a rule

Creating the Iptables Rules:

If you type in the following, you can see the current iptables rules:

sudo iptables -L

They should look like this:

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

If you have another set of rules in place or want to start fresh, you can always set the rules back to the default by flushing and deleting all of them:

sudo iptables -F

Additionally, if you want speed up your work with iptables, you can include -n in the command. This option disables DNS lookups and prevents the command from trying to find the reverse of each IP in the ruleset. You could use this to list rules, as an example:

iptables -L -n

A Basic Firewall

As it stands the current rules allow all connections, both incoming and outgoing. There are no security measures in place whatsoever. As we build up the table, keep in mind that as soon as a packet is ACCEPTED, REJECTED, or DROPPED, no further rules are processed. Therefore the rules that come first take priority over later ones.

While creating the rules, we have to be sure to prevent ourselves from accidentally blocking SSH (the method through which we connected to the server).

To start off, let’s be sure to allow all current connections, all of the connections at the time of making the rule, will stay online:

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

We can go ahead and break this down:

  1. -A tells iptables to append a rule to the table.
  2. INPUT designates this rule as part of the Input chain.
  3. m conntrack followed by the --cstate ESTABLISHED,RELATED guarantees that the result of this rule will only apply to current connections and those related to them are allowed
  4. -j ACCEPT tells the packet to JUMP to accept and the connections are still in place.

After we are assured that all the current connections to the virtual private server can stay up uninterrupted, we can proceed to start blocking off other insecure connections.

Let’s assume that we want to block all incoming traffic, except for those coming in on 2 common ports: 22 for SSH and 80 for web traffic. We proceed by allowing all traffic on the designated ports with the following commands:

sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

In both of these commands, the -p option stands for the protocol with which the connection is being made, in this case tcp, while the --dport specifies the port through which the packet is being transmitted.

After we have guaranteed that the desirable traffic will make it through the firewall, we can finish up by blocking all remaing traffic from accessing our virtual server. Because this is the last rule in the list, all traffic that matches any of the previous rules in iptables will not be affected, and will be treated as we set up previously.

Let’s make a rule to block all of the remaining traffic:

sudo iptables -P INPUT DROP

With that, we can see what our updated rules look like:

sudo iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             anywhere            ctstate RELATED,ESTABLISHED 
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh 
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:http 

We are almost finished. However, we are missing one more rule. We need to provide our VPS with loopback access. If we were to add the rule now without further qualifiers, it would go to the end of the list and, since it would follow the rule to block all traffic, would never be put into effect.

In order to counter this issue, we need to make this rule first in the list, using the INPUT option :

sudo iptables -I INPUT 1 -i lo -j ACCEPT
  1. -I INPUT 1 places this rule at the beginning of the table
  2. lo refers to the loopback interface
  3. -j ACCEPT then guarantees that the loopback traffic will be accepted

Now we have finished creating a basic firewall. Your rules should look like this (we can see the details of the iptable by typing -v):

sudo iptables -L -v
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  lo     any     anywhere             anywhere            
 1289 93442 ACCEPT     all  --  any    any     anywhere             anywhere             ctstate RELATED,ESTABLISHED
    2   212 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:ssh
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:http     

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

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

However, as soon as the virtual server reboots, the iptables rules will be wiped. The next step will go over saving and restoring the iptables rules.

Saving Iptables Rules

Although the iptables rules are effective, they will automatically be deleted if the server reboots. To make sure that they remain in effect, we can use a package called IP-Tables persistent.

We can install it using apt-get:

sudo apt-get install iptables-persistent

During the installation, you will be asked if you want to save the iptables rules to both the IPv4 rules and the IPv6 rules. Say yes to both.

Your rules will then be saved in /etc/iptables/rules.v4 and /etc/iptables/rules.v6.

Once the installation is complete, start iptables-persistent running:

sudo service iptables-persistent start

After any server reboot, you will see that the rules remain in place.

By Etel Sverdlov

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Etel Sverdlov
Etel Sverdlov
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
40 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Does does the APF firewall package work well under KVM and your CentOS or Ubuntu images? I’ve had issue on bare metal Unbuntu with some kernenls in that the netfilter portion made the apf fucntion very slow.

www.rfxn.com/projects/

They are easy to install and offer good security

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
September 13, 2012

A lot of that would depend on the exact firewall configuration you have running and what you are configuring it to do.

In most cases there should be really no impact to performance, but if you run a specific config and notice performance degradation please let us know, we’d love to look deeper into the rules and see how they are set up and perhaps be able to offer some guidance on that.

Thanks.

Entering the above rules locks me out of my VPS. I installed fail2ban as per the tutorial provided in this site. This is my iptables -L before trying the commands (luckily I have a snapshot to restore from):

Chain INPUT (policy ACCEPT) target prot opt source destination
fail2ban-ssh tcp – anywhere anywhere multiport dports ssh

Chain FORWARD (policy ACCEPT) target prot opt source destination

Chain OUTPUT (policy ACCEPT) target prot opt source destination

Chain fail2ban-ssh (1 references) target prot opt source destination
RETURN all – anywhere anywhere

all I want is to allow ssh, port 80 and loopback, and disable the rest.

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
November 22, 2012

Fail2ban is used to prevent repeated attempts to gain access to your server via SSH from outside parties.

As for the rules you want to create are there particular IPs or subnets that you would like to filter for SSH to allow access but block the rest?

Also for loopback you do not need any firewall rules as that is only available on your local server and not visible from the public internet.

Hi Raiyu thanks for getting back to me. The only ports I want to allow access from are 80 and my ssh custom port. Any idea why the above gets me blocked (ssh stops working)

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
November 23, 2012

I imagine that you would like to leave port 80 open to the public internet, while restricting access on port 22 to only your specific IP or a set of whitelisted IPs, so the rules would be different.

Let me know if you would like to also restrict IP access to port 80 as well to a white list and we can put together some rules to restrict access to SSH to only whitelisted IPs.

With the package “iptables-persistent” installed, can I make changes afterward and expect them to be sticky on a restart? or is there a command to apply my changes before a restart?

nvm, the command is “sudo /etc/init.d/iptables-persistent save” which saves the current ruleset to /etc/iptables/rules.v4 and /etc/iptables/rules.v6

Thanks again and one question: What happens with the original root user? Since I just created foo to ssh in do you just always use foo and I guess what I’m asking is do you get rid of “root” since you now have “foo”?

This article really helped. I have had such issues with this. Sharing is caring and for that I am grateful! Happy Holidays!

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
December 19, 2012

You can not and should not get rid of the root user. The root user is the superuser for the system who has access to all files and can make any changes and has ultimate authority.

For this reason you do not want to login as root to perform normal tasks or to run applications because if there is a security concern when the application breaks it will escape with the permissions of the user who initiated it which would be root.

This is why when you start system daemons such as Apache and you do it as root you will see that the root process just manages child processes which are all running as a different user. This is a security precaution.

If I wanted to add ftp/sftp to the firewall, how would I go about doing that?

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
January 16, 2013

Great question we’ll get an article written about securing FTP fo SFTP only.

@raiyu Thanks! I’m to the point where the thing that messes me up the most is figuring out a firewall. I’d love to see it somehow work with the firewall article so I have a better understanding of how all that works. Right now I’m thinking I need to completely remove the firewall and start over, but think I’m going to need to use google to find that all out. :)

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
January 16, 2013

I think thats a good approach, with how firewalls are layered it just takes practice getting it right and while its a frustrating process when it finally works there’s that eureka moment where it actually feels like you learned something and now you finally get it.

I’ve added it to our article queue to get written up and we always tweet out all of the new articles that are added to our community section so if you follow us on twitter you’ll see it pop up there.

If I changed my default SSH port to something different, should I change the command: “sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT” to include the port I chose?

In CentOS to make the changes permanent, use the comand below:

sudo service iptables save

firehol (apt-get install firehol) is a really easy to use wrapper for iptables

@swilso.86 Yes you definitely should, I didn’t and was locked out of my server for a bit haha

Hi, Following the procedure blocks the DNS access. I couldn’t to do apt-get after following the instructions for adding IPTable rules. I did a sudo iptables -F to resolve the issues. BTW - “sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT” also gave an error “iptables: No chain/target/match by that name.” not sure whether this is the reason for my DNS getting blocked as well.

Hi,

Followed you instructions, but apt-get does not work because it cannot get a connection. I also cannot connect via a terminal from my local computer. I used these commands initially.

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT sudo iptables -A INPUT -j DROP sudo iptables -I INPUT 1 -i lo -j ACCEPT sudo apt-get install iptables-persistent

then after reading this http://askubuntu.com/questions/67441/which-input-rules-do-i-need-to-add-to-iptables-so-apt-apt-get-aptitude-can-wo

Added these -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -P INPUT DROP Plus an input rules for a few other ports.Still cannot use apt-get because it cannot connect. Since I cannot use my terminal and am using the very limited console in the droplet management page I cannot cut and paste iptables -L output…

Ideas?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
May 25, 2013

@stpdave: Does apt-get work without these iptables rules?

Greetings:

After following the instructions in this tutorial, my droplet is not able to resolve DNS. When I run “nslookup google.com” the system responds with:

;; connection timed out; no servers could be reached

I’m not able to “sudo apt-get update” anymore, either. I’m running Ubuntu 12.04 & I also installed fail2ban as per the tutorial provided in this site.

Bulat
DigitalOcean Employee
DigitalOcean Employee badge
June 14, 2013

Hey Pablo,

You should allow incoming UDP packets from DNS servers in order to resolve hostnames:

iptables -I INPUT -p udp -m udp --sport 53 -j ACCEPT

It would be best to use a particular nameserver (8.8.8.8 or 8.8.4.4 or 4.2.2.1) and only allow it through:

iptables -I INPUT -p udp -m udp -s 8.8.8.8 --sport 53 -j ACCEPT iptables -I INPUT -p udp -m udp -s 8.8.4.4 --sport 53 -j ACCEPT iptables -I INPUT -p udp -m udp -s 4.2.2.1 --sport 53 -j ACCEPT

Place these lines on top of /etc/resolv.conf :

nameserver 8.8.8.8 nameserver 8.8.4.4 nameserver 4.2.2.1

Thanks bulat!!! It worked.

Does anyone have a script that they created/use for automating the process of setting up iptables after deploying a new droplet?

Also, other iptable-entries that I found useful are:

Drop all traffic to 127/8 that doesn’t use lo0. <pre>-A INPUT -i lo -j ACCEPT</pre>

Allow all outbound traffic or you can modify this to only allow certain traffic. <pre>-A OUTPUT -j ACCEPT</pre>

IP Whitelist. <pre>123.456.789.012 987.654.321.098</pre>

Default deny unless explicitly allowed policy. <pre>-A FORWARD -j DROP</pre>

These could simply be entered directly into /etc/iptables/rules.v4

Oops! RE: Dropping all traffic to 127/8 that doesn’t use lo0, replace -A INPUT -i lo -j ACCEPT with:

<pre>-A INPUT -d 127.0.0.0/8 -j REJECT</pre>

Also, the complete entries for the IP Whitelist section should be:

<pre>-A INPUT -s 123.456.789.0/23 -j ACCEPT -A INPUT -s 987.654.321.098/32 -j ACCEPT</pre>

Grrrr! I guess I need to calm down and re-read my posts b/f I submit them!

If I am using UFW to setup firewall rules, do I still need to use the IP table based solution?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
June 26, 2013

@admin UFW is a wrapper for ip-tables. I recommend using only one of them.

Hi

I have a weird problem with the last step about using iptables persistent. When i use the iptables persistent restart command, my https (or ssl) stops working, i mean people cannot connect via https. What could be the reason for it? If i flush all tables and create rules again including allowing https or port 443 without the persistent part, it works ok.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 1, 2013

@rajeev1204 you should run the following command after you edit your iptables rules so iptables-persistent saves the changes: sudo /etc/init.d/iptables-persistent save

Thanks Kamal Your command works fine, the iptables-persistent start command in the tutorial locked me out of https pages or they timed out.

I would like to limit SSH and FTP to 3 ips. How would I modify those rules above

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 6, 2013

@gasperzi: First, create a chain for SSH:

<pre>sudo iptables -N SSH</pre> and another chain for FTP:

<pre>sudo iptables -N FTP</pre> Add the whitelisted IPs to the SSH chain:

<pre>sudo iptables -A SSH -s 1.2.3.4 -j ACCEPT sudo iptables -A SSH -s 1.2.3.5 -j ACCEPT #etc.</pre> Do the same for FTP:

<pre>sudo iptables -A FTP -s 1.2.3.4 -j ACCEPT sudo iptables -A FTP -s 1.2.3.5 -j ACCEPT</pre> Then, have iptables check the SSH chain on connection to ssh and see if the IP that is trying to connect is whitelisted and if not, drop the packets:

<pre>sudo iptables -p tcp -m tcp --dport 22 -j SSH sudo iptables -p tcp -m tcp --dport 22 -j DROP</pre> Do the same for FTP:

<pre>sudo iptables -p tcp -m tcp --dport 21 -j FTP sudo iptables -p tcp -m tcp --dport 21 -j DROP</pre> Now, whenever you want to add another IP address to the whitelist, you can simply run one of these commands according to which service you want to access:

<pre>sudo iptables -A SSH -s 111.222.111.222 -j ACCEPT</pre>

Thanks. I was able to enter whitelisted IPs, but when I wanted to enter:

sudo iptables -p tcp -m tcp --dport 22 -j SSH

i get this error: iptables v1.4.12: no command specified Try `iptables -h’ or ‘iptables --help’ for more information.

what is wrong here. I am using ubuntu x64 droplet

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 11, 2013

@gasperzi: My bad, try these commands instead:

<pre>sudo iptables <strong>-A INPUT</strong> -p tcp -m tcp --dport 22 -j SSH

sudo iptables <strong>-A INPUT</strong> -p tcp -m tcp --dport 22 -j DROP

sudo iptables <strong>-A INPUT</strong> -p tcp -m tcp --dport 21 -j FTP

sudo iptables <strong>-A INPUT</strong> -p tcp -m tcp --dport 21 -j DROP</pre>

almost there, now ssh is not working, would you be so kind to check what am I missing? I may have added or missed a rule that was posted later on, or one is in conflict with the one you suggested

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT iptables -I INPUT -p udp -m udp --sport 53 -j ACCEPT sudo iptables -I INPUT 1 -i lo -j ACCEPT sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT sudo iptables -N SSH sudo iptables -N FTP sudo iptables -A SSH -s 1.2.3.4 -j ACCEPT sudo iptables -A FTP -s 1.2.3.4 -j ACCEPT sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j SSH sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j DROP sudo iptables -A INPUT -p tcp -m tcp --dport 21 -j FTP sudo iptables -A INPUT -p tcp -m tcp --dport 21 -j DROP sudo iptables -A INPUT -j DROP sudo apt-get install iptables-persistent sudo service iptables-persistent start

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 12, 2013

@gasperzi: Can you connect to FTP or does it not work either?

does not work either

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.