Explore iptables in Linux
Introduction to iptables
What is iptables?
iptablesis a user-space utility program for configuring the Linux kernel's built-in firewall (netfilter).It allows administrators to define rules for packet filtering, network address translation (NAT), and port forwarding.
It’s widely used for securing servers, managing traffic, and controlling network access.
Why is iptables important?
Securing Linux systems by filtering incoming and outgoing traffic.
Blocking malicious traffic, allowing specific services, and setting up NAT for private networks.
Key Concepts in iptables
Tables
Filter: For packet filtering (default table).
Nat: For network address translation.
Mangle: For specialized packet alteration.
Raw: For connection tracking exemptions.
Chains
INPUT: For packets destined for the local system.
OUTPUT: For packets generated by the local system.
FORWARD: For packets routed through the system.
PREROUTING: For altering packets as they arrive (before routing).
POSTROUTING: For altering packets as they leave (after routing).
Rules and Targets
ACCEPT: Allow the packet.
DROP: Silently discard the packet.
REJECT: Discard the packet and send an error message.
LOG: Log the packet for debugging.
SNAT/DNAT: Source/Destination NAT for modifying addresses.
Basic iptables Commands
Viewing Rules
iptables -L: List all rules in the filter table.iptables -L -t nat: List rules in the NAT table.iptables -L -v: Show verbose output with packet/byte counts.
Adding Rules
iptables -A INPUT -p tcp --dport 22 -j ACCEPT: Allow SSH traffic.iptables -A INPUT -p tcp --dport 80 -j ACCEPT: Allow HTTP traffic.iptables -A INPUT -j DROP: Drop all other incoming traffic.
Deleting Rules
iptables -D INPUT 2: Delete the 2nd rule in the INPUT chain.iptables -F: Flush all rules (clear the chain).
Saving and Restoring Rules
iptables-save > /etc/iptables/rules.v4: Save rules to a file.iptables-restore < /etc/iptables/rules.v4: Restore rules from a file.
Advanced Usage
Rate Limiting
Use -m limit to limit the number of connections:
iptables -A INPUT -p tcp --dport 22 -m limit --limit 5/min -j ACCEPT
Port Forwarding
Forward traffic from one port to another:
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80
Using Custom Chains
Create and use custom chains for better organization:
iptables -N MYCHAIN
iptables -A INPUT -j MYCHAIN
iptables -A MYCHAIN -p tcp --dport 22 -j ACCEPT

