20 Frequently Used iptables Examples (Linux Firewall)

IPTables Config & Chains Examples

The iptables is a command line tool that is built on the top of kernel framework called Netfilter. The netfilter framework empowers one to allow, drop or modify incoming and outgoing packets. Using iptables one can write rich set of rules to allow, block or forward traffics in a system.

Since there are two versions of internet protocol – IPv4 and IPv6 and are managed by kernel differently so there are two sets of firewall tool developed – “iptables” for IPv4 and “ip6tables” for IPv6.

In this article, we will explore basics of iptables, chains, filters and tables and thereafter write few rules to get you started with iptables.

Pre-requisites

– You have already installed IPTABLES and is enabled/running in your system.

Basics of IPTABLES

The netfilter framework in linux kernel offers a way to filter packets with the help of tables, chains and targets. A table allows filtering packets in a discrete way. Again these tables have chains attached to them and allow one to inspect packets at various checkpoints.

In simple words, a chain is a set of rules that governs what to do with packets if the rules are matched. For any incoming or outgoing packet, when a rule is matched it is given to the target otherwise default rule is applied.

A target decides destination of a packets such as allowing or rejecting it. The most commonly used targets are:

  • ACCEPT: Allows packets to pass through.
  • DROP: Packets will not be allowed to pass through.
  • REJECT: Rejects the packets. In case of TCP connection, a connection reset packet will be sent and for a UDP connection a a destination host unreachable packets will be sent.

There are five different types of tables in the netfilter framework that allows us to do specific things on packets.

The following section list each tables and their functionalities.

  • Filter table:  The default table and is used for packet filtering. This table is used to make a decision on whether a packet should be allowed to its destination or not.
  • NAT table: The NAT table allows to change source and destination address to route the packets to different host or a network.
  • Mangle table: The mangle table allows to modify various IP headers in a packet.
  • RAW table: The raw table is seldom used and allows to add exceptions like set a mark on packets so that they should not be handled by the connection tracking system.
  • Security table:  The security table is used for Mandatory Access Control (MAC) rules like networking rules, such as those enabled by the SECMARK and CONNSECMARK targets. The security table is called after the filter table, allowing any Discretionary Access Control (DAC) rules in the filter table to take effect before MAC rules.

IPTables Chains

Further, all of the above table composed of chains that allows to filter packets at various check points inside a network. The following section list each of the chains and their functionalities.

  • PREROUTING: The  pre-routing chain in available in NAT, RAW and MANGLE table and applied to packets when they arrive in the network interface.
  • INPUT: The INPUT chain is available in RAW, MANGLE, NAT and FILTER tables. The rules in this chain are applied to packets just before it is passed to a process.
  • OUTPUT: The output chain is available in RAW, MANGLE, NAT and FILTER table. This chain is for packets that are generated by the host and their destination is usually a another host but it is also possible that the destination can be the same host via the loop-back interface. Therefore not all packets that traverses through the OUTPUT chain are in fact outgoing.
  • FORWARD: The forward chain is available in MANGLE and FILTER tables. It is used for adding rules related to forwarding a packet.
  • POSTROUTING: The post-routing chain is available in the NAT and MANGLE table. This chain is applied to packets when they leave the network interface.

Now that we have a preliminary idea of tables, chains and targets associated with iptables, let us explore few commonly used iptables rules that can be used to keep your server secured.

{20} Most Frequently Used IPTables Examples for system admins

1.Check current rules of IPTABLE

One way to check the current IPTABLES rules is to use the -nvl  switch.

The “n” option specifies the numeric output where IP addresses and port numbers will be printed in numeric format. The “v” and “l” option is used for verbose output and to list all rules in the selected chain.

 # iptables -nvL
 Chain INPUT (policy ACCEPT 0 packets, 0 bytes)

 pkts bytes target     prot opt in     out     source               destination

 590K  111M ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED

    5   218 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0

   15   974 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0

  300 17564 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            state NEW tcp dpt:22

1005K  169M REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)

 pkts bytes target     prot opt in     out     source               destination

    0     0 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT 626K packets, 119M bytes)

 pkts bytes target     prot opt in     out     source               destination

 

2. Delete current rules

Before you start building iptables rules from scratch it is better to clean-up all the default and existing rules. Use flush switch along with iptables command to to do that.

# iptables -F

3. Allow SSH access

When you start writing iptables rules, add rules that will allow inbound traffic in your system so that iptables can track the state of connections. The following rule will do that for you.

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

where:

ESTABLISHED – means the packet is associated with a connection which has seen packets in both the directions.

RELATED – means the packet is starting a new connection but is associated with an existing connection like FTP or HTTP data transfer.

Now allow SSH traffic in the system. The ssh in the following rule will automatically translate to the port number 22 which is the default port for SSH daemon.

# iptables -A INPUT -p tcp --dport ssh -j ACCEPT

4. Allow Loopback Access

To enable traffic on localhost i.e to allow communications between the applications in the server to proceed normally add the following chains in the INPUT and OUTPUT table using the following iptables command.

 # iptables -A INPUT -i lo -j ACCEPT

 # iptables -A OUTPUT -o lo -j ACCEPT

5. Whitelist your IP address

Whitelist your IP address by adding a rule at the top of the policy rules and this  will ensure you are not locking yourself in your server. Remember to insert this rule as the first rule using -I switch along with iptables command.

 # iptables -I INPUT -s <YOUR_IP> -j ACCEPT

6. Block an IP address

In order to protect your server from common DoS attacks you can make use of iptables to block traffic from where DoS attack is originating. To do that, add a rule in the INPUT chain that will DROP packets from the IP address x.x.x.x

# iptables -A INPUT -s 192.168.2.123 -j DROP

Now the packets from the IP address x.x.x.x will be blocked from entering into the system. You can also block an entire IP range by adding CIDR with the IP address.

# iptables -A INPUT -s 192.168.0.0/24 -j DROP

7. Unblock an IP address

Once you have blocked an IP address, you can unblock the same whenever the needs arises using the following iptables command. The -D(delete) switch deletes the matching rule that has been previously added to block an IP address.

# iptables -D INPUT -s 192.168.2.123 -j DROP

8. IPTables Block a port

So far, we have seen how to block an IP address, you can do more by blocking a port for incoming and outgoing traffic.

To block an outgoing tcp traffic on a particular port just use the following iptables command where “xxx” is the port number.

# iptables -A OUTPUT -p tcp --dport xxx -j DROP

And to block an incoming tcp traffic in the port “xxx” use “–dport” option along with iptables command.

iptables -A INPUT -p tcp --dport xxx -j DROP

9. Block SSH connection from particular IP

Sometimes you want to block SSH connection from a  particular IP address or IP range rather than blocking connections for all.  The following iptables command uses -m option to find if the connection is tcp and then checks if the destination port is 22 by using –dport. If both the conditions are matched then connection from  that particular IP specified with -s option is blocked.

# iptables -A INPUT -p tcp -m tcp --dport 22 -s 172.23.14.23 -j DROP

10. Port forwarding with IPTABLES

In some situations, you want to forward traffic from one port to another in your server. Use the following iptables command to forward traffic that arrives in the interface “eth0” from port 80 to port 8080.

# iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

11. Block Ping

Blocking ping in your system is a good prevention measure against flooding your server with icmp packets from remote location. The following rule will block ping request in the system from outside. The protocol for ping is specified with -p option which is icmp  and the type is echo-request.

# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

Likewise, It is also possible to block ping from your server to outside using the following iptables command.

# iptables -A OUTPUT -p icmp --icmp-type echo-request -j DROP

12. Open Range of Ports

You can open a sequential port numbers using a single iptables command rather than opening the ports with different iptables command. The following iptables rule will open the port ranges between 9000 to 9005 in your system.

# iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 9000:9005 -j ACCEPT`

13. Log entries of packets

The information about packets that iptables processes can be logged in a file. Whenever a packet matches with iptables <CHAIN> -j LOG rule, a kernel log message is being generated. You just need to specify the severity of the message using the — log-level <level> option with the iptables command. But for this to work you need to add the following line in /etc/rsyslog.conf and restart rsyslog before writing iptables rule.

...
...
kern.*       -/var/log/messages
...
...

Now add the following rules to log information about packets that will be available in the file /var/log/message.

# iptables -A INPUT -j LOG --log-prefix "FW_LOG_INPUT: " --log-level 4

# iptables -A FORWARD -j LOG --log-prefix "FW_LOG_FORWARD: " --log-level 4

# iptables -A OUTPUT -j LOG --log-prefix "FW_LOG_OUTPUT: " --log-level 4

14. Block traffic from a MAC address

Using iptables mac module, it is possible to block connection to your server  that is originated from a particular MAC address.

iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP

All packets from above mentioned MAC address will now be blocked. Now suppose you changed your mind and decided to accept only SSH connection from the said MAC address then use the following iptables command.

# iptables -A INPUT -p tcp --destination-port  22  -m mac --mac-source 80:0B:9A:4L:54:22 -j ACCEPT

Remember the order of the the above two commands matters. If you place the first iptables command after the second one then SSH connections from the specified MAC address will be blocked even if you have opened it.

15. Restrict the Number of Parallel Connections

You can limit the number of parallel connections for each client using the connlimit module. Suppose you want to restrict 3 parallel ssh connections for each ssh user from a single host then use the following iptables rules along with  connlimit-above switch.

# iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT

Where the -m option loads the connlimit module and the connlimit-above options specifies the number of maximum concurrent connections.

16. Limit packets

You can also put a limit to the number of packets going in or out in your system using the limit module.  The following iptables example uses two switches –limit and –limit-burst to put a limit on the number of incoming packets.

The –limit specifies the average number of  matches per second although the unit can be in /minutes , /hour or /day. The –limit-burst parameter acts like a packet counter. For every one packet that matches, the count goes down by one, and the timer starts. The limit  sets a limit on average whereas limit-burst limits by number of packets in one go.

# iptables -A INPUT -p tcp -m limit --limit 3/hour --limit-burst 5 -j ACCEPT

The above example will let the first 5 tcp packets in for the first minute (–limit-burst 5).  Any more packets will be blocked until next 20 minutes since the limit is 3/hour i.e one packets can be allowed in every 20 minutes.

Suppose in the 25th minute 5 TCP packets arrived but since the counter is now 2 so only 2 packets will be allowed in and 3 packets will be matched against the default rules which you can set as drop.

17. Drop private IP ranges

It is recommended to block private IP ranges if you have hosted your system in the public domain and this will protect your system against IP spoofing.  Whenever a packet with non routable source address arrived in your system reject them using the following iptables syntax.

# iptables -A INPUT -i eth0 -s 192.168.0.0/24 -j DROP 

# iptables -A INPUT -i eth0 -s 10.0.0.0/8 -j DROP

18. Deny traffic during a time interval

Let us assume you have a planned downtime of your server and during that time you want to deny traffic pouring in the server. Use –timestart and –timestop options along with iptables command so that maintenance process of your server does not hamper by incoming traffic. The following iptables command exactly does this by blocking TCP and UDP packets between 4AM and 5AM.

# iptables -A INPUT -p tcp -m time --timestart 04:00 --timestop 05:00 -j DROP 

# iptables -A INPUT -p udp -m time --timestart 04:00 --timestop 05:00 -j DROP

19. Drop a packet with matching string

Using iptables, It is possible to drop any packets irrespective of it is outgoing, incoming or being forwarded, that has a specific sub string in its TCP or UDP payload. The following iptables rules searches for the string “.com”, “.exe” (–string option) in the in payload section of packets.

# iptables -A INPUT -m string --algo bm --string ".com" -j DROP

# iptables -A OUTPUT -m string --algo bm --string ".exe" -j DROP

# iptables -A FORWARD -m string --algo bm --string ".com" -j DROP

20. Block Packets With Bogus TCP Flags

Bogus packets are packets in which an attacker use combinations of TCP flag that makes no sense. It is possible for an attacker to expose flows in a network stack using bogus packets. Run the following series of iptables command to block such packets.

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP

# iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP

Conclusion:

This article describes about basics of iptables, chains, config, rules and tables. Thereafter, we have checked about 20 iptables (examples) rules to get you started with writing iptables rules.

Although the iptables examples described in this article are preliminary and used more often but once you feel comfortable with it, you can start writing more complex rules.

LEAVE A REPLY

Please enter your comment!
Please enter your name here