From 10a620a2d9e756d4a3ec96a53cac3257a6efcc44 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 15 Nov 2026 22:12:16 +0000 Subject: [PATCH 1/2] feat(ufw): let ufw_rules entries delete a rule An entry with delete: true (a boolean) removes the rule it describes, passed to community.general.ufw's delete option. It lets a consumer replace a base rule, such as an open SSH allow by narrower ones, which the role could only add before. - rules.yml applies the delete entries after every other rule, whatever their place in the list, so the replacement exists before the old rule goes. - validate.yml: the schema check requires a boolean; a new check refuses a rule the list both adds and deletes (compared without the comment, port as a string), because the delete would win while the lock-out guard counted the add; the lock-out guard no longer counts a delete entry. - service_rules keeps its own key list and does not accept delete. Molecule: prepare stores a commented 9091 rule that the base list deletes with an uncommented entry listed first; verify checks it is gone and the untagged count is unchanged; the idempotence pass covers deleting a rule that is gone. Two new refusals: an SSH rule that is only deleted (lock-out guard) and a rule both added and deleted. Verified locally: validate.yml against localhost in check mode (the planned replacement list passes; the conflict, the delete-only SSH list and a non-boolean delete are refused) and the apply order. Not verified locally: the molecule scenario (CI only), including whether ufw matches the commented rule from an uncommented delete. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- changelogs/fragments/ufw-rule-delete.yml | 7 ++++ roles/ufw/README.md | 7 ++-- roles/ufw/meta/argument_specs.yml | 7 +++- roles/ufw/molecule/default/converge.yml | 42 ++++++++++++++++++++++++ roles/ufw/molecule/default/prepare.yml | 9 +++++ roles/ufw/molecule/default/verify.yml | 10 +++++- roles/ufw/tasks/rules.yml | 7 +++- roles/ufw/tasks/validate.yml | 33 +++++++++++++++++-- 8 files changed, 114 insertions(+), 8 deletions(-) create mode 100644 changelogs/fragments/ufw-rule-delete.yml diff --git a/changelogs/fragments/ufw-rule-delete.yml b/changelogs/fragments/ufw-rule-delete.yml new file mode 100644 index 0000000..bbcf989 --- /dev/null +++ b/changelogs/fragments/ufw-rule-delete.yml @@ -0,0 +1,7 @@ +--- +minor_changes: + - >- + ufw - ``ufw_rules`` entries accept ``delete`` (a boolean). An entry with ``delete: true`` removes the rule it describes, + so a base rule can be replaced, for example an open SSH rule by narrower ones. Deletes are applied after every other + rule of the list, a delete entry never satisfies the SSH lock-out guard, and a rule that the list both adds and deletes + fails the play. ``service_rules`` does not accept the key. diff --git a/roles/ufw/README.md b/roles/ufw/README.md index f395785..e6275d3 100644 --- a/roles/ufw/README.md +++ b/roles/ufw/README.md @@ -27,7 +27,7 @@ Main entry point: | `ufw_logging` | `"on"` | no | UFW logging level. | | `ufw_require_ssh_allow` | `true` | no | Enable the SSH lock-out guard. | | `ufw_ssh_port` | `ansible_port` or 22 | no | TCP port the guard looks for. | -| `ufw_rules` | `[]` | no | Base rule list: `rule` (allow, deny, reject, limit), `port`, `proto`, `from`, `to`, `interface`, `direction`, `comment`. | +| `ufw_rules` | `[]` | no | Base rule list: `rule` (allow, deny, reject, limit), `port`, `proto`, `from`, `to`, `interface`, `direction`, `comment`, `delete` (see Notes). | | `ufw_before_rules` | `[]` | no | Entries added as ACCEPT lines to `before.rules`: `interface`, `proto`, `port`, `from`, `comment`. | | `ufw_sysctl_overrides` | `[]` | no | `{name, value}` pairs written to `/etc/ufw/sysctl.conf`. | @@ -59,7 +59,7 @@ A service role that owns firewall rules calls the role with `include_role` and ` | Variable | Default | Required | Description | |---|---|---|---| | `ufw_service_name` | none | yes | Owner of the rules, `^[a-z0-9_]+$`. `base` is reserved. | -| `ufw_service_rules` | none | yes for `present` | List of rule mappings with the keys `ufw_rules` accepts (other keys are refused; `interface` needs `direction`). An empty list makes every rule of the owner stale, and is refused together with `ufw_purge_stale: true`. | +| `ufw_service_rules` | none | yes for `present` | List of rule mappings with the keys `ufw_rules` accepts except `delete` (other keys are refused; `interface` needs `direction`). An empty list makes every rule of the owner stale, and is refused together with `ufw_purge_stale: true`. | | `ufw_service_state` | `present` | no | `present` or `absent`. | | `ufw_purge_stale` | `false` | no | For `present` only. `false`: report stale rules. `true`: delete them. `absent` always deletes. | @@ -126,7 +126,8 @@ An **orphan** is a rule tagged `ansible-ufw[:]` whose owner is neith ## Notes -- Lock-out guard: `defaults.yml` sets the deny policy before `rules.yml` adds any rule. When `ufw_enabled`, `ufw_manage_rules` and `ufw_require_ssh_allow` are true and the incoming default is deny or reject, the play fails unless `ufw_rules` holds an allow or limit rule for `ufw_ssh_port` that is TCP (or has no `proto`) and has `direction: in` or no `direction`. `direction: incoming`, which the module accepts, is not counted, so write `in`. Any `from`, `to` or `interface` restriction still counts; the guard cannot know the control host's address. +- Lock-out guard: `defaults.yml` sets the deny policy before `rules.yml` adds any rule. When `ufw_enabled`, `ufw_manage_rules` and `ufw_require_ssh_allow` are true and the incoming default is deny or reject, the play fails unless `ufw_rules` holds an allow or limit rule for `ufw_ssh_port` that is TCP (or has no `proto`) and has `direction: in` or no `direction`. `direction: incoming`, which the module accepts, is not counted, so write `in`. Any `from`, `to` or `interface` restriction still counts; the guard cannot know the control host's address. An entry with `delete: true` never counts. +- Replacing a base rule: list the new rule and the old one with `delete: true` (a boolean). Deletes are applied after every other rule, whatever their place in the list, so the replacement exists before the old rule goes, which matters when narrowing the SSH rule. The comment is not needed to match the rule being deleted, and a delete of a rule that is already gone changes nothing. An entry that deletes a rule the same list adds (same `rule`, `port`, `proto`, `from`, `to`, `interface` and `direction`) fails the play. `delete` is for `ufw_rules` only; `service_rules` removes its own stale rules. - `before.rules` is a template derived from UFW's own `before.rules` (GPL-3.0-only, see `NOTICE`) that fully replaces the stock file, including a loopback accept, conntrack (established accept and INVALID-state drop), ICMP and mDNS/UPnP entries. It is deployed whenever `ufw_enabled` is true, even with no before-rules. - Rule schema is asserted before anything changes: `rule` must be allow, deny, reject or limit, `port` a positive integer, `proto` tcp or udp, and each rule needs `port`, `from`, `to` or `interface`. - UFW is only re-enabled when `ufw status verbose` shows it inactive or the logging line differs, because the module rewrites rules and re-applies sysctl on every call. diff --git a/roles/ufw/meta/argument_specs.yml b/roles/ufw/meta/argument_specs.yml index 2907143..283e029 100644 --- a/roles/ufw/meta/argument_specs.yml +++ b/roles/ufw/meta/argument_specs.yml @@ -64,8 +64,13 @@ argument_specs: - Base list of rules, the only list the main entry applies. The role default is an empty list. - >- Each item is a mapping with C(rule) (allow, deny, reject or limit) and at least one of C(port), C(from), C(to) - or C(interface). Optional keys are C(proto) (tcp or udp), C(direction) and C(comment). + or C(interface). Optional keys are C(proto) (tcp or udp), C(direction), C(comment) and C(delete). - C(port) must be a positive integer value. + - >- + C(delete=true) (a boolean) removes the rule the other keys describe instead of adding it. The comment is not + needed to match. Deletes are applied after every other rule of the list, so a replacement exists before the old + rule goes; a rule that is both added and deleted in the list fails the play, and a delete entry never counts as + the SSH allow rule of the lock-out guard. ufw_before_rules: type: raw description: diff --git a/roles/ufw/molecule/default/converge.yml b/roles/ufw/molecule/default/converge.yml index e9b4946..f376b2e 100644 --- a/roles/ufw/molecule/default/converge.yml +++ b/roles/ufw/molecule/default/converge.yml @@ -22,6 +22,45 @@ that: "'would lock this host out' in ansible_failed_result.msg | default('')" quiet: true + # A delete entry removes the SSH rule it names, so it must not satisfy the guard. + - name: Run the role with an SSH rule that is only deleted + block: + - name: Include ufw + ansible.builtin.include_role: + name: mortis.kamino.ufw + vars: + ufw_rules: + - {rule: allow, port: 8080, proto: tcp} + - {rule: allow, port: 22, proto: tcp, delete: true} + - name: Unreachable when the guard ignores delete entries + ansible.builtin.fail: + msg: ufw counted a deleted SSH rule as the SSH allow rule + rescue: + - name: The guard stopped the play + ansible.builtin.assert: + that: "'would lock this host out' in ansible_failed_result.msg | default('')" + quiet: true + + # The same rule added and deleted: the delete would win (deletes run last) while the + # guard counted the add. The comment and the port's type do not make them different. + - name: Run the role with a rule that is both added and deleted + block: + - name: Include ufw + ansible.builtin.include_role: + name: mortis.kamino.ufw + vars: + ufw_rules: + - {rule: allow, port: "22", proto: tcp, comment: ssh} + - {rule: allow, port: 22, proto: tcp, delete: true} + - name: Unreachable when the conflict check works + ansible.builtin.fail: + msg: ufw accepted a rule that is both added and deleted + rescue: + - name: The conflict check stopped the play + ansible.builtin.assert: + that: "'both added and deleted' in ansible_failed_result.msg | default('')" + quiet: true + # Stray variable guard: variables named like _ufw_rules must fail the play # before anything changes, naming the variable. The vars sit on the include only, so they # do not reach the plays below (the base ufw_rules and ufw_before_rules never match). @@ -79,6 +118,9 @@ - role: mortis.kamino.ufw vars: ufw_rules: + # Listed first on purpose: deletes run after every other rule. The second run + # deletes a rule that is gone, which must not report a change. + - {rule: allow, port: 9091, proto: tcp, delete: true} - {rule: allow, port: 22, proto: tcp, comment: ssh} - {rule: allow, port: 8080, proto: tcp, from: 10.0.0.0/8, comment: web} - {rule: allow, port: 53, proto: udp, comment: dns} diff --git a/roles/ufw/molecule/default/prepare.yml b/roles/ufw/molecule/default/prepare.yml index 18a10a1..1e3ac0b 100644 --- a/roles/ufw/molecule/default/prepare.yml +++ b/roles/ufw/molecule/default/prepare.yml @@ -30,6 +30,15 @@ proto: tcp comment: manual + # converge.yml replaces this one through a delete entry of the base list that has no + # comment, so the delete must match the rule without it. + - name: Store a manual rule that the base list deletes + community.general.ufw: + rule: allow + port: "9091" + proto: tcp + comment: replaced + # Owners svc_c, svc_d and svc_e keep rules in converge.yml that these entries are # not part of: a stale rule to purge, a rule of a removed service, a stale rule # that is only reported. diff --git a/roles/ufw/molecule/default/verify.yml b/roles/ufw/molecule/default/verify.yml index eda9934..936ccd3 100644 --- a/roles/ufw/molecule/default/verify.yml +++ b/roles/ufw/molecule/default/verify.yml @@ -31,7 +31,8 @@ changed_when: false environment: {LC_ALL: C} - # The four base rules plus the manual rule from prepare.yml. The refused runs + # The four base rules plus the manual 7777 rule from prepare.yml (the base list deleted + # its 9091 rule). The refused runs # (guard, invalid service inputs) added none. - name: Exactly the five untagged rules exist ansible.builtin.assert: @@ -48,6 +49,13 @@ - ufw_verify_ufw.stdout is not search('7999') quiet: true + - name: The rule marked delete in the base list is gone + ansible.builtin.assert: + that: + - ufw_verify_added.stdout_lines | select('search', '9091') | list | length == 0 + - ufw_verify_ufw.stdout is not search('9091') + quiet: true + - name: The manual rule and the SSH rule were not touched ansible.builtin.assert: that: diff --git a/roles/ufw/tasks/rules.yml b/roles/ufw/tasks/rules.yml index c00e59d..806d5d9 100644 --- a/roles/ufw/tasks/rules.yml +++ b/roles/ufw/tasks/rules.yml @@ -1,4 +1,6 @@ --- +# Rules marked delete: true are applied after every other rule, whatever their place in +# the list, so a replacement rule exists before the rule it replaces is removed. - name: Apply UFW rules become: true community.general.ufw: @@ -10,9 +12,12 @@ interface: "{{ ufw_rule.interface | default(omit) }}" direction: "{{ ufw_rule.direction | default(omit) }}" comment: "{{ ufw_rule.comment | default(omit) }}" - loop: "{{ ufw_aggregated_rules | default([]) }}" + delete: "{{ ufw_rule.delete | default(omit) }}" + loop: "{{ (ufw_aggregated_rules | default([]) | reject('in', ufw_rules_deleted) | list) + ufw_rules_deleted }}" loop_control: loop_var: ufw_rule + vars: + ufw_rules_deleted: "{{ ufw_aggregated_rules | default([]) | selectattr('delete', 'defined') | selectattr('delete') | list }}" when: - ufw_enabled - ufw_manage_rules diff --git a/roles/ufw/tasks/validate.yml b/roles/ufw/tasks/validate.yml index 92bddc1..d5353d4 100644 --- a/roles/ufw/tasks/validate.yml +++ b/roles/ufw/tasks/validate.yml @@ -7,6 +7,7 @@ - ufw_rule.port is not defined or ufw_rule.port | int > 0 - ufw_rule.proto is not defined or ufw_rule.proto in ['tcp', 'udp'] - ufw_rule.port is defined or ufw_rule.from is defined or ufw_rule.to is defined or ufw_rule.interface is defined + - ufw_rule.delete is not defined or ufw_rule.delete is boolean fail_msg: "Invalid UFW rule: {{ ufw_rule }}" loop: "{{ ufw_aggregated_rules | default([]) }}" loop_control: @@ -15,6 +16,32 @@ - ufw_manage_rules - ufw_aggregated_rules | length > 0 +# A rule both added and deleted would be added, then deleted (deletes run last), and the +# lock-out guard below would still count the added one. The comment is not part of a +# rule's identity, as in ufw itself; the port is compared as a string. +- name: Refuse a rule that ufw_rules both adds and deletes + ansible.builtin.assert: + that: ufw_rules_conflicting | length == 0 + fail_msg: >- + These UFW rules are both added and deleted in the same rule list (rule|port|proto|from|to|interface|direction): + {{ ufw_rules_conflicting }}. Remove one of the two entries. + vars: + ufw_rules_conflicting: >- + {%- set ns = namespace(added=[], deleted=[]) -%} + {%- for r in ufw_aggregated_rules | default([]) -%} + {%- set spec = [r.rule | default(''), r.port | default('') | string, r.proto | default(''), r.from | default(''), + r.to | default(''), r.interface | default(''), r.direction | default('')] | join('|') -%} + {%- if r.delete | default(false) -%} + {%- set ns.deleted = ns.deleted + [spec] -%} + {%- else -%} + {%- set ns.added = ns.added + [spec] -%} + {%- endif -%} + {%- endfor -%} + {{ ns.deleted | select('in', ns.added) | unique | join(', ') }} + when: + - ufw_manage_rules + - ufw_aggregated_rules | length > 0 + - name: Validate ufw before.rules schema ansible.builtin.assert: that: @@ -33,7 +60,8 @@ # not care which variable a rule came from. A missing proto means both protocols # and a missing direction means incoming, as in ufw itself. Any `from`, `to` or # `interface` restriction still counts: the guard catches a forgotten rule, it -# cannot know which source address the control host connects from. +# cannot know which source address the control host connects from. A rule marked +# delete: true removes a rule, so it never counts. - name: Require an SSH allow rule when incoming traffic is denied by default ansible.builtin.assert: that: ufw_ssh_rule_count | int > 0 @@ -48,7 +76,8 @@ {%- if r.rule | default('') in ['allow', 'limit'] and r.port | default('') | string == ufw_ssh_port | string and r.proto | default('tcp') == 'tcp' - and r.direction | default('in') == 'in' -%} + and r.direction | default('in') == 'in' + and not r.delete | default(false) -%} {%- set ns.n = ns.n + 1 -%} {%- endif -%} {%- endfor -%} -- 2.43.0 From 43bb2ce8dc776389e5fdc2a54fcf10d2b9c22806 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 15 Nov 2026 22:24:55 +0000 Subject: [PATCH 2/2] fix(ufw): normalise the conflict check and send deletes without a comment Review findings on the delete support: - The both-added-and-deleted check compared the written fields, so direction: in or from: any on the added rule hid a conflict that ufw sees (it stores no direction as in and no address as any); the delete then removed the SSH rule the lock-out guard had counted. Fields are now normalised as ufw stores them (incoming/outgoing as in/out too). A missing proto stays distinct from tcp, as in ufw. - A delete sent with a comment that differs from the stored one matches nothing in ufw and exits 0, so the rule stayed silently. Deletes are now sent without their comment; ufw then matches the rule whatever its comment. The scenario's delete entry carries a different comment to cover it, and the conflict refusal uses the explicit defaults. - README: a delete without an address removes the IPv4 and IPv6 rules, an IPv4 from allows IPv4 only. - verify searches 9091/tcp, not a bare 9091 that an owner tag could hold. Verified locally in check mode against localhost: both bypass lists and an incoming/outgoing spelling are refused; the planned replacement list and a no-proto add with a tcp delete pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- roles/ufw/README.md | 2 +- roles/ufw/meta/argument_specs.yml | 4 ++-- roles/ufw/molecule/default/converge.yml | 8 +++++--- roles/ufw/molecule/default/verify.yml | 4 ++-- roles/ufw/tasks/rules.yml | 6 ++++-- roles/ufw/tasks/validate.yml | 12 ++++++++---- 6 files changed, 22 insertions(+), 14 deletions(-) diff --git a/roles/ufw/README.md b/roles/ufw/README.md index e6275d3..f5a3516 100644 --- a/roles/ufw/README.md +++ b/roles/ufw/README.md @@ -127,7 +127,7 @@ An **orphan** is a rule tagged `ansible-ufw[:]` whose owner is neith ## Notes - Lock-out guard: `defaults.yml` sets the deny policy before `rules.yml` adds any rule. When `ufw_enabled`, `ufw_manage_rules` and `ufw_require_ssh_allow` are true and the incoming default is deny or reject, the play fails unless `ufw_rules` holds an allow or limit rule for `ufw_ssh_port` that is TCP (or has no `proto`) and has `direction: in` or no `direction`. `direction: incoming`, which the module accepts, is not counted, so write `in`. Any `from`, `to` or `interface` restriction still counts; the guard cannot know the control host's address. An entry with `delete: true` never counts. -- Replacing a base rule: list the new rule and the old one with `delete: true` (a boolean). Deletes are applied after every other rule, whatever their place in the list, so the replacement exists before the old rule goes, which matters when narrowing the SSH rule. The comment is not needed to match the rule being deleted, and a delete of a rule that is already gone changes nothing. An entry that deletes a rule the same list adds (same `rule`, `port`, `proto`, `from`, `to`, `interface` and `direction`) fails the play. `delete` is for `ufw_rules` only; `service_rules` removes its own stale rules. +- Replacing a base rule: list the new rule and the old one with `delete: true` (a boolean). Deletes are applied after every other rule, whatever their place in the list, so the replacement exists before the old rule goes, which matters when narrowing the SSH rule. The comment of a delete entry is not sent, so the rule matches whatever its comment, and a delete of a rule that is already gone changes nothing. An entry that deletes a rule the same list adds (same `rule`, `port`, `proto`, `from`, `to`, `interface` and `direction`, where no `direction` is `in` and no `from` or `to` is `any`) fails the play. A delete without an address removes the IPv4 and the IPv6 rule; a replacement with an IPv4 `from` allows IPv4 only, so check that the hosts you connect from are covered before narrowing SSH. `delete` is for `ufw_rules` only; `service_rules` removes its own stale rules. - `before.rules` is a template derived from UFW's own `before.rules` (GPL-3.0-only, see `NOTICE`) that fully replaces the stock file, including a loopback accept, conntrack (established accept and INVALID-state drop), ICMP and mDNS/UPnP entries. It is deployed whenever `ufw_enabled` is true, even with no before-rules. - Rule schema is asserted before anything changes: `rule` must be allow, deny, reject or limit, `port` a positive integer, `proto` tcp or udp, and each rule needs `port`, `from`, `to` or `interface`. - UFW is only re-enabled when `ufw status verbose` shows it inactive or the logging line differs, because the module rewrites rules and re-applies sysctl on every call. diff --git a/roles/ufw/meta/argument_specs.yml b/roles/ufw/meta/argument_specs.yml index 283e029..09541f9 100644 --- a/roles/ufw/meta/argument_specs.yml +++ b/roles/ufw/meta/argument_specs.yml @@ -67,8 +67,8 @@ argument_specs: or C(interface). Optional keys are C(proto) (tcp or udp), C(direction), C(comment) and C(delete). - C(port) must be a positive integer value. - >- - C(delete=true) (a boolean) removes the rule the other keys describe instead of adding it. The comment is not - needed to match. Deletes are applied after every other rule of the list, so a replacement exists before the old + C(delete=true) (a boolean) removes the rule the other keys describe instead of adding it. Its comment is not + sent, so the rule matches whatever its comment. Deletes are applied after every other rule of the list, so a replacement exists before the old rule goes; a rule that is both added and deleted in the list fails the play, and a delete entry never counts as the SSH allow rule of the lock-out guard. ufw_before_rules: diff --git a/roles/ufw/molecule/default/converge.yml b/roles/ufw/molecule/default/converge.yml index f376b2e..7daa115 100644 --- a/roles/ufw/molecule/default/converge.yml +++ b/roles/ufw/molecule/default/converge.yml @@ -42,7 +42,8 @@ quiet: true # The same rule added and deleted: the delete would win (deletes run last) while the - # guard counted the add. The comment and the port's type do not make them different. + # guard counted the add. The comment, the port's type and the written default + # direction and source do not make them different. - name: Run the role with a rule that is both added and deleted block: - name: Include ufw @@ -50,7 +51,7 @@ name: mortis.kamino.ufw vars: ufw_rules: - - {rule: allow, port: "22", proto: tcp, comment: ssh} + - {rule: allow, port: "22", proto: tcp, direction: in, from: any, comment: ssh} - {rule: allow, port: 22, proto: tcp, delete: true} - name: Unreachable when the conflict check works ansible.builtin.fail: @@ -120,7 +121,8 @@ ufw_rules: # Listed first on purpose: deletes run after every other rule. The second run # deletes a rule that is gone, which must not report a change. - - {rule: allow, port: 9091, proto: tcp, delete: true} + # The comment differs from the stored one and is not sent, so it still matches. + - {rule: allow, port: 9091, proto: tcp, comment: other, delete: true} - {rule: allow, port: 22, proto: tcp, comment: ssh} - {rule: allow, port: 8080, proto: tcp, from: 10.0.0.0/8, comment: web} - {rule: allow, port: 53, proto: udp, comment: dns} diff --git a/roles/ufw/molecule/default/verify.yml b/roles/ufw/molecule/default/verify.yml index 936ccd3..fbaf7bf 100644 --- a/roles/ufw/molecule/default/verify.yml +++ b/roles/ufw/molecule/default/verify.yml @@ -52,8 +52,8 @@ - name: The rule marked delete in the base list is gone ansible.builtin.assert: that: - - ufw_verify_added.stdout_lines | select('search', '9091') | list | length == 0 - - ufw_verify_ufw.stdout is not search('9091') + - ufw_verify_added.stdout_lines | select('search', '9091/tcp') | list | length == 0 + - ufw_verify_ufw.stdout is not search('9091/tcp') quiet: true - name: The manual rule and the SSH rule were not touched diff --git a/roles/ufw/tasks/rules.yml b/roles/ufw/tasks/rules.yml index 806d5d9..61b1007 100644 --- a/roles/ufw/tasks/rules.yml +++ b/roles/ufw/tasks/rules.yml @@ -1,6 +1,8 @@ --- # Rules marked delete: true are applied after every other rule, whatever their place in -# the list, so a replacement rule exists before the rule it replaces is removed. +# the list, so a replacement rule exists before the rule it replaces is removed. A delete +# is sent without its comment: ufw matches a delete that has no comment against the rule +# whatever its comment, but one with a different comment matches nothing and does nothing. - name: Apply UFW rules become: true community.general.ufw: @@ -11,7 +13,7 @@ to: "{{ ufw_rule.to | default(omit) }}" interface: "{{ ufw_rule.interface | default(omit) }}" direction: "{{ ufw_rule.direction | default(omit) }}" - comment: "{{ ufw_rule.comment | default(omit) }}" + comment: "{{ omit if ufw_rule.delete | default(false) else ufw_rule.comment | default(omit) }}" delete: "{{ ufw_rule.delete | default(omit) }}" loop: "{{ (ufw_aggregated_rules | default([]) | reject('in', ufw_rules_deleted) | list) + ufw_rules_deleted }}" loop_control: diff --git a/roles/ufw/tasks/validate.yml b/roles/ufw/tasks/validate.yml index d5353d4..dc31ed4 100644 --- a/roles/ufw/tasks/validate.yml +++ b/roles/ufw/tasks/validate.yml @@ -17,8 +17,10 @@ - ufw_aggregated_rules | length > 0 # A rule both added and deleted would be added, then deleted (deletes run last), and the -# lock-out guard below would still count the added one. The comment is not part of a -# rule's identity, as in ufw itself; the port is compared as a string. +# lock-out guard below would still count the added one. Fields are normalised the way ufw +# stores them before comparing: no direction is in (incoming/outgoing are in/out), no from +# or to is any, the port is a string. The comment is not part of a rule's identity. A +# missing proto stays distinct from tcp, as ufw keeps the two as different rules. - name: Refuse a rule that ufw_rules both adds and deletes ansible.builtin.assert: that: ufw_rules_conflicting | length == 0 @@ -29,8 +31,10 @@ ufw_rules_conflicting: >- {%- set ns = namespace(added=[], deleted=[]) -%} {%- for r in ufw_aggregated_rules | default([]) -%} - {%- set spec = [r.rule | default(''), r.port | default('') | string, r.proto | default(''), r.from | default(''), - r.to | default(''), r.interface | default(''), r.direction | default('')] | join('|') -%} + {%- set dir = r.direction | default('in', true) | string | lower -%} + {%- set spec = [r.rule | default(''), r.port | default('') | string, r.proto | default(''), + r.from | default('any', true), r.to | default('any', true), r.interface | default(''), + {'incoming': 'in', 'outgoing': 'out'}.get(dir, dir)] | join('|') -%} {%- if r.delete | default(false) -%} {%- set ns.deleted = ns.deleted + [spec] -%} {%- else -%} -- 2.43.0