DEV Community

kingyou
kingyou

Posted on

Linux firewall- iptables

iptables Guide: Basics to Advanced NAT

iptables serves as Linux's primary firewall tool, leveraging the Netfilter framework to filter, modify, and route network packets across filter, NAT, and mangle tables. It processes packets through five key chains: PREROUTING, INPUT, FORWARD, OUTPUT, and POSTROUTING, enabling precise control over traffic flow.

Core Principles

Netfilter hooks into the kernel's networking stack, evaluating rules in chains before routing decisions. PREROUTING handles incoming packets immediately upon interface arrival for destination modifications, while POSTROUTING adjusts outgoing packets just before transmission, ideal for source NAT. Rules match packet attributes like IP, port, and protocol, jumping to targets such as ACCEPT, DROP, or DNAT/SNAT.

Common Filter Rules

Basic INPUT/OUTPUT rules secure local access:

# Default drop policy
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP

# Allow loopback and established connections
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Permit SSH from specific subnet
iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 22 -j ACCEPT
Enter fullscreen mode Exit fullscreen mode

These protect against unauthorized access while allowing essential services.

PREROUTING and POSTROUTING Examples

PREROUTING excels in DNAT for port forwarding; POSTROUTING handles SNAT/MASQUERADE for outbound traffic:

# PREROUTING: Redirect external port 80 to internal 8080
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

# PREROUTING: DNAT external IP to internal server
iptables -t nat -A PREROUTING -i eth0 -p tcp -d 10.1.1.7 --dport 80 -j DNAT --to-destination 192.168.1.2:80

# POSTROUTING: SNAT for internal clients accessing internet
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.100.0/24 -j SNAT --to-source 203.0.113.1

# POSTROUTING: MASQUERADE for dynamic outbound IP
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
Enter fullscreen mode Exit fullscreen mode

These enable load balancing, port redirection, and NAT routing on gateways.

Saving and Loading Rules

Persist rules across reboots using iptables-save and restore:

# Save all rules to file
iptables-save > /etc/iptables/rules.v4

# Restore from file
iptables-restore < /etc/iptables/rules.v4

# Ubuntu: Install iptables-persistent for auto-load
apt install iptables-persistent
netfilter-persistent save
Enter fullscreen mode Exit fullscreen mode

For RHEL/CentOS, use service iptables save. Test rules with iptables -L -v -n before saving.

Top comments (0)