Iptable 自定义链

表、链选择

使用 iptables 去设置防火墙时常用的采用 filter 做防火墙规则的过滤,也是 iptables 命令中默认使用的表,使用率最多。但是在云原生环境下 filter 表往往限制不了 dockerk8s 等一些规则,因为在云原生的环境下,他们会在 nat 表的 PREROUTING 链里面将流量做 FORWARD 处理。在这种情况下,往往不能控制 dockerk8s 的流量,需要对流量做其他的处理,比如采用其他的链表(nat 表的 PREROUTING 链)来做过滤规则。本文将从常用的使用场景下使用自定义链来做大部分系统的防火墙规则。

常用场景

  • 新增自定义链
# 在 filter 表中新增 mychain 链
/sbin/iptables -t filter -N mychain
  • 将自定义链插入到 INPUT 链首部
# 将 mychain 插入到 filter 表 INPUT 链的第一条
/sbin/iptables -I INPUT  -j mychain
  • 丰富自定义规则
# 新增允许源地址范围的白名单访问
/sbin/iptables -I mychain -m iprange --src-range 10.1.1.1-10.1.1.5 -m comment --comment "允许源区间白名单" -j ACCEPT

# 允许源地址访问
/sbin/iptables -I mychain -s 10.1.1.51,127.0.0.1,10.2.0.0/16 -m comment --comment "允许源白名单地址"  -j ACCEPT 

# 允许访问指定目标地址和指定端口
/sbin/iptables -I mychain -d 10.1.1.53 -p tcp -m multiport --dports 8080,8081 -m comment --comment "允许访问指定目标地址和端口" -j ACCEPT 

# 允许访问 web 端口
/sbin/iptables -I mychain -p tcp -m multiport --dports 80,443 -j ACCEPT

# 在末尾添加允许从内部访问外部
/sbin/iptables -A mychain -m state --state RELATED,ESTABLISHED -j ACCEPT

# 在末尾添加拒绝所有其他的地址
/sbin/iptables -A mychain -j DROP'

添加系统服务

在服务器重启后 iptables 规则清空,可以添加一条 systemd 一次性服务,确认开机时 iptables 生效。

vim /etc/systemd/system/iptables.service
[Unit]
Description=Mychain iptables Service
After=network.target

[Service]
# 执行一次
Type=oneshot
# 清空规则
#ExecStop=/bin/bash -c '/sbin/iptables -F mychain && /sbin/iptables -D INPUT -j mychain && /sbin/iptables -X mychain'
ExecStart=/bin/bash -c '/sbin/iptables -t filter -N mychain \
  && /sbin/iptables -I INPUT  -j mychain \
  && /sbin/iptables -I mychain -m iprange --src-range 10.1.1.1-10.1.1.5 -m comment --comment "允许源区间白名单" -j ACCEPT \
  && /sbin/iptables -I mychain -s 10.1.1.51,127.0.0.1,10.2.0.0/16 -m comment --comment "允许源白名单地址"  -j ACCEPT  \
  && /sbin/iptables -I mychain -d 10.1.1.53 -p tcp -m multiport --dports 8080,8081 -m comment --comment "允许访问指定目标地址和端口" -j ACCEPT \
  && /sbin/iptables -I mychain -p tcp -m multiport --dports 80,443 -j ACCEPT \
  && /sbin/iptables -A mychain -m state --state RELATED,ESTABLISHED -j ACCEPT\
  && /sbin/iptables -A mychain -j DROP'
[Install]
WantedBy=default.target
Infee Fang
Infee Fang
互联网二手搬砖工