首页 文章

使用SaltStack进行IPtables管理

提问于
浏览
1

我正在尝试使用SaltStack配置灵活的iptables管理解决方案,但我觉得它比我想象的要难 .

我的主要要求是:能够拥有一个支柱,我可以保留一份IP列表,这些IP列表应该列入所有小兵的SSH访问权限 . 这个IP列表当然会不时地改变:一些IP被添加,一些IP被删除 . 我面临的问题是删除了IP - 当我从支柱文件中删除它们时,SaltStack不会删除来自minions的实际白名单 .

我能找到的唯一解决方法是创建一个名为“removed-ips”的新密钥,每当我想删除一个IP时,我会在那里添加它 . 第二个for循环将删除它 . 当然,这是一个非常讨厌的解决方法,有没有更好的方法呢?

/srv/pillar/iptables-default.sls:

iptables-default:
  whitelisted-ips:
    - '55.55.55.55'
    - '66.66.66.66'
    - '77.77.77.77'
  removed-ips:
    - '88.88.88.88'

/srv/salt/iptables-default.sls:

{% for ip in salt['pillar.get']('iptables-default:whitelisted-ips') %}
Whitelist OSF IP {{ip}} for SSH access:
  iptables.append:
    - table: filter
    - family: ipv4
    - chain: INPUT
    - jump: ACCEPT
    - match: state
    - connstate: NEW
    - source: '{{ ip }}'
    - dport: 22
    - proto: tcp
    - save: True
{% endfor %}

{% for ip in salt['pillar.get']('iptables-default:removed-ips') %}
Remove old IPs that are not needed anymore:
  iptables.delete:
    - table: filter
    - family: ipv4
    - chain: INPUT
    - jump: ACCEPT
    - match: state
    - connstate: NEW
    - source: {{ ip }}
    - dport: 22
    - proto: tcp
    - save: True
{% endfor %}

2 回答

  • 1

    而不是使用salt的iptables状态,我喜欢管理/etc/iptables/rules.v4和v6,如下所示:

    firewall-ipv4:
      pkg.installed:
        - pkgs:
          - iptables
          - iptables-persistent
      file.managed:
        - name: /etc/iptables/rules.v4
        - source: salt://firewall/files/rules.jinja
        - template: jinja
        - context:
            slspath: {{ slspath }}
            family: ipv4
      cmd.wait:
        - name: iptables-restore rules.v4
        - cwd: /etc/iptables
        - order: last
        - watch: 
          - file: firewall-ipv4
    
    {{ similar for v6... }}
    

    其中rules.jinja从支柱生成规则集 . 这种方法的好处是,当删除支柱规则时,它可以做正确的事情,而不需要在每个高位状态上进行刷新(即更改) . 缺点是它不会注意到并从本地计算机恢复对防火墙的手动更改 .

    我有一个使用技术here的公式 . 忽略关于兼容性问题的自述文件,它适用于当前的盐 . 或者我上次检查过 .

  • 1

    在根据支柱数据附加规则之前刷新所有规则 . 因此,在添加规则的所有其他状态中添加刷新并要求此状态的状态 - 这可确保在添加规则之前刷新运行一次 .

    untested example

    flush_all_rules:
      iptables.flush:
        - table: filter
        - family: ipv4
    
    {% for ip in salt['pillar.get']('iptables-default:whitelisted-ips') %}
    Whitelist OSF IP {{ip}} for SSH access:
      iptables.append:
        - table: filter
        - family: ipv4
        # [...]
        - require:
          - iptables: flush_all_rules
    {% endfor %}
    

相关问题