DEV Community

Jacopo Valanzano
Jacopo Valanzano

Posted on

Cool "iptables" commands - Linux

The iptables command is a formidable tool that allows you to do many cool things.
Here are some of my favorite uses:

Allow all loopback ( lo0 ) traffic, and reject traffic to localhost that does not originate from lo0.

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT ! -i lo -s 127.0.0.0/8 -j REJECT
Enter fullscreen mode Exit fullscreen mode

Allow ping.

iptables -A INPUT -p icmp -m state --state NEW --icmp-type 8 -j ACCEPT
Enter fullscreen mode Exit fullscreen mode

Allow SSH connections.

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT
Enter fullscreen mode Exit fullscreen mode

Allow HTTP and HTTPS connections from anywhere ( standard web server ports ).

iptables -A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT
Enter fullscreen mode Exit fullscreen mode

Allow inbound traffic from established connections. This includes ICMP error returns.

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Enter fullscreen mode Exit fullscreen mode

Log incoming, but denied traffic.

iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables_INPUT_denied: " --log-level 7
Enter fullscreen mode Exit fullscreen mode

Reject all inbound traffic that hasn't been explicitly allowed by previous rules.

iptables -A INPUT -j REJECT
Enter fullscreen mode Exit fullscreen mode

Log any traffic that was sent to you for forwarding ( applies to packets being routed through your machine, not destined for it ).

iptables -A FORWARD -m limit --limit 5/min -j LOG --log-prefix "iptables_FORWARD_denied: " --log-level 7
Enter fullscreen mode Exit fullscreen mode

Reject all traffic forwarding.

iptables -A FORWARD -j REJECT
Enter fullscreen mode Exit fullscreen mode

Bonus: nullrouting an IP with the "ip" command ( useful against volumetric DOS attacks ).

ip route add blackhole 192.168.1.100
Enter fullscreen mode Exit fullscreen mode

And to remove the nullroute:

ip route del blackhole 192.168.1.100
Enter fullscreen mode Exit fullscreen mode

Top comments (0)