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
This commit was merged in pull request #74.
This commit is contained in:
Defame1297 committed 2026-11-08 21:28:33 +00:00
commit 565b369533
19 files changed
+560

No files matched your search

+1
View File
@@ -14,3 +14,4 @@ exclude_paths:
# a scenario's converge play. List the roles the scenarios call by FQCN.
mock_roles:
- mortis.kamino.docker
- mortis.kamino.fail2ban
+2
View File
@@ -0,0 +1,2 @@
minor_changes:
- fail2ban - New role. Installs Fail2Ban, manages jail.local and the service, deploys per-service jails into jail.d.
+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) }}