Iptables are included in almost all Linux distributions, and are used for inbound and outbound packet filtering including the Nat.
Iptables are designed in the following structure: Tables –> Chains –> Rules.
There are currently 3 tables:
As well as the following 4 chains:
- Input – Chain originated to the system.
- Output – Chain generated from the system.
- Forward – Chain packets are sent through another interface.
- RH-Firewall-1-Input – User-defined custom chain.
How to start, stop and restart iptables on Linux
- #/etc/init.d/iptables start
- #/etc/init.d/iptables stop
- #/etc/init.d/iptables restart
To start the iptables on a system boot, the following formulations can be used:
#chkconfig –level 345 iptables on
When restarting – the existing iptables rules are flushed, so in order to save it you can use:
#service iptables save
To check the current status of our iptables we can use the following command (on the terminal):
#iptables – L –n –v
Options –L (Lists ruleset), -v (Verbose) and –n (Shows in numeric format).
Accept: Allows the connection.
Drop: Drops the connection.
Reject: Do not allow the connection, and send back an error.
Now let’s look at some examples of iptables.
To block all connections from the ip address 192.168.2.2:
|Iptables –A INPUT –s 192.168.2.2 –j DROP|
To block connections from a range of IP addresses (for a network of 192.168.2.0/24). There are 2 possible ways, either by using the subnet mask or using the prefix (/) like so:
|Iptables –A INPUT –s 192.168.2.0/24 –j Drop|
|Iptables –A INPUT –s 192.168.2.0/255.255.255.0 –j Drop|
To Block ssh connections from 192.168.2.2 we use:
|Iptables –A INPUT –p tcp –dport ssh –s 192.168.2.2 –j DROP|
Keep in mind that the ssh can be replaced with the desired port number, the –p switch sends the protocol that is used to iptables. Here TCP is used however –p udp can also be used if required.
To block ssh connections from all addresses simply enter:
|Iptables –A INPUT –p tcp –dport ssh –J DROP|
There are many protocols that can perform two-way communication.
For example if we want to allow ssh connections from 192.168.2.2 we need to accept it on both the INPUT and on the OUTPUT.
Here the connection states are coming. Let’s see how it looks:
|iptables -A INPUT -p tcp –dport ssh -s 192.168.2.2 -m state –state NEW,ESTABLISHED -j ACCEPT|
|iptables -A OUTPUT -p tcp –sport 22 -d 192.168.2.2 -m state –state ESTABLISHED -j ACCEPT|
Now to save the changes to any configurations in iptables we use:
Red Hat / CentOS:
|/sbin/service iptables save|
To check how our iptables are configured we use the option –L
To Flush – to clean all currently configured rules we use:
Finally, iptables can be produced from simple lines of commands to a list of fully advanced commands in order to filter out packets; security levels in our Linux environment can be increased accordingly.