How to setup and use iptables
What’s iptables?
Iptables is the current Linux firewall and routing service. It controls incoming and outgoing network.
How to stop/start/restart iptables?
Basically just like any other Linux service:
service iptables start service iptables stop service iptables restart
How to check if iptables is currently running?
Simply call service status
service iptables status
and check the result:
Firewall is stopped.
If the status message is “Firewall is stopped.” that means that iptables are not running and you should start it with sertvice iptables start. If you get some tables with bunch of geek stuff that means that iptables are running.
How to automatically start iptables service on Linux boot?
To enable iptables starting on boot run
chkconfig iptables on
or run code below to disable it
chkconfig iptables off
How to block IP address using iptables?
This will block IP from accessing your server. Be careful not to block your IP address.
In command below replace “192.168.0.4” with correct IP address.
iptables -A INPUT -s 192.168.0.4 -j DROP
After blocking the IP address (adding it to the iptable rules) you must restart iptables calling:
service iptables restart
How to unblock IP address using iptables?
Similar to blocking, just use ACCEPT instead of DROP:
iptables -A INPUT -s 192.168.0.4 -j ACCEPT
And after allowing that IP you must also restart iptables:
service iptables restart
You can also flush your iptables rules by using:
iptables -F
This will remove all custom added rules.
How to see current rules?
Simply by running following command:
iptables -L
How to save iptable rules?
Rules created with the iptables command are stored in memory. If the system is restarted before saving the iptables rule set, all rules are lost. For rules to persist through a system reboot, they need to be saved. To save rules, type the following command:
iptables -save > /etc/iptables.rules
How to load iptable rules?
To load previously saved rules execute:
iptables --restore < /etc/iptables.rules
How to load iptable rules on Linux boot?
There are few ways and can be different on different Linux distributions. This should work on CentOS. To load rules on system boot make file /etc/init.d/iptableslr
vi /etc/init.d/iptableslr
and add these two lines to it:
#!/bin/bash /sbin/iptables-restore < /etc/iptables.rules
The file needs to be executable so change the permissions:
chmod +x /etc/init.d/iptables