--- # Entry point that finds the rules of owners nobody manages any more: a tagged rule # (`[:]: `, see service_rules.yml) whose owner is neither in # ufw_managed_owners nor in ufw_reserved_owners is an orphan. A service role that was # removed from a host leaves its rules behind, and service_rules never # runs for it again, so nothing else would clean them up. Called with # `include_role: name=mortis.kamino.ufw tasks_from=orphan_rules` after every service role ran. # # Fail closed: without ufw_managed_owners (undefined or empty) this entry point does # nothing at all, not even a report, because an empty list would make every owner an # orphan. Orphans are reported; they are deleted only with ufw_purge_orphans true, never # in check mode. Untagged rules (base, SSH, manual) and reserved owners are never touched. An # orphan line is deleted only when it is an explicit single numeric port other than # ufw_ssh_port; any other line may open SSH (no port, a range or list, ssh or openssh, a line # the SSH regex matches) and is reported as kept. A line with unexpected characters is kept too. # # The show-added parse, the SSH regex, the line-safety assertion, the delete and the verify # step are a copy of service_rules.yml: keep them in step (a shared include is a follow-up). # The caller must pass owner names equal to the ufw_service_name of the roles it keeps. # # The tags of an include_role caller do NOT reach these tasks: the caller needs # `apply: {tags: [...]}` on its include_role. - name: Skip the orphan rules when rule management is off ansible.builtin.debug: msg: "ufw_enabled or ufw_manage_rules is false: orphaned rules are not looked at" when: not (ufw_enabled and ufw_manage_rules) tags: [ufw, ufw_orphan_rules] - name: Skip the orphan rules when the managed owners are not known ansible.builtin.debug: msg: >- ufw_managed_owners is undefined or empty: orphaned rules are not looked at (an unknown list would make every owner an orphan) when: - ufw_enabled - ufw_manage_rules - ufw_managed_owners is not defined or ufw_managed_owners | length == 0 tags: [ufw, ufw_orphan_rules] - name: Report and purge the rules of owners that are no longer managed when: - ufw_enabled - ufw_manage_rules - ufw_managed_owners is defined and ufw_managed_owners | length > 0 tags: [ufw, ufw_orphan_rules] block: - name: Validate ufw_purge_orphans ansible.builtin.assert: that: ufw_purge_orphans | string | lower in ['true', 'false', 'yes', 'no', '1', '0'] fail_msg: ufw_purge_orphans must be a boolean. quiet: true - name: Validate the managed owners ansible.builtin.assert: that: - ufw_managed_owners is sequence - ufw_managed_owners is not string - ufw_managed_owners is not mapping - ufw_managed_owners | select('string') | list | length == ufw_managed_owners | length - ufw_managed_owners | map('string') | reject('match', '^[a-z0-9_]+\Z') | list | length == 0 fail_msg: >- ufw_managed_owners must be a list of strings matching ^[a-z0-9_]+$ (the owner names in the rule tags): {{ ufw_managed_owners }} quiet: true # ansible_check_mode is not used: the play-level `check_mode: true` keyword does not set # that magic variable inside include_role tasks (only --check does). A command task is # skipped in both forms and its result says so, which is the one signal that holds for both. - name: Probe whether the run is in check mode ansible.builtin.command: "true" register: ufw_oa_probe changed_when: false - name: Remember whether the run is in check mode ansible.builtin.set_fact: ufw_oa_check: "{{ ufw_oa_probe is skipped }}" - name: Read the firewall status become: true ansible.builtin.command: ufw status verbose register: ufw_oa_status changed_when: false failed_when: false check_mode: false environment: LC_ALL: C LANGUAGE: C - name: Skip the orphan rules when ufw is not active ansible.builtin.debug: msg: "ufw is not installed or not active: orphaned rules are not looked at" when: "ufw_oa_status.rc != 0 or 'Status: active' not in ufw_oa_status.stdout" - name: Reconcile the orphaned rules when: - ufw_oa_status.rc == 0 - "'Status: active' in ufw_oa_status.stdout" block: - name: Read the rules ufw has stored become: true ansible.builtin.command: ufw show added register: ufw_oa_added changed_when: false check_mode: false environment: LC_ALL: C LANGUAGE: C # Same SSH regex as service_rules.yml: it marks lines that are never deleted. - name: Index the stored rules ansible.builtin.set_fact: ufw_oa_purge: "{{ ufw_purge_orphans | bool }}" ufw_oa_known: "{{ ufw_managed_owners + ufw_reserved_owners }}" ufw_oa_ssh_regex: >- ^ufw (?:allow|limit)\b(?!(?:(?! comment ').)*(?: out |/udp|proto udp))(?:(?! comment ').)*[ ,:]{{ ufw_ssh_port }}(?:[ ,:/]|$) ufw_oa_tagged_json: >- {%- set ns = namespace(out=[]) -%} {%- for l in ufw_oa_added.stdout_lines | select('match', '^ufw ') -%} {%- set m = l | regex_findall(ufw_tag_regex) -%} {%- if m | length > 0 -%} {%- set ns.out = ns.out + [{'line': l, 'owner': m[0][0], 'key': m[0][1]}] -%} {%- endif -%} {%- endfor -%} {{ ns.out | to_json }} - name: Parse the tagged rules ansible.builtin.set_fact: ufw_oa_tagged: "{{ ufw_oa_tagged_json if ufw_oa_tagged_json is not string else ufw_oa_tagged_json | from_json }}" - name: Work out the orphaned rules ansible.builtin.set_fact: ufw_oa_orphans: "{{ ufw_oa_tagged | rejectattr('owner', 'in', ufw_oa_known) | list }}" ufw_oa_ssh_before: "{{ ufw_oa_added.stdout_lines | select('match', '^ufw ') | select('search', ufw_oa_ssh_regex) | list }}" # Fail safe. unsafe: characters outside printable ASCII or braces (never put into a # command or a message). ssh: may carry SSH (see the header). delete: the rest. The # same rule as the stale purge in service_rules.yml: keep them in step. - name: Classify the orphaned rules ansible.builtin.set_fact: ufw_oa_classified_json: >- {%- set ns = namespace(out=[]) -%} {%- for o in ufw_oa_orphans -%} {%- set body = o.line | regex_replace(" comment '.*$", '') -%} {%- set ports = body | regex_findall(ufw_port_token_regex) -%} {%- if o.line is not match('^ufw [ -~]*\Z') or '{' in o.line or '}' in o.line -%} {%- set cls = 'unsafe' -%} {%- elif o.line in ufw_oa_ssh_before or body | lower is search('ssh') or ports | length != 1 or ports[0] is not match('^[0-9]+$') or ports[0] == ufw_ssh_port | string -%} {%- set cls = 'ssh' -%} {%- else -%} {%- set cls = 'delete' -%} {%- endif -%} {%- set ns.out = ns.out + [{'owner': o.owner, 'key': o.key, 'line': o.line, 'class': cls}] -%} {%- endfor -%} {{ ns.out | to_json }} - name: Parse the classified rules ansible.builtin.set_fact: ufw_oa_classified: "{{ ufw_oa_classified_json if ufw_oa_classified_json is not string else ufw_oa_classified_json | from_json }}" - name: List the orphaned rules by class ansible.builtin.set_fact: ufw_oa_deletable: "{{ ufw_oa_classified | selectattr('class', 'eq', 'delete') | list }}" ufw_oa_kept_ssh: "{{ ufw_oa_classified | selectattr('class', 'eq', 'ssh') | list }}" ufw_oa_unsafe: "{{ ufw_oa_classified | selectattr('class', 'eq', 'unsafe') | list }}" - name: Report the orphaned rules that can be deleted ansible.builtin.debug: msg: - >- {{ ufw_oa_deletable | length }} orphaned rule(s) of owners that are not managed, {{ 'deleted' if ufw_oa_purge | bool and not ufw_oa_check else 'would be deleted (ufw_purge_orphans is false, or check mode)' }}: - "{{ ufw_oa_deletable | map(attribute='line') | list }}" when: ufw_oa_deletable | length > 0 - name: Report the orphaned rules kept as possible SSH paths ansible.builtin.debug: msg: - >- {{ ufw_oa_kept_ssh | length }} orphaned rule(s) kept, never deleted by this entry point (possible SSH path: no single numeric port, a range or list, the SSH port, or ssh/openssh): - "{{ ufw_oa_kept_ssh | map(attribute='line') | list }}" when: ufw_oa_kept_ssh | length > 0 - name: Report the orphaned rules kept as unparseable or unsafe ansible.builtin.debug: msg: >- {{ ufw_oa_unsafe | length }} orphaned rule(s) kept, unparseable or unsafe (lines not shown): {{ ufw_oa_unsafe | map(attribute='owner') | zip(ufw_oa_unsafe | map(attribute='key')) | map('join', ':') | list }} when: ufw_oa_unsafe | length > 0 # Defence in depth: the classification already excludes these lines. - name: Refuse deletable lines that cannot be deleted safely ansible.builtin.assert: that: - ufw_oa_item.line is match('^ufw [ -~]*\Z') - "'{' not in ufw_oa_item.line" - "'}' not in ufw_oa_item.line" fail_msg: "Refusing to delete the orphaned rule line, it holds unexpected characters: {{ ufw_oa_item.owner }}:{{ ufw_oa_item.key }}" quiet: true loop: "{{ ufw_oa_deletable }}" loop_control: loop_var: ufw_oa_item label: "{{ ufw_oa_item.key }}" when: ufw_oa_purge | bool # The delete argument is the line ufw printed minus the leading `ufw `, never a # rule number: the comment then matches the stored one and the v4 and v6 rules go # together. - name: Delete the orphaned rules become: true ansible.builtin.command: "ufw --force delete {{ ufw_oa_item.line | regex_replace('^ufw ', '') }}" loop: "{{ ufw_oa_deletable }}" loop_control: loop_var: ufw_oa_item label: "{{ ufw_oa_item.line }}" changed_when: true environment: LC_ALL: C LANGUAGE: C when: - ufw_oa_purge | bool - not ufw_oa_check - name: Read the rules ufw has stored after the changes become: true ansible.builtin.command: ufw show added register: ufw_oa_after changed_when: false check_mode: false environment: LC_ALL: C LANGUAGE: C when: - ufw_oa_purge | bool - not ufw_oa_check # Exactly the deleted lines are gone, every other line is as before (as a multiset) # and the SSH-like lines are unchanged. - name: Verify the outcome ansible.builtin.assert: that: - ufw_oa_after_lines | length == ufw_oa_before_lines | length - ufw_oa_deletable | length - ufw_oa_after_lines | sort == ufw_oa_before_lines | reject('in', ufw_oa_deletable | map(attribute='line') | list) | list | sort - ufw_oa_after_lines | select('search', ufw_oa_ssh_regex) | list | sort == ufw_oa_ssh_before | sort fail_msg: >- After the purge exactly the deletable orphaned rules should be gone and every other rule (the SSH rule included) must be unchanged. Rules now: {{ ufw_oa_after_lines }} quiet: true vars: ufw_oa_before_lines: "{{ ufw_oa_added.stdout_lines | select('match', '^ufw ') | list }}" ufw_oa_after_lines: "{{ ufw_oa_after.stdout_lines | select('match', '^ufw ') | list }}" when: - ufw_oa_purge | bool - not ufw_oa_check