Persistent iptables Rules
Install iptables on Debian if Needed
apt-get install iptables
Clear Existing Rules
iptables -F;iptables -X;iptables -Z
Open Ports
Allow the local loopback interface (that is, allow the local machine to access itself) and allow established or related connections
iptables -A INPUT -i lo -j ACCEPT;iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Allow all outbound traffic from the local machine
iptables -A OUTPUT -j ACCEPT
Source: https://www.cnblogs.com/goldenstones/articles/8868577.html
Allow access to port 22
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Allow access to port 80
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
Allow local access to MySQL port 3306, block external access
iptables -A INPUT -p tcp -s 127.0.0.1 --dport 3306 -j ACCEPT;iptables -A INPUT -p tcp --dport 3306 -j DROP
Allow FTP ports 21 and 20
iptables -A INPUT -p tcp --dport 21 -j ACCEPT;iptables -A INPUT -p tcp --dport 20 -j ACCEPT
Allow UDP port 161 for SafeBao monitoring
iptables -I INPUT -p udp -s 60.195.252.107 --dport 161 -j ACCEPT;iptables -I INPUT -p udp -s 60.195.252.110 --dport 161 -j ACCEPT;iptables -I INPUT -p udp -s 127.0.0.1 --dport 161 -j ACCEPT;iptables -I INPUT -p udp -s 45.63.121.42 --dport 161 -j ACCEPT;iptables -I INPUT -p udp -s 192.168.1.2 --dport 161 -j ACCEPT
# If there are other ports, the same idea applies; just modify the above commands slightly
Allow ping
iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
Reject all other rules that are not explicitly allowed (note: if port 22 is not allowed, the SSH connection will be dropped immediately.)
iptables -A INPUT -j REJECT;iptables -A FORWARD -j REJECT
Block a single IP
iptables -I INPUT -s 123.45.6.7 -j DROP
Block an entire range from 123.0.0.1 to 123.255.255.254
iptables -I INPUT -s 123.0.0.0/8 -j DROP
Block an IP range from 123.45.0.1 to 123.45.255.254
iptables -I INPUT -s 124.45.0.0/16 -j DROP
Block an IP range from 123.45.6.1 to 123.45.6.254
iptables -I INPUT -s 123.45.6.0/24 -j DROP
View the current iptables rules
iptables -L -n
iptables -L -n --line-numbers
Delete rule number 3 in INPUT
iptables -D INPUT 3
Temporarily save rules
iptables-save
Persist Rules
The rules saved by the above command will be lost after a system reboot. How do you make them persistent? Keep reading.
Normally, the iptables rules we write will disappear after the system restarts. Even if you save them with iptables-save, you still need to run iptables-restore after reboot to restore the original rules.
How do you make firewall rules survive a reboot?
Use the iptables-persistent tool:
First, install it:
apt-get install iptables-persistent
Save the current iptables firewall rules
/etc/init.d/iptables-persistent save
or
netfilter-persistent save
Reload firewall rules
/etc/init.d/iptables-persistent reload
or
netfilter-persistent reload
- Notes: the saved rule files are located at:
/etc/iptables/rules.v4
/etc/iptables/rules.v6