feat(ufw): add the ufw role
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Failing after 25s
Molecule / molecule (pull_request) Failing after 5m42s

Copied from the environment repository's local role. The files are
identical except: galaxy namespace mortis; comments, argument_specs
descriptions and the README scrubbed of environment references (issue
numbers, CI runs, playbooks, inventory paths and groups, scripts and
caller roles by name), with the technical explanation kept and reworded
generically; the stray-variable guard's fail message drops its issue
reference; the molecule scenario calls the role by its FQCN
(mortis.kamino.ufw), follows the Kamino scenario conventions
(kamino-molecule header, scenario.test_sequence) and no longer sets
ANSIBLE_COLLECTIONS_PATH or ANSIBLE_ROLES_PATH. No variable, default,
argument_specs type or task logic changed; the test coverage is the same.

The README follows the other Kamino roles: purpose, the main,
service_rules and orphan_rules entry points, variables, and example
plays with the FQCN and tasks_from. The meta licence stays
GPL-3.0-or-later AND GPL-3.0-only (templates/before.rules.j2 is derived
from ufw's own file, already annotated in REUSE.toml and NOTICE).
galaxy.yml's dependency comment names ufw as a community.general user.

Not verified locally: the molecule scenario (it runs on the
kamino-molecule runner in CI) and ansible-test sanity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
This commit is contained in:
Defame1297andClaude Opus 5.5 committed 2026-11-14 16:43:29 +00:00
1 parent 7fa6c6754d
commit e18db424ec
25 files changed
+2271 -1

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
---
# Build the lists the later tasks read: ufw_aggregated_rules from the base
# ufw_rules and ufw_aggregated_before_rules from the base ufw_before_rules.
#
# Rules of service roles are NOT collected here. Variables named *_ufw_rules
# or *_ufw_before_rules are not discovered and fail the guard in main.yml: a service role passes
# its rules explicitly through tasks_from: service_rules. No role contributes
# before-rules, so they stay a base-only list.
#
# The lists are still rebuilt (not appended) on every invocation, because
# set_fact persists for the rest of the play and the role can run more than
# once per host in a play.
- name: Set the rules to apply from the base ufw_rules
ansible.builtin.set_fact:
ufw_aggregated_rules: "{{ ufw_rules | default([]) }}"
when: ufw_manage_rules
- name: Set the before.rules entries from the base ufw_before_rules
ansible.builtin.set_fact:
ufw_aggregated_before_rules: "{{ ufw_before_rules | default([]) }}"
when: ufw_enabled
+16
View File
@@ -0,0 +1,16 @@
---
- name: Install UFW before.rules
become: true
ansible.builtin.template:
src: before.rules.j2
dest: /etc/ufw/before.rules
owner: root
group: root
mode: "0644"
notify: Reload UFW
when: ufw_enabled
# Not gated on ufw_aggregated_before_rules being non-empty: this template
# fully replaces the stock before.rules (unlike rules.yml, which only adds
# to it), and its unconditional loopback-ACCEPT block must always be
# deployed whenever UFW is enabled, even on hosts with no ufw_before_rules
# entries of their own.
+21
View File
@@ -0,0 +1,21 @@
---
- name: Set default incoming policy
become: true
community.general.ufw:
direction: incoming
policy: "{{ ufw_defaults.incoming }}"
when: ufw_enabled
- name: Set default outgoing policy
become: true
community.general.ufw:
direction: outgoing
policy: "{{ ufw_defaults.outgoing }}"
when: ufw_enabled
- name: Set default routed policy
become: true
community.general.ufw:
direction: routed
policy: "{{ ufw_defaults.routed }}"
when: ufw_enabled
+31
View File
@@ -0,0 +1,31 @@
---
# community.general.ufw runs `ufw -f enable` and `ufw logging` unconditionally
# (rewriting /etc/ufw/user.rules and re-applying sysctl.conf), so only call it
# when UFW is inactive or its logging setting differs from ufw_logging.
- name: Read current UFW status
become: true
ansible.builtin.command: ufw status verbose
register: ufw_status_verbose
changed_when: false
check_mode: false
environment:
LC_ALL: C
LANGUAGE: C
when: ufw_enabled
- name: Enable UFW
become: true
community.general.ufw:
state: enabled
logging: "{{ ufw_logging }}"
vars:
# "on" matches any level ("Logging: on (low)"); "off" and levels match exactly.
ufw_logging_expected: >-
{{ 'Logging: off' if ufw_logging == 'off'
else 'Logging: on' if ufw_logging == 'on'
else 'Logging: on (' ~ ufw_logging ~ ')' }}
when:
- ufw_enabled
- >-
'Status: active' not in ufw_status_verbose.stdout
or ufw_logging_expected not in ufw_status_verbose.stdout
+6
View File
@@ -0,0 +1,6 @@
---
- name: Install ufw
become: true
ansible.builtin.package:
name: "{{ ufw_package_name }}"
state: present
+52
View File
@@ -0,0 +1,52 @@
---
# Stray variable guard: the role does not discover rules by variable name, so a variable
# named like <role>_ufw_rules / <role>_ufw_before_rules would be silently ignored. Fail instead,
# naming it. The base lists ufw_rules and ufw_before_rules have no prefix before "_ufw_" and do not
# match; the producers' <role>_ufw_service_rules do not either. varnames covers every variable
# visible to the host (inventory, play, role and extra vars), unlike the deprecated vars dictionary.
- name: Refuse stray *_ufw_rules and *_ufw_before_rules variables
ansible.builtin.assert:
that: ufw_stray_rule_variables | length == 0
fail_msg: >-
ufw does not read variables named like *_ufw_rules or *_ufw_before_rules, so they would
be ignored: {{ ufw_stray_rule_variables | join(', ') }}. Pass the rules of a service through
the ufw role's tasks_from: service_rules entry point (ufw_service_name and ufw_service_rules),
or move base rules into ufw_rules. Delete or rename the leftover definition in group_vars,
host_vars or the play.
quiet: true
vars:
ufw_stray_rule_variables: >-
{{ lookup('ansible.builtin.varnames', '^.+_ufw_(before_)?rules$', wantlist=True) | sort }}
tags: [ufw, always]
- name: Import UFW install task
ansible.builtin.import_tasks: install.yml
tags: [ufw, ufw_install]
- name: Import UFW sysctl task
ansible.builtin.import_tasks: sysctl.yml
tags: [ufw, ufw_sysctl]
- name: Import UFW aggregate task
ansible.builtin.import_tasks: aggregate_rules.yml
tags: [ufw, ufw_aggregate]
- name: Import UFW validate task
ansible.builtin.import_tasks: validate.yml
tags: [ufw, ufw_validate]
- name: Import UFW before rules task
ansible.builtin.import_tasks: before_rules.yml
tags: [ufw, ufw_before_rules]
- name: Import UFW defaults task
ansible.builtin.import_tasks: defaults.yml
tags: [ufw, ufw_defaults]
- name: Import UFW rules task
ansible.builtin.import_tasks: rules.yml
tags: [ufw, ufw_rules]
- name: Import UFW enable task
ansible.builtin.import_tasks: enable.yml
tags: [ufw, ufw_enable]
+255
View File
@@ -0,0 +1,255 @@
---
# Entry point that finds the rules of owners nobody manages any more: a tagged rule
# (`<prefix>[<owner>:<key>]: <text>`, 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
+18
View File
@@ -0,0 +1,18 @@
---
- name: Apply UFW rules
become: true
community.general.ufw:
rule: "{{ ufw_rule.rule }}"
port: "{{ ufw_rule.port | default(omit) }}"
proto: "{{ ufw_rule.proto | default(omit) }}"
from: "{{ ufw_rule.from | default(omit) }}"
to: "{{ ufw_rule.to | default(omit) }}"
interface: "{{ ufw_rule.interface | default(omit) }}"
direction: "{{ ufw_rule.direction | default(omit) }}"
comment: "{{ ufw_rule.comment | default(omit) }}"
loop: "{{ ufw_aggregated_rules | default([]) }}"
loop_control:
loop_var: ufw_rule
when:
- ufw_enabled
- ufw_manage_rules
+396
View File
@@ -0,0 +1,396 @@
---
# 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 `<prefix>[<owner>:<key>]: <text>`, <key> 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
+37
View File
@@ -0,0 +1,37 @@
---
- name: Check whether ufw sysctl.conf exists
become: true
ansible.builtin.stat:
path: /etc/ufw/sysctl.conf
register: ufw_sysctl_stat
check_mode: false
when: ufw_enabled and ufw_sysctl_overrides | length > 0
# 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, the same probe as tasks/service_rules.yml.
- name: Probe whether the run is in check mode
ansible.builtin.command: "true"
register: ufw_sysctl_probe
changed_when: false
when: ufw_enabled and ufw_sysctl_overrides | length > 0
- name: Remember whether the run is in check mode
ansible.builtin.set_fact:
ufw_sysctl_check: "{{ ufw_sysctl_probe is skipped }}"
when: ufw_enabled and ufw_sysctl_overrides | length > 0
# In check mode on a fresh host ufw is not installed yet, so the file is absent.
- name: Set sysctl overrides in ufw sysctl.conf
become: true
ansible.builtin.lineinfile:
path: /etc/ufw/sysctl.conf
regexp: '^#?\s*{{ ufw_sysctl_override.name }}='
line: "{{ ufw_sysctl_override.name }}={{ ufw_sysctl_override.value }}"
owner: root
group: root
mode: "0644"
loop: "{{ ufw_sysctl_overrides }}"
loop_control:
loop_var: ufw_sysctl_override
when: ufw_enabled and (ufw_sysctl_stat.stat.exists or not ufw_sysctl_check)
+60
View File
@@ -0,0 +1,60 @@
---
- name: Validate ufw_rules schema
ansible.builtin.assert:
that:
- ufw_rule.rule is defined
- ufw_rule.rule in ['allow', 'deny', 'reject', 'limit']
- 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
fail_msg: "Invalid UFW rule: {{ ufw_rule }}"
loop: "{{ ufw_aggregated_rules | default([]) }}"
loop_control:
loop_var: ufw_rule
when:
- ufw_manage_rules
- ufw_aggregated_rules | length > 0
- name: Validate ufw before.rules schema
ansible.builtin.assert:
that:
- ufw_before_rule.port is not defined or ufw_before_rule.port | int > 0
- ufw_before_rule.proto is not defined or ufw_before_rule.proto in ['tcp', 'udp']
- ufw_before_rule.interface is not defined or ufw_before_rule.interface | length > 0
- ufw_before_rule.port is defined or ufw_before_rule.from is defined or ufw_before_rule.to is defined or ufw_before_rule.interface is defined
fail_msg: "Invalid UFW before-rule: {{ ufw_before_rule }}"
loop: "{{ ufw_aggregated_before_rules | default([]) }}"
loop_control:
loop_var: ufw_before_rule
when: ufw_aggregated_before_rules | length > 0
# defaults.yml sets the deny policy before rules.yml adds any rule, so a missing
# SSH rule would lock the host out mid-play. Checks the merged list only; it does
# 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.
- name: Require an SSH allow rule when incoming traffic is denied by default
ansible.builtin.assert:
that: ufw_ssh_rule_count | int > 0
fail_msg: >-
No allow/limit rule for TCP port {{ ufw_ssh_port }} (SSH) in the UFW rules, and the
incoming default is {{ ufw_defaults.incoming }}: enabling it would lock this host out.
Add the rule, or set ufw_require_ssh_allow: false if SSH is reached another way.
vars:
ufw_ssh_rule_count: >-
{%- set ns = namespace(n=0) -%}
{%- for r in ufw_aggregated_rules | default([]) -%}
{%- 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' -%}
{%- set ns.n = ns.n + 1 -%}
{%- endif -%}
{%- endfor -%}
{{ ns.n }}
when:
- ufw_enabled
- ufw_manage_rules
- ufw_require_ssh_allow
- ufw_defaults.incoming in ['deny', 'reject']