Ansible on RHEL 10: A Security Baseline for Every Server
The ninth lab in the Ansible series: one playbook hardens the kernel and network settings, closes unused services, sets a password policy with account lockout, masks Ctrl+Alt+Del and adds audit rules for the files that matter. Includes redirect settings that changed nothing, a mask Ansible reported as done that never happened, a password policy that root and Ansible both skip, and audit rules that silently stopped loading.
Goal: the same security baseline on server1 and server2, kept in one playbook:
- kernel and network settings that make the servers ignore redirects and spoofed packets
- the firewall only allows what the servers really use
- the web console doesn’t listen, and Ctrl+Alt+Del on the console doesn’t reboot the server
- passwords need at least 12 characters and three character classes, also when root sets them
- an account is locked for 15 minutes after 5 wrong passwords
- changes to users, sudo rules and the SSH configuration, and every command run as root, end up in the audit log
rootis the only account with UID 0
These are the hardening steps from my hardening checklist, done the RHEL way and kept in Ansible. SSH hardening was lab 8, and time sync was lab 7, so they aren’t repeated here.
Starting point: the setup from the earlier labs in this series: server1 is the control node, the project is in ~/ansible, and the ansible user logs in with an SSH key (lab 1). rhel-system-roles is installed (lab 2). The user alice comes from lab 4.
Before you start: take a snapshot of both servers. This lab changes how logins and passwords work. A mistake in the login rules can lock out every user with a password, and a snapshot is the quickest way back.
Lab environment:
| Host | IP address | Role |
|---|---|---|
server1 | 192.168.10.10 | control node + managed node |
server2 | 192.168.10.11 | managed node |
The addresses are examples. Replace them with your own.
Tested on: a CentOS Stream 10 virtual machine with SELinux enforcing (ansible-core 2.16, rhel-system-roles 2.4, audit 4.2, systemd 257). The VM managed itself over SSH. I ran the final playbook on a fresh VM, then again to check that nothing changes, then rebooted to check that everything stays. Every output below comes from those tests.
1. Which tool for what
| Task | Tool | In ansible-core? |
|---|---|---|
| kernel and network settings | ansible.builtin.copy to /etc/sysctl.d/ | yes |
| firewall | redhat.rhel_system_roles.firewall | no, but on the ISO |
| web console, Ctrl+Alt+Del | ansible.builtin.systemd_service, ansible.builtin.file | yes |
| password quality | ansible.builtin.copy to /etc/security/pwquality.conf.d/ | yes |
| account lockout | authselect + ansible.builtin.lineinfile | yes |
| audit rules | ansible.builtin.copy to /etc/audit/rules.d/ | yes |
| UID 0 check | ansible.builtin.getent + assert | yes |
ansible.posix.sysctl isn’t available offline. A file in /etc/sysctl.d/ does the same job, and it’s easier to read on the server.
2. Variables
Add these to group_vars/servers.yml:
hardening_sysctl:
net.ipv4.conf.*.accept_redirects: 0
net.ipv4.conf.*.send_redirects: 0
net.ipv4.conf.*.accept_source_route: 0
net.ipv4.conf.*.log_martians: 1
net.ipv6.conf.*.accept_redirects: 0
net.ipv4.icmp_echo_ignore_broadcasts: 1
net.ipv4.tcp_syncookies: 1
kernel.kptr_restrict: 2
kernel.dmesg_restrict: 1
pwquality_minlen: 12
pwquality_minclass: 3
faillock_deny: 5
faillock_unlock_time: 900
firewall_remove_services:
- cockpit
- dhcpv6-client
| Setting | What it does |
|---|---|
accept_redirects | ignore ICMP redirects, so another host can’t change our routes |
send_redirects | we’re not a router, so we don’t send redirects either |
accept_source_route | drop packets that choose their own route, a classic spoofing trick |
log_martians | log packets with impossible source addresses |
icmp_echo_ignore_broadcasts | ignore pings sent to the broadcast address |
tcp_syncookies | keep accepting connections during a SYN flood |
kptr_restrict, dmesg_restrict | hide kernel addresses and the kernel log from normal users |
The * in net.ipv4.conf.* means every network interface. Section 5 shows why the usual net.ipv4.conf.all isn’t enough.
3. The playbook
cd ~/ansible
vim hardening.yml
---
- name: Security baseline on every server
hosts: servers
become: true
vars:
firewall:
- service: "{{ firewall_remove_services }}"
state: disabled
tasks:
- name: Kernel and network settings
ansible.builtin.copy:
dest: /etc/sysctl.d/90-hardening.conf
content: |
{% for key, value in hardening_sysctl.items() %}
{{ key }} = {{ value }}
{% endfor %}
mode: "0644"
notify: Load sysctl settings
- name: Apply the sysctl settings now
ansible.builtin.meta: flush_handlers
- name: Read the values the kernel uses
ansible.builtin.command: sysctl -n {{ item.key | replace('*', ansible_default_ipv4.interface) }}
loop: "{{ hardening_sysctl | dict2items }}"
register: sysctl_now
changed_when: false
- name: The kernel uses the values we wrote
ansible.builtin.assert:
that: item.stdout == (item.item.value | string)
fail_msg: "{{ item.item.key }} is {{ item.stdout }}, expected {{ item.item.value }}"
quiet: true
loop: "{{ sysctl_now.results }}"
loop_control:
label: "{{ item.item.key }}"
- name: Unused services are closed in the firewall
ansible.builtin.include_role:
name: redhat.rhel_system_roles.firewall
- name: The web console doesn't listen
ansible.builtin.systemd_service:
name: cockpit.socket
state: stopped
enabled: false
register: cockpit
failed_when:
- cockpit is failed
- "'Could not find' not in cockpit.msg | default('')"
- name: Ctrl+Alt+Del doesn't reboot the server
ansible.builtin.file:
src: /dev/null
dest: /etc/systemd/system/ctrl-alt-del.target
state: link
force: true
notify: Reload systemd
- name: Apply the mask now
ansible.builtin.meta: flush_handlers
- name: Check that Ctrl+Alt+Del is masked
ansible.builtin.command: systemctl is-enabled ctrl-alt-del.target
register: cad
changed_when: false
failed_when: cad.stdout != 'masked'
- name: Password quality rules
ansible.builtin.copy:
dest: /etc/security/pwquality.conf.d/50-hardening.conf
content: |
minlen = {{ pwquality_minlen }}
minclass = {{ pwquality_minclass }}
enforce_for_root
mode: "0644"
- name: Read the current authselect setup
ansible.builtin.command: authselect current
register: authselect_now
changed_when: false
- name: Turn on account lockout (faillock)
ansible.builtin.command: authselect enable-feature with-faillock
when: "'with-faillock' not in authselect_now.stdout"
- name: Lockout rules
ansible.builtin.lineinfile:
path: /etc/security/faillock.conf
regexp: "^#?\\s*{{ item.key }}\\s*="
line: "{{ item.key }} = {{ item.value }}"
loop:
- { key: deny, value: "{{ faillock_deny }}" }
- { key: unlock_time, value: "{{ faillock_unlock_time }}" }
- name: Audit rules
ansible.builtin.copy:
dest: /etc/audit/rules.d/50-hardening.rules
content: |
-a always,exit -F arch=b64 -F path=/etc/passwd -F perm=wa -k identity
-a always,exit -F arch=b64 -F path=/etc/group -F perm=wa -k identity
-a always,exit -F arch=b64 -F path=/etc/shadow -F perm=wa -k identity
-a always,exit -F arch=b64 -F path=/etc/sudoers -F perm=wa -k sudoers
-a always,exit -F arch=b64 -F dir=/etc/sudoers.d -F perm=wa -k sudoers
-a always,exit -F arch=b64 -F path=/etc/ssh/sshd_config -F perm=wa -k sshd
-a always,exit -F arch=b64 -F dir=/etc/ssh/sshd_config.d -F perm=wa -k sshd
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=unset -k root_commands
mode: "0600"
notify: Load audit rules
- name: Find accounts with UID 0
ansible.builtin.getent:
database: passwd
- name: root is the only account with UID 0
ansible.builtin.assert:
that: uid0 == ['root']
fail_msg: "UID 0 accounts: {{ uid0 }}"
quiet: true
vars:
uid0: "{{ ansible_facts.getent_passwd | dict2items | selectattr('value.1', 'equalto', '0') | map(attribute='key') | list }}"
handlers:
- name: Reload systemd
ansible.builtin.systemd_service:
daemon_reload: true
- name: Load sysctl settings
ansible.builtin.command: sysctl --system
- name: Load audit rules
ansible.builtin.command: augenrules --load
How to read it:
- sysctl: the file is built from the
hardening_sysctldictionary, so a new setting is one more line ingroup_vars.flush_handlersloads the settings right away, and the next two tasks read every value back from the kernel. If another file wins over ours, the play stops (section 6). replace('*', ansible_default_ipv4.interface)turnsnet.ipv4.conf.*.accept_redirectsintonet.ipv4.conf.enp2s0.accept_redirects, or whatever your main interface is called, so the check looks at the real interface and not justall.- The firewall role removes
cockpitanddhcpv6-clientfrom the zone. It doesn’t touchsshor the SSH port from lab 8. - cockpit.socket: the web console starts when something connects to port 9090. Stopping and disabling the socket closes it.
failed_whenlets the task pass on a server where Cockpit isn’t installed at all. - Ctrl+Alt+Del: a mask is a link to
/dev/null. The playbook creates that link itself, then checks the result withsystemctl is-enabled. Section 7 explains why it doesn’t usemasked: true. - pwquality: a drop-in in
pwquality.conf.d/instead of editingpwquality.conf.minclass = 3means three of the four classes: lowercase, uppercase, digits, other characters.enforce_for_rootis section 8. - faillock: on RHEL 10, the PAM files belong to
authselect. Editing/etc/pam.d/system-authby hand works until the nextauthselectcommand overwrites it.authselect enable-feature with-faillockadds the faillock lines in the supported way. Thewhen:keeps it from running every time. - Audit rules: a file in
/etc/audit/rules.d/, loaded withaugenrules --load.perm=wameans write or attribute change. The-kkey is a label you search by later. The last rule logs every command a logged-in user runs as root.auidis the user who logged in, and it stays the same throughsudo. - UID 0:
getentreads the user list, and theassertfails if any account other thanroothas UID 0. An extra UID 0 account is a classic backdoor.
4. Run it
ansible-playbook --syntax-check hardening.yml
ansible-playbook hardening.yml
The tasks that changed something on the first run:
TASK [Kernel and network settings] *********************************************
changed: [server2]
RUNNING HANDLER [Load sysctl settings] *****************************************
changed: [server2]
TASK [redhat.rhel_system_roles.firewall : Configure firewall] ******************
changed: [server2]
TASK [The web console doesn't listen] ******************************************
changed: [server2]
TASK [Ctrl+Alt+Del doesn't reboot the server] **********************************
changed: [server2]
TASK [Password quality rules] **************************************************
changed: [server2]
TASK [Turn on account lockout (faillock)] **************************************
changed: [server2]
TASK [Lockout rules] ***********************************************************
changed: [server2] => (item={'key': 'deny', 'value': 5})
changed: [server2] => (item={'key': 'unlock_time', 'value': 900})
TASK [Audit rules] *************************************************************
changed: [server2]
RUNNING HANDLER [Load audit rules] *********************************************
changed: [server2]
PLAY RECAP *********************************************************************
server2 : ok=33 changed=10 unreachable=0 failed=0 skipped=12 ...
The second run:
PLAY RECAP *********************************************************************
server2 : ok=29 changed=0 unreachable=0 failed=0 skipped=13 ...
What ended up on the server:
ansible server2 -b -a "firewall-cmd --list-services"
ansible server2 -b -a "authselect current"
ansible server2 -b -a "auditctl -l"
ssh
Profile ID: local
Enabled features:
- with-faillock
-a always,exit -F arch=b64 -S setxattr,lsetxattr,fsetxattr,...,openat,... -F path=/etc/passwd -F perm=wa -F key=identity
...
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=-1 -F key=root_commands
auditctl -l prints each perm=wa rule as the list of system calls it watches. That’s normal.
After a reboot, everything was still in place: the sysctl values on the interface, the mask, faillock and the audit rules. The next run had changed=0 again.
5. The redirect settings that changed nothing
The first version of the variables used net.ipv4.conf.all, the way most hardening guides write it:
net.ipv4.conf.all.accept_redirects: 0
net.ipv4.conf.all.send_redirects: 0
The playbook succeeded, and sysctl net.ipv4.conf.all.accept_redirects showed 0. But every interface has its own copy of each setting, and the kernel decides per interface:
for k in all default eth0; do
printf "%-8s accept_redirects=%s send_redirects=%s\n" $k \
$(sysctl -n net.ipv4.conf.$k.accept_redirects) \
$(sysctl -n net.ipv4.conf.$k.send_redirects)
done
all accept_redirects=0 send_redirects=0
default accept_redirects=1 send_redirects=1
eth0 accept_redirects=1 send_redirects=1
The kernel documentation (ip-sysctl.rst) says that on a host that doesn’t forward packets, redirects are accepted if at least one of all and the interface value is on. The same “at least one” rule applies to send_redirects. With eth0 still at 1, setting all to 0 changed nothing. default only applies to interfaces created later.
The fix is the *. sysctl understands it and sets every interface:
* Applying /etc/sysctl.d/90-hardening.conf ...
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.eth0.accept_redirects = 0
net.ipv4.conf.lo.accept_redirects = 0
That’s also why the playbook checks the value on the real interface, not on all.
6. A file that wins over yours
To see whether the check works, I added one line to /etc/sysctl.conf, as if someone had changed a setting by hand years ago:
kernel.dmesg_restrict = 0
The next run stopped:
failed: [server2] (item=kernel.dmesg_restrict) => {... "msg": "kernel.dmesg_restrict is 0, expected 1"}
/etc/sysctl.conf is read as 99-sysctl.conf, after every file in /etc/sysctl.d/. For sysctl, the last value wins, so 99- beats our 90-. That’s the opposite of sshd_config.d in lab 8, where the first value wins. Without the check, the playbook would have reported success with a setting that wasn’t active.
To find every file that sets a value:
ansible all -b -m shell -a "grep -r dmesg_restrict /etc/sysctl.conf /etc/sysctl.d/ /usr/lib/sysctl.d/"
Remove the old line from /etc/sysctl.conf, or move the setting into your own file, and run the playbook again.
7. A mask that Ansible reported but never made
The first version masked Ctrl+Alt+Del the obvious way:
- name: Ctrl+Alt+Del doesn't reboot the server
ansible.builtin.systemd_service:
name: ctrl-alt-del.target
masked: true
The task said changed. The second run said changed again, and so did the third. A task that changes something every time is a sign that nothing was changed:
systemctl is-enabled ctrl-alt-del.target
ls -l /etc/systemd/system/ctrl-alt-del.target
alias
lrwxrwxrwx. 1 root root 37 Nov 3 05:27 /etc/systemd/system/ctrl-alt-del.target -> /usr/lib/systemd/system/reboot.target
The image I tested on had its own link in /etc/systemd/system/, pointing to reboot.target. systemctl mask refuses to replace it:
systemctl mask ctrl-alt-del.target
Failed to mask unit: File '/etc/systemd/system/ctrl-alt-del.target' already exists and is a symlink to /usr/lib/systemd/system/reboot.target
The module didn’t report that error. Run on its own, it showed CHANGED, with no message:
server2 | CHANGED => {
"changed": true,
"name": "ctrl-alt-del.target",
...
So the playbook makes the mask itself, a link to /dev/null with force: true to replace whatever is there, and then checks the result. On your servers, see what’s there first:
ansible all -a "ls -l /etc/systemd/system/ctrl-alt-del.target"
8. Passwords: who the policy doesn’t apply to
root, unless you say so. Without enforce_for_root, root gets a warning and the password is set anyway:
echo 'Short1' | sudo passwd --stdin alice
BAD PASSWORD: The password is shorter than 12 characters
I compared the hash in /etc/shadow before and after, and it had changed: alice now had the weak password. With enforce_for_root, the hash stayed the same:
BAD PASSWORD: The password is shorter than 12 characters
passwd: (user alice) pam_chauthtok() failed, error:
Authentication token manipulation error
Both times, passwd returned exit code 0. A script that checks $? after passwd can’t tell whether the password was changed. Check the hash, or test a login.
Ansible. In lab 4, passwords come from Vault as hashes. The user module writes the hash straight into /etc/shadow, without PAM, so pwquality never sees the password. I set a three-character password for alice with the user module, with enforce_for_root on:
ansible server2 -b -m ansible.builtin.user -a "name=alice password={{ 'abc' | password_hash('sha512') }}"
The hash changed, and alice could log in with abc. The password policy protects passwords people type. For passwords in Vault, the length and strength are your job.
Account lockout. After 5 wrong passwords, the right one is refused too:
su - alice # 5 times with a wrong password, then with the right one
su: Authentication failure
journalctl -n 20 | grep faillock
faillock --user alice
pam_faillock(su-l:auth): Consecutive login failures for user alice account temporarily locked
alice:
When Type Source Valid
2026-11-25 12:41:41 TTY /dev/pts/0 V
2026-11-25 12:41:46 TTY /dev/pts/0 V
...
After 15 minutes (unlock_time = 900) the lock lifts on its own. To unlock right away:
faillock --user alice --reset
Two things faillock doesn’t do:
It doesn’t block SSH keys. While
alicewas locked, she could still log in with her SSH key. faillock only counts password logins. That’s why theansibleuser can’t be locked out by it, but it also means a locked account isn’t a disabled one. To really stop an account, expire it:usermod -e 1 alice ssh alice@server2Your account has expired; please contact your system administrator. Connection closed by 192.168.10.11 port 22That stops the key too.
usermod -e '' alicelets her back in.It doesn’t lock root. That’s the default, so a wrong password on the console can’t lock you out of your own server.
even_deny_rootinfaillock.confchanges it, but think twice before you use it.
9. Audit rules: what they catch, and two traps
Creating a user leaves a trail:
ansible server2 -b -a "useradd carol"
ansible server2 -b -a "ausearch -k identity -i" | grep type=SYSCALL | tail -1
... auid=ansible uid=root ... comm=useradd exe=/usr/sbin/useradd ...
auid=ansible shows who did it, although the command ran as root. A summary of all keys:
ansible server2 -b -a "aureport -k --summary"
Key Summary Report
===========================
total key
===========================
1252 root_commands
53 identity
13 sudoers
12 sshd
Every root_commands event came from the ansible user. Every task Ansible runs with become is audited, about 600 events per run of this playbook. For a bank’s auditors that’s exactly the point: automation leaves the same trail as a person. It’s also the biggest source of audit log volume, so plan the log size for it.
auditd can’t be restarted with systemctl. The usual handler fails:
ansible server2 -b -m ansible.builtin.systemd_service -a "name=auditd state=restarted"
"msg": "Unable to restart service auditd: Failed to restart auditd.service: Operation refused, unit auditd.service may be requested by dependency only (it is configured to refuse manual start/stop)."
auditd refuses to be stopped by systemd, so that nobody can switch auditing off quietly. New rules don’t need a restart anyway: augenrules --load merges the files in rules.d/ into audit.rules and loads them.
-w still works, but it’s the old syntax. My first version used the short form, -w /etc/passwd -p wa -k identity. It works, but every load printed:
Old style watch rules are slower
The -a always,exit -F path=... -F perm=wa form in the playbook does the same thing.
-e 2 locks the rules until the next reboot. Many hardening guides end the audit rules with -e 2, which makes them immutable: nobody, not even root, can change or delete them while the system runs. I added it as 99-finalize.rules:
auditctl -s | grep enabled
enabled 2
Then I added one more rule to 50-hardening.rules and loaded it:
server2 | CHANGED | rc=0 >>
/sbin/augenrules: Audit system is in immutable mode - exiting with no changes
Exit code 0, and Ansible reported CHANGED, but the new rule wasn’t loaded. It only appears after a reboot. If you use -e 2, every rule change needs a reboot, and a successful run proves nothing until then. I left it out of this lab for that reason. It belongs on a production server, together with a reboot plan.
Verification
From ~/ansible on server1:
ansible all -a "sysctl net.ipv4.conf.all.accept_redirects net.ipv4.conf.default.accept_redirects"
ansible all -m setup -a "filter=ansible_default_ipv4" # your interface name
ansible all -b -a "firewall-cmd --list-services" # no cockpit, no dhcpv6-client
ansible all -a "systemctl is-enabled ctrl-alt-del.target" # masked (Ansible shows rc=1, that's normal for masked)
ansible all -b -a "authselect current" # with-faillock
ansible all -b -a "grep -E '^(deny|unlock_time)' /etc/security/faillock.conf"
ansible all -b -a "auditctl -l" # the 8 rules
ansible all -b -a "aureport -k --summary"
ansible-playbook hardening.yml # changed=0 on both
Then test a lockout by hand on one server, with a test user, and unlock it with faillock --user <name> --reset.
Safety notes
- Take a snapshot first. Account lockout and password rules change how everyone logs in.
- Use
authselect, not your editor, for PAM. Hand edits in/etc/pam.d/system-authare overwritten by the nextauthselectcommand. - Check what the kernel uses, not what the file says. For sysctl, the last file wins, and
/etc/sysctl.confcomes last. - Use
net.ipv4.conf.*, not onlyall. For redirects, one interface left on is enough. - A task that is
changedon every run didn’t do its job. Look at the server, as in section 7. - The password policy doesn’t cover Ansible. Hashes from Vault skip PAM, so choose strong passwords yourself.
- A locked account isn’t a disabled one. SSH keys still work. Expire the account to stop it.
- Don’t restart auditd, reload the rules. Use
augenrules --load. -e 2needs a reboot for every rule change. Add it only when you have a reboot plan.