Skip to content

Iptables basic commands

Basic commands

Showing current status

iptables -L -v -n

Adding rules

iptables -A chain_name -p protocol –dport port -j action

Allow tcp connection with port 22 input:

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

Disallow tcp connection with port 22 input:

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

Deleting rules

Deleting all rules
iptables -F
Deleting selected rule

Listing all rules with line numbers.

iptables -L --line-numbers

Deleting the rule of selected line.

iptables -D INPUT rule_line_number

Useful Rules

Allowing local connections.
iptables -A INPUT -i lo -j ACCEPT
Only allowing 21/22/80/443 port’s connection for web service.
iptables -A INPUT -p icmp -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 21 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
iptables -I INPUT -i lo -j ACCEPT
iptables -I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -j DROP
Only allowing 21/22/80/443 port’s connection of IPv6 for web service.
ip6tables -A INPUT -p icmpv6 -j ACCEPT
ip6tables -A INPUT -p tcp -m tcp --dport 21 -j ACCEPT
ip6tables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
ip6tables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
ip6tables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
ip6tables -I INPUT -i lo -j ACCEPT
ip6tables -I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -j DROP

Redirect port

iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-port 8080

Restoring rules when system start

Saving iptables setting to /etc/iptables.rules

Method1

Install a package to perisit iptables configuration.

apt install iptables-persistent

Then, save it.

iptables-save

Method2

iptables-save >/etc/iptables.rules
Restoring when system startup

Editing network configuration file

vim /etc/network/interfaces

Appending following codes

pre-up iptables-restore < /etc/iptables.rules
Leave a Reply