diff --git a/changelogs/fragments/ufw-role.yml b/changelogs/fragments/ufw-role.yml new file mode 100644 index 0000000..9ddb3f3 --- /dev/null +++ b/changelogs/fragments/ufw-role.yml @@ -0,0 +1,6 @@ +minor_changes: + - ufw - New role. Installs and enables UFW with default policies, base rules, ``before.rules`` and + sysctl overrides, and refuses to run when the rules would lock the host out of SSH. Besides ``main``, + the ``service_rules`` entry point applies a service role's own rules tagged with its name, and the + ``orphan_rules`` entry point reports, and optionally deletes, the tagged rules of owners that are no + longer managed. diff --git a/galaxy.yml b/galaxy.yml index 5317d67..891c5d7 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -18,7 +18,8 @@ documentation: https://git.rkdr.net/mortis/kamino/src/branch/main/README.md homepage: https://git.rkdr.net/mortis/kamino issues: https://git.rkdr.net/mortis/kamino/issues # Lower bounds are the versions CI tests against; no upper bound, so a consumer's -# newer pin does not conflict. Used by system_baseline. +# newer pin does not conflict. community.general is used by system_baseline and ufw, +# ansible.posix by system_baseline. dependencies: community.general: ">=14.0.0" ansible.posix: ">=2.2.0" diff --git a/roles/ufw/README.md b/roles/ufw/README.md new file mode 100644 index 0000000..f395785 --- /dev/null +++ b/roles/ufw/README.md @@ -0,0 +1,134 @@ +# ufw + +Installs UFW and applies sysctl overrides, `/etc/ufw/before.rules`, default policies and allow rules, then enables it, refusing to run when the rules would lock the host out of SSH. The main entry point applies `ufw_rules` only; a service role passes its own rules explicitly through the `service_rules` entry point, and `orphan_rules` cleans up the rules of services that are no longer managed. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. + +## Supported platforms + +Ubuntu 24.04 (noble), the image the molecule scenario runs on. 22.04 (jammy) is listed in `meta/main.yml` but not verified by a test. The role uses `ansible.builtin.package` and the `community.general.ufw` module; `community.general` is a dependency of the Collection. + +## Requirements and run order + +- Use it by its fully qualified name, `mortis.kamino.ufw`. +- Run the `system_baseline` role of this Collection before this role. UFW's stock `/etc/ufw/sysctl.conf` re-applies sysctl values when UFW is enabled, which undoes baseline hardening. Mirror the baseline values in `ufw_sysctl_overrides`. +- Main entry point: apply it in the play that hardens a host, after `system_baseline` and `systemd_hardening`, before `fail2ban`. +- `service_rules` entry point: called by each service role that owns firewall rules (`include_role` with `tasks_from: service_rules`), after the main entry point has run, passing `ufw_service_name` and `ufw_service_rules`. +- `orphan_rules` entry point: called once per host after every service role ran, with `ufw_managed_owners` set to the owners that are still managed. +- `ufw_rules` must contain an allow or limit rule for the SSH port (see Notes). + +## Role variables + +Main entry point: + +| Variable | Default | Required | Description | +|---|---|---|---| +| `ufw_enabled` | `true` | no | Skip all UFW configuration when false (the package is still installed). | +| `ufw_manage_rules` | `true` | no | Skip the `ufw_rules` schema check, the lock-out guard and rule application when false. Before-rules validation and `before.rules`, defaults and enable still run (gated on `ufw_enabled`). | +| `ufw_defaults` | `incoming: deny`, `outgoing: allow`, `routed: deny` | no | Default policies. All three keys are read, so override all of them. | +| `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_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`. | + +There is no discovery by variable name, and a variable that looks like one fails the play: at the start of the role, a guard refuses any variable whose name matches `^.+_ufw_(before_)?rules$` (a `foo_ufw_rules` or `foo_ufw_before_rules` defined as any variable visible to the host: inventory, play and role vars, extra vars, set_fact and registered variables) and names it in the error. Pass service rules through `tasks_from: service_rules` (`ufw_service_name`, `ufw_service_rules`; a caller's own `_ufw_service_rules` does not match), or put base rules in `ufw_rules`. The guard is unconditional, has no switch, and carries the tags `ufw` and `always`. `ufw_before_rules` is base-only: no entry point adds before-rules. + +## Tags + +`ufw` (everything), `ufw_install`, `ufw_sysctl`, `ufw_aggregate`, `ufw_validate`, `ufw_before_rules`, `ufw_defaults`, `ufw_rules`, `ufw_enable`. + +Skipping `ufw_aggregate` leaves the lists the later tasks read (`ufw_aggregated_rules`, `ufw_aggregated_before_rules`) undefined or stale, so do not select a later tag alone. + +## Example play + +```yaml +- name: Harden and firewall the servers + hosts: servers + roles: + - role: mortis.kamino.ufw + vars: + ufw_rules: + - {rule: allow, port: 22, proto: tcp, comment: ssh} + - {rule: allow, port: 8080, proto: tcp, from: 10.0.0.0/8, comment: web} +``` + +## `service_rules` entry point + +A service role that owns firewall rules calls the role with `include_role` and `tasks_from: service_rules` after the main entry has run, with `apply: {tags: [...]}` so `--tags ` reaches these tasks. The entry point installs nothing and touches no default policy, no `before.rules` and no base rule. Outside check mode (`--check` or the `check_mode` keyword; the role detects it with a skipped probe task, not `ansible_check_mode`) it fails when ufw is not installed and active. In check mode it skips the reconcile only when `ufw status` fails (ufw not installed yet, the main entry may not have reached the host); a host with ufw installed but inactive is reconciled as usual. + +| 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_state` | `present` | no | `present` or `absent`. | +| `ufw_purge_stale` | `false` | no | For `present` only. `false`: report stale rules. `true`: delete them. `absent` always deletes. | + +Tags: `ufw`, `ufw_service_rules`. They select the entry point's tasks under `--tags`; the tags of an `include_role` caller do not reach the included tasks unless the caller sets `apply: {tags: [...]}` on its `include_role`. Skipped with a debug message when `ufw_enabled` or `ufw_manage_rules` is false. + +```yaml +- name: Open the service ports + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + apply: + tags: [webapp] + vars: + ufw_service_name: webapp + ufw_purge_stale: true + ufw_service_rules: + - {rule: allow, port: 3000, proto: tcp, comment: web} +``` + +**Tag format.** Each rule is applied with the comment `ansible-ufw[:]: `. `` is the first ten hex characters of the sha1 of `rule|port|proto|from|to|interface|direction` (null counts as omitted; `any`, `Anywhere`, `0.0.0.0/0` and `::/0` in `from`/`to` count as empty, a host mask `/32` on IPv4 or `/128` on IPv6 is dropped, `incoming` counts as `in`), so changing any of those fields is a new rule and the old one becomes stale; changing only the comment updates the rule in place (verified on ufw 0.36). `` is the rule's own comment. Comments must be printable ASCII without a single quote or backslash and without leading or trailing whitespace. The prefix and the regexes that read it back are role defaults (`ufw_tag_prefix`, `ufw_tag_regex`, `ufw_tag_comment_regex`); changing the prefix orphans rules already tagged. + +**Stale rules.** The role reads `ufw show added` and looks only at lines whose comment carries a tag of this owner; no rule syntax is parsed. A stale rule is one whose key is not in the desired list. With `ufw_service_state: absent` the desired list is empty, so every rule of the owner is stale. + +**Purge.** With `ufw_purge_stale: false` (the default) stale rules of a `present` owner are only reported. With `true`, or with `ufw_service_state: absent` (an explicit removal request that does not need `ufw_purge_stale`), they are deleted once every desired rule was applied, by `ufw --force delete ` (never by rule number, so the comment matches and the IPv4 and IPv6 rules go together). Check mode never deletes. Afterwards the role re-reads the rules and fails unless every desired rule is present, no stale rule remains and the SSH rule is unchanged. + +**Never deleted.** Rules without a tag (base rules, the SSH rule, manual rules) and rules of other owners. A stale line is deleted only when it is an explicit single numeric port other than `ufw_ssh_port` (`ufw allow 7401/tcp`, a deny works too). Every other line may open SSH and is kept and listed as a possible SSH path: no port (`allow in on tailscale0`, `allow from 10.0.0.0/24`), a port range or list (`20:30/tcp`, `22,80/tcp`), the word `ssh` or `openssh` outside the comment (a service name or an application profile, any case), the SSH port itself, or a line the SSH-port regex matches. `ufw_port_token_regex` finds the port tokens. + +**Refused before anything changes.** A rule listed twice by one owner; a rule whose spec another owner already holds (ufw stores identical specs once, so the tag would swap on every run); a rule that allows or limits `ufw_ssh_port` over TCP in the incoming direction (it would retag the untagged base SSH rule, and a purge could then delete it). Stale lines that hold characters outside printable ASCII, or braces, are refused rather than turned into a command. A desired rule that matches an untagged manual rule exactly adopts it: its comment is replaced by the tag and the owner manages it from then on. + +**Limitations.** Two owners cannot hold the same spec: a shared rule such as 80/443 aborts the second owner. A service rule with the same spec as a rule of the base `ufw_rules` list is retagged by the service call and rewritten by the next base run, back and forth, so keep the two lists disjoint. + +## `orphan_rules` entry point + +`service_rules` cleans up the rules of an owner only while that owner's role still runs. A service removed from a host leaves its tagged rules behind, and nothing calls `service_rules` for it again. `include_role` with `tasks_from: orphan_rules` finds those rules. + +An **orphan** is a rule tagged `ansible-ufw[:]` whose owner is neither in `ufw_managed_owners` nor in `ufw_reserved_owners`. + +| Variable | Default | Required | Description | +|---|---|---|---| +| `ufw_managed_owners` | none | no (undefined or empty: does nothing, see below) | Owners that are still managed, each `^[a-z0-9_]+$`. When a play derives it from a per-host list of service roles, each owner name must equal the role name in that list, because that is the `ufw_service_name` the role passes. | +| `ufw_purge_orphans` | `false` | no | `false`: orphans are reported. `true`: they are deleted. | + +- **Fail closed.** `ufw_managed_owners` has no default. While it is undefined or empty the entry point does nothing at all, not even a report, because an unknown list would make every owner an orphan. A malformed entry fails the play. +- **Report only by default.** The role default is `false`; a caller that wants the purge passes `true` in the task `vars:` of its call, rather than in inventory variables that every play would see. The log lists three groups: orphans that can be deleted (said to be deleted only when they were), orphans kept as a possible SSH path, and orphans kept as unparseable or unsafe (characters outside printable ASCII, or braces; only owner and key are shown). Deletion needs `ufw_purge_orphans: true` (a boolean, anything else fails), and never happens in check mode. +- **Never touched.** Untagged rules (base, SSH, manual) and rules of managed or reserved owners (`base`). A tagged line is deleted only when it is an explicit single numeric port other than `ufw_ssh_port` (`ufw allow 7401/tcp`, a deny works too). Every other line may open SSH and is kept and listed as a possible SSH path: no port (`allow in on tailscale0`, `allow from 10.0.0.0/24`), a port range or list (`20:30/tcp`, `22,80/tcp`), the word `ssh` or `openssh` outside the comment (a service name or an application profile, any case), the SSH port itself, or a line the SSH-port regex matches. `ufw_port_token_regex` finds the port tokens. The same rule guards the stale purge of `service_rules`. +- **Verified.** After a delete the rules are read again; the play fails unless exactly the deleted lines are gone and every other rule, the SSH rule included, is unchanged. +- Skipped with a debug message when `ufw_enabled` or `ufw_manage_rules` is false, and with a debug message when ufw is not installed or not active (the play does not fail). +- **Limitation.** The owner of a rule is the `ufw_service_name` a role passes. A role that is called by another role, which calls `service_rules` with its own owner name, is reported as an orphan unless that name is in `ufw_managed_owners`. Keep each role's `ufw_service_name` equal to its own role name. +- Tags: `ufw`, `ufw_orphan_rules`. As for `service_rules`, an `include_role` caller needs `apply: {tags: [...]}` for its own tags to reach the tasks. +- The parse, the SSH regex, the line check, the delete and the verify step duplicate `tasks/service_rules.yml`: keep them in step. + +```yaml +- name: Purge the rules of owners that are no longer managed + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: orphan_rules + apply: + tags: [ufw, ufw_orphan_rules] + vars: + ufw_managed_owners: "{{ host_services | default([]) }}" + ufw_purge_orphans: true + tags: [ufw, ufw_orphan_rules] +``` + +## 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. +- `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. +- The `Reload UFW` handler runs `ufw reload`. +- `no_log` is not used: the role handles no secrets. diff --git a/roles/ufw/defaults/main.yml b/roles/ufw/defaults/main.yml new file mode 100644 index 0000000..ea16148 --- /dev/null +++ b/roles/ufw/defaults/main.yml @@ -0,0 +1,53 @@ +--- +ufw_enabled: true +ufw_manage_rules: true + +ufw_defaults: + incoming: deny + outgoing: allow + routed: deny + +ufw_logging: "on" + +# Lock-out guard: with a deny/reject incoming default the play refuses to run +# unless an allow/limit rule for this TCP port is in the rule list, since the +# default is applied before the rules and a missing rule cuts the SSH session. +ufw_require_ssh_allow: true +ufw_ssh_port: "{{ ansible_port | default(22, true) }}" + +ufw_rules: [] +ufw_before_rules: [] + +# Keys/values written into /etc/ufw/sysctl.conf so ufw's stock file does not +# reset values set by the system_baseline role of this Collection. Set per group of hosts. +ufw_sysctl_overrides: [] + +# service_rules entry point. The owner tag is written into each rule's +# comment as `[:]: `; stale detection reads it back +# from `ufw show added`. The regex captures (owner, key) and must match the tag +# built from the prefix: change both together, and note that changing either +# orphans every rule already tagged. +ufw_tag_prefix: ansible-ufw +ufw_tag_regex: "comment 'ansible-ufw\\[([a-z0-9_]+):([0-9a-f]{10})\\]:" +# Characters allowed in a tagged comment: printable ASCII without the single +# quote (it breaks the ufw module) and the backslash. +ufw_tag_comment_regex: '^[] -&(-[^-~]*\Z' +# Finds the port tokens of a rule line (comment removed): a number or a range or list such as +# 20:30 or 22,80, followed by /tcp, /udp, a space or the end, and not part of an address, +# interface name or CIDR. A line is deleted as stale or orphaned only with exactly one plain +# numeric token that is not ufw_ssh_port; every other line may carry SSH and is kept. +ufw_port_token_regex: '(?- + Installs ufw, applies sysctl overrides, reads the base C(ufw_rules) and C(ufw_before_rules) lists (a defined + variable named C(*_ufw_rules) or C(*_ufw_before_rules) fails the play, service roles use the + C(service_rules) entry point), then sets default policies, rules and enables UFW. + - >- + Refuses to run when the incoming default is deny or reject and no allow or limit rule for the SSH TCP port exists + in C(ufw_rules). Only rules with C(direction=in) or no C(direction) count; C(direction=incoming), which + the module accepts, does not. + options: + ufw_enabled: + type: bool + default: true + description: + - When false every task that touches UFW is skipped, except installing the package. + ufw_manage_rules: + type: bool + default: true + description: + - >- + When false the C(ufw_rules) schema check, the SSH lock-out guard and rule + application are skipped. Before-rules validation, C(before.rules), default policies and + enabling still run, gated on C(ufw_enabled). + ufw_defaults: + type: dict + description: + - Default policies applied before any rule. The role default is C(incoming=deny), C(outgoing=allow), C(routed=deny). + - All three keys must be present when this is overridden, because each is read unconditionally. + options: + incoming: + type: str + choices: [allow, deny, reject] + description: Default policy for incoming traffic. + outgoing: + type: str + choices: [allow, deny, reject] + description: Default policy for outgoing traffic. + routed: + type: str + choices: [allow, deny, reject] + description: Default policy for routed (forwarded) traffic. + ufw_logging: + type: str + default: "on" + choices: ["on", "off", low, medium, high, full] + description: + - UFW logging setting. UFW is only re-enabled when it is inactive or its current logging line differs from this value. + ufw_require_ssh_allow: + type: bool + default: true + description: + - Enables the lock-out guard. Set false only when the host is reached without SSH on C(ufw_ssh_port). + ufw_ssh_port: + type: raw + description: + - TCP port the lock-out guard looks for, compared as a string. The role default is the Jinja expression C(ansible_port | default(22, true)). + ufw_rules: + type: raw + description: + - 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). + - C(port) must be a positive integer value. + ufw_before_rules: + type: raw + description: + - >- + Base list of ACCEPT entries written into /etc/ufw/before.rules, the only source of entries (no role contributes + before-rules). The role default is an empty list. + - >- + Each item is a mapping with at least one of C(port), C(from), C(to) or C(interface). Optional keys are + C(proto) (tcp or udp) and C(comment). Only C(interface), C(proto), C(port) and C(from) are written to the + file. + ufw_sysctl_overrides: + type: raw + description: + - >- + List of C({name, value}) mappings written as C(name=value) into /etc/ufw/sysctl.conf, so UFW does not reset + values set by the system_baseline role of this Collection. The role default is an empty list. + - C(name) uses slashes, for example C(net/ipv4/conf/all/log_martians). + service_rules: + short_description: Apply the firewall rules of one service, tagged with its name + description: + - >- + Entry point for a service role that owns firewall rules, used with C(include_role) and C(tasks_from=service_rules). + The main entry must have run before: this entry point installs nothing and touches no default policy, no + before.rules and no base rule. + - >- + Each rule is applied with the comment C(ansible-ufw[:]: ). C() is the first ten hex + characters of the sha1 of the rule's spec (rule, port, proto, from, to, interface, direction), so a changed spec + is a new rule and the old one becomes stale. Stale rules (tagged with this owner, key no longer wanted) are + reported, and deleted when C(ufw_purge_stale) is true or the state is C(absent). + - >- + A stale line is deleted only when it is an explicit single numeric port other than C(ufw_ssh_port); a line with no + port, a port range or list, C(ssh) or C(openssh) outside the comment, or one the SSH regex matches may open SSH + and is kept. + - >- + Rules without a tag (base rules, the SSH rule, manual rules) are never read as stale and never deleted. The play + fails before changing anything when a rule is listed twice, when another owner already holds the same spec, or + when a rule would allow the SSH port (C(ufw_ssh_port), TCP, incoming), because that would retag the base SSH rule. + options: + ufw_enabled: + type: bool + default: true + description: + - When false nothing is applied and a debug message says so. + ufw_manage_rules: + type: bool + default: true + description: + - When false nothing is applied and a debug message says so. + ufw_ssh_port: + type: raw + description: + - TCP port whose rule is never retagged or deleted, compared as a string. The role default is C(ansible_port | default(22, true)). + ufw_service_name: + type: str + required: true + description: + - >- + Owner of the rules, lower-case letters, digits and underscores (C(^[a-z0-9_]+$), asserted in the tasks). + C(base) is reserved. + ufw_service_rules: + type: raw + description: + - >- + List of rule mappings with the keys C(ufw_rules) accepts: C(rule) (allow, deny, reject or limit), at least + one of C(port), C(from), C(to) or C(interface), and optional C(proto), C(direction) and C(comment). Other keys are + refused, and C(interface) needs C(direction). + Comments are printable ASCII without a single quote or backslash. + - Required when C(ufw_service_state) is C(present); an empty list makes every rule of the owner stale. Ignored for C(absent). + - Typed raw because callers pass a templated variable. It is asserted to be a list. + ufw_service_state: + type: str + default: present + choices: [present, absent] + description: + - >- + C(absent) makes the desired set empty, so every tagged rule of the owner is stale, and it is an explicit + removal request: they are deleted whatever C(ufw_purge_stale) says (not in check mode, never an SSH-like line). + ufw_purge_stale: + type: bool + default: false + description: + - >- + Only for C(ufw_service_state=present). When true, stale rules of this owner are deleted after every desired rule + was applied (never in check mode, never a rule that looks like the SSH rule), then the result is verified. When + false they are only reported. True with an empty C(ufw_service_rules) is refused: use C(absent) to remove all. + ufw_tag_prefix: + type: str + default: ansible-ufw + description: + - Prefix of the owner tag. Must agree with C(ufw_tag_regex); changing it orphans rules already tagged. + ufw_tag_regex: + type: str + default: "comment 'ansible-ufw\\[([a-z0-9_]+):([0-9a-f]{10})\\]:" + description: + - Regular expression with two groups (owner, key) that finds the tag in a line of C(ufw show added). + ufw_tag_comment_regex: + type: str + default: '^[] -&(-[^-~]*\Z' + description: + - Regular expression a rule comment must match. + ufw_port_token_regex: + type: str + description: + - >- + Regular expression that finds the port tokens (a number, a range such as C(20:30) or a list such as + C(22,80)) of a rule line without its comment. A line is deleted only with exactly one plain numeric + token other than C(ufw_ssh_port). See the role defaults. + ufw_reserved_owners: + type: list + elements: str + default: [base] + description: + - Owner names a service may not use. + orphan_rules: + short_description: Report, and optionally delete, the tagged rules of owners that are no longer managed + description: + - >- + Entry point used with C(include_role) and C(tasks_from=orphan_rules), after every service role of the host ran. + An orphan is a rule tagged C(ansible-ufw[:]) whose owner is neither in C(ufw_managed_owners) nor in + C(ufw_reserved_owners). It is what a service removed from the host leaves behind, because C(service_rules) is + never called for that owner again. + - >- + Fails closed: when C(ufw_managed_owners) is undefined or empty nothing is read, reported or deleted. Orphans are + reported; they are deleted only when C(ufw_purge_orphans) is true, never in check mode and never a line that looks + like the SSH rule. Untagged rules (base, SSH, manual), rules of managed or reserved owners are never touched. + A tagged orphan line is deleted only when it is an explicit single numeric port other than C(ufw_ssh_port); + a line with no port, a port range or list, C(ssh) or C(openssh) outside the comment, or one the SSH regex matches + may open SSH and is kept and reported. Lines with unexpected characters are kept and only their owner and key are + reported. The owner is the C(ufw_service_name) a role passes: a role called by another role that calls + C(service_rules) under its own name is reported as an orphan unless that name is in the list. + After a delete the rules are read again and the play fails unless exactly the deletable orphan lines are gone + and every other rule, SSH included, is unchanged (kept lines stay and are reported). Skipped with a debug message when ufw is not active. + options: + ufw_enabled: + type: bool + default: true + description: + - When false nothing is looked at and a debug message says so. + ufw_manage_rules: + type: bool + default: true + description: + - When false nothing is looked at and a debug message says so. + ufw_ssh_port: + type: raw + description: + - TCP port whose rule is never deleted, compared as a string. The role default is C(ansible_port | default(22, true)). + ufw_managed_owners: + type: list + elements: str + description: + - >- + Owner names that are still managed, each C(^[a-z0-9_]+$) (asserted in the tasks). No default: undefined or empty + makes the entry point do nothing. When a play derives the owners from a per-host list of service roles, each owner name must equal the + role name in that list, which the service passes as C(ufw_service_name). + ufw_purge_orphans: + type: bool + default: false + description: + - When true the orphaned rules are deleted (not in check mode, never an SSH-like line). When false they are only reported. + ufw_tag_prefix: + type: str + default: ansible-ufw + description: + - Prefix of the owner tag. Must agree with C(ufw_tag_regex). + ufw_tag_regex: + type: str + default: "comment 'ansible-ufw\\[([a-z0-9_]+):([0-9a-f]{10})\\]:" + description: + - Regular expression with two groups (owner, key) that finds the tag in a line of C(ufw show added). + ufw_port_token_regex: + type: str + description: + - >- + Regular expression that finds the port tokens (a number, a range such as C(20:30) or a list such as + C(22,80)) of a rule line without its comment. A line is deleted only with exactly one plain numeric + token other than C(ufw_ssh_port). See the role defaults. + ufw_reserved_owners: + type: list + elements: str + default: [base] + description: + - Owner names that are never orphans. diff --git a/roles/ufw/meta/main.yml b/roles/ufw/meta/main.yml new file mode 100644 index 0000000..2404269 --- /dev/null +++ b/roles/ufw/meta/main.yml @@ -0,0 +1,18 @@ +--- +galaxy_info: + role_name: ufw + namespace: mortis + author: Defame1297 + license: GPL-3.0-or-later AND GPL-3.0-only + description: Install and configure UFW with default policies, allow rules, before.rules and sysctl overrides, guarded against SSH lock-out. + min_ansible_version: "2.19" + platforms: + - name: Ubuntu + versions: + - jammy + - noble + galaxy_tags: + - firewall + - ufw + - security +dependencies: [] diff --git a/roles/ufw/molecule/default/converge.yml b/roles/ufw/molecule/default/converge.yml new file mode 100644 index 0000000..e9b4946 --- /dev/null +++ b/roles/ufw/molecule/default/converge.yml @@ -0,0 +1,448 @@ +--- +# Lock-out guard: default-deny without an SSH allow rule must be refused before +# any policy is touched. +- name: Refuse default-deny without an SSH allow rule + hosts: all + gather_facts: false + tasks: + - name: Run the role with only a non-SSH rule + block: + - name: Include ufw + ansible.builtin.include_role: + name: mortis.kamino.ufw + vars: + ufw_rules: + - {rule: allow, port: 8080, proto: tcp} + - name: Unreachable when the guard works + ansible.builtin.fail: + msg: ufw ran without an SSH allow rule + rescue: + - name: The guard, not something else, stopped the play + ansible.builtin.assert: + that: "'would lock this host out' 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). +- name: Refuse stray variables named like the old *_ufw_rules + hosts: all + gather_facts: false + tasks: + - name: A stray *_ufw_rules variable + block: + - name: Include ufw with a stray rules variable + ansible.builtin.include_role: + name: mortis.kamino.ufw + vars: + ufw_rules: + - {rule: allow, port: 22, proto: tcp, comment: ssh} + stray_ufw_rules: # noqa: var-naming[no-role-prefix] + - {rule: allow, port: 7999, proto: tcp, comment: stray} + - name: Unreachable when the stray variable guard works + ansible.builtin.fail: + msg: a stray *_ufw_rules variable was accepted + rescue: + - name: The stray guard, not something else, stopped the play + ansible.builtin.assert: + that: + - "'stray_ufw_rules' in ansible_failed_result.msg | default('')" + - "'stray_ufw_before_rules' not in ansible_failed_result.msg | default('')" + - "'service_rules' in ansible_failed_result.msg | default('')" + quiet: true + + - name: A stray *_ufw_before_rules variable + block: + - name: Include ufw with a stray before-rules variable + ansible.builtin.include_role: + name: mortis.kamino.ufw + vars: + ufw_rules: + - {rule: allow, port: 22, proto: tcp, comment: ssh} + stray_ufw_before_rules: # noqa: var-naming[no-role-prefix] + - {proto: udp, port: 7998, comment: stray} + - name: Unreachable when the stray variable guard works + ansible.builtin.fail: + msg: a stray *_ufw_before_rules variable was accepted + rescue: + - name: The stray guard, not something else, stopped the play + ansible.builtin.assert: + that: + - "'stray_ufw_before_rules' in ansible_failed_result.msg | default('')" + - "'stray_ufw_rules' not in ansible_failed_result.msg | default('')" + quiet: true + +- name: Converge with an SSH rule and service rules + hosts: all + gather_facts: true + roles: + - role: mortis.kamino.ufw + vars: + ufw_rules: + - {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} + # no proto: both protocols, and the guard must cope with the key missing + - {rule: allow, port: 9090, comment: metrics} + +# The service_rules entry point. prepare.yml stored a stale rule for svc_c, +# a rule of the removed service svc_d and a stale rule for svc_e, so every pass here +# is a no-op after the first one, purge included. +- name: Converge the rules of several services through the entry point + hosts: all + gather_facts: false + tasks: + - name: Two rules for svc_a + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_a + ufw_service_rules: + - {rule: allow, port: 8001, proto: tcp, comment: alpha web} + - {rule: allow, port: 8002, proto: udp, from: 10.1.0.0/16, comment: alpha dns} + + - name: Two rules for svc_b, one without a comment + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_b + ufw_service_rules: + - {rule: allow, port: 8003, proto: tcp, comment: beta} + - {rule: deny, port: 8004} + + - name: Keep one rule for svc_c and purge its stale rule + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_c + ufw_purge_stale: true + ufw_service_rules: + - {rule: allow, port: 7101, proto: tcp, comment: gamma} + + - name: Remove svc_d, which deletes without ufw_purge_stale + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_d + ufw_service_state: absent + + - name: Keep the stale rule of svc_e because purging is off + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_e + ufw_service_rules: + - {rule: allow, port: 7201, proto: tcp, comment: epsilon} + + - name: A comment that mentions the SSH port on another port + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_g + ufw_service_rules: + - {rule: allow, port: 8022, proto: tcp, comment: forward to 22 here} + + - name: Purge svc_h without touching its stale rule that looks like the SSH rule + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_h + ufw_purge_stale: true + ufw_service_rules: + - {rule: allow, port: 7301, proto: tcp, comment: eta} + +- name: Purge svc_p but keep its stale rules that may carry SSH + hosts: all + gather_facts: false + tasks: + # prepare.yml stored four stale rules for svc_p: a numeric port (deleted), and a rule + # with no port, a source-only rule and a range, which are kept as possible SSH paths. + - name: Keep one rule for svc_p and purge its stale rules + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_p + ufw_purge_stale: true + ufw_service_rules: + - {rule: allow, port: 7602, proto: tcp, comment: desired} + +# Inputs the entry point must refuse, each before it changes anything. Every block +# proves the refusal and its message; the play still passes, so the idempotence run +# stays clean and verify.yml proves no rule was left behind. +- name: Refuse invalid service rule inputs + hosts: all + gather_facts: false + vars: + # A failed looped task reports "One or more items failed" in msg and the item + # messages in results; an unlooped one has the message in msg. + ufw_converge_failure: >- + {{ ansible_failed_result.msg | default('') }} + {{ ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ') }} + tasks: + - name: An owner name outside the allowed characters + block: + - name: Include with an invalid owner name + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: Bad-Name + ufw_service_rules: + - {rule: allow, port: 8101, proto: tcp} + - name: Unreachable when the owner name is checked + ansible.builtin.fail: + msg: an invalid owner name was accepted + rescue: + - name: The owner check stopped the play + ansible.builtin.assert: + that: "'ufw_service_name must be a string matching' in ufw_converge_failure" + quiet: true + + - name: The reserved owner base + block: + - name: Include as base + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: base + ufw_service_rules: + - {rule: allow, port: 8102, proto: tcp} + - name: Unreachable when base is reserved + ansible.builtin.fail: + msg: the reserved owner base was accepted + rescue: + - name: The reserved name stopped the play + ansible.builtin.assert: + that: "'reserved for the base play' in ufw_converge_failure" + quiet: true + + - name: A single quote in a comment + block: + - name: Include with a quote in the comment + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_f + ufw_service_rules: + - {rule: allow, port: 8103, proto: tcp, comment: "it's"} + - name: Unreachable when comments are checked + ansible.builtin.fail: + msg: a quote in a comment was accepted + rescue: + - name: The comment check stopped the play + ansible.builtin.assert: + that: "'single quote' in ufw_converge_failure" + quiet: true + + - name: A rule another owner already holds + block: + - name: Include with the spec of a svc_a rule + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_f + ufw_service_rules: + - {rule: allow, port: 8001, proto: tcp, comment: other text} + - name: Unreachable when collisions are checked + ansible.builtin.fail: + msg: a rule owned by svc_a was accepted for svc_f + rescue: + - name: The collision check stopped the play + ansible.builtin.assert: + that: "'already owned by another tag' in ufw_converge_failure" + quiet: true + + - name: A rule that would retag the SSH rule + block: + - name: Include with an allow rule for the SSH port + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_f + ufw_service_rules: + - {rule: allow, port: 22, proto: tcp} + - name: Unreachable when the SSH port is protected + ansible.builtin.fail: + msg: a service rule for the SSH port was accepted + rescue: + - name: The SSH check stopped the play + ansible.builtin.assert: + that: "'allows the SSH port' in ufw_converge_failure" + quiet: true + + - name: An unknown rule key + block: + - name: Include with a to_port key + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_f + ufw_service_rules: + - {rule: allow, to_port: 8104, proto: tcp} + - name: Unreachable when keys are checked + ansible.builtin.fail: + msg: an unknown rule key was accepted + rescue: + - name: The key check stopped the play + ansible.builtin.assert: + that: "'has an unknown key' in ufw_converge_failure" + quiet: true + + - name: An interface without a direction + block: + - name: Include with an interface and no direction + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_f + ufw_service_rules: + - {rule: allow, port: 8105, proto: tcp, interface: eth0} + - name: Unreachable when the direction is required + ansible.builtin.fail: + msg: an interface without a direction was accepted + rescue: + - name: The direction check stopped the play + ansible.builtin.assert: + that: "'interface without direction' in ufw_converge_failure" + quiet: true + + - name: Purging with an empty rule list + block: + - name: Include with an empty list and ufw_purge_stale + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_a + ufw_purge_stale: true + ufw_service_rules: [] + - name: Unreachable when an empty list is refused + ansible.builtin.fail: + msg: an empty list with ufw_purge_stale was accepted + rescue: + - name: The empty list stopped the play + ansible.builtin.assert: + that: "'use ufw_service_state: absent' in ufw_converge_failure" + quiet: true + +# The orphan_rules entry point. prepare.yml stored two rules of svc_o1, a rule of +# svc_o2 that looks like the SSH rule, and a rule of svc_m. The managed owners below are +# the ones used above plus svc_m (listed but never called), so svc_o1 and svc_o2 are +# orphans. The cases that must change nothing run first and the purge last, so the +# idempotence run finds nothing left to delete. Check mode is not exercised: whether it +# reaches the tasks of an include_role is not verified. +- name: Report and purge the rules of unmanaged owners + hosts: all + gather_facts: false + vars: + ufw_converge_managed: + - svc_a + - svc_b + - svc_c + - svc_d + - svc_e + - svc_g + - svc_h + - svc_m + - svc_p + ufw_converge_failure: >- + {{ ansible_failed_result.msg | default('') }} + {{ ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ') }} + tasks: + # The marker is written after the purge, so the expected counts are absolute on both + # passes: svc_o1 holds 2 rules before the purge and 0 once the marker exists. + - name: Look for the marker of an earlier purge + ansible.builtin.stat: + path: /var/tmp/ufw-orphans-purged + register: ufw_conv_marker + + - name: Work out the expected number of rules of svc_o1 + ansible.builtin.set_fact: + ufw_conv_o1_initial: "{{ 0 if ufw_conv_marker.stat.exists else 2 }}" + + - name: Assert it before the first case + ansible.builtin.include_tasks: tasks/orphan_check.yml + + - name: No managed owners given, purge requested + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: orphan_rules + vars: + ufw_purge_orphans: true + + - name: Nothing was deleted without a list + ansible.builtin.include_tasks: tasks/orphan_check.yml + + - name: An empty list of managed owners, purge requested + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: orphan_rules + vars: + ufw_managed_owners: [] + ufw_purge_orphans: true + + - name: Nothing was deleted with an empty list + ansible.builtin.include_tasks: tasks/orphan_check.yml + + - name: An invalid managed owner + block: + - name: Include with an owner name outside the allowed characters + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: orphan_rules + vars: + ufw_managed_owners: [svc_a, Bad-Name] + ufw_purge_orphans: true + - name: Unreachable when the owners are checked + ansible.builtin.fail: + msg: an invalid managed owner was accepted + rescue: + - name: The owner check stopped the play + ansible.builtin.assert: + that: "'ufw_managed_owners must be a list of strings matching' in ufw_converge_failure" + quiet: true + + - name: Nothing was deleted after the invalid owner + ansible.builtin.include_tasks: tasks/orphan_check.yml + + - name: Report the orphans only + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: orphan_rules + vars: + ufw_managed_owners: "{{ ufw_converge_managed }}" + ufw_purge_orphans: false + + - name: Reporting deleted nothing + ansible.builtin.include_tasks: tasks/orphan_check.yml + + - name: Purge the orphans + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: orphan_rules + vars: + ufw_managed_owners: "{{ ufw_converge_managed }}" + ufw_purge_orphans: true + + - name: Only svc_o1 is gone, the kept orphans and svc_m stay + ansible.builtin.include_tasks: tasks/orphan_check.yml + vars: + ufw_conv_o1_want: 0 + + - name: Mark the purge as done + ansible.builtin.command: touch /var/tmp/ufw-orphans-purged + changed_when: false diff --git a/roles/ufw/molecule/default/molecule.yml b/roles/ufw/molecule/default/molecule.yml new file mode 100644 index 0000000..410db4d --- /dev/null +++ b/roles/ufw/molecule/default/molecule.yml @@ -0,0 +1,43 @@ +--- +# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 image +# (MOLECULE_IMAGE, the pin in .gitea/workflows/molecule.yml). No privileged mode: systemd needs a +# writable cgroup and the firewall tools need NET_ADMIN, nothing else. +driver: + name: docker +platforms: + - name: ufw-instance + image: ${MOLECULE_IMAGE} + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + capabilities: + - NET_ADMIN + security_opts: + - apparmor=unconfined +provisioner: + name: ansible +verifier: + name: ansible +scenario: + # molecule's default sequence minus its first destroy: the workflow removes what a killed run + # left before any scenario starts, so that destroy only waits out the + # driver's 5 s poll on a container that is not there. After an aborted local run, run + # `molecule destroy` yourself. + test_sequence: + - dependency + - cleanup + - syntax + - create + - prepare + - converge + - idempotence + - side_effect + - verify + - cleanup + - destroy diff --git a/roles/ufw/molecule/default/prepare.yml b/roles/ufw/molecule/default/prepare.yml new file mode 100644 index 0000000..18a10a1 --- /dev/null +++ b/roles/ufw/molecule/default/prepare.yml @@ -0,0 +1,74 @@ +--- +# Rules that must already be stored before the role runs, so converge stays +# idempotent while still exercising the purge: a second converge finds them +# deleted (or kept, for the report-only owner) and changes nothing. ufw is +# installed here; it stays inactive until the role enables it. +- name: Prepare + hosts: all + gather_facts: false + tasks: + - name: Install ufw + ansible.builtin.package: + name: ufw + state: present + + # An application profile whose name holds openssh, for the orphan seeds below. + - name: Define an application profile named like SSH + ansible.builtin.copy: + dest: /etc/ufw/applications.d/orphan-openssh + mode: "0644" + content: | + [OrphanOpenSSH] + title=Orphan test + description=Test profile for the orphan_rules molecule seeds + ports=22/tcp + + - name: Store a manual rule without a tag + community.general.ufw: + rule: allow + port: "7777" + proto: tcp + comment: manual + + # 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. + - name: Store tagged rules that are no longer wanted + community.general.ufw: + rule: allow + port: "{{ ufw_prepare_rule.port | default(omit) }}" + proto: "{{ 'tcp' if ufw_prepare_rule.port is defined else omit }}" + from: "{{ ufw_prepare_rule.from | default(omit) }}" + interface: "{{ ufw_prepare_rule.interface | default(omit) }}" + direction: "{{ ufw_prepare_rule.direction | default(omit) }}" + name: "{{ ufw_prepare_rule.name | default(omit) }}" + comment: "{{ ufw_prepare_rule.comment }}" + loop: + # svc_c: the old spec of a rule whose port changed (key of allow|7001|tcp||||in) + - {port: 7001, comment: "ansible-ufw[svc_c:128c086248]: old"} + - {port: 7002, comment: "ansible-ufw[svc_d:abcdef0123]: gone"} + - {port: 7003, comment: "ansible-ufw[svc_e:aaaaaaaaaa]: kept"} + # svc_h: a stale rule that looks like an SSH rule, which a purge must skip + - {port: 22, from: 10.9.0.0/16, comment: "ansible-ufw[svc_h:bbbbbbbbbb]: old"} + # orphan_rules: svc_o1 and svc_o2 are never listed as managed owners in converge.yml. + # svc_o2's rule looks like the SSH rule and must survive a purge; svc_m is managed + # but its role is never called, so its rule must survive too. + - {port: 7401, comment: "ansible-ufw[svc_o1:1111111111]: orphan one"} + - {port: 7402, comment: "ansible-ufw[svc_o1:2222222222]: orphan two"} + - {port: 22, from: 10.9.1.0/24, comment: "ansible-ufw[svc_o2:3333333333]: orphan ssh lookalike"} + - {port: 7501, comment: "ansible-ufw[svc_m:4444444444]: managed, never called"} + # orphan_rules, owner svc_o3: tagged orphans that may carry SSH and must be kept by a + # purge: no port (interface only), no port (source only), a range spanning 22, an + # application profile named like SSH. + - {interface: tailscale0, direction: in, comment: "ansible-ufw[svc_o3:5555555551]: no port"} + - {from: 10.20.0.0/24, comment: "ansible-ufw[svc_o3:5555555552]: source only"} + - {port: "20:30", comment: "ansible-ufw[svc_o3:5555555553]: range over 22"} + - {name: OrphanOpenSSH, comment: "ansible-ufw[svc_o3:5555555554]: openssh profile"} + # service_rules purge of svc_p (converge.yml keeps only a rule for 7602): 7601 is stale + # and deleted, the other three are stale and may carry SSH, so they stay. + - {port: 7601, comment: "ansible-ufw[svc_p:6666666664]: stale numeric"} + - {interface: wg0, direction: in, comment: "ansible-ufw[svc_p:6666666661]: no port"} + - {from: 10.30.0.0/24, comment: "ansible-ufw[svc_p:6666666662]: source only"} + - {port: "40:50", comment: "ansible-ufw[svc_p:6666666663]: range"} + loop_control: + loop_var: ufw_prepare_rule diff --git a/roles/ufw/molecule/default/tasks/orphan_check.yml b/roles/ufw/molecule/default/tasks/orphan_check.yml new file mode 100644 index 0000000..f256497 --- /dev/null +++ b/roles/ufw/molecule/default/tasks/orphan_check.yml @@ -0,0 +1,27 @@ +--- +# Included by converge.yml after each orphan_rules case. The counts are absolute: svc_o1 +# holds ufw_conv_o1_want rules (default ufw_conv_o1_initial: 2 before the purge, 0 after), +# and the tagged total is 20 plus those. The 20: svc_a 2, svc_b 2, svc_c 1, svc_e 2, svc_g 1, +# svc_h 2, svc_m 1, svc_o2 1, svc_o3 4 (kept orphans that may carry SSH), svc_p 4 (its +# desired rule and three kept stale rules). +- name: Read the rules ufw would load + ansible.builtin.command: ufw show added + register: ufw_conv_added + changed_when: false + environment: {LC_ALL: C} + +- name: The seeds are as this case leaves them + ansible.builtin.assert: + that: + - ufw_conv_added.stdout_lines | select('search', 'svc_o1:') | list | length == ufw_conv_o1_count | int + - ufw_conv_added.stdout_lines | select('search', 'svc_o2:3333333333') | list | length == 1 + - ufw_conv_added.stdout_lines | select('search', 'svc_o3:555555555[1-4]') | list | length == 4 + - ufw_conv_added.stdout_lines | select('search', 'svc_m:4444444444') | list | length == 1 + - ufw_conv_added.stdout_lines | select('search', 'svc_p:666666666[123]') | list | length == 3 + - ufw_conv_added.stdout_lines | select('search', 'svc_p:6666666664') | list | length == 0 + - ufw_conv_added.stdout_lines | select('match', '^ufw ') | select('search', 'ansible-ufw') | list | length == 20 + ufw_conv_o1_count | int + - ufw_conv_added.stdout_lines | select('match', '^ufw ') | reject('search', 'ansible-ufw') | list | length == 5 + fail_msg: "Unexpected rules after the orphan_rules case: {{ ufw_conv_added.stdout_lines }}" + quiet: true + vars: + ufw_conv_o1_count: "{{ ufw_conv_o1_want | default(ufw_conv_o1_initial) }}" diff --git a/roles/ufw/molecule/default/verify.yml b/roles/ufw/molecule/default/verify.yml new file mode 100644 index 0000000..eda9934 --- /dev/null +++ b/roles/ufw/molecule/default/verify.yml @@ -0,0 +1,209 @@ +--- +- name: Verify + hosts: all + gather_facts: false + tasks: + - name: Read the firewall state + ansible.builtin.command: ufw status verbose + register: ufw_verify_ufw + changed_when: false + environment: {LC_ALL: C} + + - name: UFW is active and denies incoming by default + ansible.builtin.assert: + that: + - "'Status: active' in ufw_verify_ufw.stdout" + - "'deny (incoming)' in ufw_verify_ufw.stdout" + quiet: true + + - name: The SSH rule and the service rules were rendered + ansible.builtin.assert: + that: + - ufw_verify_ufw.stdout is search('22/tcp\s+ALLOW IN\s+Anywhere') + - ufw_verify_ufw.stdout is search('8080/tcp\s+ALLOW IN\s+10\.0\.0\.0/8') + - ufw_verify_ufw.stdout is search('53/udp\s+ALLOW IN\s+Anywhere') + - ufw_verify_ufw.stdout is search('9090\s+ALLOW IN\s+Anywhere') + quiet: true + + - name: Read the rules ufw would load + ansible.builtin.command: ufw show added + register: ufw_verify_added + changed_when: false + environment: {LC_ALL: C} + + # The four base rules plus the manual rule from prepare.yml. The refused runs + # (guard, invalid service inputs) added none. + - name: Exactly the five untagged rules exist + ansible.builtin.assert: + that: ufw_verify_untagged | length == 5 + quiet: true + vars: + ufw_verify_untagged: "{{ ufw_verify_added.stdout_lines | select('match', '^ufw ') | reject('search', 'ansible-ufw') | list }}" + + # converge.yml proves the guard's message; the 7999 and 7998 absence checks are redundant confirmation that the stray rules never reached the host. + - name: A stray *_ufw_rules variable did not reach the firewall + ansible.builtin.assert: + that: + - ufw_verify_added.stdout_lines | select('search', '7999') | list | length == 0 + - ufw_verify_ufw.stdout is not search('7999') + quiet: true + + - name: The manual rule and the SSH rule were not touched + ansible.builtin.assert: + that: + - ufw_verify_untagged | select('search', "7777/tcp comment 'manual'") | list | length == 1 + - ufw_verify_untagged | select('search', "22/tcp comment 'ssh'") | list | length == 1 + quiet: true + vars: + ufw_verify_untagged: "{{ ufw_verify_added.stdout_lines | select('match', '^ufw ') | reject('search', 'ansible-ufw') | list }}" + + # Keys are the first ten hex characters of the sha1 of + # rule|port|proto|from|to|interface|direction. + - name: The service rules carry their owner tag + ansible.builtin.assert: + that: + - ufw_verify_tagged | select('search', ufw_verify_svc_a_web) | list | length == 1 + - 'ufw_verify_tagged | select("search", "8002.*ansible-ufw\[svc_a:[0-9a-f]{10}\]: alpha dns") | list | length == 1' + - 'ufw_verify_tagged | select("search", "8003.*ansible-ufw\[svc_b:[0-9a-f]{10}\]: beta") | list | length == 1' + - 'ufw_verify_tagged | select("search", "8004.*ansible-ufw\[svc_b:[0-9a-f]{10}\]:.$") | list | length == 1' + - 'ufw_verify_tagged | select("search", "7101.*ansible-ufw\[svc_c:[0-9a-f]{10}\]: gamma") | list | length == 1' + - 'ufw_verify_tagged | select("search", "7201.*ansible-ufw\[svc_e:[0-9a-f]{10}\]: epsilon") | list | length == 1' + - 'ufw_verify_tagged | select("search", "8022/tcp comment .ansible-ufw\[svc_g:[0-9a-f]{10}\]: forward to 22 here") | list | length == 1' + - 'ufw_verify_tagged | select("search", "7301.*ansible-ufw\[svc_h:[0-9a-f]{10}\]: eta") | list | length == 1' + quiet: true + vars: + ufw_verify_tagged: "{{ ufw_verify_added.stdout_lines | select('match', '^ufw ') | select('search', 'ansible-ufw') | list }}" + ufw_verify_key_a_web: "{{ ('allow|8001|tcp||||in' | hash('sha1'))[:10] }}" + ufw_verify_svc_a_web: "8001/tcp comment 'ansible-ufw\\[svc_a:{{ ufw_verify_key_a_web }}\\]: alpha web'" + + - name: Stale rules were purged only where purging was on, and svc_d is gone + ansible.builtin.assert: + that: + - ufw_verify_added.stdout_lines | select('search', 'svc_c:128c086248') | list | length == 0 + - ufw_verify_added.stdout_lines | select('search', 'svc_d:') | list | length == 0 + - ufw_verify_added.stdout_lines | select('search', '7003.*svc_e:aaaaaaaaaa') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', 'svc_h:bbbbbbbbbb') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', 'ansible-ufw') | list | length == 20 + quiet: true + + # Twenty tagged rules: svc_a 2, svc_b 2, svc_c 1, svc_e 2, svc_g 1, svc_h 2, svc_m 1, the + # SSH lookalike of svc_o2, four orphans of svc_o3 and four rules of svc_p (its desired + # rule and three stale ones). Both rules of svc_o1 and the numeric stale rule of svc_p were + # deleted; the kept ones may carry SSH. + - name: Orphans were purged except those that may carry SSH, a managed owner kept its rule + ansible.builtin.assert: + that: + - ufw_verify_added.stdout_lines | select('search', 'svc_o1:') | list | length == 0 + - ufw_verify_added.stdout_lines | select('search', '10\.9\.1\.0/24.* port 22 .*svc_o2:3333333333') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', 'tailscale0.*svc_o3:5555555551') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', '10\.20\.0\.0/24.*svc_o3:5555555552') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', '20:30.*svc_o3:5555555553') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', 'OrphanOpenSSH.*svc_o3:5555555554') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', '7501.*svc_m:4444444444') | list | length == 1 + quiet: true + + - name: The stale purge of service_rules kept the lines that may carry SSH + ansible.builtin.assert: + that: + - ufw_verify_added.stdout_lines | select('search', 'svc_p:6666666664') | list | length == 0 + - ufw_verify_added.stdout_lines | select('search', '7601') | list | length == 0 + - ufw_verify_added.stdout_lines | select('search', 'wg0.*svc_p:6666666661') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', '10\.30\.0\.0/24.*svc_p:6666666662') | list | length == 1 + - ufw_verify_added.stdout_lines | select('search', '40:50.*svc_p:6666666663') | list | length == 1 + - 'ufw_verify_added.stdout_lines | select("search", "7602.*ansible-ufw\\[svc_p:[0-9a-f]{10}\\]: desired") | list | length == 1' + quiet: true + + - name: No rejected input left a rule behind + ansible.builtin.assert: + that: + - 'ufw_verify_added.stdout_lines | select("search", "( 8101| 8102| 8103)([ /]|$)|svc_f") | list | length == 0' + quiet: true + + - name: A stray *_ufw_before_rules variable did not reach before.rules + ansible.builtin.command: grep -q 7998 /etc/ufw/before.rules + register: ufw_verify_stray_before + changed_when: false + failed_when: ufw_verify_stray_before.rc != 1 + + - name: The before.rules file keeps the loopback accept + ansible.builtin.command: grep -q -- '-A ufw-before-input -i lo -j ACCEPT' /etc/ufw/before.rules + changed_when: false + + - name: The before.rules file drops INVALID-state input packets + ansible.builtin.command: grep -q -- '-A ufw-before-input -m conntrack --ctstate INVALID -j DROP' /etc/ufw/before.rules + changed_when: false + + - name: The INVALID drop logs through ufw-logging-deny first + ansible.builtin.command: grep -q -- '-A ufw-before-input -m conntrack --ctstate INVALID -j ufw-logging-deny' /etc/ufw/before.rules + changed_when: false + + - name: Read the before.rules input rules in order + ansible.builtin.command: grep -n -- '^-A ufw-before-input ' /etc/ufw/before.rules + register: ufw_verify_input_rules + changed_when: false + + - name: The INVALID drop sits after the established accept, behind its logging rule, and before the ICMP accepts + ansible.builtin.assert: + that: + - ufw_verify_idx_established < ufw_verify_idx_logging + - ufw_verify_idx_logging < ufw_verify_idx_invalid + - ufw_verify_idx_invalid < ufw_verify_idx_icmp + quiet: true + vars: + ufw_verify_lines: "{{ ufw_verify_input_rules.stdout_lines }}" + ufw_verify_idx_established: "{{ ufw_verify_lines | select('search', '--ctstate RELATED,ESTABLISHED') | first | split(':') | first | int }}" + ufw_verify_idx_logging: "{{ ufw_verify_lines | select('search', '--ctstate INVALID -j ufw-logging-deny') | first | split(':') | first | int }}" + ufw_verify_idx_invalid: "{{ ufw_verify_lines | select('search', '--ctstate INVALID -j DROP') | first | split(':') | first | int }}" + ufw_verify_idx_icmp: "{{ ufw_verify_lines | select('search', '-p icmp') | first | split(':') | first | int }}" + +# Check mode of the entry point. It lives in verify, not in converge: a check-mode +# apply of community.general.ufw reports changed for the would-be rule, so molecule's +# idempotence run (a second converge) would fail on it. Verify runs once, outside that count. +# The play runs under the check_mode keyword, which does not set ansible_check_mode in the +# included role; the role detects check mode with a probe task instead (a command task is +# skipped under the keyword). A present call that would add a rule and an absent call for an +# owner that holds rules must change nothing. The two reads of the rule list are forced to +# run (check_mode: false) and compared as a whole. +- name: Check mode of service_rules changes nothing + hosts: all + gather_facts: false + check_mode: true + tasks: + - name: Read the rules before + ansible.builtin.command: ufw show added + register: ufw_verify_chk_before + changed_when: false + check_mode: false + environment: {LC_ALL: C} + + - name: A present call that would add a rule for a new owner + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_chk + ufw_service_rules: + - {rule: allow, port: 7701, proto: tcp, comment: check mode} + + - name: An absent call for svc_a, which holds two rules + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_a + ufw_service_state: absent + + - name: Read the rules after + ansible.builtin.command: ufw show added + register: ufw_verify_chk_after + changed_when: false + check_mode: false + environment: {LC_ALL: C} + + - name: Check mode added and deleted nothing + ansible.builtin.assert: + that: + - ufw_verify_chk_before.stdout_lines | select('search', 'svc_a:') | list | length == 2 + - ufw_verify_chk_after.stdout_lines == ufw_verify_chk_before.stdout_lines + - ufw_verify_chk_after.stdout_lines | select('search', 'svc_chk|7701') | list | length == 0 + quiet: true diff --git a/roles/ufw/tasks/aggregate_rules.yml b/roles/ufw/tasks/aggregate_rules.yml new file mode 100644 index 0000000..7a93b5a --- /dev/null +++ b/roles/ufw/tasks/aggregate_rules.yml @@ -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 diff --git a/roles/ufw/tasks/before_rules.yml b/roles/ufw/tasks/before_rules.yml new file mode 100644 index 0000000..2da14ed --- /dev/null +++ b/roles/ufw/tasks/before_rules.yml @@ -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. diff --git a/roles/ufw/tasks/defaults.yml b/roles/ufw/tasks/defaults.yml new file mode 100644 index 0000000..db659d1 --- /dev/null +++ b/roles/ufw/tasks/defaults.yml @@ -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 diff --git a/roles/ufw/tasks/enable.yml b/roles/ufw/tasks/enable.yml new file mode 100644 index 0000000..e346da3 --- /dev/null +++ b/roles/ufw/tasks/enable.yml @@ -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 diff --git a/roles/ufw/tasks/install.yml b/roles/ufw/tasks/install.yml new file mode 100644 index 0000000..606a728 --- /dev/null +++ b/roles/ufw/tasks/install.yml @@ -0,0 +1,6 @@ +--- +- name: Install ufw + become: true + ansible.builtin.package: + name: "{{ ufw_package_name }}" + state: present diff --git a/roles/ufw/tasks/main.yml b/roles/ufw/tasks/main.yml new file mode 100644 index 0000000..7926dcd --- /dev/null +++ b/roles/ufw/tasks/main.yml @@ -0,0 +1,52 @@ +--- +# Stray variable guard: the role does not discover rules by variable name, so a variable +# named like _ufw_rules / _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' _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] diff --git a/roles/ufw/tasks/orphan_rules.yml b/roles/ufw/tasks/orphan_rules.yml new file mode 100644 index 0000000..c5e7ea8 --- /dev/null +++ b/roles/ufw/tasks/orphan_rules.yml @@ -0,0 +1,255 @@ +--- +# 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 diff --git a/roles/ufw/tasks/rules.yml b/roles/ufw/tasks/rules.yml new file mode 100644 index 0000000..c00e59d --- /dev/null +++ b/roles/ufw/tasks/rules.yml @@ -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 diff --git a/roles/ufw/tasks/service_rules.yml b/roles/ufw/tasks/service_rules.yml new file mode 100644 index 0000000..b18578b --- /dev/null +++ b/roles/ufw/tasks/service_rules.yml @@ -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 `[:]: `, 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 diff --git a/roles/ufw/tasks/sysctl.yml b/roles/ufw/tasks/sysctl.yml new file mode 100644 index 0000000..bddbdc5 --- /dev/null +++ b/roles/ufw/tasks/sysctl.yml @@ -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) diff --git a/roles/ufw/tasks/validate.yml b/roles/ufw/tasks/validate.yml new file mode 100644 index 0000000..92bddc1 --- /dev/null +++ b/roles/ufw/tasks/validate.yml @@ -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'] diff --git a/roles/ufw/templates/before.rules.j2 b/roles/ufw/templates/before.rules.j2 new file mode 100644 index 0000000..b4d97c3 --- /dev/null +++ b/roles/ufw/templates/before.rules.j2 @@ -0,0 +1,84 @@ +{# + SPDX-License-Identifier: GPL-3.0-only + Derived from ufw conf/before.rules (https://git.launchpad.net/ufw), + Copyright 2008-2023 Canonical Ltd., GPL-3.0-only. Modified by Defame1297. +#} +# Managed by Ansible – UFW before.rules + +*filter + +:ufw-before-input - [0:0] +:ufw-before-output - [0:0] +:ufw-before-forward - [0:0] +:ufw-not-local - [0:0] + +# Allow all traffic on loopback - this file fully replaces the stock +# /etc/ufw/before.rules (which always includes this), so without it any +# fresh (non-conntrack-established) loopback connection - e.g. DNS queries +# to systemd-resolved's 127.0.0.53 stub - is silently dropped by the +# default-deny INPUT policy. +-A ufw-before-input -i lo -j ACCEPT +-A ufw-before-output -o lo -j ACCEPT + +# Allow established and related connections +-A ufw-before-input -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT +-A ufw-before-output -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT +-A ufw-before-forward -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT + +# drop INVALID packets (logs these in loglevel medium and higher) +-A ufw-before-input -m conntrack --ctstate INVALID -j ufw-logging-deny +-A ufw-before-input -m conntrack --ctstate INVALID -j DROP + +# The rules in this file mirror stock ufw's before.rules (checked against +# ufw 0.36.2); the only deviations are this file's header comments, the +# omitted stock "End required lines" markers and the aggregated rules loop +# at the end. Since this template fully replaces that file rather than +# layering on top of it, dropping the stock rules would silently break +# ping/PMTU-discovery and treat broadcast/multicast traffic as spoofed +# non-local input on every host, custom aggregated rules or not. + +# ok icmp codes for INPUT +-A ufw-before-input -p icmp --icmp-type destination-unreachable -j ACCEPT +-A ufw-before-input -p icmp --icmp-type time-exceeded -j ACCEPT +-A ufw-before-input -p icmp --icmp-type parameter-problem -j ACCEPT +-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT + +# ok icmp codes for FORWARD +-A ufw-before-forward -p icmp --icmp-type destination-unreachable -j ACCEPT +-A ufw-before-forward -p icmp --icmp-type time-exceeded -j ACCEPT +-A ufw-before-forward -p icmp --icmp-type parameter-problem -j ACCEPT +-A ufw-before-forward -p icmp --icmp-type echo-request -j ACCEPT + +# allow dhcp client to work +-A ufw-before-input -p udp --sport 67 --dport 68 -j ACCEPT + +# +# ufw-not-local +# +-A ufw-before-input -j ufw-not-local + +# if LOCAL, RETURN +-A ufw-not-local -m addrtype --dst-type LOCAL -j RETURN + +# if MULTICAST, RETURN +-A ufw-not-local -m addrtype --dst-type MULTICAST -j RETURN + +# if BROADCAST, RETURN +-A ufw-not-local -m addrtype --dst-type BROADCAST -j RETURN + +# all other non-local packets are dropped +-A ufw-not-local -m limit --limit 3/min --limit-burst 10 -j ufw-logging-deny +-A ufw-not-local -j DROP + +# allow MULTICAST mDNS for service discovery +-A ufw-before-input -p udp -d 224.0.0.251 --dport 5353 -j ACCEPT + +# allow MULTICAST UPnP for service discovery +-A ufw-before-input -p udp -d 239.255.255.250 --dport 1900 -j ACCEPT + +{% for rule in ufw_aggregated_before_rules %} +# {{ rule.comment | default('before-rule') }} +-A ufw-before-input{% if rule.interface is defined %} -i {{ rule.interface }}{% endif %}{% if rule.proto is defined %} -p {{ rule.proto }}{% endif %}{% if rule.port is defined %} --dport {{ rule.port }}{% endif %}{% if rule.from is defined %} -s {{ rule.from }}{% endif %} -j ACCEPT +{% endfor %} + +COMMIT diff --git a/roles/ufw/vars/main.yml b/roles/ufw/vars/main.yml new file mode 100644 index 0000000..2653094 --- /dev/null +++ b/roles/ufw/vars/main.yml @@ -0,0 +1,2 @@ +--- +ufw_package_name: ufw