iptables
is a powerful firewall tool that can help secure your Linux server by filtering incoming and outgoing traffic based on specific rules.
Listing Rules
The first thing you should do when working with iptables is to list the existing rules. You can use the following command to display the current iptables configuration:
sudo iptables -L
This command will show you the rules for each table and chain.
Adding Rules
The next step is to add rules to iptables. To do this, you need to specify the table, chain, and rule action. The following example shows how to add a rule to the INPUT chain of the filter table to allow incoming traffic on port 80 (HTTP):
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
This command adds a rule to the end of the INPUT chain (-A
), specifying that the protocol is TCP (-p tcp
), the destination port is 80 (--dport 80
), and the action is to accept the traffic (-j ACCEPT
).
Deleting Rules
To delete a rule, you need to specify the table, chain, and rule number. To obtain the rule number, run:
sudo iptables -L --line-number
You can see the rules you have added, e.g.
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT tcp -- anywhere anywhere tcp dpt:http
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
The following example shows how to delete the first rule (num
of 1) in the INPUT chain of the filter table:
sudo iptables -D INPUT 1
This command deletes the first rule (-D INPUT 1
) in the INPUT chain of the filter table.