# iptables

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/iptables

## Quick definition

iptables is a tool built into Linux that controls what network traffic can enter, leave, or pass through your computer. It works by checking each piece of data against a list of rules you create. If a rule matches, the data is either accepted, rejected, or dropped. You can think of it as a security guard checking IDs at the door of a building.

## Simple meaning

Imagine your computer is like a house with multiple doors and windows. Some doors are for people coming in, some are for people going out, and some connect one room to another inside the house. In the world of Linux networking, iptables is the tool that lets you decide who gets to use each door, what they can carry, and whether they can even knock.

Every piece of information that travels over a network is broken into small chunks called packets. Each packet carries a source address (where it came from), a destination address (where it is going), and often a port number that tells what kind of service it wants (like web traffic or email). iptables looks at each packet as it arrives and compares it to a set of rules you have written.

A rule might say: If a packet comes from a specific IP address and wants to reach port 22 (used for secure shell access), then drop it. Or it might say: Allow all packets that are trying to reach a web server on port 80. If no rule matches, iptables uses a default policy, which might be to allow everything or block everything.

iptables organizes its rules into chains. A chain is just a list of rules applied in order. There are built-in chains for incoming traffic (INPUT), outgoing traffic (OUTPUT), and traffic passing through the system (FORWARD). You can also create your own custom chains to group related rules. The last rule in a chain usually tells iptables what to do if no other rule matched, like accept or drop the packet.

In short, iptables gives you fine-grained control over network security. It is one of the most important tools for system administrators and is often tested in IT certification exams like CompTIA Linux+, LPIC, and Red Hat certifications.

## Technical definition

iptables is a user-space utility program that allows a system administrator to configure the IP packet filter rules of the Linux kernel firewall, implemented as different Netfilter modules. The tool operates by defining tables that contain chains of rules. Each rule in a chain contains a set of matches (conditions) and a target (action to take if the packet matches).

The kernel's networking stack processes packets in several hook points: NF_IP_PRE_ROUTING, NF_IP_LOCAL_IN, NF_IP_FORWARD, NF_IP_LOCAL_OUT, and NF_IP_POST_ROUTING. iptables attaches its rules to these hooks via tables. The three main tables are: filter (for packet filtering decisions), nat (for Network Address Translation), and mangle (for modifying packet headers). A fourth table, raw, is used to bypass connection tracking for special cases.

Inside each table, packets travel through chains. The filter table uses the INPUT, OUTPUT, and FORWARD chains. The nat table uses PREROUTING and POSTROUTING chains, plus OUTPUT for local packets. The mangle table can hook into all five pre-defined chains. Rules within a chain are evaluated sequentially from top to bottom. When a packet matches a rule, the target is executed. Common targets include ACCEPT (let the packet through), DROP (silently discard), REJECT (discard and send an error back), LOG (log the packet), and RETURN (continue to the next chain or return from a custom chain).

Each rule can match on criteria such as source and destination IP addresses (using the -s and -d flags), source and destination ports (using --sport and --dport), protocol (-p tcp, udp, icmp), interface (-i for input, -o for output), connection state (using the conntrack module with -m state --state), and even MAC addresses, TCP flags, or packet length. Rules can also include time-based or rate-limit matches.

The command syntax typically follows: iptables -A CHAIN -m MODULE --MATCH_OPTIONS -j TARGET. For example, iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100 -j ACCEPT adds a rule to the INPUT chain that accepts TCP traffic to port 22 from IP 192.168.1.100. iptables -A INPUT -p tcp --dport 22 -j DROP would then drop all other SSH attempts.

To make rules persistent across reboots, administrators must save the rule set using tools like iptables-save (which outputs the rules in a flat file format) and then load them at boot with iptables-restore. Modern Linux distributions are migrating to nftables as a successor, but iptables remains widely used and is heavily tested in certification exams due to its long history and ubiquity.

## Real-life example

Think of your computer as a secure office building with three sets of doors. The INPUT door is for visitors entering the building from outside. The OUTPUT door is for people leaving the building to go outside. The FORWARD door is for people who walk through the building from one entrance to another without stopping (like a delivery person crossing the lobby).

Now, you are the building security manager. You have a clipboard with a list of rules. For example, Rule 1: Allow the CEO (192.168.1.10) to enter any door at any time. Rule 2: Allow the IT guy (192.168.1.20) to enter only the server room door (port 22 for SSH). Rule 3: Allow the mail carrier to enter only the mailroom (port 25 for SMTP). Rule 4: Block anyone who tries to enter the server room if they are not on the list. Rule 5: Allow everyone else to leave freely. If you had no rules at all, anyone could walk in. With a default-deny policy, only the people on your list get in.

iptables works exactly like this. Each packet is a person walking to a door. The security guard (the kernel) reads the person's badge (source IP, destination IP, port, protocol) and checks it against your clipboard (the rule chain). If the badge matches a rule, the guard follows the instruction: wave them through (ACCEPT), politely tell them to leave (REJECT), or ignore them completely (DROP). If no rule matches, the guard follows the default policy, which you set. This analogy helps you understand that iptables is all about who gets in, who gets out, and who passes through.

## Why it matters

iptables is a fundamental tool for securing Linux systems, which means it matters for any IT professional who manages servers, networks, or cloud infrastructure. Without a properly configured firewall, your system is exposed to unauthorized access, port scans, denial-of-service attacks, and data exfiltration. iptables gives you the ability to enforce security policies at the network layer, which is often the first line of defense.

In practical IT environments, iptables is used to restrict SSH access to only trusted IPs, block brute-force attacks by rate-limiting connections, allow web traffic while blocking everything else, set up NAT for internet sharing, and create DMZs for public-facing services. Many container and virtualization technologies, like Docker, interact with iptables rules to manage network isolation between containers.

For system administrators, understanding iptables is critical for troubleshooting connectivity issues. If a service is unreachable, one of the first checks is whether iptables rules are blocking the port. Similarly, when deploying a new application, the admin must ensure the firewall allows the required traffic. Misconfigured iptables rules can cause services to fail silently, leading to downtime and security holes.

From a certification perspective, iptables appears heavily in Linux-focused exams such as CompTIA Linux+ (XK0-005), LPIC-1 (101-500), and Red Hat Certified System Administrator (RHCSA). The exams test your ability to write, interpret, and modify rules, as well as understand packet flow through tables and chains. Mastering iptables not only helps you pass exams but also builds practical confidence in managing production systems.

## Why it matters in exams

In IT certification exams, iptables is a core objective for several Linux and security certifications. For the CompTIA Linux+ exam (XK0-005), objectives include configuring firewall rules using iptables and understanding the differences between filter, nat, and mangle tables. You might be asked to add a rule that blocks incoming SSH traffic from a specific IP range, or to save the current rule set so it persists after reboot.

For LPIC-1 (101-500), the exam covers iptables under Topic 110.1: Perform basic firewall configuration. You need to know how to use iptables to filter packets, set default policies, and understand connection tracking with the state module. Often, the exam presents a scenario where a server is not reachable on port 80, and you must identify that the INPUT chain has a default DROP policy with no rule to allow HTTP traffic.

For Red Hat Certified System Administrator (RHCSA, EX200), iptables is part of the network services section. You may be required to configure a firewall to allow HTTP and HTTPS traffic, block all traffic from a specific network, and make the rules persistent using iptables-save and iptables-restore. The exam environment uses a virtual machine, so you must be comfortable typing commands and verifying the effect with tools like iptables -L -n -v.

Even the CompTIA Security+ (SY0-601) touches on host-based firewalls, where iptables is used as a prime example. You might see a question about the difference between stateful and stateless filtering, with iptables used to illustrate stateful inspection via the conntrack module. Understanding that iptables can track the state of connections (NEW, ESTABLISHED, RELATED) is a key exam point.

In all these exams, question types include multiple-choice, fill-in-the-blank (where you complete a command), and scenario-based questions where you determine the effect of a given rule set. You need to be comfortable reading the output of iptables -L and identifying missing rules, incorrect options, or ordering issues. The exams value both accuracy and speed, so memorizing common syntax patterns and the order of table chains is essential.

## How it appears in exam questions

In certification exams, iptables questions typically fall into three patterns: command completion, rule interpretation, and troubleshooting scenarios.

Command completion questions give you a partial command and ask you to fill in the missing flags or arguments. For example, the question might show: iptables -A INPUT -p tcp --dport 22 _____ and ask whether the missing part is -j DROP or -j ACCEPT. You may also be asked to identify the correct interface flag: -i eth0 for incoming traffic on a specific interface, or the protocol flag -p udp. Multiple-choice options often include common distractors like using -s when -d is required, or confusing -A (append) with -D (delete).

Rule interpretation questions present a list of iptables rules and ask what the rules accomplish. For instance: iptables -P INPUT DROP, iptables -A INPUT -p tcp --dport 80 -j ACCEPT, iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT. The correct answer is that the server only allows web traffic and responses to connections it initiated, while blocking everything else. Distractors might claim that SSH is allowed, or that the server allows all outgoing traffic.

Troubleshooting scenarios describe a situation where a service is not working as expected. For example, a web server is running, but clients cannot connect. The logs show no connection attempts reaching the server. The question might ask which iptables command to run to diagnose the issue. The correct answer could be iptables -L -n to check if port 80 is being dropped. Or the question might show the current rules and ask why HTTPS traffic is being blocked, with the answer being that port 443 is not in the rule set.

Another common pattern involves saving and restoring rules. A question might ask: After adding rules with iptables, the rules disappear after reboot. Which command must be run to save them? The acceptable answer is iptables-save > /etc/sysconfig/iptables (on Red Hat) or iptables-save > /etc/iptables/rules.v4 (on Debian). The exam may also ask about the order of chains: which chain is checked first for incoming traffic destined for a local process? The answer is the INPUT chain in the filter table.

Stateful filtering questions are also frequent. They ask which module is used to track connection states: the correct answer is conntrack, invoked with -m state. The states are NEW, ESTABLISHED, RELATED, and INVALID. The exam might present a rule like iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT and ask what it does. The answer is that it allows packets that are part of an already established connection, which is essential for interactive services like SSH or HTTP.

Finally, exam questions often test your understanding of default policies. A common trick is to set the default policy to ACCEPT but then add a DROP rule at the end. In that case, the default policy applies only to packets that do not match any rule. But if the default policy is DROP and no rule allows traffic, all traffic is blocked. These nuances are regularly tested.

## Example scenario

You are studying for the CompTIA Linux+ exam, and a practice question reads: A system administrator needs to secure a Linux server so that it only accepts SSH connections from the local network (192.168.1.0/24) and allows all traffic to a web server on port 80 from anywhere. The server is also used by administrators to browse the internet. The current iptables policy is to accept all traffic. Write the commands to restrict access appropriately.

First, you set the default policies to DROP for inbound traffic, but ACCEPT for outbound traffic so that administrators can still browse the internet. The commands would be: iptables -P INPUT DROP and iptables -P OUTPUT ACCEPT. You also set FORWARD to DROP since the server is not a router.

Next, you add a rule to allow SSH only from the local network: iptables -A INPUT -p tcp --dport 22 -s 192.168.1.0/24 -j ACCEPT. This rule permits SSH connections from any device whose IP starts with 192.168.1.

Then, you add a rule to allow web traffic from anywhere: iptables -A INPUT -p tcp --dport 80 -j ACCEPT. You also want to allow related return traffic, so you add: iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT. This is critical because when your server sends a response to a web client, the return packets would otherwise be blocked by the default DROP policy.

Finally, you test the rules by running iptables -L -n to verify. You see the rules in order: first the ESTABLISHED,RELATED allow rule, then SSH from the local network, then HTTP from anywhere. The order matters: you want the stateful rule first so that response packets are always allowed before checking the specific source IP rules.

To save the configuration, you run iptables-save > /etc/iptables/rules.v4 (on Debian) or iptables-save > /etc/sysconfig/iptables (on Red Hat). The scenario demonstrates that a seemingly simple task requires careful thinking about rule order, default policies, and stateful filtering, which are all common exam topics.

## Common mistakes

- **Mistake:** Forgetting to allow established/related traffic when using a default DROP policy on the INPUT chain.
  - Why it is wrong: Without the stateful allow rule, any response to outgoing connections (like DNS replies or web page data) will be dropped, causing the system to fail to function normally even if it can initiate outbound connections.
  - Fix: Add the rule: iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT as one of the first rules in the INPUT chain.
- **Mistake:** Using -s (source) when the rule should apply to destination, or vice versa.
  - Why it is wrong: This mistake causes the rule to match the wrong packets. For example, to allow web traffic to your server, you need -d for destination, but many beginners accidentally use -s, which would only match traffic originating from the server itself.
  - Fix: For incoming traffic, use -d for the server's IP (or omit it) and --dport for the port. For outgoing traffic, use -s for the server and --sport.
- **Mistake:** Placing a restrictive DROP rule before a more general ACCEPT rule, causing the ACCEPT rule to never be reached.
  - Why it is wrong: iptables processes rules in order. If the first rule drops traffic from a specific IP, a later rule that accepts traffic on a specific port from any IP will never apply to that IP because it is already dropped.
  - Fix: Order rules from most specific to least specific for the same type of action, or place ACCEPT rules before DROP rules for the same condition. Alternatively, use the order: allow established, then allow specific services, then drop everything else.
- **Mistake:** Not making rules persistent after a reboot, then wondering why the firewall is reset.
  - Why it is wrong: iptables rules exist only in memory. A reboot clears all rules unless they are saved to a file and loaded at startup. The system may become vulnerable or non-functional until the rules are reapplied.
  - Fix: After configuring rules, run iptables-save and redirect the output to the appropriate file for your distribution (e.g., /etc/iptables/rules.v4). Also ensure the iptables service or netfilter-persistent service is enabled to load rules on boot.
- **Mistake:** Confusing the -A (append) and -I (insert) flags, leading to rules appearing in the wrong order.
  - Why it is wrong: Using -A adds a rule at the end of the chain. If you have a default DROP policy, rules added with -A may never be reached because all packets are already dropped by the default policy. Using -I without a position number inserts at the top, which may disrupt intended logic.
  - Fix: Understand rule ordering. Insert rules at a specific position with iptables -I CHAIN [rule_number] ... or be aware that when using -A, you must ensure prior rules do not prevent the new rule from being evaluated.

## Exam trap

{"trap":"An exam question states: 'A server has a default policy of ACCEPT on the INPUT chain. A rule is added: iptables -A INPUT -p tcp --dport 22 -j DROP. Another rule is added later: iptables -A INPUT -s 192.168.1.10 -p tcp --dport 22 -j ACCEPT. Will the user at 192.168.1.10 be able to SSH into the server?'","why_learners_choose_it":"Learners see the second rule explicitly allows SSH from the specific IP, so they believe the connection will be accepted. They overlook the fact that the first rule drops all SSH traffic, and the second rule comes after the first, so it is never evaluated for any SSH packet.","how_to_avoid_it":"Always pay attention to the order of rules in iptables. The first matching rule wins. To allow a specific IP, the allow rule must be placed before the broader deny rule. The correct approach would be to use the insert flag: iptables -I INPUT 1 -s 192.168.1.10 -p tcp --dport 22 -j ACCEPT, then append the deny rule. In exam questions, read the order carefully and remember that later rules are ignored if an earlier rule already decided the packet's fate."}

## Commonly confused with

- **iptables vs nftables:** nftables is the modern replacement for iptables in the Linux kernel. While iptables uses separate tools for IPv4 (iptables) and IPv6 (ip6tables), nftables uses a single unified framework. The syntax is different: nftables uses a more structured, declarative language rather than the command-line flags of iptables. Many recent distributions default to nftables, though compatibility tools exist. (Example: In iptables, you run: iptables -A INPUT -p tcp --dport 80 -j ACCEPT. In nftables, you would define a table and chain first, then run: nft add rule inet filter input tcp dport 80 accept.)
- **iptables vs ufw (Uncomplicated Firewall):** ufw is a front-end for iptables (or nftables) designed to simplify firewall management. It uses easy commands like ufw allow 22/tcp instead of long iptables commands. ufw is commonly used on Ubuntu and Debian. However, ufw is not a separate firewall engine; it just generates the underlying iptables rules for you. (Example: To allow SSH with ufw: ufw allow 22/tcp. The equivalent iptables command would be: iptables -A INPUT -p tcp --dport 22 -j ACCEPT (along with any stateful rules).)
- **iptables vs firewalld:** firewalld is a firewall management tool for Linux that uses zones and services to define rules. It can use either iptables or nftables as its backend. Unlike iptables, firewalld supports dynamic changes without restarting the service and has a D-Bus interface. firewalld is the default on RHEL/CentOS 7 and later. (Example: In firewalld, you would run: firewall-cmd --permanent --add-service=http to allow web traffic. The equivalent iptables command is more complex and requires adding multiple rules for port 80 and established connections.)

## Step-by-step breakdown

1. **Packet Arrival at the Network Interface** — A packet arrives at the network interface card (e.g., eth0). The kernel's networking stack identifies the packet and sends it to the first Netfilter hook: NF_IP_PRE_ROUTING. This hook is before any routing decision, so iptables rules in the raw table (if any) can modify the packet before connection tracking.
2. **Routing Decision: Is the Packet for This Host?** — The kernel makes a routing decision based on the destination IP. If the destination is the local host, the packet moves to the NF_IP_LOCAL_IN hook, which corresponds to the INPUT chain. If the destination is another host, the packet goes to the NF_IP_FORWARD hook (FORWARD chain). If the packet is generated locally, it starts at the NF_IP_LOCAL_OUT hook (OUTPUT chain).
3. **Traversal of the INPUT Chain (for local-bound packets)** — The packet enters the filter table's INPUT chain. The kernel evaluates each rule in order, checking matches such as protocol, source IP, destination port, interface, and connection state. The first rule that matches determines the packet's fate: ACCEPT, DROP, REJECT, LOG, or jump to a custom chain.
4. **Target Execution (Accept, Drop, or Reject)** — If the target is ACCEPT, the packet is allowed to proceed to the local process (e.g., the web server). If DROP, the packet is silently discarded with no response. If REJECT, the kernel sends a TCP RST or ICMP unreachable back to the sender. If the packet hits a LOG target, it is logged (but continues to the next rule), useful for debugging.
5. **Post-Routing for Outgoing Packets (NAT)** — For packets leaving the host (either locally generated or forwarded), they pass through the NF_IP_POST_ROUTING hook. The nat table's POSTROUTING chain is evaluated here, commonly used for source NAT (masquerading) to hide internal IPs behind a public IP. The packet is then transmitted out the network interface.

## Practical mini-lesson

To really understand iptables, you need to practice building a firewall from scratch. Start by checking your current rules: sudo iptables -L -n -v. The -v flag gives packet and byte counts, which help you see whether rules are actually being hit. If the packet count is zero for a rule you just added, it might be in the wrong chain or a previous rule is blocking the traffic.

Next, understand the three built-in tables. The filter table is where you do most of your work: controlling what traffic is allowed to reach your services. The nat table is essential for network address translation, whether for internet sharing or port forwarding. The mangle table is used for specialized tasks like changing the TTL or marking packets for quality of service.

When writing rules, always consider the order. A good practice is to start with a clean slate: set the default policies to ACCEPT temporarily, add your allow rules, then change the default policy to DROP. This way, you can test that your allow rules work before applying the restrictive policy. For example:

sudo iptables -P INPUT ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -s 192.168.1.0/24 -j ACCEPT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -j DROP
sudo iptables -P INPUT DROP

Notice that the last rule before the default policy is a catch-all DROP, which will block any traffic that does not match the earlier rules. This is redundant if the default policy is also DROP, but it makes the rule set more self-documenting and ensures that changing the default policy later does not accidentally open the firewall.

Professionals also use iptables -S to list rules in a format that can be directly reused in scripts. For example, iptables -S will output something like: -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 22 -j ACCEPT. This output is useful for backup and version control.

One common mistake in production is forgetting to allow loopback traffic. The loopback interface (lo) is used for internal communication between processes on the same machine. Without a rule like iptables -A INPUT -i lo -j ACCEPT, many services that rely on localhost connections (like database servers) will break.

Another practical consideration is using connection limiting to prevent brute-force attacks. For example, iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set can track new SSH connections. Combined with a limit, you can drop IPs that exceed a certain rate. This is not just an exam concept; it is used daily on production servers.

Finally, always test your firewall from another machine. Use tools like nmap to scan your server and verify that only the expected ports are open. The iptables -L -n -v command will show you packet counts, which confirm that your rules are being hit. If the count does not increase after you test, something is wrong with the rule logic.

## Commands

```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


## Troubleshooting clues

- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined

## Memory tip

Remember 'FORWARD is for friends, INPUT is for me, OUTPUT is for leaving.' This helps you recall the three main filter chains: FORWARD (traffic passing through), INPUT (incoming to your system), OUTPUT (outgoing from your system).

## FAQ

**Is iptables still relevant in 2025?**

Yes, even though nftables is the modern replacement, iptables is still widely used in legacy systems and many enterprise environments. Certifications like CompTIA Linux+ and LPIC-1 still test iptables, so it remains relevant for exam preparation and real-world system administration.

**How do I save iptables rules after reboot?**

Use the command iptables-save and redirect the output to a file, typically /etc/iptables/rules.v4 on Debian/Ubuntu or /etc/sysconfig/iptables on RHEL/CentOS. Then, enable the appropriate service (like iptables or netfilter-persistent) to load the rules at boot.

**What is the difference between DROP and REJECT?**

DROP silently discards the packet without sending any response, which can make a port appear as closed or invisible. REJECT drops the packet but sends an error message back (like a TCP RST or ICMP port unreachable). DROP is often preferred for security because it gives no information to a potential attacker.

**Can iptables filter based on MAC addresses?**

Yes, using the MAC module. For example: iptables -A INPUT -p tcp --dport 22 -m mac --mac-source 00:11:22:33:44:55 -j ACCEPT. This is useful for restricting access on local networks where IP addresses can be easily spoofed.

**How do I delete a specific rule in iptables?**

First list rules with line numbers using iptables -L --line-numbers. Then delete by number: iptables -D INPUT 3 (deletes rule number 3 in the INPUT chain). Alternatively, you can delete by specifying the exact rule: iptables -D INPUT -p tcp --dport 80 -j ACCEPT.

**What does the state module do in iptables?**

The state module (invoked with -m state) allows rules to match packets based on their connection state: NEW (first packet of a connection), ESTABLISHED (part of an existing connection), RELATED (associated with an existing connection, like ICMP errors), and INVALID (malformed packets). This enables stateful firewall functionality.

## Summary

iptables is a powerful and essential firewall tool for Linux systems, allowing administrators to control network traffic with granular rules based on IP addresses, ports, protocols, and connection states. It operates within the kernel's Netfilter framework and organizes rules into tables and chains. The filter table is used for permitting or denying traffic, the nat table for network address translation, and the mangle table for packet modifications.

Understanding iptables is critical for IT professionals because it provides the foundation for Linux security at the network layer. Misconfigurations can lead to security breaches or service outages, while proper configuration ensures that only intended traffic reaches services like SSH, HTTP, or databases. The tool is heavily tested in certification exams such as CompTIA Linux+, LPIC-1, and RHCSA, where candidates must demonstrate the ability to write, interpret, and troubleshoot rule sets.

Key exam takeaways include: knowing the three default chains (INPUT, OUTPUT, FORWARD), understanding the order of rule evaluation, being able to use the state module for stateful filtering, and knowing how to save rules persistently. Common traps involve rule ordering, confusing default policies with explicit rules, and failing to allow established traffic. By mastering iptables, you not only earn exam points but also build practical skills that are invaluable in any Linux administration role.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/iptables
