暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

ipset 封端口

生有可恋 2023-04-17
1509

通常我们使用 iptables 的 --dport 规则实现封服务器端口,当端口数量很多时需要写多条策略。而使用 ipset 的 bitmap:port 端口组可以合并策略,减少 iptables 的策略数。

常规的 iptables 封端口命令为:

    $ iptables -I INPUT -p tcp --dport 8080 -j ACCEPT

    如果换成 ipset 的端口组,则命令为:

      $ ipset create p bitmap:port range 1-65535
      $ iptables -I INPUT -p tcp -m set --match-set p dst -j DROP

      其中 p 是端口组的名称,可以随意起名字。后续添加或删除端口不用再动 iptables 策略,只用操作 ipset 即可。

      添加端口组对象:

        $ ipset add p 111
        $ ipset add p 6000
        $ ipset add p 53
        ...

        查看端口组对象:

          $ ipset list p
          Name: p
          Type: bitmap:port
          Revision: 3
          Header: range 1-65535
          Size in memory: 8296
          References: 1
          Number of entries: 10
          Members:
          25
          53
          111
          631
          6000
          8005
          8009
          8100
          8101
          51377

          删除其中的一个端口:

            $ ipset del p 51377

            当有大量端口需要封堵时,可以通过 ipset 创建端口组,对端口组进行封堵即可。通过 ipset 改造后的 iptables 规则列表会非常精简,同时维护 iptables 规则也会非常简单,只用操作 ipset 端口组即可让规则生效。

            ipset 配置可以通过文件来保存,执行 save 命令可以导出配置文件

              $ ipset save -f ipset.latest
              $ cat ipset.latest
              create p bitmap:port range 1-65535
              add p 25
              add p 53
              add p 111
              add p 631
              add p 6000
              add p 8005
              add p 8009
              add p 8100
              add p 8101
              add p 51377

              当需要恢复 ipset 配置时可以重新执行配置文件中的命令,或者使用 restore 命令:

                $ ipset restore -f ipset.latest
                ipset v6.38: Error in line 1: Set cannot be created: set with the same name already exists
                $ ipset destroy p
                ipset v6.38: Set cannot be destroyed: it is in use by a kernel component

                当 ipset 对象存在时,restore 会失败。当 ipset 对象被引用时,destroy 命令也会失败。如果需要销毁一个 ipset 对象,需要先在 iptables 中解除引用。

                ipset 相当于 iptables 功能上的一个增强,有了 ipset,iptables 才支持对象组的概念。

                参考:

                  https://www.cnblogs.com/faberbeta/p/ipset.html
                  https://ipset.netfilter.org/ipset.man.html
                  https://www.cnblogs.com/gentlemanhai/p/12845273.html
                  https://www.spinics.net/lists/netfilter/msg59012.html
                  https://unix.stackexchange.com/questions/200518/how-to-match-properly-against-an-ip-set-of-type-haship-port
                  https://www.cnblogs.com/vijayfly/p/7205559.html

                  全文完。

                  如果转发本文,文末务必注明:“转自微信公众号:生有可恋”。

                  文章转载自生有可恋,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                  评论