Iptables firewall memo

Iptables firewall memo

This article explains how to configure some basic iptables firewall rules in order to permit or deny traffic to your server.

Listing currently active rules

Run the iptables command with the -L option to list currently active rules. The -n options converts domain names to numeric IP addresses. In this example there are no active rules.

Command:

iptables -nL

Output:

Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

Allowing access

Allow access from specific IP address to a specific port. Keep in mind that option -I will add a rule at the top of the list and the option -A will add the rule at the end of the list in your iptables firewall rule-set. Where option -p is for protocol, option -s is for the source IP address, option –dport is for the destination port on your server, option -j is for the action performed.

iptables -I INPUT -p tcp -s 192.168.0.1 –dport 22 -j ACCEPT

Allow access from all IP addresses in a specific IP range to a specific port.

iptables -I INPUT -p tcp -s 192.168.0.0/16 –dport 22 -j ACCEPT

Allow access from all IP addresses to a specific port.

iptables -I INPUT -p tcp -s 0.0.0.0/0 –dport 22 -j ACCEPT

Allow access from a specific IP addresses to any port.

iptables -I INPUT -s 192.168.0.1 -j ACCEPT

Allow access from all IP addresses to any port.

iptables -I INPUT -p tcp -s 0.0.0.0/0 -j ACCEPT

Denying access

Blocking access to your server works in a very similar fashion. Use the option -j DROP instead of -j ACCEPT and incoming traffic will be blocked. If you use the option -j REJECT the connection will also be blocked, however, an error message will be displayed.

iptables -A INPUT -s 192.168.0.1 -j DROP

iptables -A INPUT -s 192.168.0.1 -j REJECT

iptables -I INPUT -p tcp -s 192.168.0.1 –dport 22 -j DROP

Removing iptables firewall rules

If you made a mistake or just need to remove a certain rule or two. First, use the following command to list INPUT, OUTPUT or FORWARD rules.

iptables -nL INPUT –line-numbers

Output:

Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT all — 0.0.0.0/0 0.0.0.0/0
2 DROP udp — 0.0.0.0/0 0.0.0.0/0

Then, use the following command in order to delete a rule by the rule number. Let’s remove INPUT rule number 2.

iptables -D INPUT 2

NOTE: Keep in mind that iptables utility is a very powerful tool, which offers much more options than just these basic examples.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.