Iptables – basic examples

Iptables – basic examples
Iptables – basic examples

iptables is a powerful tool used for configuring and managing the Linux kernel’s netfilter firewall. It allows you to set up rules for filtering network traffic. Here are some basic examples of iptables commands:

1. View Current Rules:

To view the current rules, use the following command:

sudo iptables -L

2. Allow All Outgoing Traffic, Block All Incoming Traffic:

Allow all outgoing traffic and block all incoming traffic:

sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

3. Allow SSH (Port 22) Traffic:

Allow incoming SSH traffic:

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

Allow incoming traffic that is part of an established connection or related to an established connection:

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

5. Allow Loopback Traffic:

Allow traffic on the loopback interface:

sudo iptables -A INPUT -i lo -j ACCEPT

6. Allow Specific IP Address:

Allow traffic from a specific IP address:

sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT

7. Block Specific IP Address:

Block traffic from a specific IP address:

sudo iptables -A INPUT -s 192.168.1.200 -j DROP

8. Delete a Rule:

Delete a specific rule (replace rule_number with the actual rule number):

sudo iptables -D INPUT rule_number

9. Flush Rules:

Delete all rules:

sudo iptables -F 
sudo iptables -X 
sudo iptables -Z

10. Save Rules:

Save the current rules to make them persistent across reboots:

sudo service iptables save # For older systems
sudo iptables-save > /etc/sysconfig/iptables # For newer systems

Important Notes:

  • Always be cautious when configuring iptables rules, as incorrect configurations may lead to loss of connectivity.
  • Changes made using iptables are not persistent by default. You need to save them to ensure they survive a reboot.
  • On modern Linux distributions, you might be using nftables instead of iptables. Be aware of the tool your system is using.

These are basic examples, and iptables offers a wide range of options for more advanced configurations. Be sure to refer to the official documentation and consider using more user-friendly tools like ufw for simpler rule management.

Leave a Reply

Your email address will not be published. Required fields are marked *

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