# 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 `mortis.kamino.system_baseline` 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.system_baseline - 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.