Skip to content

Instantly share code, notes, and snippets.

@harpagon210
Last active May 2, 2020 22:28
Show Gist options
  • Save harpagon210/73aaf438acefbcc0f5c0ea0a9506a554 to your computer and use it in GitHub Desktop.
Save harpagon210/73aaf438acefbcc0f5c0ea0a9506a554 to your computer and use it in GitHub Desktop.
iptables cheat sheet for basics

some default rules

iptables -A INPUT -i lo -m comment --comment "allow traffic on loopback interface" -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -m comment --comment "allow connections that are already established or related" -j ACCEPT
iptables -A INPUT -p icmp -m comment --comment "allow ping" -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m comment --comment "allow ssh" -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -m comment --comment "allow http" -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -m comment --comment "allow https" -j ACCEPT
iptables -P -m comment --comment "drop the rest of the incoming traffic" INPUT DROP
iptables -P -m comment --comment "drop the forwarding traffic" FORWARD DROP
iptables -P -m comment --comment "allow outgoing traffic" OUTPUT ACCEPT

display rules

iptables -L

add comment to a rule

iptables -A INPUT -p tcp --dport 443 -m comment --comment "allow https" -j ACCEPT

allow all trafic on loopback interface

iptables -A INPUT -i lo -j ACCEPT

allow connections that are already established or related

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

allow a specific tcp port

iptables -A INPUT -p tcp --dport 22 -j ACCEPT

allow a specific udp port

iptables -A INPUT -p udp --dport 1194 -j ACCEPT

allow all traffic from a specific IP address

iptables -A INPUT -s 192.168.0.100 -j ACCEPT

block all traffic from a specific IP address

iptables -A INPUT -s 192.168.0.200 -j DROP

block all the ports (must be done after opening the needed ports)

iptables -P INPUT DROP

block all forwarding traffic

iptables -P FORWARD DROP

allow all outgoing traffic

iptables -P OUTPUT ACCEPT

reset iptables

iptables -F

Saving Rules

On Ubuntu 16.04/18.04

sudo apt install iptables-persistent netfilter-persistent

edit rules

/etc/iptables/rules.v4
/etc/iptables/rules.v6

useful commands

# save rules
netfilter-persistent save
# load rules
netfilter-persistent start

# service stop/start/restart
systemctl stop    netfilter-persistent
systemctl start   netfilter-persistent
systemctl restart netfilter-persistent

Additional rules

Block and IP Address and Reject

iptables -A INPUT -s 192.168.1.10 -j REJECT

Specifying Multiple Ports with multiport

iptables -A INPUT -i eth0 -p tcp -m state --state NEW -m multiport --dports ssh,smtp,http,https -j ACCEPT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment