Every public role README has the headings Supported platforms, Requirements and run order, Role variables, Entry points (when several), Variables set by the role (when any), Tags, Example play, Tests and Notes, in that order, with an "Idempotent" line in Notes. Role-specific sections move under Entry points or Notes; nothing is removed. The internal _binary_update README keeps its own headings and gains the platform and Idempotent lines. Closes #136 Assisted-by: Claude Code:claude-opus-5-5
162 lines
18 KiB
Markdown
162 lines
18 KiB
Markdown
# 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 platform the molecule scenario runs on.
|
|
|
|
Untested platforms: Ubuntu 22.04 (jammy), listed in `meta/main.yml` but not verified by a test.
|
|
|
|
Ubuntu hosts only: the role firewalls Ubuntu guests; the `pve` profile of `system_baseline` does not install ufw, so Proxmox hosts are not targeted.
|
|
|
|
## Requirements and run order
|
|
|
|
- The role uses `ansible.builtin.package` and the `community.general.ufw` module; `community.general` is a dependency of the Collection.
|
|
- 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 dependencies: none.
|
|
|
|
## 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`, `delete` (see Notes). |
|
|
| `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 `<role>_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.
|
|
|
|
## Entry points
|
|
|
|
- `main`: applies `ufw_rules` and the base configuration, as in the example play.
|
|
- `service_rules`: a service role's own rules, see [`service_rules`](#service_rules).
|
|
- `orphan_rules`: cleans up the rules of owners no longer managed, see [`orphan_rules`](#orphan_rules).
|
|
|
|
### `service_rules`
|
|
|
|
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 <role>` 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 except `delete` (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[<owner>:<key>]: <text>`. `<key>` 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). `<text>` 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 <printed line>` (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`
|
|
|
|
`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[<owner>:<key>]` 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]
|
|
```
|
|
|
|
## 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}
|
|
```
|
|
|
|
## Tests
|
|
|
|
The scenario `molecule/default/` runs in CI only, on one platform: `${MOLECULE_IMAGE}`, an Ubuntu 24.04 (noble) container with `NET_ADMIN`. The sequence runs prepare, converge, idempotence and verify; it has no check-mode step.
|
|
|
|
- Prepare installs ufw and stores rules the role must handle: an untagged manual rule, a manual rule the base list deletes, and tagged rules of service owners that are stale, removed or orphaned, some of them looking like an SSH path (port 22 with a source, no port, a range, an application profile named like SSH).
|
|
- Converge applies the base `ufw_rules` (one entry with `delete: true`), then calls `service_rules` for several owners (purge on, purge off, `absent`), and `orphan_rules` with no list, an empty list, report only and purge.
|
|
- Verify first checks that each refusal stops the run with its message and changes nothing: default deny without an SSH rule (also when the SSH rule is only deleted, or added and deleted), a stray `*_ufw_rules` or `*_ufw_before_rules` variable, the invalid `service_rules` inputs (owner name, reserved `base`, a quote in a comment, a rule another owner holds, a rule that would retag the SSH rule, an unknown key, an interface without a direction, a purge with an empty list), and an invalid managed owner for `orphan_rules`.
|
|
- Verify then reads `ufw status verbose` and `ufw show added`: ufw is active with default deny incoming, the base rules are loaded, the deleted rule is gone, the manual and SSH rules are untouched, the service rules carry their owner tag, stale and orphan rules are deleted only where purging was on and only when they cannot carry SSH.
|
|
- Verify checks `before.rules`: the loopback accept, the INVALID-state drop behind its logging rule and in its place among the input rules.
|
|
- Verify runs `service_rules` under the `check_mode` keyword and checks that the rule list did not change.
|
|
|
|
Not covered: `ufw_before_rules` entries and `ufw_sysctl_overrides` are never set, and `orphan_rules` is not run in check mode.
|
|
|
|
## Notes
|
|
|
|
- Idempotent: yes.
|
|
- 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. An entry with `delete: true` never counts.
|
|
- Replacing a base rule: list the new rule and the old one with `delete: true` (a boolean). Deletes are applied after every other rule, whatever their place in the list, so the replacement exists before the old rule goes, which matters when narrowing the SSH rule. The comment of a delete entry is not sent, so the rule matches whatever its comment, and a delete of a rule that is already gone changes nothing. An entry that deletes a rule the same list adds (same `rule`, `port`, `proto`, `from`, `to`, `interface` and `direction`, where no `direction` is `in` and no `from` or `to` is `any`) fails the play. A delete without an address removes the IPv4 and the IPv6 rule; a replacement with an IPv4 `from` allows IPv4 only, so check that the hosts you connect from are covered before narrowing SSH. `delete` is for `ufw_rules` only; `service_rules` removes its own stale rules.
|
|
- `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.
|