Introduction:
Iptables is a powerful tool used to manage the Linux firewall. It is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel. One of the most common use cases of iptables is to block incoming access from specific IP addresses.
--append -A Append to chain --delete -D Delete matching rule from chain --delete -D Delete rule rulenum (1 = first) from chain --insert -I Insert in chain as rulenum (default 1=first) --replace -R Replace rule rulenum (1 = first) in chain --list -L List the rules in a chain or all chains --source -s [!] address[/mask] source specification --destination -d [!] address[/mask] destination specification --jump -j target INPUT = Incoming Access OUTPUT = Outgoing Access -I = Insert -D = Delete -s = Source Ip Address -j = Target Action DROP = Block action
In this guide, we will show you how to drop or block incoming access from a specific IP address using iptables.
Step 1: Check Current Iptables Rules
Before we begin, let’s check the current iptables rules by running the following command:
sudo iptables -L
This will display the current iptables rules.
Step 2: Add a Rule to Block Incoming Access from a Specific IP Address
To block incoming access from a specific IP address, we need to add a new rule to iptables. The rule will drop all incoming traffic from the IP address.
To add the rule, run the following command:
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
In this command, we are adding a new rule to the INPUT chain to drop all traffic from IP address 192.168.1.100.
Step 3: Save the Rule
To ensure that the new rule persists after a reboot, we need to save the iptables rules.
To save the current iptables rules, run the following command:
sudo sh -c "iptables-save > /etc/iptables.rules"
This command will save the current iptables rules to the file /etc/iptables.rules.
Step 4: Load the Rule on Boot
To ensure that the new rule is loaded on boot, we need to modify the /etc/rc.local file.
Open the file in a text editor:
sudo nano /etc/rc.local
Add the following line to the file before the exit 0 line:
iptables-restore < /etc/iptables.rules
This command will load the saved iptables rules from the file /etc/iptables.rules on boot.
Step 5: Test the Rule
To test the new rule, try to access your server from the blocked IP address. You should not be able to establish a connection.
Commands Mentioned:
- iptables - tool used to manage the Linux firewall
- iptables-save - saves the current iptables rules to a file
- iptables-restore - loads the saved iptables rules from a file
Conclusion:
In this guide, we have shown you how to drop or block incoming access from a specific IP address using iptables. By adding a new rule to iptables, we can drop all traffic from the specified IP address. Remember to save the iptables rules and load them on boot to ensure that the new rule persists after a reboot.