DEV Community

Jacopo Valanzano
Jacopo Valanzano

Posted on • Edited 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 (not 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

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay