iptables & firewalld Cheatsheet
iptables
很灵活。值得花时间把常用用法掌握学习。firewalld
是iptables
的一个上层封装。有时候不明白为什么的时候,看看iptables
的规则库,就理解了。这里把我常用的iptables
与 firewalld
命令做个汇总。
封ip
iptables -I INPUT -s 211.1.2.1 -j DROP
对应的解封
iptables -L --line-numbers
iptables -D INPUT 1
端口转发
本机端口转发
iptables -t nat -A OUTPUT -d localhost -p tcp --dport 80 -j REDIRECT --to-ports 8080
注意这样配置,在本机是不能访问80
端口的。如果要本机也能访问,要这么配(但下面配法我没实践过。不知可行否。)
iptables -t nat -A OUTPUT -d localhost -p tcp --dport 80 -j REDIRECT --to-ports 8080
firewall-cmd 端口转发
允许转发
vi /etc/sysctl.conf
net.ipv4.ip_forward=1
sysctl -w net.ipv4.ip_forward=1
firewall-cmd --query-masquerade # 检查是否允许伪装IP
firewall-cmd --add-masquerade # 允许防火墙伪装IP
firewall-cmd --remove-masquerade # 禁止防火墙伪装IP
firewall-cmd --zone=external --add-forward-port=port=1122:proto=tcp:toport=22:toaddr=172.17.1.71 --permanent
firewall-cmd --remove-forward-port=port=1122:proto=tcp:toport=22:toaddr=172.17.1.71 --zone=external
success
# 保存到permanent
firewall-cmd --runtime-to-permanent
# 从permanent中加载规则
firewall-cmd --reload
IP白名单
firewall-cmd --add-rich-rule="rule family="ipv4" source address="192.168.1.1/24" accept"
firewall-cmd --add-rich-rule="rule family="ipv4" source address="192.168.1.1/24" accept" --permanent
更复杂的firewall-cmd
firewall-cmd --direct --get-all-rules
firewall-cmd --direct --add-rule ipv4 nat OUTPUT 0 -p tcp -o lo --dport 443 -j REDIRECT --to-ports 9999