--- # Entry point for a service role that owns firewall rules. Called with # `include_role: name=mortis.kamino.ufw tasks_from=service_rules` and explicit vars. The base # play (main.yml) must have run first: this entry point neither installs ufw nor # touches default policies, before.rules or the base rule list. # # Every rule gets the comment `[:]: `, being a # hash of the rule's spec. Rules of this owner whose key is no longer desired # are stale: they are reported, and deleted with ufw_purge_stale (state present) # or always (state absent, an explicit removal request). Rules without a tag # (base, SSH, manual) are never considered. # # The tasks sit in blocks that carry the tags [ufw, ufw_service_rules], so # `--tags ufw` and `--tags ufw_service_rules` include every task. The tags of an # include_role caller do NOT reach these tasks: the caller needs # `apply: {tags: [...]}` on its include_role for that. - name: Validate the service rule inputs tags: [ufw, ufw_service_rules] block: - name: Validate the owner name ansible.builtin.assert: that: - ufw_service_name is string - ufw_service_name is match('^[a-z0-9_]+$') fail_msg: ufw_service_name must be a string matching ^[a-z0-9_]+$. quiet: true - name: Refuse a reserved owner name ansible.builtin.assert: that: ufw_service_name not in ufw_reserved_owners fail_msg: >- ufw_service_name {{ ufw_service_name }} is reserved for the base play (reserved: {{ ufw_reserved_owners | join(', ') }}). quiet: true - name: Validate the state ansible.builtin.assert: that: - ufw_service_state in ['present', 'absent'] - ufw_purge_stale | string | lower in ['true', 'false', 'yes', 'no', '1', '0'] fail_msg: ufw_service_state must be present or absent and ufw_purge_stale a boolean. quiet: true - name: Require the rule list when the owner keeps rules ansible.builtin.assert: that: - ufw_service_state == 'absent' or ufw_service_rules is defined - ufw_service_rules | default([]) is sequence - ufw_service_rules | default([]) is not string - ufw_service_rules | default([]) is not mapping fail_msg: >- ufw_service_rules must be passed as a list when ufw_service_state is present. An empty list is allowed and makes every rule of the owner stale. quiet: true - name: Refuse to purge everything from an empty rule list ansible.builtin.assert: that: ufw_service_state == 'absent' or not (ufw_purge_stale | bool) or ufw_service_rules | length > 0 fail_msg: >- ufw_service_rules is empty with ufw_purge_stale true: use ufw_service_state: absent to remove all of an owner's rules. quiet: true - name: Refuse unknown rule keys and an interface without a direction ansible.builtin.assert: that: - ufw_service_rule is mapping - ufw_service_rule.keys() | list | difference(ufw_sr_known_keys) | length == 0 - (ufw_service_rule.interface | default('', true)) == '' or (ufw_service_rule.direction | default('', true)) != '' fail_msg: >- Rule {{ ufw_service_rule }} of {{ ufw_service_name }} has an unknown key (allowed: {{ ufw_sr_known_keys | join(', ') }}) or sets interface without direction (the module requires direction with interface). quiet: true vars: ufw_sr_known_keys: [rule, port, proto, from, to, interface, direction, comment] loop: "{{ ufw_service_rules | default([]) }}" loop_control: loop_var: ufw_service_rule # Same checks as tasks/validate.yml applies to ufw_rules; keep them in step. - name: Validate the service rule schema ansible.builtin.assert: that: - ufw_service_rule is mapping - ufw_service_rule.rule is defined - ufw_service_rule.rule in ['allow', 'deny', 'reject', 'limit'] - ufw_service_rule.port is not defined or ufw_service_rule.port | int > 0 - ufw_service_rule.proto is not defined or ufw_service_rule.proto in ['tcp', 'udp'] - >- ufw_service_rule.port is defined or ufw_service_rule.from is defined or ufw_service_rule.to is defined or ufw_service_rule.interface is defined fail_msg: "Invalid UFW rule for {{ ufw_service_name }}: {{ ufw_service_rule }}" quiet: true loop: "{{ ufw_service_rules | default([]) }}" loop_control: loop_var: ufw_service_rule - name: Validate the rule comments ansible.builtin.assert: that: - (ufw_service_rule.comment | default('', true) | string) is match(ufw_tag_comment_regex) - (ufw_service_rule.comment | default('', true) | string) == (ufw_service_rule.comment | default('', true) | string | trim) fail_msg: >- Rule comments must be printable ASCII without a single quote or backslash and without leading or trailing whitespace (a single quote breaks the ufw module): {{ ufw_service_rule }} quiet: true loop: "{{ ufw_service_rules | default([]) }}" loop_control: loop_var: ufw_service_rule - name: Skip the service rules when rule management is off ansible.builtin.debug: msg: "ufw_enabled or ufw_manage_rules is false: no rules applied for {{ ufw_service_name }}" when: not (ufw_enabled and ufw_manage_rules) tags: [ufw, ufw_service_rules] - name: Apply, report and purge the rules of one service when: - ufw_enabled - ufw_manage_rules tags: [ufw, ufw_service_rules] block: # 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_sr_probe changed_when: false - name: Remember whether the run is in check mode ansible.builtin.set_fact: ufw_sr_check: "{{ ufw_sr_probe is skipped }}" - name: Read the firewall status become: true ansible.builtin.command: ufw status verbose register: ufw_sr_status changed_when: false failed_when: false check_mode: false environment: LC_ALL: C LANGUAGE: C # Rules can be stored while ufw is inactive, but then nothing enforces them # and the base play has not run: a caller mistake. In check mode a host the # base play has not reached yet is expected, so the rest is skipped instead. - name: Require the base play to have enabled ufw ansible.builtin.assert: that: - ufw_sr_status.rc == 0 - "'Status: active' in ufw_sr_status.stdout" fail_msg: >- ufw is not installed or not active: run the ufw role (main entry) before adding the rules of {{ ufw_service_name }}. quiet: true when: not ufw_sr_check - name: Reconcile the rules of the owner when: ufw_sr_status.rc == 0 block: # The key is the first 10 hex characters of the sha1 of the rule's spec fields in # a fixed order. A null value counts as omitted; from and to of any, Anywhere, # 0.0.0.0/0 or ::/0 are empty, a host mask (/32 on IPv4, /128 on IPv6) is dropped # (ufw stores it without), incoming is in. The list is passed through JSON so the # result is the same with or without native types. - name: Compute the desired rules ansible.builtin.set_fact: ufw_sr_desired_json: >- {%- set ns = namespace(out=[]) -%} {%- for r in (ufw_service_rules | default([])) if ufw_service_state == 'present' -%} {%- set f = r.from | default('', true) | string -%} {%- set f = '' if f in ['any', 'Anywhere', '0.0.0.0/0', '::/0'] else f -%} {%- set f = f | regex_replace('^([0-9.]+)/32$', '\\1') | regex_replace('^([0-9a-fA-F:.]*:[0-9a-fA-F:.]*)/128$', '\\1') -%} {%- set t = r.to | default('', true) | string -%} {%- set t = '' if t in ['any', 'Anywhere', '0.0.0.0/0', '::/0'] else t -%} {%- set t = t | regex_replace('^([0-9.]+)/32$', '\\1') | regex_replace('^([0-9a-fA-F:.]*:[0-9a-fA-F:.]*)/128$', '\\1') -%} {%- set d = r.direction | default('in', true) | string -%} {%- set d = 'in' if d == 'incoming' else ('out' if d == 'outgoing' else d) -%} {%- set canon = [r.rule, r.port | default('', true) | string, r.proto | default('', true) | string, f, t, r.interface | default('', true) | string, d] | join('|') -%} {%- set key = (canon | hash('sha1'))[:10] -%} {%- set text = r.comment | default('', true) | string -%} {%- set tag = ufw_tag_prefix ~ '[' ~ ufw_service_name ~ ':' ~ key ~ ']:' -%} {%- set ns.out = ns.out + [{'key': key, 'comment': tag ~ (' ' ~ text if text else ''), 'spec': r}] -%} {%- endfor -%} {{ ns.out | to_json }} - name: Parse the desired rules ansible.builtin.set_fact: ufw_sr_desired: "{{ ufw_sr_desired_json if ufw_sr_desired_json is not string else ufw_sr_desired_json | from_json }}" - name: List the desired keys ansible.builtin.set_fact: ufw_sr_desired_keys: "{{ ufw_sr_desired | map(attribute='key') | list }}" - name: Refuse rules the owner lists twice ansible.builtin.assert: that: ufw_sr_desired_keys | length == ufw_sr_desired_keys | unique | length fail_msg: >- ufw_service_rules of {{ ufw_service_name }} lists the same rule twice (same rule, port, proto, from, to, interface and direction). quiet: true # The base SSH rule is untagged. A service rule of the same spec would retag it # (ufw merges identical rules) and a later purge could delete it. - name: Refuse rules that would retag the SSH rule ansible.builtin.assert: that: >- not (ufw_sr_item.spec.rule in ['allow', 'limit'] and ufw_sr_item.spec.port | default('', true) | string == ufw_ssh_port | string and ufw_sr_item.spec.proto | default('tcp', true) == 'tcp' and ufw_sr_item.spec.direction | default('in', true) in ['in', 'incoming']) fail_msg: >- The rule {{ ufw_sr_item.spec }} of {{ ufw_service_name }} allows the SSH port {{ ufw_ssh_port }}: the SSH rule belongs to the base play and is never tagged or purged by a service. quiet: true loop: "{{ ufw_sr_desired }}" loop_control: loop_var: ufw_sr_item # `show added` works while ufw is inactive, keeps comments and lists rules in # insertion order. No rule syntax is parsed: a line is matched on its tag only. - name: Read the rules ufw has stored become: true ansible.builtin.command: ufw show added register: ufw_sr_added changed_when: false check_mode: false environment: LC_ALL: C LANGUAGE: C # Any allow/limit line naming the SSH port as a whole token, TCP or without # proto, not outgoing. Deliberately wide: it only decides what is never deleted. # Nothing from the first ` comment '` on is looked at (tempered dots), so a # comment that mentions the port does not count. - name: Index the stored rules ansible.builtin.set_fact: ufw_sr_purge: "{{ ufw_service_state == 'absent' or (ufw_purge_stale | bool) }}" ufw_sr_ssh_regex: >- ^ufw (?:allow|limit)\b(?!(?:(?! comment ').)*(?: out |/udp|proto udp))(?:(?! comment ').)*[ ,:]{{ ufw_ssh_port }}(?:[ ,:/]|$) ufw_sr_tagged_json: >- {%- set ns = namespace(out=[]) -%} {%- for l in ufw_sr_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_sr_tagged: "{{ ufw_sr_tagged_json if ufw_sr_tagged_json is not string else ufw_sr_tagged_json | from_json }}" # Stale: tagged with this owner, key not desired. Foreign: a desired key held # by another owner, which would swap the tag on every run. - name: Work out the stale and the colliding rules ansible.builtin.set_fact: ufw_sr_foreign: "{{ ufw_sr_tagged | rejectattr('owner', 'eq', ufw_service_name) | selectattr('key', 'in', ufw_sr_desired_keys) | list }}" ufw_sr_stale: "{{ ufw_sr_tagged | selectattr('owner', 'eq', ufw_service_name) | rejectattr('key', 'in', ufw_sr_desired_keys) | list }}" ufw_sr_ssh_before: "{{ ufw_sr_added.stdout_lines | select('match', '^ufw ') | select('search', ufw_sr_ssh_regex) | list }}" # A stale line is deleted only when it is an explicit single numeric port other than # the SSH port. Kept as a possible SSH path: no port, a port range or list, the word # ssh or openssh (service name or application profile) outside the comment, or a line # the SSH regex matches. Same rule as tasks/orphan_rules.yml: keep them in step. - name: Work out the stale lines kept as possible SSH paths ansible.builtin.set_fact: ufw_sr_kept_lines_json: >- {%- set ns = namespace(out=[]) -%} {%- for o in ufw_sr_stale -%} {%- set body = o.line | regex_replace(" comment '.*$", '') -%} {%- set ports = body | regex_findall(ufw_port_token_regex) -%} {%- if o.line in ufw_sr_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 ns.out = ns.out + [o.line] -%} {%- endif -%} {%- endfor -%} {{ ns.out | to_json }} - name: Parse the kept stale lines ansible.builtin.set_fact: ufw_sr_kept_lines: "{{ ufw_sr_kept_lines_json if ufw_sr_kept_lines_json is not string else ufw_sr_kept_lines_json | from_json }}" - name: Refuse rules another owner already holds ansible.builtin.assert: that: ufw_sr_foreign | length == 0 fail_msg: >- A rule of {{ ufw_service_name }} is already owned by another tag; the same spec cannot belong to two owners: {{ ufw_sr_foreign | map(attribute='line') | list }} quiet: true # The delete command is built from lines read off the host. - name: Refuse stale lines that cannot be deleted safely ansible.builtin.assert: that: - ufw_sr_stale_item.line is match('^ufw [ -~]*\Z') - "'{' not in ufw_sr_stale_item.line" - "'}' not in ufw_sr_stale_item.line" fail_msg: "Refusing to delete the stale rule line, it holds unexpected characters: {{ ufw_sr_stale_item.line }}" quiet: true loop: "{{ ufw_sr_stale }}" loop_control: loop_var: ufw_sr_stale_item label: "{{ ufw_sr_stale_item.key }}" when: ufw_sr_purge | bool - name: Apply the rules of the owner become: true community.general.ufw: rule: "{{ ufw_sr_item.spec.rule }}" port: "{{ ufw_sr_item.spec.port | default(omit) }}" proto: "{{ ufw_sr_item.spec.proto | default(omit) }}" from: "{{ ufw_sr_item.spec.from | default(omit) }}" to: "{{ ufw_sr_item.spec.to | default(omit) }}" interface: "{{ ufw_sr_item.spec.interface | default(omit) }}" direction: "{{ ufw_sr_item.spec.direction | default(omit) }}" comment: "{{ ufw_sr_item.comment }}" loop: "{{ ufw_sr_desired }}" loop_control: loop_var: ufw_sr_item label: "{{ ufw_sr_item.comment }}" - name: Report the stale rules of the owner ansible.builtin.debug: msg: >- {{ ufw_sr_stale | length }} stale rule(s) of {{ ufw_service_name }} ({{ 'deleted' if ufw_sr_purge | bool and not ufw_sr_check else 'kept' }}): {{ ufw_sr_stale | map(attribute='line') | list }} when: ufw_sr_stale | length > 0 # Only after every apply above succeeded. 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. A line kept as a # possible SSH path (see above) is skipped. - name: Delete the stale rules of the owner become: true ansible.builtin.command: "ufw --force delete {{ ufw_sr_stale_item.line | regex_replace('^ufw ', '') }}" loop: "{{ ufw_sr_stale | rejectattr('line', 'in', ufw_sr_kept_lines) | list }}" loop_control: loop_var: ufw_sr_stale_item label: "{{ ufw_sr_stale_item.line }}" changed_when: true environment: LC_ALL: C LANGUAGE: C when: - ufw_sr_purge | bool - not ufw_sr_check - name: Read the rules ufw has stored after the changes become: true ansible.builtin.command: ufw show added register: ufw_sr_after changed_when: false check_mode: false environment: LC_ALL: C LANGUAGE: C when: not ufw_sr_check - name: Index the rules stored after the changes ansible.builtin.set_fact: ufw_sr_after_json: >- {%- set ns = namespace(out=[]) -%} {%- for l in ufw_sr_after.stdout_lines | select('match', '^ufw ') -%} {%- set m = l | regex_findall(ufw_tag_regex) -%} {%- if m | length > 0 and m[0][0] == ufw_service_name -%} {%- set ns.out = ns.out + [m[0][1]] -%} {%- endif -%} {%- endfor -%} {{ ns.out | to_json }} when: not ufw_sr_check - name: Verify the outcome ansible.builtin.assert: that: - ufw_sr_after_keys | length == ufw_sr_after_keys | unique | length - ufw_sr_desired_keys | difference(ufw_sr_after_keys) | length == 0 - not (ufw_sr_purge | bool) or ufw_sr_after_keys | difference(ufw_sr_desired_keys) | difference(ufw_sr_kept_keys) | length == 0 - ufw_sr_ssh_after | length == ufw_sr_ssh_before | length fail_msg: >- After the change {{ ufw_service_name }} should hold its desired rules {{ 'and no stale rule ' if ufw_sr_purge | bool else '' }}and the SSH rule must be unchanged. Rules now: {{ ufw_sr_after.stdout_lines | select('match', '^ufw ') | list }} quiet: true vars: ufw_sr_after_keys: "{{ ufw_sr_after_json if ufw_sr_after_json is not string else ufw_sr_after_json | from_json }}" # Stale rules kept as possible SSH paths legitimately remain. ufw_sr_kept_keys: "{{ ufw_sr_stale | selectattr('line', 'in', ufw_sr_kept_lines) | map(attribute='key') | list }}" ufw_sr_ssh_after: "{{ ufw_sr_after.stdout_lines | select('match', '^ufw ') | select('search', ufw_sr_ssh_regex) | list }}" when: not ufw_sr_check