- Structure and flow: tables, chains, and how traffic flows
- Rules and Policies: Commands, Matches, and Key Objectives
- NAT and Publishing: SNAT/MASQUERADE and DNAT in Real-World Scenarios
- Secure Design: Functional DMZ and Good Operating Practices
If you manage Linux distributions to protect your security and privacy, sooner or later you will have to deal with iptables. This packet filtering system is the heart of the classic firewall in GNU/Linux, capable of deciding what traffic enters, exits, or is forwarded between networks. Properly configured, it's like having a very fine gatekeeper at your network's door, enforcing your rules without flinching and with surgical precision.
In the following lines you will find a complete and updated guide that integrates the essentials: firewall concepts, Netfilter, tables and chains, packet flow, key commands, rule extensions and targets advanced, as well as practical scenarios such as NAT, redirects, default policies, and a functional DMZ. All explained in relatable yet rigorous language, so you can apply it to your infrastructure right away.
Firewalls in Context: From Nightclub Bouncers to the DMZ
A firewall is, in essence, a filter between networks that applies rules to decide the destination of each packet. Think of it like a nightclub bouncer with a list of criteriaIf the package complies, it passes; if not, it's out. This metaphor helps to understand that what matters is the logic of the rules and the order in which they are evaluated.
Within network design, some topologies are more secure than others. The DMZ (demilitarized zone) is an intermediate network that hosts public services (such as a web or FTP server) separating them from the corporate LAN. Why? Because if an attacker were to compromise a public server, segmentation prevents them from having direct access to the rest of the internal network.
Linux as a firewall: Netfilter and iptables
The Linux kernel incorporates Netfilter, a framework with hooks to intercept and manipulate packetsIn user space, iptables is the utility that defines the rules the kernel will apply to traffic flow. This kernel/user separation allows for high performance with great flexibility.
It is convenient to distinguish the utilities by protocol: iptables (IPv4), ip6tables (IPv6), arptables (ARP), and ebtables (Ethernet frames). In the kernel, the common module is x_tables, which shares the logic for matching extensions and targets. And a historical note: iptables replaced ipchains and, in turn, nftables succeeded iptables in kernel 3.13, although iptables is still very present in many systems.
To operate, you will need administrator privileges. Run iptables as root (or with sudo), usually in /usr/sbin/iptables (Debian/derivatives) or /sbin/iptables (Red Hat/derivatives). The official documentation is at man iptables and at netfilter.org.
iptables structure: tables, chains and rules
Iptables organizes its logic into tables composed of chains full of rulesEach rule specifies match conditions and a target to apply when the packet matches.
- Filter table (default, pure filtering)
- INPUT: traffic directed to the machine itself.
- FORWARD: traffic that passes through the equipment (routing).
- OUTPUT: locally generated traffic.
- Nat table (address translation; evaluated on new connections)
- PREROUTING: before deciding on a route; ideal for DNAT/port forwarding.
- OUTPUT: locally originated packets before routing.
- POSTROUTING: after routing; typical for SNAT/MASQUERADE.
- Mangrove table (fine header adjustments: TOS, TTL, marking, etc.)
- PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING: available all the way.
- Raw table (connection tracking control/conntrack)
- PREROUTING y OUTPUT: to mark traffic that should be skipped by conntrack.
When a packet arrives at a chain, is compared sequentially with each rule; if it matches, its goal is executed and the traversal stops. If it reaches the end without matching any and the chain is predefined, the default policy (chain policy) of that chain.
Packet flow: where they pass and when
Understanding the route that traffic follows is key to correctly locating the rules. A packet leaving your LAN to the Internet It is typically processed like this: first PREROUTING (possible DNAT/mangrove), passes through FORWARD (traffic filtering), and before leaving the team touches POSTROUTING (SNAT/MASQUERADE if applicable).
However, if the destination is the firewall itself, PREROUTING → INPUT will intervene; if issued by the local machine, the path will be OUTPUT → POSTROUTINGThis mental matrix saves you headaches when something doesn't add up.
Basic commands: list, clear, create, and default policies
To audit the current status, uses iptables -L (optionally -v for detail and -n (to not resolve names). You can also create and delete chains with -N y -X respectively, and set default policies with -P.
When you need to start from scratch, clean rules with -F (flush) and, if applicable, counters. Remember that you can specify tables with -t and specific chains; for example, iptables -F -t nat for the NAT.
When defining rules, the most common options are straightforward: -A duck, -I insert, -R replaces and -D erase. Then you add selectors like -p (protocol), -s/-d (origin/destination), -i/-o (interfaces) and the target with -j (e.g., ACCEPT, DROP or REJECT).
The default policies define what happens if no rules match. A typical hardened scheme on a host would be INPUT DROP, FORWARD DROP, OUTPUT ACCEPT, blocking everything incoming except what is explicitly allowed and allowing what comes out.
Match extensions (-m): TCP, UDP, ICMP, MAC, stateful, and multiport
Iptables extends its filters with matching modules using -m. The TCP one allows tuning by ports and flags: --dport/--sport y --syn for new connection openings, for example.
For UDP, You can also delimit ports of origin and destinationA classic case: opening the 80/443 to a web server or allowing outgoing DNS queries on 53/UDP.
With ICMP, --icmp-type lets you discriminate types (e.g., echo-request y echo-reply for pings). This is useful to allow diagnostics without leaving the door open to full ICMP.
There is also the module mac to filter by MAC address --mac-source. Useful if you want to authorize a managed computer with a dynamic IP to ping the firewall without relying on the IP.
And, perhaps most importantly at the operational level, the module state (or conntrack) with --state NEW, ESTABLISHED, RELATEDThis allows responses from already established connections to be allowed, drastically reducing the number of rules required.
To group ports, multiport Add --sports y --dports with comma-separated lists. It is convenient to open HTTP, HTTPS and SSH in a single rule.
Targets beyond ACCEPT/DROP: NAT and company
In addition to accepting or discarding, iptables can rewrite addresses and ports to connect private networks to the Internet or publish internal services.
MASQUERADE (At POSTROUTING of the table nat) replaces the source IP with the firewall's output IP, ideal when the public IP is dynamic (DHCP). This is the typical outbound NAT for an entire LAN.
SNAT (also in POSTROUTING) explicitly sets the source IP/port with --to-source. It is used when you have a static public IP and you want to precisely control the translation.
DNAT (At PREROUTING o OUTPUT) change the destination IP with --to-destination. It is the famous "open ports": You receive traffic on the public IP and redirect it to a server in the DMZ, for example an internal website at 192.168.1.2.
Simple example: filtering traffic between two networks
Imagine a machine acting as a router/firewall between two subnets. If you want only host B to talk to C and only via TCP, the table will be filter and the correct string is FORWARD, because traffic passes through the equipment.
First you would apply a default policy DROP on FORWARD and then you would explicitly allow traffic B→C on TCP (and, if applicable, C→B). This “deny by default, allow as little as possible” pattern is the foundation of a strong security posture.
Everyday cases on a catwalk: typical rules
A gateway with two interfaces, for example eth1 (LAN) and eth0 (WAN), usually needs to forward packets from the LAN to the Internet. To do this, it adds FORWARD -i eth1 -o eth0 -j ACCEPT, and allows in reverse only ESTABLISHED,RELATED -m state.
In the firewall itself, it is advisable to authorize incoming traffic that is a response to outgoing connections INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT, and always allow loopback: INPUT -i lo -j ACCEPT.
To allow LAN computers to browse, apply outbound NAT: -t nat -A POSTROUTING -s 192.168.0.0/24 -o eth0 -j SNAT --to-source X.Y.Z.W (o MASQUERADE if the IP is dynamic). This translates the private IPs to your public IP.
A basic hardening is blocking Incoming packets over the WAN with incorrect source IPs (your own public IP, private ranges 192.168.0.0/24, 127.0.0.0/8, etc.), as these usually indicate spoofing.
To expose services on the firewall (e.g., SMTP 25, HTTP 80, HTTPS 443, or SSH 22), you can allow TCP packets with the SYN flag to those destination ports. If you want to narrow down by destination IP, add -d to the IP of the service.
Common infrastructure services: DHCP (traffic from port 68 to 67) on the LAN interface, and DNS from the authorized resolver (UDP 53) if you filter by source. These openings allow clients to obtain IP addresses and resolve names.
If you have to close access, DROP to incoming SSH/Telnet It's direct; you can also REJECT outputs to banned IPs from the local network so that the sender receives notification of rejection.
Installing and managing the service on Red Hat/CentOS systems
In legacy environments with CentOS/RHEL 5/6, it was enough to install with yum -y install iptablesAlthough many new distros today favor nftables, iptables is still present in production systems and appliances.
Integration with SysV services allowed to manage and persist rules: service iptables start|stop|restart y service iptables save, saving in /etc/sysconfig/iptables. To enable at boot: chkconfig iptables on at levels 2–5.
In modern systems, although the wrappers, the idea persists: define rules, test them and stick to them so that they survive reboots, either with system tools or scripts.
Listing, deleting, and editing rules with precision
To see the status with rule numbers, uses iptables -L --line-numbers -n -v. This way you can delete by index with -D INPUT 3 or replace with -R without confusion.
If you need a selective delete, Clean only the chain or board that touches (-F FORWARD o -F -t nat). Avoid remote global sweeps without a “safety net” or you may lose SSH access.
As a common practice, First set rules that allow your SSH session, apply changes gradually and have a rollback window (e.g., a cron that restores rules in 5 minutes if you don't commit).
Persistence with iptables-save and iptables-restore
To save your settings, iptables-save > /ruta/backup/iptables.rules Generates a machine-readable dump of all tables. It's ideal for change control and migrations.
To charge it, use iptables-restore < /ruta/backup/iptables.rulesYou can automate boot restore with systemd, init scripts, or a cron job. @reboot, ensuring that the firewall remains active after a reboot.
Add to this good operating practices: runs with appropriate privileges, save files outside /tmp and align them with the environment (correct interfaces and subnets) to avoid surprises.
DMZ in detail: a complete and realistic example
Suppose a Linux firewall is connected to a router in “single-user” mode (without NAT), with three interfaces: eth0 (LAN 192.168.1.1/24), eth1 (DMZ 192.168.2.1/24) and eth2 (WAN with IP by DHCP). The DMZ hosts a Apache web server (192.168.2.2) and one FTP (192.168.2.3).
Policy objectives: publish HTTP/HTTPS and FTP from the DMZ to the Internet, allow SSH administration from the LAN to the firewall, and allow the LAN to browse (HTTP/HTTPS), FTP transfers, and DNS resolution. Everything else is denied.
Broadly speaking: in filter/FORWARD allows LAN→WAN transit with response, and WAN→DMZ to published ports only ESTABLISHED,RELATED for the answers. In nat/PREROUTING, applies DNAT to publish services; in nat/POSTROUTING, SNAT/MASQUERADE for LAN/DMZ output.
Examples of openings: DNAT 80/443 to 192.168.2.2 and 21/20 (depending on mode) to 192.168.2.3 with the corresponding FORWARD Allowing those ports. Secure the control and data channels for FTP (active/passive) or limit the passive range and reflect this on the firewall.
For LAN: allows exit to 80, 443, 21 and 53 and its return, applying outbound NAT in POSTROUTING. In the firewall, authorize Incoming SSH only from the 192.168.1.0/24 subnet and blocks unwanted access from the WAN.
Don't forget hygiene: DROP to invalid ranges over the WAN (private, loopback, your own public) and record whatever interests you. With restrictive default policies and minimal openings, your exposure is reduced to the bare minimum.
Good practices and operational tricks
Always work with a plan: document what you allow and why, verify the expected flow with a simple diagram and apply rules in the correct order to avoid overlaps.
Use a combination of modules with a head: state/conntrack for responses, tcp con --syn in openings, and multiport to groupThis way you simplify and reduce the risk of inconsistencies.
For environments with frequent changes, consider separating rules by function: custom chains (With -N) calls from INPUT/OUTPUT/FORWARD, so that keeping or reversing pieces is cleaner.
The transition to nftables is underway on many distros, but if your platform/product uses iptables, Knowing these pieces thoroughly will give you complete control.And if you migrate, you'll easily understand the equivalent mind map in nftables.
With what you've seen, you now have a solid foundation for deploying and maintaining iptables in production: You understand the architecture (tables, chains, and flow), you master the essential commands, you apply NAT and publishing with DNAT/SNAT, and you know how to set up a secure DMZ.From here, it's up to you to adjust to your specific case, audit periodically, and keep your rules as clear as your network model.
Table of Contents
- Firewalls in Context: From Nightclub Bouncers to the DMZ
- Linux as a firewall: Netfilter and iptables
- iptables structure: tables, chains and rules
- Packet flow: where they pass and when
- Basic commands: list, clear, create, and default policies
- Match extensions (-m): TCP, UDP, ICMP, MAC, stateful, and multiport
- Targets beyond ACCEPT/DROP: NAT and company
- Simple example: filtering traffic between two networks
- Everyday cases on a catwalk: typical rules
- Installing and managing the service on Red Hat/CentOS systems
- Listing, deleting, and editing rules with precision
- Persistence with iptables-save and iptables-restore
- DMZ in detail: a complete and realistic example
- Good practices and operational tricks