iptables Introduction

I have always wanted to learn how to write iptables rules for Linux. In my quest, I have used these resources to teach me what little I have learned so far: Hardening Linux; Iptables Tutorial; Ubuntu Setup;. This is an introduction to iptables.

First, we need to learn how to write an iptables rule. The general format would be

iptables table command chain match target

There are three main tables: filter, nat, and mangle. filter is considered to be default if you do not specify a table. So your first rule would start to look like

iptables -t filter

Commands include, but are not limited to, append, insert, delete, and replace. Let’s say we are adding a new rule so our command now looks like

iptables -t filter -A

There are three main chains: input, output, and forward. Input deals with all traffic incoming to the server, output is traffic generated by server, and forward is traffic not for the server but for some other machine. Let’s say we need to deal with incoming traffic. Now our command looks like

iptables -t filter -A INPUT

Matching is the heart and soul of the rule. The most common things in matching are interface, source IP address, source port, destination IP address, destination port, and protocol. Let’s say our example deals with incoming interface eth0, for HTTP from any computer. Our command may look like

iptables -t filter -A INPUT -i eth0 -dport 80 -p tcp

Since any computer may connect, we have left out source IP and source ports.

Last part is target. Most common targets are accept, reject, and drop. Since we are looking to accept HTTP traffic in our source example, we will use accept. Now our command looks like

iptables -t filter -A INPUT -i eth0 -dport 80 -p tcp -j ACCEPT

We have created our first iptables rule. It will accept all incoming web traffic on port 80. See, it isn’t too hard to get started with iptables.

Location of iptables Rules in CentOS

CentOS stores its rules in /etc/sysconfig/iptables

Location of iptables Rules in Ubuntu

By default, Ubuntu has a policy of accepting all incoming traffic. Therefore, there are no default iptable rules. However, if you want to create your own, then put them in a file and modify /etc/network/interfaces by adding the following line:

pre-up iptables-restore < /etc/iptables.up.rules

where iptables.up.rules is the file where all rules were stored.


2 Responses to iptables Introduction

%d bloggers like this: