From cf8f4b5bf091458da9416c98eb9a1269fd212f7d Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Tue, 10 Nov 2026 15:09:48 +0000 Subject: [PATCH] feat(roles): add the systemd_hardening and network_interfaces roles Copied from the environment repository's roles and scrubbed for the Collection: galaxy namespace mortis, molecule scenarios call the roles by their FQCN and take their paths from the workflow, README examples use mortis.kamino.* and documentation addresses, repository-local references (issue numbers, ADRs, inventory paths) are dropped. network_interfaces loses its Legacy name guard and the molecule play that tested it: the guard only protected the in-repo rename, and a new consumer never had the old names. mock_roles in .ansible-lint lists both FQCNs. Not verified locally: the molecule scenarios (they run on the kamino-molecule runner in CI) and ansible-test sanity. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- .ansible-lint | 2 + ...emd-hardening-network-interfaces-roles.yml | 5 + roles/network_interfaces/README.md | 60 +++++++++++ roles/network_interfaces/defaults/main.yml | 9 ++ roles/network_interfaces/handlers/main.yml | 5 + .../meta/argument_specs.yml | 80 ++++++++++++++ roles/network_interfaces/meta/main.yml | 17 +++ .../molecule/default/converge.yml | 27 +++++ .../molecule/default/molecule.yml | 26 +++++ .../molecule/default/prepare.yml | 29 +++++ .../molecule/default/verify.yml | 102 ++++++++++++++++++ roles/network_interfaces/tasks/apply.yml | 33 ++++++ roles/network_interfaces/tasks/main.yml | 9 ++ roles/network_interfaces/tasks/read.yml | 5 + roles/network_interfaces/tasks/render.yml | 9 ++ roles/network_interfaces/tasks/revert.yml | 13 +++ .../templates/interfaces.j2 | 36 +++++++ roles/systemd_hardening/README.md | 56 ++++++++++ roles/systemd_hardening/defaults/main.yml | 53 +++++++++ roles/systemd_hardening/handlers/main.yml | 6 ++ .../systemd_hardening/meta/argument_specs.yml | 53 +++++++++ roles/systemd_hardening/meta/main.yml | 21 ++++ .../molecule/default/converge.yml | 102 ++++++++++++++++++ .../molecule/default/molecule.yml | 26 +++++ .../molecule/default/prepare.yml | 31 ++++++ .../molecule/default/verify.yml | 65 +++++++++++ .../tasks/disable_services.yml | 11 ++ roles/systemd_hardening/tasks/dropins.yml | 41 +++++++ .../tasks/harden_manager.yml | 26 +++++ roles/systemd_hardening/tasks/main.yml | 57 ++++++++++ .../systemd_hardening/tasks/mask_services.yml | 10 ++ roles/systemd_hardening/templates/dropin.j2 | 19 ++++ 32 files changed, 1044 insertions(+) create mode 100644 changelogs/fragments/systemd-hardening-network-interfaces-roles.yml create mode 100644 roles/network_interfaces/README.md create mode 100644 roles/network_interfaces/defaults/main.yml create mode 100644 roles/network_interfaces/handlers/main.yml create mode 100644 roles/network_interfaces/meta/argument_specs.yml create mode 100644 roles/network_interfaces/meta/main.yml create mode 100644 roles/network_interfaces/molecule/default/converge.yml create mode 100644 roles/network_interfaces/molecule/default/molecule.yml create mode 100644 roles/network_interfaces/molecule/default/prepare.yml create mode 100644 roles/network_interfaces/molecule/default/verify.yml create mode 100644 roles/network_interfaces/tasks/apply.yml create mode 100644 roles/network_interfaces/tasks/main.yml create mode 100644 roles/network_interfaces/tasks/read.yml create mode 100644 roles/network_interfaces/tasks/render.yml create mode 100644 roles/network_interfaces/tasks/revert.yml create mode 100644 roles/network_interfaces/templates/interfaces.j2 create mode 100644 roles/systemd_hardening/README.md create mode 100644 roles/systemd_hardening/defaults/main.yml create mode 100644 roles/systemd_hardening/handlers/main.yml create mode 100644 roles/systemd_hardening/meta/argument_specs.yml create mode 100644 roles/systemd_hardening/meta/main.yml create mode 100644 roles/systemd_hardening/molecule/default/converge.yml create mode 100644 roles/systemd_hardening/molecule/default/molecule.yml create mode 100644 roles/systemd_hardening/molecule/default/prepare.yml create mode 100644 roles/systemd_hardening/molecule/default/verify.yml create mode 100644 roles/systemd_hardening/tasks/disable_services.yml create mode 100644 roles/systemd_hardening/tasks/dropins.yml create mode 100644 roles/systemd_hardening/tasks/harden_manager.yml create mode 100644 roles/systemd_hardening/tasks/main.yml create mode 100644 roles/systemd_hardening/tasks/mask_services.yml create mode 100644 roles/systemd_hardening/templates/dropin.j2 diff --git a/.ansible-lint b/.ansible-lint index 4141e2e..7ac0883 100644 --- a/.ansible-lint +++ b/.ansible-lint @@ -15,3 +15,5 @@ exclude_paths: mock_roles: - mortis.kamino.docker - mortis.kamino.fail2ban + - mortis.kamino.network_interfaces + - mortis.kamino.systemd_hardening diff --git a/changelogs/fragments/systemd-hardening-network-interfaces-roles.yml b/changelogs/fragments/systemd-hardening-network-interfaces-roles.yml new file mode 100644 index 0000000..c222448 --- /dev/null +++ b/changelogs/fragments/systemd-hardening-network-interfaces-roles.yml @@ -0,0 +1,5 @@ +minor_changes: + - network_interfaces - New role. Renders /etc/network/interfaces from a layout of manual + interfaces and bridges, validates it with ifreload and restores the backup if validation fails. + - systemd_hardening - New role. Disables and masks risky services per system type, writes a + systemd manager hardening drop-in and renders opt-in per-service sandboxing drop-ins. diff --git a/roles/network_interfaces/README.md b/roles/network_interfaces/README.md new file mode 100644 index 0000000..6ff0fb3 --- /dev/null +++ b/roles/network_interfaces/README.md @@ -0,0 +1,60 @@ +# network_interfaces + +Renders `/etc/network/interfaces` from a list of manual interfaces and bridges, validates it with `ifreload`, and restores the backup if validation fails. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. + +## Supported platforms + +Debian-based hosts using `ifupdown2` (`ifreload`), such as Proxmox hosts. The molecule scenario (`molecule/default/`, CI only) runs on Ubuntu 24.04 without `ifupdown2`: the validate and reload commands are stubs, so it tests the rendered file, the backup, the single reload and the restore after a failing validation. It does not test `ifreload`, so no Debian release or `ifupdown2` version is verified by a test. + +## Requirements and run order + +- `ifupdown2` must be installed, because the validate and apply commands call `ifreload`. +- Use it by its fully qualified name, `mortis.kamino.network_interfaces`. +- Run it with `serial: 1` and the most important host last, so a bad change is caught on another host first. It rewrites the host's network configuration, so run it before roles that depend on the network. +- Gathered facts are not read. The tasks use `become` where they write. +- `network_interfaces_layout` normally comes from inventory (group_vars or host_vars), so each host can have its own layout. + +## Role variables + +| Variable | Default | Required | Description | +|---|---|---|---| +| `network_interfaces_layout` | `manual: []`, `bridges: []` | no | `manual` is a list of interface names. `bridges` is a list of mappings with `name`, `method`, `address`, `netmask`, `gateway`, `ports`, `stp`, `fd`, `vlan_aware`, `vlan_ids`. | +| `network_interfaces_file` | `/etc/network/interfaces` | no | File rewritten. | +| `network_interfaces_backup` | `/etc/network/interfaces.bak` | no | Backup path. | +| `network_interfaces_validate_command` | `ifreload -s -a` | no | Validation command. | +| `network_interfaces_apply_command` | `ifreload -a` | no | Reload command, run by the handler. | + +The `address` sub-option is typed `raw` in the spec so that an inventory can template it, for example from `ansible_host`. + +## Tags + +None. The role does not tag its tasks, so only a play-level tag applies. + +## Example play + +```yaml +- hosts: hypervisors + serial: 1 + roles: + - role: mortis.kamino.network_interfaces + vars: + network_interfaces_layout: + manual: [nic0, nic1] + bridges: + - name: vmbr0 + method: static + address: 192.0.2.10 + netmask: 255.255.255.0 + gateway: 192.0.2.1 + ports: nic0 + vlan_aware: true +``` + +## Notes + +- The template replaces the whole file: any stanza not described by `network_interfaces_layout` is dropped. Interfaces carried by other consumers (for example a bridge that carries a router VM's WAN) must be listed. +- Only a content difference triggers work. Idempotent runs change nothing. +- On change the order is: copy the current file to `network_interfaces_backup`, write the new file (notifies `Reload Interfaces`), run the validate command, flush handlers. Any failure in that block restores the backup and fails with "Invalid network configuration detected. Previous config restored." The restore does not reload the interfaces. +- The validate command runs after the file is written, and the reload runs right after it. A configuration that passes validation but breaks connectivity is not detected. +- With `method: static`, `address` and `netmask` are required by the template. +- `no_log` is not used: the role handles no secrets. diff --git a/roles/network_interfaces/defaults/main.yml b/roles/network_interfaces/defaults/main.yml new file mode 100644 index 0000000..9f48b6a --- /dev/null +++ b/roles/network_interfaces/defaults/main.yml @@ -0,0 +1,9 @@ +--- +network_interfaces_layout: + manual: [] + bridges: [] +network_interfaces_file: /etc/network/interfaces +network_interfaces_backup: /etc/network/interfaces.bak + +network_interfaces_validate_command: "ifreload -s -a" +network_interfaces_apply_command: "ifreload -a" diff --git a/roles/network_interfaces/handlers/main.yml b/roles/network_interfaces/handlers/main.yml new file mode 100644 index 0000000..10038b3 --- /dev/null +++ b/roles/network_interfaces/handlers/main.yml @@ -0,0 +1,5 @@ +--- +- name: Reload Interfaces + become: true + ansible.builtin.command: "{{ network_interfaces_apply_command }}" + changed_when: true diff --git a/roles/network_interfaces/meta/argument_specs.yml b/roles/network_interfaces/meta/argument_specs.yml new file mode 100644 index 0000000..2fbc0f3 --- /dev/null +++ b/roles/network_interfaces/meta/argument_specs.yml @@ -0,0 +1,80 @@ +--- +argument_specs: + main: + short_description: Manage /etc/network/interfaces + description: + - >- + Reads the interfaces file, renders it from C(network_interfaces_layout), and when the content differs backs up the current file, writes the new + one, validates it and reloads. A failed validation restores the backup and fails the play. + - Needs C(ifupdown2), because validation and reload use C(ifreload). + options: + network_interfaces_layout: + type: dict + default: {manual: [], bridges: []} + description: + - >- + Desired network layout. The file is fully replaced with a loopback stanza, one C(iface inet manual) per C(manual) entry and one + stanza per bridge. Both keys are optional when the variable is set. + options: + manual: + type: list + elements: str + description: Interface names configured as C(inet manual), without C(auto). + bridges: + type: list + elements: dict + description: Bridges, rendered in order with C(auto ). + options: + name: + type: str + required: true + description: Bridge name, for example C(vmbr0). + method: + type: str + description: Address method. The template default is C(manual). With C(static), C(address) and C(netmask) are read unconditionally. + address: + type: raw + description: >- + IP address, only used when C(method) is C(static). Typed raw so that an inventory can template it, for + example from C(ansible_host). + netmask: + type: str + description: Netmask, only used when C(method) is C(static). + gateway: + type: str + description: Default gateway, only used when C(method) is C(static) and the key is present. + ports: + type: str + description: Value of C(bridge_ports). The template default is C(none). + stp: + type: str + description: Value of C(bridge_stp). The template default is C(off). Quote C("off"), because unquoted YAML turns it into a boolean. + fd: + type: raw + description: Value of C(bridge_fd), written only when C(stp) is not C(off). The template default is 2. + vlan_aware: + type: bool + description: Adds C(bridge_vlan_aware yes) and C(bridge_vids). The template default is false. + vlan_ids: + type: str + description: Value of C(bridge_vids) when C(vlan_aware) is true. The template default is C(2-4094). + network_interfaces_file: + type: path + default: /etc/network/interfaces + description: + - File that is read, compared and rewritten. + network_interfaces_backup: + type: path + default: /etc/network/interfaces.bak + description: + - Where the current file is copied before it is replaced, and restored from when validation fails. + network_interfaces_validate_command: + type: str + default: ifreload -s -a + description: + - Command run after the new file is written, in syntax-check mode. A failure triggers the restore. + network_interfaces_apply_command: + type: str + default: ifreload -a + description: + - Command run by the C(Reload Interfaces) handler, which the role flushes right after validation. diff --git a/roles/network_interfaces/meta/main.yml b/roles/network_interfaces/meta/main.yml new file mode 100644 index 0000000..ab3eb61 --- /dev/null +++ b/roles/network_interfaces/meta/main.yml @@ -0,0 +1,17 @@ +--- +galaxy_info: + role_name: network_interfaces + namespace: mortis + author: Defame1297 + license: GPL-3.0-or-later + description: Render /etc/network/interfaces for Proxmox hosts from manual and bridge definitions, validate with ifreload and restore the backup on failure. + min_ansible_version: "2.19" + platforms: + - name: Debian + versions: + - all + galaxy_tags: + - network + - bridge + - proxmox +dependencies: [] diff --git a/roles/network_interfaces/molecule/default/converge.yml b/roles/network_interfaces/molecule/default/converge.yml new file mode 100644 index 0000000..b8fc208 --- /dev/null +++ b/roles/network_interfaces/molecule/default/converge.yml @@ -0,0 +1,27 @@ +--- +# ifupdown2 and its ifreload are not in the image, and a real reload could cut the +# container's own network, so the validate command is `true` and the apply command appends +# to a marker file. The role itself (read, render, compare, back up, write, validate, +# flush handlers) runs unchanged. +- name: Converge the role with a layout of manual interfaces and bridges + hosts: all + gather_facts: false + vars: + network_interfaces_validate_command: /bin/true + network_interfaces_apply_command: '/bin/sh -c "echo reloaded >> /var/tmp/network-interfaces-reload.log"' + network_interfaces_layout: + manual: [eno1] + bridges: + - name: vmbr0 + method: static + address: 10.0.0.2 + netmask: 255.255.255.0 + gateway: 10.0.0.1 + ports: eno1 + stp: "off" + vlan_aware: true + - name: vmbr1 + stp: "on" + fd: 5 + roles: + - role: mortis.kamino.network_interfaces diff --git a/roles/network_interfaces/molecule/default/molecule.yml b/roles/network_interfaces/molecule/default/molecule.yml new file mode 100644 index 0000000..e8380d5 --- /dev/null +++ b/roles/network_interfaces/molecule/default/molecule.yml @@ -0,0 +1,26 @@ +--- +# 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: network-interfaces-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 diff --git a/roles/network_interfaces/molecule/default/prepare.yml b/roles/network_interfaces/molecule/default/prepare.yml new file mode 100644 index 0000000..c3c1cbc --- /dev/null +++ b/roles/network_interfaces/molecule/default/prepare.yml @@ -0,0 +1,29 @@ +--- +# The role slurps the interfaces file before it compares, so the file must exist, and the +# image has no /etc/network. Both files get a legacy body that differs from anything the +# template renders, so the converge has a change to make and a backup to take. +- name: Prepare + hosts: all + gather_facts: false + tasks: + - name: Create /etc/network + ansible.builtin.file: + path: /etc/network + state: directory + owner: root + group: root + mode: "0755" + + - name: Seed the interfaces files with a legacy body + ansible.builtin.copy: + dest: "{{ item }}" + content: | + # legacy seed + auto lo + iface lo inet loopback + owner: root + group: root + mode: "0644" + loop: + - /etc/network/interfaces + - /etc/network/interfaces.rollback diff --git a/roles/network_interfaces/molecule/default/verify.yml b/roles/network_interfaces/molecule/default/verify.yml new file mode 100644 index 0000000..250c34c --- /dev/null +++ b/roles/network_interfaces/molecule/default/verify.yml @@ -0,0 +1,102 @@ +--- +# The rendered file, the backup of the legacy body and the single reload. The last play is the +# role's lock-out protection: a failing validation must put the previous file back. It +# changes the container, so it lives here and not in converge.yml, where the idempotence +# run would see it change twice. It works on its own copy of the file. +- name: Verify the converged layout + hosts: all + gather_facts: false + tasks: + - name: Read the interfaces file, its backup and the reload marker + ansible.builtin.slurp: + src: "{{ item }}" + loop: + - /etc/network/interfaces + - /etc/network/interfaces.bak + - /var/tmp/network-interfaces-reload.log + register: network_interfaces_verify_files + + - name: The file holds the loopback, the manual interface and both bridges + ansible.builtin.assert: + that: + - lines is contains('iface lo inet loopback') + - lines is contains('iface eno1 inet manual') + - lines is contains('auto vmbr0') + - lines is contains('iface vmbr0 inet static') + - lines is contains(' address 10.0.0.2') + - lines is contains(' netmask 255.255.255.0') + - lines is contains(' gateway 10.0.0.1') + - lines is contains(' bridge_ports eno1') + - lines is contains(' bridge_stp off') + - lines is contains(' bridge_vlan_aware yes') + - lines is contains(' bridge_vids 2-4094') + - lines is contains('auto vmbr1') + - lines is contains('iface vmbr1 inet manual') + - lines is contains(' bridge_ports none') + - lines is contains(' bridge_stp on') + - lines is contains(' bridge_fd 5') + - lines | select('search', 'bridge_fd') | list | length == 1 + - lines | select('search', 'bridge_vlan_aware') | list | length == 1 + - "'legacy seed' not in content" + quiet: true + vars: + content: "{{ network_interfaces_verify_files.results[0].content | b64decode }}" + lines: "{{ content.split('\n') }}" + + - name: The backup is the legacy body and the reload ran once + ansible.builtin.assert: + that: + - "'# legacy seed' in (network_interfaces_verify_files.results[1].content | b64decode)" + - "'vmbr0' not in (network_interfaces_verify_files.results[1].content | b64decode)" + - (network_interfaces_verify_files.results[2].content | b64decode).split('\n') | select | list | length == 1 + quiet: true + +- name: A failing validation restores the previous file + hosts: all + gather_facts: false + vars: + network_interfaces_file: /etc/network/interfaces.rollback + network_interfaces_backup: /etc/network/interfaces.rollback.bak + network_interfaces_validate_command: /bin/false + # A handler notified by the write is still pending when the block is rescued, and it + # runs at the end of the play, so it must not touch the reload marker. + network_interfaces_apply_command: /bin/true + network_interfaces_layout: + manual: [eno1] + bridges: + - name: vmbr9 + tasks: + - name: Read the file before + ansible.builtin.slurp: + src: /etc/network/interfaces.rollback + register: network_interfaces_verify_before + + - name: Apply the role with a validation that fails + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.network_interfaces + - name: Fail when the invalid configuration was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The role reverted and refused + ansible.builtin.assert: + that: "'Previous config restored' in ansible_failed_result.msg | default('')" + quiet: true + + - name: Read the file and the backup after + ansible.builtin.slurp: + src: "{{ item }}" + loop: + - /etc/network/interfaces.rollback + - /etc/network/interfaces.rollback.bak + register: network_interfaces_verify_after + + - name: The previous file is back and the bad one is gone + ansible.builtin.assert: + that: + - network_interfaces_verify_after.results[0].content == network_interfaces_verify_before.content + - network_interfaces_verify_after.results[1].content == network_interfaces_verify_before.content + - "'vmbr9' not in (network_interfaces_verify_after.results[0].content | b64decode)" + quiet: true diff --git a/roles/network_interfaces/tasks/apply.yml b/roles/network_interfaces/tasks/apply.yml new file mode 100644 index 0000000..b5d4a83 --- /dev/null +++ b/roles/network_interfaces/tasks/apply.yml @@ -0,0 +1,33 @@ +--- +- name: Apply network configuration safely + become: true + when: network_interfaces_changed + block: + - name: Backup current interfaces file + ansible.builtin.copy: + src: "{{ network_interfaces_file }}" + dest: "{{ network_interfaces_backup }}" + remote_src: true + owner: root + group: root + mode: "0644" + + - name: Write new interfaces configuration + ansible.builtin.copy: + content: "{{ network_interfaces_rendered }}" + dest: "{{ network_interfaces_file }}" + owner: root + group: root + mode: "0644" + notify: Reload Interfaces + + - name: Validate network configuration + ansible.builtin.command: "{{ network_interfaces_validate_command }}" + changed_when: false + + - name: Trigger network reload + ansible.builtin.meta: flush_handlers + + rescue: + - name: Revert interfaces + ansible.builtin.import_tasks: revert.yml diff --git a/roles/network_interfaces/tasks/main.yml b/roles/network_interfaces/tasks/main.yml new file mode 100644 index 0000000..19857e9 --- /dev/null +++ b/roles/network_interfaces/tasks/main.yml @@ -0,0 +1,9 @@ +--- +- name: Read current network configuration + ansible.builtin.import_tasks: read.yml + +- name: Render desired network configuration + ansible.builtin.import_tasks: render.yml + +- name: Apply network configuration if changed + ansible.builtin.import_tasks: apply.yml diff --git a/roles/network_interfaces/tasks/read.yml b/roles/network_interfaces/tasks/read.yml new file mode 100644 index 0000000..dd72571 --- /dev/null +++ b/roles/network_interfaces/tasks/read.yml @@ -0,0 +1,5 @@ +--- +- name: Read current interfaces config + ansible.builtin.slurp: + src: "{{ network_interfaces_file }}" + register: network_interfaces_current diff --git a/roles/network_interfaces/tasks/render.yml b/roles/network_interfaces/tasks/render.yml new file mode 100644 index 0000000..6d3e8cc --- /dev/null +++ b/roles/network_interfaces/tasks/render.yml @@ -0,0 +1,9 @@ +--- +- name: Render interfaces template + ansible.builtin.set_fact: + network_interfaces_rendered: "{{ lookup('template', 'interfaces.j2') }}" + +- name: Detect interface configuration changes + ansible.builtin.set_fact: + network_interfaces_changed: >- + {{ network_interfaces_rendered != (network_interfaces_current.content | b64decode) }} diff --git a/roles/network_interfaces/tasks/revert.yml b/roles/network_interfaces/tasks/revert.yml new file mode 100644 index 0000000..a536986 --- /dev/null +++ b/roles/network_interfaces/tasks/revert.yml @@ -0,0 +1,13 @@ +--- +- name: Restore previous interfaces configuration + ansible.builtin.copy: + src: "{{ network_interfaces_backup }}" + dest: "{{ network_interfaces_file }}" + remote_src: true + owner: root + group: root + mode: "0644" + +- name: Abort due to invalid network configuration + ansible.builtin.fail: + msg: "Invalid network configuration detected. Previous config restored." diff --git a/roles/network_interfaces/templates/interfaces.j2 b/roles/network_interfaces/templates/interfaces.j2 new file mode 100644 index 0000000..8cd1136 --- /dev/null +++ b/roles/network_interfaces/templates/interfaces.j2 @@ -0,0 +1,36 @@ +# Managed by Ansible – DO NOT EDIT + +# Loopback +auto lo +iface lo inet loopback + +# Manual interfaces +{% for iface in network_interfaces_layout.manual | default([]) %} +iface {{ iface }} inet manual +{% endfor %} + +# Bridges +{% for br in network_interfaces_layout.bridges | default([]) %} +auto {{ br.name }} +iface {{ br.name }} inet {{ br.method | default('manual') }} +{% if br.method | default('manual') == 'static' %} + address {{ br.address }} + netmask {{ br.netmask }} +{% if br.gateway is defined %} + gateway {{ br.gateway }} +{% endif %} +{% endif %} +{% if br.ports is defined %} + bridge_ports {{ br.ports }} +{% else %} + bridge_ports none +{% endif %} + bridge_stp {{ br.stp | default('off') }} +{% if br.stp | default('off') != 'off' %} + bridge_fd {{ br.fd | default(2) }} +{% endif %} +{% if br.vlan_aware | default(false) %} + bridge_vlan_aware yes + bridge_vids {{ br.vlan_ids | default('2-4094') }} +{% endif %} +{% endfor %} diff --git a/roles/systemd_hardening/README.md b/roles/systemd_hardening/README.md new file mode 100644 index 0000000..74e07a3 --- /dev/null +++ b/roles/systemd_hardening/README.md @@ -0,0 +1,56 @@ +# systemd_hardening + +Disables and masks risky services, writes a systemd manager hardening drop-in and renders opt-in per-service sandboxing drop-ins. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. + +## Supported platforms + +Hosts with systemd and `systemctl list-unit-files`: Ubuntu 24.04 (noble) LXCs, Ubuntu 22.04 (jammy) VMs and Debian 13 (trixie) Proxmox hosts. The role is applied to the three system types in `systemd_hardening_profiles`: `pve` (Proxmox hosts), `ubuntu_lxc` and `ubuntu_vm`. The molecule scenario (`molecule/default/`, CI only) runs the `ubuntu_lxc` profile on Ubuntu 24.04 against stub unit files, because the test image installs none of the services the role disables or masks. It checks the disable and mask results, the manager and service drop-ins (loaded by systemd after the reload) and the refusals; it cannot show that a real `rpcbind` or similar stops. The `pve` and `ubuntu_vm` profiles and Ubuntu 22.04 and Debian 13 are not verified by a test. + +## Requirements and run order + +- `systemd_hardening_system_type` is required and has no default (the role does not read a global such as `system_type`; map it in the inventory). The role fails if it is undefined or not a key of `systemd_hardening_profiles`. +- Use it by its fully qualified name, `mortis.kamino.systemd_hardening`. +- Run it after your baseline role and before the roles that manage firewalls and jails. +- Needs privilege escalation: tasks use `become`. + +## Role variables + +Two variables below, `systemd_hardening_disable_services_extra` and `systemd_hardening_disable_services_effective`, are deliberately not in the spec: their defaults index the profile by `systemd_hardening_system_type`, and the spec is templated before the role's assert runs, so an invalid `systemd_hardening_system_type` would otherwise fail with a templating error instead of the role's own message. + +| Variable | Default | Required | Description | +|---|---|---|---| +| `systemd_hardening_system_type` | none | yes | Profile key. Every play that includes the role sets it. | +| `systemd_hardening_profiles` | `pve`, `ubuntu_lxc`, `ubuntu_vm` profiles | no | Per type `disable_services_extra`. Overriding replaces all profiles. | +| `systemd_hardening_disable_services` | `rpcbind`, `avahi-daemon`, `cups`, `bluetooth`, `nfs-server` | no | Disabled on every type. | +| `systemd_hardening_disable_services_extra` | profile entry for `systemd_hardening_system_type` | no | Added to the list above. | +| `systemd_hardening_disable_services_effective` | base plus extra | no | Result, do not set. | +| `systemd_hardening_mask_services` | `telnet`, `rsh`, `rlogin`, `xinetd` | no | Masked. | +| `systemd_hardening_services` | `{}` | no | Unit to directive map for drop-ins. | + +## Tags + +Only `always` (the `systemd_hardening_system_type` assert) works as intended. `disable`, `mask`, `harden-manager` and `dropins` sit on the `include_tasks` lines in `tasks/main.yml`, and tags on a dynamic include select only the include itself: the included tasks are untagged, so they are skipped. `--tags disable` or `--tags mask` therefore runs only the assert and the unit listing, and `--tags harden-manager` or `--tags dropins` runs only the assert. Do not use these tags for selective runs; run the role untagged. + +## Example play + +```yaml +- name: Harden LXC services + hosts: lxc_guests + vars: + systemd_hardening_system_type: ubuntu_lxc + roles: + - role: mortis.kamino.systemd_hardening + vars: + systemd_hardening_services: + myservice: + ProtectSystem: strict + NoNewPrivileges: true +``` + +## Notes + +- Only units that appear in `systemctl list-unit-files --type=service` are disabled or masked, with or without the `.service` suffix. +- The manager drop-in (`DefaultLimitNOFILE`, `DefaultLimitNPROC`, `DefaultLimitCORE`, and task, memory and CPU accounting) is written verbatim by `tasks/harden_manager.yml` and has no variable. +- Drop-in and manager changes notify `systemd reload`, which runs `daemon-reload`. Handlers are flushed at the end of the role. +- Policy lives in defaults, not `vars/`, so group_vars and host_vars can override it. +- `no_log` is not used: the role handles no secrets. diff --git a/roles/systemd_hardening/defaults/main.yml b/roles/systemd_hardening/defaults/main.yml new file mode 100644 index 0000000..c0925e6 --- /dev/null +++ b/roles/systemd_hardening/defaults/main.yml @@ -0,0 +1,53 @@ +--- +# Per-systemd_hardening_system_type policy. Overridable from group_vars/host_vars: set +# systemd_hardening_disable_services_extra (replaces the list for every type in that scope), or +# override systemd_hardening_profiles (replaces ALL profiles, so copy the ones you +# keep). Not in vars/ or include_vars: both outrank group_vars and host_vars. +systemd_hardening_profiles: + pve: + disable_services_extra: [] + ubuntu_lxc: + # Not present or not meaningful in an LXC + disable_services_extra: + - systemd-journal-remote + ubuntu_vm: + disable_services_extra: + - multipathd + +# Default services to disable globally +systemd_hardening_disable_services: + - rpcbind + - avahi-daemon + - cups + - bluetooth + - nfs-server + +# Added to the list above for this systemd_hardening_system_type. Lazy (read at use), no set_fact, +# so a group_vars override of the flat name wins. +systemd_hardening_disable_services_extra: "{{ systemd_hardening_profiles[systemd_hardening_system_type].disable_services_extra }}" + +# What the role actually disables: base + extra. Read-only result, do not set. +systemd_hardening_disable_services_effective: "{{ systemd_hardening_disable_services + systemd_hardening_disable_services_extra }}" + +# High-risk services to mask completely (security policy) +systemd_hardening_mask_services: + - telnet + - rsh + - rlogin + - xinetd + +# Per-service hardening overrides (opt-in) +# Map of -> {Directive: value}. Values render as: +# booleans -> yes/no, lists -> space-joined, everything else as-is. +# Example: +# systemd_hardening_services: +# myservice: +# ProtectSystem: "strict" +# NoNewPrivileges: true +# +# Do NOT add ssh/sshd here. Sandboxing directives on sshd.service +# (ProtectSystem, PrivateTmp, NoNewPrivileges, ...) are inherited by every +# SSH login session and everything spawned from it, including sudo. That +# makes admin and Ansible sessions see a read-only filesystem / private /tmp +# and can break privilege escalation. Harden sshd via the sshd role instead. +systemd_hardening_services: {} diff --git a/roles/systemd_hardening/handlers/main.yml b/roles/systemd_hardening/handlers/main.yml new file mode 100644 index 0000000..56e5f61 --- /dev/null +++ b/roles/systemd_hardening/handlers/main.yml @@ -0,0 +1,6 @@ +--- +- name: Reload systemd daemon + become: true + ansible.builtin.systemd: + daemon_reload: true + listen: "systemd reload" diff --git a/roles/systemd_hardening/meta/argument_specs.yml b/roles/systemd_hardening/meta/argument_specs.yml new file mode 100644 index 0000000..9381667 --- /dev/null +++ b/roles/systemd_hardening/meta/argument_specs.yml @@ -0,0 +1,53 @@ +--- +argument_specs: + main: + short_description: Harden systemd for a system type + description: + - >- + Validates C(systemd_hardening_system_type) against C(systemd_hardening_profiles), then disables the unwanted services and masks the high-risk + services that have an installed unit file, writes C(/etc/systemd/system.conf.d/hardening.conf) and renders a drop-in for every + unit in C(systemd_hardening_services). + - Units that are not installed are skipped. Handlers are flushed at the end of the role. + - >- + The role also reads C(systemd_hardening_disable_services_extra) (default is the profile entry for C(systemd_hardening_system_type)) and the + derived C(systemd_hardening_disable_services_effective) (the base list plus the extra list, a result, do not set it). They are + deliberately not listed as options because their defaults index C(systemd_hardening_profiles[systemd_hardening_system_type]) and would fail + argument validation on an invalid C(systemd_hardening_system_type), ahead of the role's own assert. Overriding the extra list replaces it for + every system type in that scope. + options: + systemd_hardening_system_type: + type: str + required: true + description: + - >- + Selects the entry in C(systemd_hardening_profiles). The role default of C(systemd_hardening_disable_services_extra) reads it, and + tasks/main.yml asserts that it is a key of C(systemd_hardening_profiles) (C(pve), C(ubuntu_lxc) or C(ubuntu_vm) by default). + - Not restricted by C(choices) so that the assert keeps its own message. + systemd_hardening_profiles: + type: dict + description: + - >- + Per system type policy. Each profile holds C(disable_services_extra), a list of unit names. The role default has C(pve) (empty), + C(ubuntu_lxc) (C(systemd-journal-remote)) and C(ubuntu_vm) (C(multipathd)). + - Overriding it replaces all profiles, so copy the ones you keep. + systemd_hardening_disable_services: + type: list + elements: str + default: [rpcbind, avahi-daemon, cups, bluetooth, nfs-server] + description: + - Services stopped and disabled on every system type, with or without the C(.service) suffix. Only installed units are touched. + systemd_hardening_mask_services: + type: list + elements: str + default: [telnet, rsh, rlogin, xinetd] + description: + - Services masked and stopped. Only installed units are touched. + systemd_hardening_services: + type: dict + default: {} + description: + - >- + Opt-in drop-ins, a mapping of unit name without C(.service) to a mapping of directive to value. Written to + C(/etc/systemd/system/.service.d/hardening.conf). Booleans render as yes or no, lists are space-joined, anything else as is. + - Each value must itself be a mapping, otherwise the role fails before writing anything. + - Do not add C(ssh) or C(sshd). Sandboxing directives on sshd.service are inherited by every login session, including sudo. diff --git a/roles/systemd_hardening/meta/main.yml b/roles/systemd_hardening/meta/main.yml new file mode 100644 index 0000000..f31eb32 --- /dev/null +++ b/roles/systemd_hardening/meta/main.yml @@ -0,0 +1,21 @@ +--- +galaxy_info: + role_name: systemd_hardening + namespace: mortis + author: Defame1297 + license: GPL-3.0-or-later + description: Disable and mask risky services per system type, harden the systemd manager and apply opt-in per-service sandboxing drop-ins. + min_ansible_version: "2.19" + platforms: + - name: Ubuntu + versions: + - jammy + - noble + - name: Debian + versions: + - trixie + galaxy_tags: + - systemd + - hardening + - security +dependencies: [] diff --git a/roles/systemd_hardening/molecule/default/converge.yml b/roles/systemd_hardening/molecule/default/converge.yml new file mode 100644 index 0000000..c389edc --- /dev/null +++ b/roles/systemd_hardening/molecule/default/converge.yml @@ -0,0 +1,102 @@ +--- +# The production LXC profile with one opt-in drop-in. The stub units come from prepare.yml. +- name: Converge the role with a valid profile + hosts: all + vars: + systemd_hardening_system_type: ubuntu_lxc + systemd_hardening_services: + testsvc: + ProtectSystem: strict + NoNewPrivileges: true + ReadWritePaths: [/var/tmp, /run] + LimitNOFILE: 1024 + roles: + - role: mortis.kamino.systemd_hardening + +# The plays below are refusals. The missing and unknown system types stop before the role +# changes anything. The malformed drop-in plays fail at dropins.yml, after the disable, mask +# and manager drop-in tasks ran, but those are no-ops after the converge above, so the +# idempotence run stays clean. A sentinel in the failure message tells "the role refused" +# from "the fail task after the role ran", which a bare rescue cannot. +- name: A run without systemd_hardening_system_type is refused + hosts: all + gather_facts: false + tasks: + - name: Apply the role without a system type + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the missing type was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The role refused the run + ansible.builtin.assert: + that: "'missing required arguments' in ansible_failed_result.msg | default('')" + quiet: true + +- name: An unknown system type is refused + hosts: all + gather_facts: false + vars: + systemd_hardening_system_type: not_a_type + tasks: + - name: Apply the role with an unknown type + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the unknown type was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The profile check stopped the play + ansible.builtin.assert: + that: "'is invalid' in ansible_failed_result.msg | default('')" + quiet: true + +- name: A drop-in entry that is not a mapping is refused + hosts: all + gather_facts: false + vars: + systemd_hardening_system_type: ubuntu_lxc + systemd_hardening_services: + testsvc: not-a-mapping + tasks: + - name: Apply the role with a malformed drop-in + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the malformed drop-in was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The drop-in validation stopped the play + ansible.builtin.assert: + that: "'must be a mapping' in ansible_failed_result.msg | default('')" + quiet: true + +- name: A drop-in list that is not a mapping is refused + hosts: all + gather_facts: false + vars: + systemd_hardening_system_type: ubuntu_lxc + systemd_hardening_services: [testsvc] + tasks: + - name: Apply the role with a list instead of a mapping + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the list was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The role refused the run + ansible.builtin.assert: + that: + - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" + - "'systemd_hardening_services' in ansible_failed_result.msg | default('')" + quiet: true diff --git a/roles/systemd_hardening/molecule/default/molecule.yml b/roles/systemd_hardening/molecule/default/molecule.yml new file mode 100644 index 0000000..7b5f79b --- /dev/null +++ b/roles/systemd_hardening/molecule/default/molecule.yml @@ -0,0 +1,26 @@ +--- +# 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: systemd-hardening-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 diff --git a/roles/systemd_hardening/molecule/default/prepare.yml b/roles/systemd_hardening/molecule/default/prepare.yml new file mode 100644 index 0000000..b6e0da6 --- /dev/null +++ b/roles/systemd_hardening/molecule/default/prepare.yml @@ -0,0 +1,31 @@ +--- +# The image installs none of the services the role touches, so the units it acts on are +# stubs in /usr/lib/systemd/system (not /etc: `systemctl mask` refuses to replace a regular +# file there). Nothing is started. rpcbind is enabled so the role has something to +# disable; telnet only needs to exist; testsvc receives the drop-in. +- name: Prepare + hosts: all + gather_facts: false + tasks: + - name: Install the stub unit files + ansible.builtin.copy: + dest: "/usr/lib/systemd/system/{{ item }}.service" + content: | + [Unit] + Description=molecule stub for {{ item }} + + [Service] + ExecStart=/bin/sleep 3600 + + [Install] + WantedBy=multi-user.target + owner: root + group: root + mode: "0644" + loop: [rpcbind, telnet, testsvc] + + - name: Enable rpcbind and reload systemd + ansible.builtin.systemd: + name: rpcbind + enabled: true + daemon_reload: true diff --git a/roles/systemd_hardening/molecule/default/verify.yml b/roles/systemd_hardening/molecule/default/verify.yml new file mode 100644 index 0000000..f0ba84c --- /dev/null +++ b/roles/systemd_hardening/molecule/default/verify.yml @@ -0,0 +1,65 @@ +--- +# What the role is for: the installed risky units are disabled or masked, the manager +# drop-in is in place, and the opt-in drop-in renders and is loaded by systemd. The +# directives restate the converge vars, not the role's whole policy. +- name: Verify + hosts: all + gather_facts: false + tasks: + - name: Ask systemd about the stub units + ansible.builtin.systemd: + name: "{{ item }}.service" + loop: [rpcbind, telnet] + register: systemd_hardening_verify_units + check_mode: true + + - name: The disabled unit is disabled and the masked unit is masked + ansible.builtin.assert: + that: + - systemd_hardening_verify_units.results[0].status.UnitFileState == "disabled" + - systemd_hardening_verify_units.results[1].status.UnitFileState == "masked" + quiet: true + + - name: Read the manager drop-in + ansible.builtin.slurp: + src: /etc/systemd/system.conf.d/hardening.conf + register: systemd_hardening_verify_manager + + - name: The manager drop-in holds the limits + ansible.builtin.assert: + that: + - (systemd_hardening_verify_manager.content | b64decode).split('\n') is contains('[Manager]') + - (systemd_hardening_verify_manager.content | b64decode).split('\n') is contains('DefaultLimitNOFILE=65535') + - (systemd_hardening_verify_manager.content | b64decode).split('\n') is contains('DefaultLimitCORE=0') + quiet: true + + - name: Read the service drop-in + ansible.builtin.slurp: + src: /etc/systemd/system/testsvc.service.d/hardening.conf + register: systemd_hardening_verify_dropin + + - name: The drop-in renders booleans, lists and plain values + ansible.builtin.assert: + that: + - (systemd_hardening_verify_dropin.content | b64decode).split('\n') | select | list == systemd_hardening_verify_expected + quiet: true + vars: + systemd_hardening_verify_expected: + - "[Service]" + - ProtectSystem=strict + - NoNewPrivileges=yes + - ReadWritePaths=/var/tmp /run + - LimitNOFILE=1024 + + - name: Ask systemd about the drop-in service + ansible.builtin.systemd: + name: testsvc.service + register: systemd_hardening_verify_testsvc + check_mode: true + + - name: The daemon reload made systemd load the drop-in + ansible.builtin.assert: + that: + - systemd_hardening_verify_testsvc.status.NoNewPrivileges == "yes" + - systemd_hardening_verify_testsvc.status.ProtectSystem == "strict" + quiet: true diff --git a/roles/systemd_hardening/tasks/disable_services.yml b/roles/systemd_hardening/tasks/disable_services.yml new file mode 100644 index 0000000..6bcde21 --- /dev/null +++ b/roles/systemd_hardening/tasks/disable_services.yml @@ -0,0 +1,11 @@ +--- +- name: Disable unwanted services if present + become: true + ansible.builtin.systemd: + name: "{{ item }}" + enabled: false + state: stopped + loop: "{{ systemd_hardening_disable_services_effective }}" + # Only act on installed units; items may be given with or without the + # ".service" suffix. + when: (item | regex_replace('\.service$', '') ~ '.service') in systemd_hardening_installed_units diff --git a/roles/systemd_hardening/tasks/dropins.yml b/roles/systemd_hardening/tasks/dropins.yml new file mode 100644 index 0000000..9c2608b --- /dev/null +++ b/roles/systemd_hardening/tasks/dropins.yml @@ -0,0 +1,41 @@ +--- +- name: Apply hardening drop-ins to opted-in services + vars: + # default(..., true) also covers an explicitly empty/null override + systemd_hardening_dropin_map: "{{ systemd_hardening_services | default({}, true) }}" + block: + - name: Validate systemd_hardening_services + ansible.builtin.assert: + that: + - systemd_hardening_dropin_map is mapping + - systemd_hardening_dropin_map.values() | reject('mapping') | list | length == 0 + fail_msg: >- + systemd_hardening_services must be a mapping of unit -> mapping of + directives. + quiet: true + + - name: Create drop-in directory for service + become: true + ansible.builtin.file: + path: "/etc/systemd/system/{{ systemd_hardening_item.key }}.service.d" + state: directory + owner: root + group: root + mode: "0755" + loop: "{{ systemd_hardening_dropin_map | dict2items }}" + loop_control: + loop_var: systemd_hardening_item + notify: "systemd reload" + + - name: Create drop-in configuration + become: true + ansible.builtin.template: + src: dropin.j2 + dest: "/etc/systemd/system/{{ systemd_hardening_item.key }}.service.d/hardening.conf" + owner: root + group: root + mode: "0644" + loop: "{{ systemd_hardening_dropin_map | dict2items }}" + loop_control: + loop_var: systemd_hardening_item + notify: "systemd reload" diff --git a/roles/systemd_hardening/tasks/harden_manager.yml b/roles/systemd_hardening/tasks/harden_manager.yml new file mode 100644 index 0000000..6fafdc4 --- /dev/null +++ b/roles/systemd_hardening/tasks/harden_manager.yml @@ -0,0 +1,26 @@ +--- +- name: Ensure system.conf.d directory exists + become: true + ansible.builtin.file: + path: /etc/systemd/system.conf.d + state: directory + owner: root + group: root + mode: "0755" + +- name: Harden systemd manager (global settings) + become: true + ansible.builtin.copy: + dest: /etc/systemd/system.conf.d/hardening.conf + content: | + [Manager] + DefaultLimitNOFILE=65535 + DefaultLimitNPROC=16384 + DefaultLimitCORE=0 + DefaultTasksAccounting=yes + DefaultMemoryAccounting=yes + DefaultCPUAccounting=yes + owner: root + group: root + mode: "0644" + notify: "systemd reload" diff --git a/roles/systemd_hardening/tasks/main.yml b/roles/systemd_hardening/tasks/main.yml new file mode 100644 index 0000000..e2f13ac --- /dev/null +++ b/roles/systemd_hardening/tasks/main.yml @@ -0,0 +1,57 @@ +--- +# Required input with no default: the role does not read a global such as system_type; +# the inventory maps it onto systemd_hardening_system_type. +- name: Require systemd_hardening_system_type + ansible.builtin.assert: + that: + - systemd_hardening_system_type is defined + fail_msg: >- + systemd_hardening_system_type is required and has no default. Set it in + the play or the inventory. + tags: always + +- name: Validate systemd_hardening_system_type variable + ansible.builtin.assert: + that: + - systemd_hardening_system_type in systemd_hardening_profiles + fail_msg: >- + systemd_hardening_system_type '{{ systemd_hardening_system_type }}' is invalid. + Must be one of: {{ systemd_hardening_profiles.keys() | list | join(', ') }}. + success_msg: "systemd_hardening_system_type '{{ systemd_hardening_system_type }}' is valid." + tags: always + +# Not service_facts: it returns a fact named `services`, which (with +# inject_facts_as_vars) overrides the host_vars `services` list used by +# playbooks/install_services.yml. Only installed unit files are listed, so +# units that are merely referenced (LoadState not-found) are excluded. +- name: List installed service unit files # noqa: command-instead-of-module + become: true + ansible.builtin.command: systemctl list-unit-files --type=service --no-legend --plain + register: systemd_hardening_unit_files + changed_when: false + check_mode: false + tags: [disable, mask] + +- name: Set installed service units + ansible.builtin.set_fact: + systemd_hardening_installed_units: "{{ systemd_hardening_unit_files.stdout_lines | map('split') | map('first') | list }}" + tags: [disable, mask] + +- name: Disable unwanted services + ansible.builtin.include_tasks: disable_services.yml + tags: disable + +- name: Mask high-risk services + ansible.builtin.include_tasks: mask_services.yml + tags: mask + +- name: Harden systemd manager globally + ansible.builtin.include_tasks: harden_manager.yml + tags: harden-manager + +- name: Apply per-service drop-ins + ansible.builtin.include_tasks: dropins.yml + tags: dropins + +- name: Flush handlers early + ansible.builtin.meta: flush_handlers diff --git a/roles/systemd_hardening/tasks/mask_services.yml b/roles/systemd_hardening/tasks/mask_services.yml new file mode 100644 index 0000000..5571139 --- /dev/null +++ b/roles/systemd_hardening/tasks/mask_services.yml @@ -0,0 +1,10 @@ +--- +- name: Mask high-risk services + become: true + ansible.builtin.systemd: + name: "{{ item }}" + masked: true + state: stopped + loop: "{{ systemd_hardening_mask_services }}" + # A unit that isn't installed can't be started, so masking it is unnecessary. + when: (item | regex_replace('\.service$', '') ~ '.service') in systemd_hardening_installed_units diff --git a/roles/systemd_hardening/templates/dropin.j2 b/roles/systemd_hardening/templates/dropin.j2 new file mode 100644 index 0000000..89d6e35 --- /dev/null +++ b/roles/systemd_hardening/templates/dropin.j2 @@ -0,0 +1,19 @@ +[Service] +{# + Rendering rules (checked in this order): + - booleans -> yes/no + - real lists -> space-joined (strings are Jinja sequences too, so + they must be excluded explicitly, otherwise + "strict" renders as "s t r i c t") + - strings/numbers/etc -> rendered as-is + systemd_hardening_item.value is validated as a mapping in tasks/dropins.yml before rendering. +#} +{% for k, v in systemd_hardening_item.value.items() %} +{% if v is boolean %} +{{ k }}={{ 'yes' if v else 'no' }} +{% elif v is iterable and v is not string and v is not mapping %} +{{ k }}={{ v | join(' ') }} +{% else %} +{{ k }}={{ v }} +{% endif %} +{% endfor %} -- 2.43.0