How can I programmatically manage iptables rules on the fly?

后端 未结 9 1275
盖世英雄少女心
盖世英雄少女心 2020-11-29 00:20

I need to query existing rules, as well as being able to easily add and delete rules. I haven\'t found any API\'s for doing this. Is there something that I\'m missing?

9条回答
  •  日久生厌
    2020-11-29 00:49

    Using iptables-save and iptables-restore to query and regenerate rules is easily the most efficient way of doing it. These used to, once, be shell scripts, but now they are C programs that work very efficiently.

    However, I should point out that there is a tool that you can use which will make maintaining iptables much easier. Most dynamic rulesets are really the same rule repeated many times, such as:

    iptables -A INPUT -s 1.1.1.1 -p tcp -m --dport 22 -j ACCEPT
    iptables -A INPUT -s 2.2.2.0/24 -p tcp -m --dport 22 -j ACCEPT
    iptables -A INPUT -p tcp -m tcp --dport 22 -j REJECT
    

    Instead of replacing those rules every time you want to change what ports can access port 22 (useful for say, port knocking), you can use ipsets. Viz:

    ipset -N ssh_allowed nethash
    iptables -A ssh_allowed -m set --set ssh_allowed src -p tcp -m --dport 22 -j ACCEPT
    ipset -A ssh_allowed 1.1.1.1
    ipset -A ssh_allowed 2.2.2.0/24
    

    Sets can hold ip addresses, networks, ports, mac addresses, and have timeouts on their records. (Ever wanted to add something for just an hour?).

    There is even an atomic way of swapping one set with another, so a refresh means creating a new temporary set, then swapping it in as the name of the existing set.

提交回复
热议问题