Introduction
Linux kernel Netfilter provides packet filtering, NAT, and connection tracking. iptables and nftables are user-space tools for this framework.
Debian/Ubuntu and RHEL 8+ are moving to nftables; iptables remains common and can run over nftables.
This guide covers basic concepts, rule chains, stateful filtering, and production templates.
Netfilter Concepts
Tables: filter, nat, mangle. Chains: INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING.
Policies: ACCEPT, DROP, REJECT. Default DROP policy is more secure; only explicitly allowed traffic passes.
sudo iptables -L -n -v
sudo nft list rulesetiptables Basic Rules
iptables -A INPUT -p tcp --dport 22 -j ACCEPT opens SSH. -m state --state ESTABLISHED,RELATED allows existing connections (stateful).
-s 10.0.0.0/8 filters source IP. -j DROP silently drops; REJECT returns ICMP error.
# Temel sunucu kuralları
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPTnftables Syntax
nftables offers unified table/chain/rule syntax; more consistent than iptables. Add rules with nft add table/filter, nft add chain, nft add rule.
On Debian iptables-nft backend translates iptables commands to nftables.
nft add table inet filter
nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }
nft add rule inet filter input iif lo accept
nft add rule inet filter input ct state established,related accept
nft add rule inet filter input tcp dport { 22, 80, 443 } acceptNAT and Port Forwarding
MASQUERADE is outbound NAT; lets internal network reach the internet. DNAT for port forwarding uses PREROUTING chain.
Docker and Kubernetes add their own iptables rules; watch for conflicts.
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 10.0.0.5:80Persistence and Management
Save rules with iptables-save > /etc/iptables/rules.v4. netfilter-persistent loads at boot. ufw is a simple Ubuntu frontend over iptables.
Guarantee SSH access before rule changes; do not lock yourself out.
Varsayılan politika DROP + stateful ESTABLISHED,RELATED kuralı her üretim firewall'ının temelidir.
Security Checklist
Open only required ports. Add fail2ban or rate limit for SSH. Restrict ICMP if unnecessary. Log DROP rules for attack analysis.
Regularly audit rules with iptables -L -n -v or nft list ruleset.
- Varsayılan DROP
- Stateful filtering
- SSH koruması
- Kural kalıcılığı
- Düzenli denetim
Conclusion
iptables and nftables are essential for Linux server security. Prefer nftables for new projects; maintain existing iptables scripts with a migration plan.
Manage firewall rules as infrastructure-as-code and validate changes in a test environment.