Iptables is a powerful firewall tool that allows system administrators to configure packet filtering rules to manage network traffic on Linux systems. This comprehensive guide will walk you through how to use iptables to control network traffic on an Ubuntu system.
An Introduction to iptables
Iptables is a user-space application that allows configuring IPv4 packet filtering rules in the Linux kernel‘s netfilter framework. Essentially, iptables provides the controls to manage network packets and traffic coming in and out of the system.
Some key features of iptables include:
- Filtering packets based on source/destination IP addresses, protocols, and ports
- Setting up complex combinations of rules using extensions
- Stateful inspection for TCP, UDP, and ICMP protocols
- Rate limiting to prevent denial-of-service (DoS) attacks
- Network address translation (NAT) for IP masquerading
Iptables use a set of tables containing built-in chains to match packets. These tables include:
- Filter – Contains INPUT, FORWARD and OUTPUT chains for filtering packets
- NAT – Includes PREROUTING, POSTROUTING and OUTPUT chains for network address translation
- Mangle – Has PREROUTING, POSTROUTING, INPUT, OUTPUT, and FORWARD chains for specialized packet alterations
- Raw – For configuration exemptions from connection tracking
The subsequent sections cover how to configure iptables rules to control network traffic on an Ubuntu 20.04 system.
Getting Started with iptables
To start working with iptables, you need to have iptables installed. Most Ubuntu versions come with iptables pre-installed.
To verify whether you have iptables set up on your system, run:
sudo iptables --version
This should display iptables version information if set up correctly:
iptables v1.8.4 (legacy)
Now let‘s inspect the current iptables policies and rules configured using:
sudo iptables -L -v
With no configuration done, you will likely see empty chains allowing all traffic for the filter table.
To understand and effectively create iptables policies, you need to grasp some essential concepts like tables, chains, targets and rules.
Iptables Components
Iptables policies have the following key components:
Tables
Tables group related chains for different categories of packet processing functions. As outlined earlier, iptables provides filter, NAT, mangle and raw predefined tables.
For instance, the filter table contains rules for filtering packets, while NAT does network address translation.
Chains
Chains provide hooks for governing packet traversal through various processing stages. Iptables tables contain built-in chains, while users can also create custom chains.
Important built-in chains include:
- PREROUTING – Packets entering the system traverse this chain before routing
- INPUT – Controls packets coming into the system for local processes
- FORWARD – Manages routed packets not originating from or destined for the system
- OUTPUT – Filters locally generated packets before routing
- POSTROUTING – Deals with packets leaving the system
Targets
These specify an action for matching packets like ACCEPT, DROP, REJECT, LOG, etc. For example, ACCEPT allows the packet through, while DROP blocks it.
Rules
Iptables rules define matching conditions to match packets traversing a chain. A rule may match source/destination IP/port, protocol, state, etc.
Rules also link packets to targets that determine packet handling. Rules get checked in order, with the first match determining the fate of each packet.
Viewing Iptables Policies
With the basics covered, let‘s inspect the current iptables policies. The -L option lists all chains and rules as shown below:
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Here the filter table is displaying empty chains that ACCEPT all traffic by default.
Use -v for extended output showing packet and byte counters per rule:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
This default permissive access allows all traffic exposing the system to threats. Let‘s learn to configure stricter iptables policies.
Setting Default Policies for Chains
The first step is setting default chain policies that get applied to packets not matching any rules. This controls what traffic is allowed if no rules are specified.
For example, to DROP all incoming packets on the INPUT chain, do:
sudo iptables -P INPUT DROP
To allow only established connections rather than all traffic:
sudo iptables -P INPUT ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A INPUT -j DROP
This ACCEPTs related and established traffic only, dropping everything else.
Let‘s set defaults to DROP on all filter table chains and add rules later for only allowing required access explicitly.
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT DROP
Verify using -L that default chain policies now DROP packets:
Chain INPUT (policy DROP)
target prot opt source destination
Chain FORWARD (policy DROP)
target prot opt source destination
Chain OUTPUT (policy DROP)
target prot opt source destination
With this secured default stance set, explicit rules can selectively enable services. Next, let‘s look into some essential iptables options and parameters.
Iptables Rule Options
Iptables supports various command options for managing rules:
-A – Append rule to end of chain
-I – Insert as rule number 1 (default)
-D – Delete matching rule
-R – Replace rule
-L – List rules
-F – Flush all rules from chain
-Z – Set byte/packet counters to 0
-N – Create new user-defined chain
-X – Delete user-defined chain
Use these for adding, updating, deleting and viewing iptables rules.
For rules themselves, important matching parameters are:
-s – Source IP/network
-d – Destination IP/network
-p – Protocol (TCP/UDP/ICMP etc)
–sport – Source port
–dport – Destination port
Let‘s now move on to configuring custom iptables rules.
Adding Iptables Rules
With default policies set to DROP, explicit rules need to be defined to allow required traffic.
Rules in iptables get checked sequentially from top to bottom. The first match triggers the associated action for that packet.
Hence rule order is vital, with more specific rules at the top progressing onto broader allowances.
Also, note that iptables rule sets cannot have gaps in ordering thanks to rule checking linearly. So use -I instead of -A for inserting rules to maintain sequence.
Now some examples for allowing different types of access by adding iptables rules.
Allow Loopback Traffic
Allow all access over the loopback interface to local services:
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
This permits unrestricted traffic over lo catering to local IPC that require complete accessibility.
Allow Established Connections
Rather than keeping default policies open, lock down to established connections only:
sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
This enables only incoming packets belonging to existing connections, blocking everything else.
Open a Port
Allow incoming SSH traffic by opening port 22:
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
Permit new TCP sessions to destination port 22. All other inbound traffic gets dropped due to default policy.
Similarly open for any other protocols and ports like HTTP(80), HTTPS(443) etc.
Allow Ping Requests
Allow ICMP Echo requests to test connectivity:
sudo iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT
This specifically passes type 8 ICMP requests required for ping to work.
Forward Traffic To Another System
To route traffic via an interface to a separate host, ACCEPT packets marked for FORWARDing:
sudo iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
Adapt interfaces appropriately either side of the routing system for forwarding.
Restrict Connections From An IP
Block incoming connections from a particular IP address:
sudo iptables -A INPUT -s 192.168.5.10 -j DROP
Customize IP address being blocked as suitable.
Similarly, allow only specified IP subnets access by selectively adding rules permitting them.
Rate Limiting
To restrict TCP connections initiated per second from a specific network to prevent DoS:
sudo iptables -A INPUT -p tcp -s 192.168.0.0/24 --syn -m limit --limit 3/s --limit-burst 3 -j ACCEPT
Customize the CIDR block being rate limited along with allowed limits per this template. Bursts accommodate temporary spikes crossing limit.
Logging Packets
Log packets hitting a particular rule instead of accept/drop for debugging purposes:
sudo iptables -A INPUT -s 192.168.0.15 -j LOG --log-prefix "iptables denied: " --log-level 7
Investigate /var/log/messages or /var/log/syslog to check the blocked packet logs based on where your system is configured to log kernel messages.
Similarly, add more fine-grained rules permitting or denying specific source/dest IP ranges, subnets, ports and protocols catering to business needs.
Saving Iptables Rules
Iptables rules defined from the command line do not persist across reboots. To retain configurations, save defined rule sets.
On Ubuntu, use iptables-persistent for managing saved set of rules:
-
Install iptables-persistent package if missing:
sudo apt install iptables-persistent -
During install, save current ip4tables and ip6tables rule sets when prompted.
-
Custom rules get saved to
/etc/iptables/rules.v4and/etc/iptables/rules.v6and applied on next reboot.
Alternatively, to manually save iptables rules:
-
View current iptables output using
sudo iptables -L -v > /tmp/iptables.rules -
Copy /tmp/iptables.rules to e.g /etc/network/iptables.up.rules
-
Add
iptables-restore < /etc/network/iptables.up.rulesto system startup sequence to restore rules on booting up.
Testing Iptables Rules
After configuring iptables policies, thoroughly test out connectivity for required services.
Basic tests include:
- Local IPC using ping, curl etc works fine
- Allowed ports are accessible remotely over various protocols
- Restricted IP ranges are unable to connect beyond limitations
- Forwarding functionality is routing traffic correctly
- Any rejections are responding with REJECT packets as opposed to silent drops
- Traffic matches intended policies – check counters using
-vnx
Investigate any connectivity issues for services designed to have access but failing with diagnostics.
Look at traffic counters and kernel logs in case of permitted services not functioning as expected for further debugging.
Fix issues by selectively allowing required packets that may get blocked inadvertently due to overrestrictive rules. Achieve this by adding exceptions prior to rejections higher up in the chain.
Iteratively refine rules based on business needs and troubleshooting findings for streamlining control over network traffic flowing via the system.
Conclusion
Iptables is extremely capable at managing network access leveraging Linux netfilter functionality. Configuring well-considered rules leads to sound firewalled environments preventing unauthorized traffic.
Start by defining restrictive default policies across built-in chains, then explicitly add rules opening up only essential services and system interfaces. Maintain strict rule ordering and save them to disk for persistence on reboots.
Implement good change management when altering live production iptables policies to prevent breaking critical connectivity. Test updates thoroughly first outside business hours before deploying widely.
Use this iptables introduction for controlling network traffic on your Ubuntu systems as per administration needs through flexible policies. Extend built-in chains into more complex combinations utilizing custom ones for specialized regulations when required.
Thus with iptables you can lock down or open up network-level access to Linux systems and workloads running on them as deemed appropriate. Use it for safeguarding environments by only allowing authorized connectivity aligned to business objectives.


