Created at:

Modified at:

iptables basics

Tutorial: Iptables Basics

NAT with iptables

What's the interface you use to get connected to the internet? Probably ppp0 if you connect using ADSL. But, it can be eth0 if you get connected with DHCP.

So, following the NAT HOWTO below, you just need to execute, as root::

    # iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
    # echo 1 > /proc/sys/net/ipv4/ip_forward

Linux 2.4 NAT HOWTO

Then, set others computers in your network to use yours as default router.

Adding a new entry to a chain

(2012-09-06)

Iptables concept work with *chains*. The most obvious are *INPUT*, *OUTPUT*, *FORWARD*, which names are self-explanatory. You might create ones if you want. To ses all rules in chains, use the -L flag::

    # iptables -L

You might want to pass a chain name and other parameters to filter its output. In our example we have::

    ACCEPT     all  --  localhost            localhost
    ACCEPT     tcp  --  anywhere             sshserver           tcp dpt:ssh 
    DROP       tcp  --  anywhere             anywhere            tcp dpt:ssh 

That is, allow local connections and ssh connections to the ssh server, and drop everything else. This machine is like a gateway to another network.

Imagine you want to include a new rule in the *OUTPUT* chain. Let's say you want the computer to access address 172.16.98.232. All you have to do is::

    # iptables -I OUTPUT -d 172.16.98.232 -j ACCEPT

And it will include a first entry to the chain::

    ACCEPT     all  --  anywhere             172.16.98.232
    ACCEPT     all  --  localhost            localhost
    ACCEPT     tcp  --  anywhere             sshserver           tcp dpt:ssh 
    DROP       tcp  --  anywhere             anywhere            tcp dpt:ssh 

Instead of -I you might want to include other mutual exclusive options, that are -A and -D. -A includes an entry to the *end* of the chain, which doesn't make sense in our case, because the DROP clause would be considered first and cancel any clause that comes after. See::

    ACCEPT     all  --  localhost            localhost
    ACCEPT     tcp  --  anywhere             sshserver           tcp dpt:ssh 
    DROP       tcp  --  anywhere             anywhere            tcp dpt:ssh 
    ACCEPT     all  --  anywhere             172.16.98.232

The -D flag drops the rule and we get back to the original setup::

    # iptables -D OUTPUT -d 172.16.98.232 -j ACCEPT

A small table resumes the -I, -A and D options

Option Meaning
-I Includes the rule at the first entry of a chain
-A Includes the rule at the last entry of a chain (appends)
-D Deletes the rule from a chain

Example of allowing a machine to access connections from IP 192.168.0.34, port 22::

    iptables -I INPUT -s 192.168.0.34 -p tcp --dport 22 -j ACCEPT

Insert rules in a persistent file

(2013-09-23)

Just execute the command::

    # iptables-save > /etc/iptables.rules

(The file path may differ depending on your Linux distribution).