IPTables: A Comprehensive Guide

A Face Behind the Mask: What Is A Social Engineer?

IPTables: A Comprehensive Guide

IPTables is a powerful firewall software that protects your computer by blocking unwanted traffic. This guide will go over the basics of the whats, whys, and hows of IPTables.

IPTables is a Linux-based firewall that works at the Network Layer of the OSI model. It’s a great way to add another layer of protection to your home network, especially if you have any Linux experience under your belt.

For those looking for an added security layer, IPTables can be configured to guard against common network attacks and malicious activity by blocking traffic from specific IP addresses or entire networks. 

Why Should You Use IPTables?

There are many reasons to use IPTables. Here are a few:

  • Block IP addresses (e.g.: block traffic from China)
  • Prevent DDoS attacks (Distributed Denial of Service)
  • Restrict access between networks (e.g.: restrict your kids’ computer access at night or when they should be studying.)
  • Restrict access to your home network (e.g.: stop a neighbor from using up all of your bandwidth)
  • Filter and monitor your traffic (e.g: block Facebook but allow Gmail)

What Is The Difference Between IPTables And Firewalld?

While IPTables essentially provides the same functionality as FirewallD, there are a few differences that may lead you to choose one or the other. The first and most obvious difference is their names. While both projects aim at providing similar functionalities, they go about it in different ways.

IPTables does not use zones (just chains)FirewallD uses zones for managing trust levels of existing rulesets
IPTables requires all rules to be added under the same chain name.FirewallD can manage multiple sets of rule-sets simultaneously
For example, If we want to block access from China on our local network level, we could create two separate custom chains based on built-in IN_VPN and IN_LOCAL chains.If we use IPTable we’d need to manually add these rules under the same chain name such as DROP for both our local network and VPN networks; each rule-set must end with RETURN before another set of actions can take place; this means creating two separate custom chains instead of inheriting from built-in ones like FirewallD does.For example, If we want to block access from China on our local network level, we could create two separate custom chains based on built-in IN_VPN and IN_LOCAL chains.If we use FirewallD, all that needs to be done is create a new zone and assign it an interface (i.e.: LAN) that would inherit those two rulesets as well as any other existing rules in the parent zones. 

Are IPTables Stateful Or Stateless?

IPTables is stateful. This means that connections are tracked on a per-protocol basis (UDP, TCP) and the firewall rules define how packets for each connection should be treated by giving information about what traffic can come in or out of your network through specific ports.

What Does IPTable being Stateful Mean?

This means that the firewall rules must be defined for each protocol (i.e.: UDP, TCP) and tell your machine how it should handle traffic coming in/out of your network through specific ports.

Let’s say you have an SSH server running on port 22 while browsing Facebook which runs over port 80: If all incoming traffic to port 80 were blocked but allow outgoing traffic from it, then you’d still be able to browse Facebook because only outgoing web requests would try hitting your computer; however, if we block both incoming AND outgoing access to port 80, then nobody will be able to connect via Facebook until either the protocol is reset or the connection terminates.

Some Basic IPTable Commands

Installing IPTable On Your Computer Or Server

  1. First, you need to know what kernel your system uses.

For Debian-based distribution like Ubuntu or Kali Linux then:

$ uname -r  (Or) $ cat /proc/version

For CentOS and Fedora systems:

$ uname -a (Or) $ rpm -qa | grep kernel

  1. Next, type in the following command to download IPTables on your machine: 

# sudo apt install IPTables (Debian/Ubuntu derivatives such as Xubuntu etc.) # yum install IPTables (Fedora; RHEL; CentOS; Scientific Linux etc.) # dnf install IPTables (Fedora 22+) 

Based on which package manager above is being used, the IPTables package name may differ.

  1. Also, you need to get a compiler for your machine if it doesn’t have one already installed: 

# sudo apt-get install build-essential (Debian/Ubuntu derivatives such as Xubuntu etc.) # yum groupinstall ‘Development Tools’ -y  (Fedora; RHEL; CentOS) 

  1. Finally, run this command to compile and install IPTables on your system:

$ sudo make && sudo make install 

Uninstalling IPTables On Your Computer Or Server

If you’d like to uninstall afterward using dpkg or rpm, use something similar with these commands instead of installing in the beginning: 

$ sudo dpkg –remove IPTables OR $ sudo rpm -e ip*tables 

Display A List Of Basic IPTable Commands

To start working with IPTables, you need to know the basics of its command-line syntax. You can display a list of basic IPTables commands using -h or –help switch: 

# IPTables -h

Listing The Rules In The Machine’s IPTables Configuration File

For example, if I’m interested in listing out all rules currently set in my machine’s IPTables configuration file which is /etc/IPTables/rules.v0 by default then I’d run this command instead:

$ sudo IPTables -S | less 

Flushing Memory Without Restarting The System

You may also flush them from memory without having to restart your system entirely by running something like this, though it will only apply to the table specified here (e.g.: filter ): 

$ sudo ip*tables -F [TABULAR DATA OMITTED]

$ sudo IPTables -t filter -F  

To List Available Tables With the Corresponding Number

To list the available tables and their corresponding number, you can run: 

$ ip*tables –help OR $ IPTables –help | grep ‘\-t’ 

Delete Rule From IPTables

To delete a specific rule from IPTables, for example, one that was created by mistake or added in error, first match it with these commands then remove it as follows: 

# sudo IPTables -D INPUT [RULE_ID(s)] (for IPv[46]) # sudo ip*tables -D PREROUTING [RULE_ID(s)) (For IPv[46])

Note: “rule ID” can be matched using any of these switch combinations; they’re not case sensitive: –sport, -s  -p tcp–dport, -p udp–dport, or any of these abbreviations as well.

How To Use IPTables With Examples

Now that we’ve gone through a few basics of IPTables, let’s go over some specific examples.

Prevent DDoS Attacks

To prevent DDoS attacks to our server by blocking any connection from China:

  1. First, add an INPUT chain rule in the PREROUTING section which blocks all incoming traffic from the previously mentioned country with 

-m geoip –src-cc CN 

  1. Then add another rule after it for filtering out bad destination ports so the only SSH is allowed (e.g.: proto tcp dport ssh).
  2. Specify state NEW, meaning these rules will apply to new connections. 
  3. Finally, append RETURN at the end of each rule before adding more actions/rulesets. 
  4. Block IP addresses or if you wish to block access from China, you could add the same rules as above in the INPUT chain with the -s (source) option. 
  5. Or if you want to blacklist an entire ISP’s address range: Add a rule under FORWARD section using their CIDR notation and specifying state NEW.

Restrict Access Between Networks

One of the most common uses for IPTables is restricting internet usage between different networks or LAN devices on your network. 

Some examples include,

  • Preventing your kids’ computer(s) from accessing Facebook when they should be studying while allowing them some leeway during breaks
  • Stopping all bandwidth-consuming traffic coming into your home by blocking any incoming connections outside port 80/443 which are usually used for web browsing
  • Separating your network into several subnets for different purposes such as production vs. development to prevent one from interfering with the other.

Allow/Deny Connections Based On Port

You can use IPTables rulesets to allow or deny access via specific ports. 

For example, say you wish to block all incoming traffic except those coming in through ports 80 and 443 (which we blocked earlier) which is common for web browsing; 

  1. We could do so by adding another rule at the top of our chain under the PREROUTING section using 

-p tcp –dport [80,443]

Where [X,Y] means between X and Y values inclusive (e.g.: 20-30 ). 

  1. Then add a new rule after them specifying state NEW.

Allow/Deny Connections Based On IP Address

If you’re looking to allow or deny access from a specific subnet, then use the -s (source) option instead of –dport. 

For example: If we want all traffic coming into our network except those originating in China (those with an IP starting with 111.222 ),

  1. We could do so by adding another rule before our last one using -s 111.222.*, 

Where * is used for matching any value.

  1. Finally, append RETURN at the end of each set before creating new ones.

Allow/Deny Connections Based On MAC Address

The -m (match) option can be used to filter traffic using a specific device’s layer-two or hardware address. 

For example, if we only wanted to allow our computer(s)’ internet usage while blocking all other devices from doing so: 

  1. First, add an INPUT chain rule in the PREROUTING section which blocks any incoming traffic with its destination being your machine by specifying –dst 192.168.* 

Where * means anything

  1. Then create another one for forwarding packets out of it and use state NEW. 
  2. Then append RETURN at the end of each set before adding more actions/rulesets.

Secure SSH Access Via Custom Port

If you wish to secure SSH access by allowing it only from a custom port, say port 22222, then 

  1. Add another rule in the PREROUTING section under TCP using –dport 22222 and state NEW. 
  2. Then append RETURN at the end of each set before adding more actions/rulesets.

Drop Packets VS. Reject Them

There is a difference between DROPPING an incoming packet versus REJECTING it: 

For example, if we wanted to drop all traffic coming into our network except those originating from China (those with an IP starting 111.222 ),

  1. We could do so by adding another rule before our last one as specified earlier with -s 111.*.* ; 
  2. Then create another after that for forwarding packets out of it and use state NEW. 

However, this will simply drop anything coming from 111.222 or a subnet within it without sending out any notification back to the sender; 

  1. If we use REJECT instead of DROP, then an error message is sent back along with connection reset which can help debug situations where you’re under attack and wish to see what’s being attempted against your system/network.

Logging IPTables Rules

You can log packets that are matched by specific sets using 

-j LOG –log-prefix “[SUBNET] DENY IN=eth0 OUT= MAC=00:11:22:33:44:55 SRC=111.222.333.444 DST=192.168.” –log-level [EMERG,ALERT,CRIT,ERR,WARNING,NOTICE,INFO] 

where 111.222 is the source IP address in this case; you may specify “!” before it to negate a set that would otherwise match all incoming traffic from that subnet while leaving the log intact for matching packets coming within its range (e.g.: -j !111.222 ).

Restart IPTables Service

Once you are done with creating rulesets to allow or deny access based on your requirements and desire using –dport, –sport, etc, be sure to restart your firewall by running sudo /etc/init.d/IPTables restart. 

You should also periodically check logs under var/log/syslog or wherever your distribution stores them to make sure no unauthorized rulesets are created by accident.

IPTables is an extremely powerful tool for configuring Linux-based systems’ packet filtering/traffic shaping capabilities which can be used to configure 

  1. Network Address Translation (NAT), 
  2. Port forwarding, 
  3. Transparent proxying etc.
  4. As well as locking out attackers attempting to break into your system via various means including brute-forcing SSH login credentials using tools like Hydra, medusa, and others. 

Also, you mustn’t forget about fail open scenarios where packets that would have otherwise been dropped get through because of a rule not being set up properly or the order in which they’re specified. You should also periodically check logs under var/log/syslog .

Frequently Asked Questions

Q. What are the most commonly used chains in IPTables? 

A. PREROUTING , POSTROUTING , INPUT, and OUTPUT. Also, there is one known issue with using sudo to run IPTables commands: you will need to specify -P FORWARD ACCEPT after every rule added, or else all packets being forwarded through your system are dropped which can be extremely frustrating when troubleshooting network connectivity issues.

Q. How do I set up port forwarding/proxying?

A. Depending on your use case, you can set up a rule for forwarding packets across interfaces and/or subnets: 

-A PREROUTING -i eth0 ! –src -j DNAT –to-destination 192.168.*.* :8080 

Where the last port number ( 8080 ) would be used to specify which service such as Apache running on such hosts should receive incoming traffic; if it’s not specified then the ruleset will simply forward all connections matching that criteria so you’d do well in specifying one to avoid having other services trying to grab those ports unexpectedly unless they’re meant to do so of course!

Q: How does state tracking work?

A: Allowing or denying packets based on the presence or absence of a particular flag (concerning TCP, UDP, and ICMP protocols) is referred to as state track; this can be done via, 

-m conntrack –ctstate [INVALID,ESTABLISHED,NEW] 

where INVALID would denote packets attempting to establish an invalid connection such as one that doesn’t exist while ESTABLISHED indicates those which have successfully matched all necessary criteria and are allowed through. The NEW flag applies only for new connections/packets trying to make their way in from the outside world into your system.

Q: How do I create custom chains? 

A: You first need to specify a unique name for it by using something like -N LOGGING-CHAIN where you can then append rules to it using -A LOGGING-CHAIN #

You should also change its handling policy so it’s not treated as a normal chain by specifying the following options: 

–jump [ ACCEPT, DROP ]  

Specifies whether packets matching those criteria are allowed through or dropped.

–return [ ACK, REJECT , DENY ] 

Specifies an appropriate response to such packets i.e.: returning an acknowledge (ACK) message, dropping them outright, or denying access respectively.

Q: What is the difference between target and match extensions?

 A: While both perform similar tasks of allowing/denying certain types of connections based on their properties, they do have some differences in how they’re implemented:

– The former uses the traditional asterisk * character for wildcard matching whereas the latter makes use of a pair of square brackets [] and can also be used to specify multiple values within them.

– Targets do not allow negation in their rules, i.e., you cannot add -j DROP [! IN_ZONE], however, it is possible with matches by using ! .

Recent Posts