4

基于注释的 iptables 规则控制

 3 years ago
source link: https://ralf.ren/comment-based-iptables-control/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

利用注释控制 iptables 规则,可以使得管理 iptables 规则变得非常简单高效。通过检索 iptables 规则内的注释内容,可以方便地列出与移除一组 iptables 规则。

何谓“利用注释控制 iptables”

iptables 提供了注释功能,可以在添加规则的同时对添加的规则进行注释。如图,列出的 iptables 规则中,在 /* */ 中的即为注释。

iptables-rules-1024x348.pngiptables 规则示例

通过检索 iptables 规则中的注释,可以实现以下的功能:

  • 列出所有的注释
  • 对于给定的注释内容,列出所有匹配的规则
  • 对于给定的注释内容,删除所有匹配的规则

下面针对各个功能分别进行说明:

注释的添加

注释的添加通过 -m comment --comment [注释内容] 来完成。以下是一条示例语句:

iptables -I INPUT -p tcp --dport 443 -j REJECT -m comment --comment reject-https

上面的语句创建了一条拒绝 HTTPS 传入连接的 iptables 规则,并注释为 reject-https

注释的内容不建议使用空格。因为 bash 使用空格来分隔命令与参数。

列出所有注释

iptables-save | grep -oP "(?<=--comment\ ).*?(?=\ -)" | sort | uniq

上面的命令会列出所有的注释,以上图之内容举例,会输出:

catboy-web
noobamici

以下的命令也会输出相同的内容,但是因为速度太慢,因此不推荐:

iptables -L | grep -oP "(?<=/*\ ).*?(?=\ */)" | sort | uniq

列出所有匹配注释内容的规则

iptables-save | grep $comment

其中,$comment 是注释内容。以上图为例,有如下输出:

# iptables-save | grep catboy-web
-A INPUT -s 1.2.3.4/32 -p tcp -m tcp --dport 443 -m comment --comment catboy-web -j ACCEPT
-A INPUT -s 1.2.3.4/32 -p tcp -m tcp --dport 80 -m comment --comment catboy-web -j ACCEPT

删除所有匹配注释内容的规则

iptables-save | grep -v $comment | iptables-restore

其中,$comment 是注释内容。若 $commentcatboy-web,则该命令会删除所有匹配 catboy-web 注释的规则。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK