10 Commits
Author SHA1 Message Date
Defame1297 15e0b44364 Merge pull request 'chore(release): 1.2.0' (#79) from release/1.2.0 into main
Lint / lint (push) Successful in 16s
Molecule / molecule (push) Successful in 4m42s
Build / build (push) Successful in 10s
Reviewed-on: #79
2026-11-10 18:26:07 +00:00
Defame1297andClaude Sonnet 5.5 de68aadf9b chore(release): 1.2.0
Build / build (pull_request) Successful in 9s
Lint / lint (pull_request) Successful in 17s
Molecule / molecule (pull_request) Successful in 4m38s
Adds the network_interfaces and systemd_hardening roles. Version bump in
galaxy.yml, the changelog built by antsibull-changelog release, README pin
example and status text, CLAUDE.md.

Verified: the commit hooks. Not verified: ansible-test sanity and the
importer (CI). The tag is the maintainer's.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-11-10 18:16:40 +00:00
Defame1297 db1caa9b28 Merge pull request 'feat(roles): add the systemd_hardening and network_interfaces roles' (#78) from feat/systemd-hardening-network-interfaces-roles into main
Build / build (push) Successful in 10s
Lint / lint (push) Successful in 16s
Molecule / molecule (push) Successful in 4m42s
Reviewed-on: #78
2026-11-10 18:15:52 +00:00
Defame1297andClaude Sonnet 5.5 cf8f4b5bf0 feat(roles): add the systemd_hardening and network_interfaces roles
Build / build (pull_request) Successful in 10s
Lint / lint (pull_request) Successful in 17s
Molecule / molecule (pull_request) Successful in 4m43s
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 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-11-10 15:09:48 +00:00
kamino-renovate Bot 21dda27b00 Merge pull request 'chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.14' (#76) from renovate/git.rkdr.net-mortis-ci-0.x into main
Build / build (push) Successful in 9s
Lint / lint (push) Successful in 14s
2026-11-09 03:21:48 +00:00
renovate-bot 57f16b5129 chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.14
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 21s
Lint / lint (pull_request) Successful in 14s
Molecule / molecule (pull_request) Successful in 3m20s
2026-11-09 03:17:48 +00:00
Defame1297 e036aa8789 Merge pull request 'chore(release): 1.1.0' (#75) from release/1.1.0 into main
Lint / lint (push) Successful in 16s
Molecule / molecule (push) Successful in 3m16s
Build / build (push) Successful in 23s
Reviewed-on: #75
2026-11-08 21:36:17 +00:00
Defame1297andClaude Sonnet 5.5 ad9b07e399 chore(release): 1.1.0
Build / build (pull_request) Successful in 21s
Lint / lint (pull_request) Successful in 17s
Molecule / molecule (pull_request) Successful in 3m13s
Adds the fail2ban role. Version bump in galaxy.yml, the changelog built by
antsibull-changelog release, README pin example and status text, CLAUDE.md.

Verified: the commit hooks. Not verified: ansible-test sanity and the
importer (CI). The tag is the maintainer's.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-11-08 21:29:32 +00:00
Defame1297 565b369533 Merge pull request 'feat(fail2ban): add the fail2ban role' (#74) from feat/fail2ban-role into main
Build / build (push) Successful in 22s
Lint / lint (push) Successful in 16s
Molecule / molecule (push) Successful in 3m12s
Reviewed-on: #74
2026-11-08 21:28:33 +00:00
Defame1297andClaude Sonnet 5.5 1ea478b124 feat(fail2ban): add the fail2ban role
Build / build (pull_request) Successful in 23s
Lint / lint (pull_request) Successful in 16s
Molecule / molecule (pull_request) Successful in 3m11s
Copied from the environment repository's roles/fail2ban and scrubbed for the
Collection: galaxy namespace mortis, the molecule scenario calls the role by
its FQCN (and takes its paths from the workflow, like docker's), README
examples use mortis.kamino.fail2ban, repository-local issue references are
dropped. mock_roles in .ansible-lint lists the new FQCN.

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

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-11-08 21:20:08 +00:00
56 changed files with 1653 additions and 7 deletions

No files matched your search

+3
View File
@@ -14,3 +14,6 @@ exclude_paths:
# a scenario's converge play. List the roles the scenarios call by FQCN.
mock_roles:
- mortis.kamino.docker
- mortis.kamino.fail2ban
- mortis.kamino.network_interfaces
- mortis.kamino.systemd_hardening
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
timeout-minutes: 30
# The ci image (images/ci, built by image.yml): tag for the release, digest enforced.
container:
image: git.rkdr.net/mortis/ci:0.2.13@sha256:ada3d4723eb9930e05c6fb8874dc2e4283872ee458cb52f0fbbf23036273c3cd
image: git.rkdr.net/mortis/ci:0.2.14@sha256:301bdf3981014664aae2d2b8b283347c722980405b46c792499fcd2796890e87
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
steps:
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
# The tag says which release, the digest is what is enforced (bump both together
# when image.yml publishes a new version).
container:
image: git.rkdr.net/mortis/ci:0.2.13@sha256:ada3d4723eb9930e05c6fb8874dc2e4283872ee458cb52f0fbbf23036273c3cd
image: git.rkdr.net/mortis/ci:0.2.14@sha256:301bdf3981014664aae2d2b8b283347c722980405b46c792499fcd2796890e87
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
PRE_COMMIT_HOME: /opt/pre-commit
+17
View File
@@ -4,6 +4,23 @@ mortis.kamino Release Notes
.. contents:: Topics
v1.2.0
======
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.
v1.1.0
======
Minor Changes
-------------
- fail2ban - New role. Installs Fail2Ban, manages jail.local and the service, deploys per-service jails into jail.d.
v1.0.0
======
+1 -1
View File
@@ -6,7 +6,7 @@ Guidance for Claude Code (claude.ai/code) in this repository.
`mortis.kamino`: an Ansible Collection (GPL-3.0-or-later, REUSE-compliant), extracted role by
role from the author's homelab environment repository. The design contract is ADR 0004 (in the
maintainer's environment repository). Roles arrive here wave by wave; the first, `docker`, is in 1.0.0.
maintainer's environment repository). Roles arrive here wave by wave; `docker` is in 1.0.0, `fail2ban` in 1.1.0, `network_interfaces` and `systemd_hardening` in 1.2.0.
Fork pull requests from untrusted users are not accepted for now: a fork controls its own
workflow file, so the `if:` guards are a convenience, not a boundary (see the header of
+2 -2
View File
@@ -4,7 +4,7 @@ An Ansible Collection of reusable, hardened roles for a self-hosted home lab:
Linux baseline, firewall, SSH, user management and, in later releases, Proxmox,
Gitea and Gitea Actions runner roles.
Status: roles arrive in waves. Release 1.0.0 holds the `docker` role.
Status: roles arrive in waves. Release 1.2.0 holds the `docker`, `fail2ban`, `network_interfaces` and `systemd_hardening` roles.
## Consuming
@@ -16,7 +16,7 @@ name (FQCN) only, `mortis.kamino.<role>`:
collections:
- name: https://git.rkdr.net/mortis/kamino.git
type: git
version: v1.0.0
version: v1.2.0
```
```yaml
+13 -1
View File
@@ -4,6 +4,18 @@ objects:
description: Install, update or remove Docker Engine
name: docker
version_added: null
fail2ban:
description: Install and configure Fail2Ban
name: fail2ban
version_added: null
network_interfaces:
description: Manage /etc/network/interfaces
name: network_interfaces
version_added: null
systemd_hardening:
description: Harden systemd for a system type
name: systemd_hardening
version_added: null
plugins:
become: {}
cache: {}
@@ -20,4 +32,4 @@ plugins:
strategy: {}
test: {}
vars: {}
version: 1.0.0
version: 1.2.0
+20
View File
@@ -33,3 +33,23 @@ releases:
- release-1.0.0.yml
- scaffold.yml
release_date: '2026-11-08'
1.1.0:
changes:
minor_changes:
- fail2ban - New role. Installs Fail2Ban, manages jail.local and the service,
deploys per-service jails into jail.d.
fragments:
- fail2ban-role.yml
release_date: '2026-11-08'
1.2.0:
changes:
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.
fragments:
- systemd-hardening-network-interfaces-roles.yml
release_date: '2026-11-10'
+1 -1
View File
@@ -1,7 +1,7 @@
---
namespace: mortis
name: kamino
version: 1.0.0
version: 1.2.0
readme: README.md
authors:
- Defame1297
+73
View File
@@ -0,0 +1,73 @@
# fail2ban
Installs Fail2Ban, writes `/etc/fail2ban/jail.local` from `fail2ban_jails`, ensures the service runs and verifies the enabled jails loaded. A second entry point, `service_jail`, lets a service role deploy its own jail and filter into `jail.d`. 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. The default `sshd` jail reads the systemd journal because sshd logs there on that release. The role installs `python3-systemd`, which `backend = systemd` jails need.
## Requirements and run order
- Use it by its fully qualified name, `mortis.kamino.fail2ban`.
- No hard prerequisite. `system_baseline` also lists `fail2ban` among its packages, so it normally runs first; this role installs it regardless.
- Main entry point: apply it after `ufw` in the play that hardens a host.
- `service_jail` entry point: called by a service role such as `gitea` (`include_role` with `tasks_from: service_jail`) after it has installed the service.
- A file named by a jail's `logpath` must exist when `fail2ban-client -t` runs, or the configuration test fails.
## Role variables
Main entry point:
| Variable | Default | Required | Description |
|---|---|---|---|
| `fail2ban_package_name` | `fail2ban` | no | Package name. |
| `fail2ban_jails` | one `sshd` jail (systemd backend, maxretry 3, bantime 1h, findtime 10m) | no | Jails written to `jail.local`. Each needs `name`, `enabled`, `filter`, `maxretry`, `bantime`, `findtime` and `logpath`, `journalmatch` or `backend: systemd`. |
| `fail2ban_service` | `enabled: true`, `state: started` | no | Service enablement and state. |
| `fail2ban_defaults` | `maxretry: 5`, `bantime: 600`, `findtime: 600` | no | Fallbacks for those keys. Only used by the `service_jail` entry point; main-entry jails must set all three (`tasks/validate.yml` asserts them), so there the fallback only applies when validation is skipped, for example under `--tags fail2ban_configure`. |
`service_jail` entry point:
| Variable | Default | Required | Description |
|---|---|---|---|
| `fail2ban_service_name` | none | yes | Jail name and file name under `filter.d` and `jail.d`. |
| `fail2ban_service_jail` | none | yes | Jail mapping; needs `logpath` or `journalmatch`. |
| `fail2ban_service_filter` | none | yes | Filter mapping; needs `failregex`, optional `ignoreregex`. |
| `fail2ban_package_name`, `fail2ban_defaults` | as above | no | Read from the role defaults. |
## Tags
Main entry point: `fail2ban` (everything), `fail2ban_install`, `fail2ban_validate`, `fail2ban_configure`, `fail2ban_service`.
`service_jail`: `fail2ban`, `fail2ban_install`, `fail2ban_service_jail`.
## Example play
```yaml
- hosts: pve_lxcs
roles:
- role: mortis.kamino.fail2ban
vars:
fail2ban_defaults:
maxretry: 5
bantime: 600
findtime: 600
- hosts: gitea
tasks:
- name: Deploy a service jail
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: gitea
fail2ban_service_jail: "{{ gitea_fail2ban_jail }}"
fail2ban_service_filter: "{{ gitea_fail2ban_filter }}"
```
## Notes
- Each service owns `jail.d/<name>.local`, so one play cannot overwrite another service's jail. `jail.local` only holds `fail2ban_jails`.
- Changing `jail.local` restarts Fail2Ban, which drops the in-memory ban list. Service jails only trigger a reload.
- `fail2ban-client -t` runs on every invocation of both entry points, not only when a file changed, so a broken file fails every run until fixed. It also runs in check mode.
- `fail2ban_service_jail` and `fail2ban_service_filter` must be passed as a single templated expression so they stay mappings, not strings or lists.
- `no_log` is not used: the role handles no secrets.
+25
View File
@@ -0,0 +1,25 @@
---
fail2ban_package_name: fail2ban
fail2ban_jails:
- name: sshd
enabled: true
port: ssh
filter: sshd
# Read the journal, not /var/log/auth.log: sshd logs to the journal on
# Ubuntu 24.04 and rsyslog's auth.log stays empty. Pinned so detection does
# not depend on the package's default backend. The filter's own journalmatch
# applies.
backend: systemd
maxretry: 3
bantime: "1h"
findtime: "10m"
fail2ban_service:
enabled: true
state: started
fail2ban_defaults:
maxretry: 5
bantime: 600
findtime: 600
+17
View File
@@ -0,0 +1,17 @@
---
- name: Restart Fail2Ban
become: true
ansible.builtin.service:
name: fail2ban
state: restarted
# Service jails only add a jail.d file, so reload instead of restarting the
# daemon (a restart drops the in-memory ban list). state=reloaded starts the
# service if it is not running. The config test runs as a task in
# service_jail.yml, so a broken file fails every run instead of only the one
# that wrote it.
- name: Reload Fail2Ban
become: true
ansible.builtin.systemd:
name: fail2ban
state: reloaded
+99
View File
@@ -0,0 +1,99 @@
---
argument_specs:
main:
short_description: Install and configure Fail2Ban
description:
- >-
Installs fail2ban and python3-systemd, validates C(fail2ban_jails), writes /etc/fail2ban/jail.local, tests the
configuration, ensures the service and checks that every enabled jail is loaded.
options:
fail2ban_package_name:
type: str
default: fail2ban
description:
- Name of the Fail2Ban package.
fail2ban_jails:
type: list
elements: dict
description:
- Jails written to jail.local. The role default is a single C(sshd) jail on the systemd backend.
- >-
Each item needs C(name), C(enabled), C(filter), C(maxretry), C(bantime) and C(findtime), plus one of
C(logpath), C(journalmatch) or C(backend) set to systemd.
- Optional keys are C(port) (default any), C(backend), C(journalmatch) and C(logpath).
fail2ban_service:
type: dict
description:
- Service management. The role default is C(enabled=true), C(state=started). Missing keys fall back to those values.
- Enabled jails are only checked with fail2ban-client when state is started.
options:
enabled:
type: bool
description: Whether the service starts at boot.
state:
type: str
description: Desired systemd state of the service, for example started or stopped.
fail2ban_defaults:
type: dict
description:
- >-
Fallback C(maxretry), C(bantime) and C(findtime). The role default is 5, 600 and 600. Only used by the
service_jail entry point; main-entry jails must set all three (C(tasks/validate.yml) asserts them), so
there the fallback only applies when validation is skipped, for example under C(--tags fail2ban_configure).
options:
maxretry:
type: int
description: Fallback number of failures before a ban.
bantime:
type: raw
description: Fallback ban duration, seconds or a Fail2Ban time string.
findtime:
type: raw
description: Fallback window in which failures are counted, seconds or a Fail2Ban time string.
service_jail:
short_description: Deploy one service jail and filter into jail.d
description:
- Entry point for a service role that owns its jail, used with C(include_role) and C(tasks_from=service_jail).
- >-
Installs Fail2Ban, writes /etc/fail2ban/filter.d/<name>.conf and /etc/fail2ban/jail.d/<name>.local, reloads
Fail2Ban and tests the configuration. It never touches jail.local.
options:
fail2ban_package_name:
type: str
default: fail2ban
description:
- Name of the Fail2Ban package installed by this entry point.
fail2ban_service_name:
type: str
required: true
description:
- Service name, used as the jail section name and the file names under filter.d and jail.d.
fail2ban_service_jail:
type: raw
required: true
description:
- >-
Mapping describing the jail. Must contain C(logpath) or C(journalmatch). Optional keys are C(enabled) (default
true), C(port) (default any), C(filter) (default the service name), C(backend) (default systemd, only used
with journalmatch), C(maxretry), C(bantime) and C(findtime), which fall back to C(fail2ban_defaults).
- Typed raw because callers pass a templated variable, for example C(gitea_fail2ban_jail). It is asserted to be a mapping.
fail2ban_service_filter:
type: raw
required: true
description:
- Mapping with C(failregex) (required) and C(ignoreregex) (optional, default empty).
- Typed raw because callers pass a templated variable. It is asserted to be a mapping.
fail2ban_defaults:
type: dict
description:
- Fallback C(maxretry), C(bantime) and C(findtime), read from the role defaults.
options:
maxretry:
type: int
description: Fallback number of failures before a ban.
bantime:
type: raw
description: Fallback ban duration.
findtime:
type: raw
description: Fallback failure counting window.
+16
View File
@@ -0,0 +1,16 @@
---
galaxy_info:
role_name: fail2ban
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: Install Fail2Ban, manage jail.local and the service, and deploy per-service jails and filters into jail.d.
min_ansible_version: "2.19"
platforms:
- name: Ubuntu
versions:
- noble
galaxy_tags:
- fail2ban
- security
dependencies: []
@@ -0,0 +1,57 @@
---
- name: Converge the base role (jail.local, sshd jail on the systemd backend)
hosts: all
roles:
- role: mortis.kamino.fail2ban
# The entry point service roles use. Two services must not overwrite each other:
# each gets its own jail.d file.
- name: Converge two service jails through the entry point
hosts: all
tasks:
- name: Service jail with a logpath
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: svc-a
fail2ban_service_jail:
port: "8080"
logpath: /var/log/svc-a.log
maxretry: 4
fail2ban_service_filter:
failregex: "^.*auth failure from <HOST>.*$"
- name: Service jail with a journalmatch
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: svc-b
fail2ban_service_jail:
port: "9090"
journalmatch: "_SYSTEMD_UNIT=ssh.service"
fail2ban_service_filter:
failregex: "^.*denied for <HOST>.*$"
# An input the entry point must reject. The block proves it is refused (the
# verify step proves no file was left behind); the play still passes, so the
# idempotence run stays clean.
- name: Missing failregex is rejected
block:
- name: Service jail without a failregex
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: svc-bad
fail2ban_service_jail:
logpath: /var/log/svc-a.log
fail2ban_service_filter: {}
- name: Fail when the invalid input was accepted
ansible.builtin.fail:
msg: service_jail accepted a filter without a failregex
rescue:
- name: The entry point refused the input
ansible.builtin.debug:
msg: Rejected as expected
@@ -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: fail2ban-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
@@ -0,0 +1,13 @@
---
# The log file a service jail watches must exist, or `fail2ban-client -t` fails.
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Create the log file the logpath jail watches
ansible.builtin.file:
path: /var/log/svc-a.log
state: touch
mode: "0644"
access_time: preserve
modification_time: preserve
@@ -0,0 +1,55 @@
---
# What matters: the daemon accepts the whole configuration, loads the base jail and
# both service jails (each from its own jail.d file, #433), the sshd jail does not
# fall back to the empty auth.log, and a rejected input left nothing behind. The
# file contents are the templates' own output and are not restated here.
- name: Verify
hosts: all
gather_facts: false
tasks:
- name: Read jail.local
ansible.builtin.slurp:
src: /etc/fail2ban/jail.local
register: fail2ban_verify_jail_local
- name: The sshd jail reads the journal, not auth.log
ansible.builtin.assert:
that: "'/var/log/auth.log' not in (fail2ban_verify_jail_local.content | b64decode)"
quiet: true
- name: Stat the service jails and the rejected one
ansible.builtin.stat:
path: "{{ item }}"
loop:
- /etc/fail2ban/jail.d/svc-a.local
- /etc/fail2ban/jail.d/svc-b.local
- /etc/fail2ban/jail.d/svc-bad.local
- /etc/fail2ban/filter.d/svc-bad.conf
register: fail2ban_verify_files
- name: Each service has its own file and the rejected input left nothing behind
ansible.builtin.assert:
that:
- fail2ban_verify_files.results[0].stat.exists
- fail2ban_verify_files.results[1].stat.exists
- not fail2ban_verify_files.results[2].stat.exists
- not fail2ban_verify_files.results[3].stat.exists
quiet: true
- name: Test the configuration the daemon will load
ansible.builtin.command: fail2ban-client -t
changed_when: false
- name: Ask the running daemon for its jails
ansible.builtin.command: fail2ban-client status
register: fail2ban_verify_status
changed_when: false
- name: The daemon loaded the base and both service jails
ansible.builtin.assert:
that:
- "'sshd' in fail2ban_verify_status.stdout"
- "'svc-a' in fail2ban_verify_status.stdout"
- "'svc-b' in fail2ban_verify_status.stdout"
- "'svc-bad' not in fail2ban_verify_status.stdout"
quiet: true
+10
View File
@@ -0,0 +1,10 @@
---
- name: Configure Fail2Ban jail.local
become: true
ansible.builtin.template:
src: jail.local.j2
dest: /etc/fail2ban/jail.local
owner: root
group: root
mode: "0600"
notify: Restart Fail2Ban
+9
View File
@@ -0,0 +1,9 @@
---
- name: Install Fail2Ban package
become: true
ansible.builtin.package:
name:
- "{{ fail2ban_package_name }}"
# Required for `backend = systemd` jails (journalmatch), e.g. gitea's.
- python3-systemd
state: present
+16
View File
@@ -0,0 +1,16 @@
---
- name: Install Fail2Ban
ansible.builtin.import_tasks: install.yml
tags: [fail2ban, fail2ban_install]
- name: Validate Fail2Ban jails
ansible.builtin.import_tasks: validate.yml
tags: [fail2ban, fail2ban_validate]
- name: Configure Fail2Ban
ansible.builtin.import_tasks: configure.yml
tags: [fail2ban, fail2ban_configure]
- name: Ensure Fail2Ban service
ansible.builtin.import_tasks: service.yml
tags: [fail2ban, fail2ban_service]
+36
View File
@@ -0,0 +1,36 @@
---
# -t loads every jail, so a jail that cannot start (missing logpath, bad
# backend) fails here. -d only dumps the config and treats those as warnings.
- name: Test Fail2Ban configuration
become: true
ansible.builtin.command: fail2ban-client -t
register: fail2ban_test
failed_when: fail2ban_test.rc != 0
changed_when: false
check_mode: false
- name: Ensure Fail2Ban service is running
become: true
ansible.builtin.systemd:
name: fail2ban
enabled: "{{ fail2ban_service.enabled | default(true) }}"
state: "{{ fail2ban_service.state | default('started') }}"
# Handlers run at the end of the play; flush so the restart happens before the
# jail check below.
- name: Apply pending Fail2Ban handlers
ansible.builtin.meta: flush_handlers
- name: Verify enabled jails are loaded
become: true
ansible.builtin.command: "fail2ban-client status {{ item.name }}"
loop: "{{ fail2ban_jails | selectattr('enabled') }}"
loop_control:
label: "{{ item.name }}"
register: fail2ban_jail_status
until: fail2ban_jail_status.rc == 0
retries: 5
delay: 2
changed_when: false
check_mode: false
when: fail2ban_service.state | default('started') == 'started'
+57
View File
@@ -0,0 +1,57 @@
---
# Entry point for a service role that owns its own jail. Called with
# `include_role: name=mortis.kamino.fail2ban tasks_from=service_jail` and explicit vars; the
# jail lands in jail.d/<name>.local, never in the shared jail.local, so one
# play cannot overwrite another service's jail.
- name: Install Fail2Ban
ansible.builtin.import_tasks: install.yml
tags: [fail2ban, fail2ban_install]
- name: Validate service jail inputs
ansible.builtin.assert:
that:
- fail2ban_service_name is string
- fail2ban_service_jail is mapping
- fail2ban_service_filter is mapping
- fail2ban_service_filter.failregex is defined
- fail2ban_service_jail.logpath is defined or fail2ban_service_jail.journalmatch is defined
fail_msg: >-
fail2ban_service_jail and fail2ban_service_filter must be dicts. Pass the
variable as a single templated expression, not wrapped in a list or
embedded in a string.
tags: [fail2ban, fail2ban_service_jail]
- name: Deploy service filter definition
become: true
ansible.builtin.copy:
dest: "/etc/fail2ban/filter.d/{{ fail2ban_service_name }}.conf"
content: |
[Definition]
failregex = {{ fail2ban_service_filter.failregex }}
ignoreregex = {{ fail2ban_service_filter.ignoreregex | default('') }}
owner: root
group: root
mode: "0644"
notify: Reload Fail2Ban
tags: [fail2ban, fail2ban_service_jail]
- name: Deploy service jail
become: true
ansible.builtin.template:
src: service_jail.local.j2
dest: "/etc/fail2ban/jail.d/{{ fail2ban_service_name }}.local"
owner: root
group: root
mode: "0644"
notify: Reload Fail2Ban
# Read-only, so it also runs in check mode. A failure leaves the broken file on
# disk and fails every run until fixed, instead of only the run that wrote it.
tags: [fail2ban, fail2ban_service_jail]
- name: Test Fail2Ban configuration
become: true
ansible.builtin.command: fail2ban-client -t
changed_when: false
check_mode: false
tags: [fail2ban, fail2ban_service_jail]
+13
View File
@@ -0,0 +1,13 @@
---
- name: Validate Fail2Ban jails
ansible.builtin.assert:
that:
- item.name is defined
- item.enabled is defined
- item.filter is defined
- item.logpath is defined or item.journalmatch is defined or item.backend | default('') == 'systemd'
- item.maxretry is defined
- item.bantime is defined
- item.findtime is defined
fail_msg: "Invalid Fail2Ban jail: {{ item }}"
loop: "{{ fail2ban_jails }}"
+21
View File
@@ -0,0 +1,21 @@
# Managed by Ansible - Fail2Ban jail.local
{% for jail in fail2ban_jails %}
[{{ jail.name }}]
enabled = {{ jail.enabled | default(true) }}
port = {{ jail.port | default('any') }}
filter = {{ jail.filter | default(jail.name) }}
{% if jail.backend is defined or jail.journalmatch is defined %}
backend = {{ jail.backend | default('systemd') }}
{% endif %}
{% if jail.journalmatch is defined %}
journalmatch = {{ jail.journalmatch }}
{% endif %}
{% if (jail.backend | default('systemd' if jail.journalmatch is defined else 'auto')) != 'systemd' %}
logpath = {{ jail.logpath | default('/var/log/auth.log') }}
{% endif %}
maxretry = {{ jail.maxretry | default(fail2ban_defaults.maxretry) }}
bantime = {{ jail.bantime | default(fail2ban_defaults.bantime) }}
findtime = {{ jail.findtime | default(fail2ban_defaults.findtime) }}
{% endfor %}
@@ -0,0 +1,14 @@
# Managed by Ansible - Fail2Ban jail for {{ fail2ban_service_name }}
[{{ fail2ban_service_name }}]
enabled = {{ fail2ban_service_jail.enabled | default(true) | lower }}
port = {{ fail2ban_service_jail.port | default('any') }}
filter = {{ fail2ban_service_jail.filter | default(fail2ban_service_name) }}
{% if fail2ban_service_jail.journalmatch is defined %}
backend = {{ fail2ban_service_jail.backend | default('systemd') }}
journalmatch = {{ fail2ban_service_jail.journalmatch }}
{% else %}
logpath = {{ fail2ban_service_jail.logpath }}
{% endif %}
maxretry = {{ fail2ban_service_jail.maxretry | default(fail2ban_defaults.maxretry) }}
bantime = {{ fail2ban_service_jail.bantime | default(fail2ban_defaults.bantime) }}
findtime = {{ fail2ban_service_jail.findtime | default(fail2ban_defaults.findtime) }}
+60
View File
@@ -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.
@@ -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"
@@ -0,0 +1,5 @@
---
- name: Reload Interfaces
become: true
ansible.builtin.command: "{{ network_interfaces_apply_command }}"
changed_when: true
@@ -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 <name> 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 <name>).
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.
+17
View File
@@ -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: []
@@ -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
@@ -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
@@ -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
@@ -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
+33
View File
@@ -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
+9
View File
@@ -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
+5
View File
@@ -0,0 +1,5 @@
---
- name: Read current interfaces config
ansible.builtin.slurp:
src: "{{ network_interfaces_file }}"
register: network_interfaces_current
@@ -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) }}
+13
View File
@@ -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."
@@ -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 %}
+56
View File
@@ -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.
+53
View File
@@ -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 <unit name without .service> -> {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: {}
@@ -0,0 +1,6 @@
---
- name: Reload systemd daemon
become: true
ansible.builtin.systemd:
daemon_reload: true
listen: "systemd reload"
@@ -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/<unit>.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.
+21
View File
@@ -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: []
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
+41
View File
@@ -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"
@@ -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"
+57
View File
@@ -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
@@ -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
@@ -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 %}