The Ansible Tour, Part 5: IT Security – Firewall, SSH, fail2ban, Hardening, SELinux and Detection

Part 5 of the Ansible Tour: every security role in one place – how each layer is built, what it protects against, and what to do when it alerts.

Comic in the Ansible Tour series, route map with station 5: the man adds one more wall ring to a model castle with several walls and a moat

🌐 Also available in: Deutsch · Français · Español · Italiano · Português · Nederlands · Polski

Part 5 of the Ansible Tour. After the platform, the blog and Nextcloud, this part gathers all security roles in one place, across both stacks. The series describes release v3.3.0 (opens in a new tab), with later changes added as addenda.

In short: Part 5 of the Ansible (opens in a new tab) tour collects all security roles in one place. Security here comes from layers, each catching what the previous one missed: firewall, SSH, fail2ban, hardening along the CIS benchmark, SELinux and detection with auditd, AIDE, rkhunter (opens in a new tab) and ClamAV (opens in a new tab). The code is public – protection has to come from keys, layers and alerts, not from secrecy.

Security here comes from layers: each one catches what the previous one missed. From the outside in, these are the firewall, the SSH login, the reaction to attacks in the logs (fail2ban), the hardening of the operating system, containment by SELinux, and detection by auditd, AIDE, rkhunter and ClamAV. The code is public, so an attacker can read it too. That is fine: the protection has to come from keys, layers and alerts, not from secrecy. Exact thresholds still stay vague here.

Table of Contents

🧱 common_firewall: nftables with its own table

The firewall is nftables. Every chain has policy drop: whatever is not explicitly allowed is dropped, outgoing traffic included. Incoming, only web, SSH from a country list and what the cluster needs are allowed; outgoing, only DNS, NTP, HTTP(S), mail and the pods’ traffic. High up in the input chain sit the ban sets – even before the rule for established connections, so that a ban also ends a connection that is already open. One set per fail2ban jail, one for manual bans, one for port scan detection, all expiring automatically in the kernel.

The most important line of the role is not a rule but the way the firewall is reloaded. The shipped service clears every rule in the kernel with flush ruleset. On a Kubernetes node that also deletes the tables of kube-proxy, Flannel and K3s’s policy controller, and for 30 to 90 seconds the Kubernetes services do not work – Nextcloud could not reach its database after every firewall reload. The role therefore replaces only its own table, in one transaction, and teaches systemd to do the same with a drop-in.

Because replacing the table also recreates the ban sets empty, a second handler then restarts fail2ban, which puts every active ban back from its database. Without it, after a playbook run most bans existed only in fail2ban’s memory while the firewall let the addresses back in.

Kubernetes also opens a back door: kube-proxy forwards the NodePorts on every local address, the public one included, and that traffic goes through the forward chain, not through input. The metrics exporters were reachable from the internet that way. A dedicated chain drops new connections to them. Its priority is chosen precisely – after connection tracking. In the first version it ran before it and also dropped replies to the pods’ outgoing connections whose random source port fell into that range: for two months about 4 percent of such connections ran into a timeout.

On the very first run the role does not start the firewall live: SSH moves to a new port at the same time, and Ansible’s existing connection would match no rule – the play would simply hang. Instead the server reboots, Ansible switches to the new port and continues there.

The takeaway: a firewall on a Kubernetes host is never alone. Replace only your own table, and test every assumption about order and priorities.

🔑 common_ssh: the door, and what you can do inside

SSH listens on a different port – no security in itself, but it keeps almost all automated noise out of the logs. Only keys, only root, few attempts, no forwarding and a short list of modern algorithms are allowed. One lesson came from two servers: for a keyword set twice, sshd takes the first value, and the provider’s image dropped a file saying PasswordAuthentication yes that silently beat the “no” in the main file. The role therefore writes a drop-in called 00-hardening.conf that is read before everything else.

A systemd drop-in confines the SSH service, and everything it starts inherits that – every session and every Ansible task. Nobody who logs in over SSH can load a kernel module or change a kernel parameter, not even an attacker with a stolen key. Legitimate changes go through systemd-run (part 2). What had to be removed again on the way is instructive: without AF_NETLINK, nft, ip and ss fail in every session, of all times while repairing the firewall; and a private /tmp for sshd was inherited by every session and destroyed under running sessions on every restart. That turned into a rule: strict sandboxing belongs on services that do not start sessions.

Restarting SSH over your own SSH connection is the trickiest part of the role. A chain of handlers first checks the configuration with sshd -t, then restarts sshd asynchronously without waiting for an answer that could never arrive over the dying connection, discards the old connection and waits until a new one comes up. If sshd did not come back, the play fails loudly – while you probably still have a second session open.

The takeaway: a hardening applies to the administrator too. Before switching on a restriction, check what you yourself still need to be able to do in an emergency.

🚫 common_fail2ban: reacting to the logs

Where a point describes a change, a link leads to the commit that made it.

Seven jails watch the system journal (SSH), the ingress log (logins of WordPress, Nextcloud and Grafana, scanners, paths that are never legitimate here) and fail2ban’s own log (repeat offenders get a much longer ban). The ban goes straight into the jail’s set in the firewall, with the ban time as expiry; nftables removes it by itself, even if fail2ban has stopped running in the meantime.

Hardly any part of the setup had so many quiet bugs. After a reboot the HTTP jails watched a log file that no longer existed for days, because its name changes with every container restart. IPv6 bans failed on an IPv4 set while fail2ban logged “Ban”. A set shared by all jails let the unban of a short jail lift the longer ban of another. And on 26 October 2026 it turned out that the filter for Nextcloud logins had not counted a single attempt since July – it looked for /login, Nextcloud uses /index.php/login. The fail2ban deep dive tells all six cases. → 3109879 (opens in a new tab), 4c4d053 (opens in a new tab), b64939a (opens in a new tab), 8cbfe32 (opens in a new tab)

Since then the final check of every run tests the effect instead of only the state: every filter gets a real log line in today’s format, every jail briefly bans an address from the documentation ranges that has to arrive in the kernel’s set, and an unban in one jail must not lift a ban in another. Once a week a script checks from the outside whether a ban really ends a connection that is already open. → 8cbfe32 (opens in a new tab)

The takeaway: “Ban” in the log does not mean “blocked”. The truth is in the kernel’s set, and you check it with real input.

🛡️ common_cis_hardening: the benchmark with judgement

The CIS benchmark produced more than a hundred findings. The role implements the safe ones, and its header starts with what it deliberately does not do, each with a reason: no rework of PAM (a mistake there locks out every local login, and SSH runs key-only anyway), no bootloader password (protects against physical access a VPS does not have), no custom crypto policy, and IP forwarding stays on because Kubernetes needs it. For anyone running a similar setup, this list is the most useful part.

What it implements includes: AIDE as a file integrity check with a nightly run at midnight and a renewed baseline at 04:00, after the updates; blocked kernel modules for old file systems and USB storage; no core dumps; sudo with a log file, written with visudo -cf as validation so that a broken file never replaces the real one; and /tmp, /var/tmp and /dev/shm with noexec. The image’s default user loses its password-less sudo and its login shell. On 26 October 2026 a hand-made cron file from August also turned up on the blog that ran AIDE a second time every day; the role now removes it.

The takeaway: a benchmark is a list of suggestions. The reasoned list of what you do not implement is as valuable as the implementation itself.

🏷️ common_selinux: containment

SELinux gives every process and every file a type, and the policy says which process type may touch which file – root included. Container processes run as container_t and may only write files of type container_file_t. A container that breaks out of its file system finds a host on which almost nothing carries this label. The role puts this label on the directories mounted into the pods, as a persistent rule in the policy – before the deployment, or the database does not start.

For weeks this held only halfway: SELinux was enforcing, the labels were right, but K3s started its container runtime without SELinux support, because selinux: true was missing from its configuration. Every pod ran unconfined. A look at ps -eZ showed it; no check had ever asked. Since 19 October 2026 every pod runs as container_t, and since 26 October the final check also verifies the domain of every host service. The SELinux deep dive tells the whole story.

The takeaway: mode and labels say nothing about whether a process is confined. Only the domain of the running process shows that.

🔎 Detection: auditd, AIDE, rkhunter, ClamAV

These four assume that someone got in – or that something changed that must not change. Their common rule: silent when all is well, a mail when it is not. A detector that mails every night trains you to ignore it.

  • auditd watches writes to user files, sudo, SSH, cron and K3s’s security-critical files. A small script mails only four keys – such as K3s’s auto-deploy directory, which applies whatever lands there. The noisy keys stay in the log for investigations. This notifier once did not run for six weeks, because a command was missing and an || true swallowed the error.
  • AIDE renews its baseline at the end of every playbook run, but only if something really changed. Its exit code is a bit mask: 1 to 7 means “differences found”, which is normal right after a run, not an error.
  • rkhunter compares system binaries with a stored database. A dnf plugin updates that database after every package installation, or every update would be a warning the next night.
  • ClamAV scans what users upload at night, at low priority, and never deletes anything itself. It skips previews, because they are made from files that are scanned anyway.

Since 26 October 2026 each of these jobs reports a timestamp to the monitoring after a successful run, and an alert fires when one is overdue. A detector that stays silent because it no longer runs is the most dangerous silence. → f45a900 (opens in a new tab)

The takeaway: a silent detector is only a good sign if you know it ran.

🛠️ Running it

  • SSH login alert: someone logged in interactively. If it was not you, act at once: check last -i, rotate the keys.
  • AIDE reports changes: expected after a planned change, otherwise investigate – before the next playbook run renews the baseline.
  • auditd event: something that must never change has changed. Treat it as an incident until it is explained.
  • Locked yourself out: fail2ban-client set <jail> unbanip <address> from another connection, or wait. Never test attack paths from the machine you administer from.
  • SSH does not come back after a change: the provider’s web console. That is why: test the console before you need it.

🎯 Conclusion: The lessons of part 5

  • On a Kubernetes host, replace only your own firewall table.
  • For sshd the first value wins – your own hardening has to be read first.
  • Test protection with real input, not with its status.
  • Check the domain of running processes, not only mode and labels.
  • Every detector needs a sign of life, or failure looks like calm.

🧭 Where the tour goes next

Part 6 closes the tour with the monitoring. The technology under this part is explained in the deep dives on nftables, fail2ban and SELinux.

Addendum (28 November 2026): The www_k3s repository is now archived and has been split: the Nextcloud part lives on in nextcloud_k3s (opens in a new tab), the blog server in www_hugo (opens in a new tab). The links in this post point to the state at the time and still work.

Some text, images, videos and audio on this site are AI-assisted or AI-generated. Details