Back to tools
What is iptables?
iptables is the Linux kernel command-line tool for configuring the Netfilter firewall. It is essential for Linux server security.
- Tables: filter, nat (translation), mangle (modification)
- Chains: INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING
- Actions: ACCEPT, DROP, REJECT, LOG, DNAT, SNAT, MASQUERADE
- Matches: -p (protocol), -s (source), -d (destination), --dport
- States: NEW, ESTABLISHED, RELATED, INVALID
Frequently Asked Questions
How to block an IP address with iptables on Linux?
To block a specific IP use `iptables -A INPUT -s 192.168.1.100 -j DROP`. `-A INPUT` appends the rule to the INPUT chain, `-s` specifies the source IP and `-j DROP` silently discards all packets. To block only new connections add `-m state --state NEW`. To log before dropping: `iptables -A INPUT -s 192.168.1.100 -j LOG --log-prefix "BLOCKED: "`. Save rules with `iptables-save > /etc/iptables/rules.v4` to make them persistent across reboots on Debian-based systems.
What is the difference between filter, nat and mangle tables in iptables?
The `filter` table is the default and controls traffic by accepting (ACCEPT), dropping (DROP) or rejecting (REJECT) packets on INPUT, OUTPUT and FORWARD chains. The `nat` table handles address translation: SNAT changes source IP (outbound to Internet), DNAT changes destination IP (incoming access). The `mangle` table modifies packet headers like TTL or TOS fields, useful for QoS and load balancing. The `raw` and `security` tables serve advanced use cases such as connection tracking exceptions and SELinux policies.
How to configure iptables to allow only SSH and HTTP traffic?
A minimal secure iptables configuration: `iptables -P INPUT DROP` (default policy: drop all), `iptables -P FORWARD DROP`, `iptables -P OUTPUT ACCEPT`. Then allow SSH: `iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT`. Allow HTTP/HTTPS: `iptables -A INPUT -p tcp -m multiport --dports 80,443 -m state --state NEW -j ACCEPT`. Allow established traffic: `iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT`. Allow loopback: `iptables -A INPUT -i lo -j ACCEPT`.
How to redirect ports with iptables using DNAT and SNAT?
Use DNAT in the nat table for port redirection. Redirect incoming port 8080 to internal port 80: `iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination :80`. Redirect to another IP: `iptables -t nat -A PREROUTING -p tcp --dport 443 -j DNAT --to-destination 192.168.1.10:443`. Enable IP forwarding with `sysctl net.ipv4.ip_forward=1`. For SNAT to masquerade outbound traffic: `iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE`.