System and Endpoint Hardening Questions
Making operating systems, hosts, and endpoints resistant to compromise. Covers secure baseline configuration (CIS Benchmarks, Microsoft security baselines) and drift against the baseline, including detecting drift and deciding what to report versus auto-correct, OS and application hardening for Linux and Windows (SSH, host firewalls, service minimization, SELinux and AppArmor, file permissions, least privilege, application allow-listing, local administrator accounts), patch management and rollout (asset inventory, prioritisation, patch cadence, deployment rings and canaries, maintenance windows, emergency and out-of-cycle patching, post-patch verification, rollback, patch compliance metrics, immutable images, Windows and Linux update tooling such as Windows Update for Business, Intune, WSUS, Configuration Manager and Azure Update Manager), scripted audits and enforcement of host settings (Ansible, PowerShell, shell), and the host-side conditions that protect an endpoint (device posture checks, disk encryption, protection agent status). The host-level preventive layer. Detecting and investigating attacks, vulnerability scanning and scoring, network device and perimeter security, identity and key management, Active Directory attack hardening, operating WSUS or ConfigMgr as server roles, and container platform security are covered elsewhere.
A bad OS patch has gone out to thousands of servers. What rollback options do you have, how do you choose between them for different workloads, and when is rollback simply not possible?
Sample Answer
Direct answer
First stop the damage spreading: pause the rollout and withdraw the update from every distribution point (a server or repository that hosts fetch update files from) so no more hosts take it. Then roll back per workload, not fleet-wide with one method. Replace stateless hosts from the last known-good image (the golden image: a prebuilt, tested machine image from before the patch), undo the update with the package manager on long-lived servers, and for databases fail over to an unpatched standby instead of reverting a snapshot that would discard recent writes. Rollback is not possible when the update changed data or firmware in a one-way fashion, or when the old version no longer exists anywhere you can fetch it. In those cases you roll forward with a fixed patch or a workaround.
First 30 minutes: contain
- Pause the deployment ring or schedule. Withdraw the update at its source: move the repository snapshot pointer back, or unapprove it in WSUS (Windows Server Update Services, Microsoft's on-premises patch distribution service).
- Define the blast radius (how many hosts and services the bad update has touched): which hosts took the patch, which are rebooted and running the new kernel or components, which have not yet rebooted. The last two groups differ because an update to the kernel (the core of the operating system) only takes effect at the next boot: a host that installed it but has not rebooted still runs the old kernel, so for those hosts the fix is to remove the pending update before any restart, whereas rebooted hosts need the old version installed and booted again.
- Decide per workload with the owner whether the symptom needs rollback at all, or a config workaround.
The rollback options
| Option | How it works | Fits | Limit |
|---|---|---|---|
| Replace from last good image | Redeploy instances or VMs from the previous golden image | Stateless, auto-scaled hosts | Needs an image from before the patch and no local state |
| Package-manager undo | On dnf systems (dnf is the Red Hat-family package manager), dnf history list then dnf history info to find the transaction, then dnf history undo for that transaction or dnf history rollback to a point before it; dnf downgrade for one package | Long-lived Linux servers | undoing an upgrade or removal needs the older package versions to be installable from an enabled repository or local cache (a practical requirement, so keep them in your mirror); the dnf documentation says that if some operations cannot be undone because of the current state of the RPM database, it undoes none of the transaction |
| Hold or pin | apt-mark hold <pkg> stops a package being upgraded or removed until unhold | Stops further drift on Debian-family hosts while you decide | Does not revert what is installed |
| Snapshot or backup revert | Revert the VM or volume snapshot taken before patching | Hosts with no meaningful state change since | Everything written since the snapshot is lost |
| Fail over to an unpatched standby | Promote a replica or standby that has not been patched, patch later | Databases and clustered services | Needs a standby that was deliberately patched last |
| Uninstall the Windows update | Remove the update through the OS or your endpoint tool | Windows hosts | Check the method: DISM (Deployment Image Servicing and Management, the Windows servicing tool) /Remove-Package accepts only .cab packages, not .msu files |
| Roll forward | Ship a fixed patch or config change | When rollback is blocked | Takes longer than a revert |
Reading the commands
The transaction IDs, package and dates below are illustrative; the shape of the output is what a real run prints, trimmed to the key lines (a real info also prints begin and end times, rpmdb checksums, the user and the return code, and a real undo also prints a dependency table, a transaction summary and a transaction check). This was run in an AlmaLinux 9 container (a Red Hat-family system using dnf): first the history, then the details of the newest transaction, then the undo.
$ dnf history list | head -n 4
ID | Command line | Date and time | Action(s) | Altered
-------------------------------------------------------------------------------
3 | -y -q install tree | 2026-10-06 08:19 | Install | 1
2 | reinstall -y --installro | 2026-10-02 09:09 | R | 2
$ dnf history info last
Transaction ID : 3
Command Line : -y -q install tree
Packages Altered:
Install tree-1.8.0-10.el9.aarch64 @baseos
$ dnf history undo last -y
Removing:
tree aarch64 1.8.0-10.el9 @baseos 161 k
Erasing : tree-1.8.0-10.el9.aarch64 1/1
Removed:
tree-1.8.0-10.el9.aarch64
Complete!
$ rpm -q tree
package tree is not installed
How to read it: the ID column is the transaction number you pass to dnf history info <ID> and dnf history undo <ID> (last means the newest); Action(s) says what kind of change it was; Altered counts the packages it touched. info lists exactly which package versions were installed, upgraded or removed, which is how you confirm you are about to undo the right transaction. undo applies the inverse (here the install of tree became a removal), and rpm -q confirms the end state. If the RPM database state makes any part of the undo impossible, dnf refuses the whole transaction, as the table says, and an undo that needs an older version no repository still offers cannot succeed, so check that the old versions are available before you start. On a kernel update, dnf keeps older kernels installed (the default installonly_limit=3 in this container's /etc/dnf/dnf.conf keeps three), so the previous kernel is normally still there to select at boot; uname -r prints the kernel that is running right now.
Pinning on Debian-family hosts, same container method with debian:12:
$ apt-mark hold tree
tree set on hold.
$ apt-mark showhold
tree
$ apt-mark unhold tree
Canceled hold on tree.
hold pins the package at its current version so upgrades skip it (it does not revert anything), showhold lists what is pinned, and unhold releases it.
On Windows, a .cab is a Windows cabinet archive and an .msu is a Windows Update Standalone Installer file. DISM /Remove-Package takes either /PackageName:<name in the image> or /PackagePath:<path to a .cab>, and only .cab packages, never .msu. To find the name, Dism /Online /Get-Packages /Format:Table lists the packages in the running system; copy the one you need into /PackageName.
Choosing per workload (worked example)
Suppose 3,000 servers took the patch: 1,800 stateless web hosts (60 percent), 900 long-lived application servers (30 percent) and 300 databases (10 percent). 1,800 + 900 + 300 = 3,000.
- 1,800 web hosts: replace, do not repair. Rebuild from the previous image and let the load balancer shift traffic as health checks pass. This is the fastest and leaves no half-reverted state.
- 900 application servers: package-manager undo in batches, 10 percent at a time (90 hosts), verifying the application health check after each batch before the next. Start with a canary (a few hosts used first as an early test) to confirm the undo works on a real host.
- 300 databases: do not revert snapshots blindly. If the standby was patched last, fail over to it, then remove the patch from the former primary offline. Reverting a snapshot is only acceptable when you can state how many seconds of writes you can lose (the RPO, recovery point objective) and the business accepts it.
When rollback is simply not possible
- The update ran a one-way data or schema migration, or a database upgrade script rewrote on-disk formats; older software cannot read the new format.
- Firmware or BIOS updates that the vendor does not support downgrading.
- Windows images where component cleanup used
/ResetBase: Microsoft documents that installed updates cannot be uninstalled afterDISM /Cleanup-Image /StartComponentCleanup /ResetBase. - The old package or image is gone: repository mirror pruned it, or the golden image was overwritten.
- State changed since the snapshot and the business cannot lose it.
In those cases the answer is roll forward: ship a fixed or patched build, apply the vendor workaround, or restore service by failing over to hosts that never took the update.
Trade-offs and pitfalls
- Rolling back everything the same way wastes time on stateless hosts and risks data on stateful ones.
- Unverified rollbacks create a second incident: test the undo on a canary host before 900 hosts.
- Prevention matters more: patch in rings (a small canary group first, then wider groups with a soak period between), keep a known-good image and pre-patch snapshots, and keep old package versions in your mirror for the rollback window.
A small Linux web server serves only HTTPS to the public and takes SSH from a few admins. Design its host firewall policy, show the ruleset, and explain how you would test it and make it survive a reboot without cutting your own session.
Sample Answer
Direct answer
Use the kernel's own packet filter, nftables, on the server with a default-deny inbound policy: accept packets that belong to connections already allowed, accept loopback, accept a minimal set of ICMP, accept TCP 443 from anywhere, accept TCP 22 only from a named set of admin addresses, and drop everything else. Do not filter outbound for this host unless there is a reason (see the trade-off below). Test the file for syntax before applying it, apply it with a timed automatic rollback armed, confirm from a second, new session before cancelling the rollback, and make it permanent by putting it in the file the distribution's nftables service loads at boot.
If the host is already managed with ufw or firewalld, use that tool and express the same policy in it. Two firewall managers writing rules on one host is the failure to avoid.
Policy
| Traffic | Decision | Why |
|---|---|---|
| Inbound packets of an already-established or related connection | accept (first rule) | replies to the server's own outbound requests, and your existing SSH session, keep working while rules change |
Inbound packets in connection-tracking state invalid | drop | not part of any valid connection |
| Loopback interface | accept | local services talk to each other over it |
| ICMP and ICMPv6 error messages (destination-unreachable, time-exceeded, parameter-problem, packet-too-big) | accept | path MTU discovery (how hosts learn the largest packet that fits along the path) and error reporting fail without them. RFC 4890 section 4.3.1 says Destination Unreachable (all codes), Packet Too Big, Time Exceeded code 0 and Parameter Problem codes 1 and 2 must not be dropped, and section 4.3.2 says Time Exceeded code 1 and Parameter Problem code 0 normally should not be dropped; the ruleset accepts every code of all four types |
| ICMPv6 neighbour discovery (neighbour solicitation and advertisement, router advertisement) | accept | IPv6 hosts use them to find the other hosts on the link and the default gateway; blocking them breaks IPv6 on this host |
| Echo request (ping), IPv4 and IPv6 | accept, limited to 5 per second | lets monitoring and humans check reachability, with a cap on abuse |
| TCP 443 | accept from anywhere | the service this host exists to provide |
| TCP 22 | accept only from admin_v4 / admin_v6 sets | SSH exposed to the internet is the most attacked port; a handful of known addresses removes that exposure |
| Anything else inbound | drop (policy drop) | default deny: a service nobody planned for is not reachable by accident |
| Forwarding | drop | this is a server, not a router |
| Outbound | accept (see below) |
The firewall runs in the input hook of the server itself, so every packet addressed to the host passes it before any local program sees it. It complements, and does not replace, a cloud security group or a perimeter firewall: the host firewall is what still protects the server from other machines on the same network that have already been compromised.
The ruleset
#!/usr/sbin/nft -f
# Host firewall for a public HTTPS server with SSH from a few admin addresses.
# Replace only our own table, so rules from other tools (Docker, fail2ban) survive.
table inet filter
delete table inet filter
table inet filter {
set admin_v4 {
type ipv4_addr
elements = { 10.77.0.10, 10.77.0.11 }
}
set admin_v6 {
type ipv6_addr
elements = { fd00:77::10 }
}
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
ct state invalid drop
iifname "lo" accept
# IPv6 does not work without neighbour discovery
icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert, destination-unreachable, packet-too-big, time-exceeded, parameter-problem } accept
icmp type { destination-unreachable, time-exceeded, parameter-problem } accept
icmp type echo-request limit rate 5/second accept
icmpv6 type echo-request limit rate 5/second accept
tcp dport 443 accept
tcp dport 22 ip saddr @admin_v4 accept
tcp dport 22 ip6 saddr @admin_v6 accept
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}
Reading the ruleset, line by line
| Line | What it means |
|---|---|
table inet filter | A table is a named container for chains and sets. The family inet makes one table cover IPv4 and IPv6 together; filter is only the table's name |
set admin_v4 { type ipv4_addr; elements = { ... } } | A named list of addresses. Rules refer to it as @admin_v4, so the allowed admins live in one place |
chain input { | A chain is an ordered list of rules. Packets are checked against the rules from top to bottom |
type filter hook input priority filter; policy drop; | type filter: this chain accepts or drops packets. hook input: attach it where packets addressed to this host arrive (forward is for packets passing through, output for packets the host sends). priority filter: the order among chains on the same hook; filter is the standard name for priority 0. policy drop: a packet that reaches the end without being accepted is dropped |
ct state established,related accept | ct is connection tracking, the kernel's memory of each flow. A packet that belongs to a connection already allowed (a reply, or a related error message) is accepted straight away, which is why this rule comes first |
ct state invalid drop | Packets that fit no known connection are dropped |
iifname "lo" accept | iifname is the input interface name. lo is the loopback interface, used by programs on this host talking to each other |
icmpv6 type { nd-neighbor-solicit, ... } accept | Accept the listed ICMPv6 message types: neighbour discovery (nd-...) plus the error types |
icmp type echo-request limit rate 5/second accept | Accept ping requests only while fewer than 5 per second arrive; the excess does not match this rule, falls through to the end and meets policy drop |
tcp dport 443 accept | dport is the destination port: anyone may connect to HTTPS |
tcp dport 22 ip saddr @admin_v4 accept | Port 22 and the source address (saddr) is in the set. The ip6 saddr line does the same for IPv6 |
chain forward / chain output | forward drops everything (not a router); output is policy accept, so outbound is unfiltered |
Each term in the policy table has a line that implements it:
| Policy row | Ruleset line |
|---|---|
| connection tracking (replies keep working) | ct state established,related accept and ct state invalid drop |
| path MTU discovery | packet-too-big in the icmpv6 line, destination-unreachable in the icmp line |
| neighbour solicitation and advertisement | nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert in the icmpv6 line |
| SSH from admins only | the two tcp dport 22 ... saddr @admin_... lines |
Notes on the file:
- The first two lines of the table section (
table inet filterthendelete table inet filter) make the file re-loadable: the first creates the table if it does not exist (so the delete never fails), the second removes it, and the definition that follows rebuilds it. Only this table is replaced, so tables created by other tools (Docker's, fail2ban's) are left alone.flush rulesetwould wipe those too. I loaded the file onto an empty ruleset, then again onto the existing table, and it succeeded both times; a tableinet othercreated beforehand survived. - The family
inetcovers IPv4 and IPv6 in one table, so there is no forgotten IPv6 path with no rules. The two address sets are separate because the address types differ. The example addresses are a documentation-style private range (10.77.0.0/24) and a unique-local IPv6 address; replace them with your admin or bastion addresses. - Sets can be changed without reloading the file:
nft add element inet filter admin_v4 '{ 10.77.0.99 }'adds an address. To make it permanent, add it to the file as well, or the next reload forgets it. ct stateis connection tracking: the kernel remembers each flow, which is why one rule accepts all replies.
Test it before trusting it
-
Syntax check without applying:
nft -c -f /etc/nftables.confparses the file and reports errors without changing the running ruleset. -
Behaviour test from outside, using throwaway containers. This needs Docker on a Linux machine. Three containers share one Docker network: a server with the ruleset loaded and listeners on 22, 443 and 8080, one probe at an admin address and one at an address that is not in the set (the network, names and addresses are illustrative):
bash# setup, run from a directory holding web-fw.nft (the ruleset above), echo_server.py, server.sh and probe.sh docker network create --subnet 10.77.0.0/24 fw-test-net docker run -d --name fw-server --network fw-test-net --ip 10.77.0.2 --cap-add NET_ADMIN \ -v "$PWD":/w ubuntu:24.04 bash /w/server.sh docker run -d --name fw-admin --network fw-test-net --ip 10.77.0.10 -v "$PWD":/w ubuntu:24.04 sleep 300 docker run -d --name fw-other --network fw-test-net --ip 10.77.0.50 -v "$PWD":/w ubuntu:24.04 sleep 300 # wait for the server to finish installing and loading (about 30 seconds), then probe from each client docker exec fw-admin bash /w/probe.sh docker exec fw-other bash /w/probe.sh # cleanup docker rm -f fw-server fw-admin fw-other && docker network rm fw-test-net--cap-add NET_ADMINlets the server container change its own firewall; the clients do not need it. The echo server is a few lines of Python that listens on port 22 and sends back whatever it receives:python# echo_server.py import socket s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("0.0.0.0", 22)) s.listen() while True: c, _ = s.accept() while True: d = c.recv(100) if not d: break c.sendall(d)bash# server.sh (runs in the server container: Ubuntu 24.04) apt-get update -qq && apt-get install -y -qq nftables python3 > /dev/null python3 /w/echo_server.py & # echo server on TCP 22 for p in 443 8080; do python3 -m http.server "$p" --bind 0.0.0.0 > /dev/null 2>&1 & done nft -c -f /w/web-fw.nft && nft -f /w/web-fw.nft wait # keep the container (and the listeners) alive # probe.sh (runs in each client container; the server is 10.77.0.2) for p in 22 443 8080; do timeout 2 bash -c "exec 3<>/dev/tcp/10.77.0.2/$p" 2>/dev/null \ && echo "port $p open" || echo "port $p blocked/timeout" doneReading the probe:
/dev/tcp/HOST/PORTis not a real file but a bash feature, andexec 3<>/dev/tcp/10.77.0.2/22makes bash try to open a TCP connection to that address and port as file descriptor 3. If the connection is accepted the command succeeds, so&&prints "open". A dropped packet gets no reply, so the attempt hangs untiltimeout 2kills it after 2 seconds and||prints "blocked/timeout". A closed port that is not firewalled would answer at once with a refusal and print the same blocked message. Without the finalwaitthe script ends, the container exits and every probe prints blocked/timeout. With it, the probes printed exactly the table below.Probe from port 22 port 443 port 8080 admin address 10.77.0.10 open open blocked/timeout other address 10.77.0.50 blocked/timeout open blocked/timeout This confirms all three decisions: the public service is reachable by everyone, SSH only by the admin set, and an unplanned port by nobody.
-
Check that reloading does not drop a live session. A client at an admin address opens a TCP session to port 22, the server's ruleset is reloaded with
nft -fwhile the session is open, and the client sends again:python# session_client.py <server-ip> import socket, sys, time s = socket.create_connection((sys.argv[1], 22), timeout=5) s.sendall(b"before"); print("echo 1:", s.recv(100)) time.sleep(6) # the server reloads its ruleset during this pause s.sendall(b"after-reload"); print("echo 2:", s.recv(100))Output:
echo 1: b'before'thenecho 2: b'after-reload'. The established-connection rule is what carries the session across the reload.
Applying it on a real host without cutting yourself off
Two ways lock-outs happen: a typo in the admin address set, and rules that load fine but block the path you are using. Guard against both:
# 1. save our own table so it can be put back (or removed again if it did not exist)
{ echo 'table inet filter'; echo 'delete table inet filter'; nft list table inet filter 2>/dev/null; } > /root/fw-before.nft
# 2. arm a rollback in 2 minutes (systemd transient timer)
systemd-run --unit=fw-revert --on-active=2min /usr/sbin/nft -f /root/fw-before.nft
# 3. validate, then apply
nft -c -f /etc/nftables.conf && nft -f /etc/nftables.conf
# 4. from a SECOND terminal, open a new SSH connection from an admin address
# and request the HTTPS page from outside; only then cancel the rollback:
systemctl stop fw-revert.timer
Reading step 1: the curly braces form a brace group, which runs the three commands one after the other and lets one > send their combined output to a single file. The file therefore starts with table inet filter (create the table if it is missing, so the next line cannot fail) and delete table inet filter (remove it), followed by nft list table inet filter (the current definition of that table in loadable form, or nothing if there is no such table). Loading the file later first removes our table and then re-creates the old one if there was one. Only our own table is touched, which matches how the ruleset file itself is loaded. In step 2, systemd-run --on-active=2min schedules that load to run once, 2 minutes from now.
If the new rules strand you, you do nothing and the timer restores the old behaviour in 2 minutes. The saved file begins with the create-then-delete pair because loading a file does not remove rules that are already present; I checked that loading an empty file left the new rules in place, that the saved file removed the table again when none existed beforehand, and that, when one did exist, adding a rule and then loading the saved file brought back exactly the saved rules. I did not save the whole ruleset with flush ruleset because that is not safe on a host that also runs Docker: nft list ruleset prints the iptables-nft compatibility tables too, and in a test container nft -f refused to load them back with unsupported xtables compat expression. A file loads as one transaction, so that error would have meant the revert changed nothing and the lock-out stayed in place, and a successful flush would also have wiped the other tools' tables that the ruleset file takes care to leave alone. systemd-run --on-active= creates a transient timer, and with --unit= the timer is named fw-revert.timer; the revert command itself was not run here, because the test containers have no systemd. Keep out-of-band access (a cloud serial console or hypervisor console) ready, since it is the only route back if even the timer fails.
Surviving a reboot
On Debian and Ubuntu the nftables package ships nftables.service, whose ExecStart is /usr/sbin/nft -f /etc/nftables.conf, so the file above goes in /etc/nftables.conf and systemctl enable nftables makes it load at boot. On the RHEL family the service loads /etc/sysconfig/nftables.conf instead (in the AlmaLinux 9 package, whose ExecStart is /sbin/nft -f /etc/sysconfig/nftables.conf, that file ships with the sample include commented out), so use include there or put the rules in that file. To test persistence without waiting for a reboot, run nft flush ruleset from a console session and then systemctl restart nftables and list the ruleset; then do one real reboot in a maintenance window, with console access open, before calling it done.
Trade-offs and what would change the design
- Outbound
accept: a web server that can reach anywhere makes data theft and reverse shells easier after a compromise. The alternative is an outbound allow-list (DNS, time sync, package repositories, the specific APIs the application calls). I would take that for a server holding sensitive data, and accept the maintenance cost (every new dependency is a ticket). For a small server whose compromise has limited blast radius, accept-all outbound plus egress monitoring is a defensible choice. - SSH allow-list versus a bastion or VPN: if admins have changing addresses, an allow-list becomes constant churn and lock-outs. Allow SSH only from the bastion's address instead, and control who can use the bastion.
- Rate-limiting echo and new connections is a convenience, not a security boundary. Real denial-of-service protection happens upstream.
- Containers on the same host (Docker, Kubernetes) add their own rules and forwarding behaviour. The scoped
delete tableapproach avoids deleting them, but you must test the combination.
Pitfalls
- Putting
ct state established,related acceptafter the SSH rule, or omitting it, and cutting off the session when the policy loads. - Forgetting IPv6: an IPv4-only ruleset leaves the host wide open over IPv6 if it has an address, which is why the table is
inet. - Setting
policy dropon the input chain before confirming the ICMPv6 neighbour-discovery rules, so the host loses its default gateway and drops off the network. - Testing only from inside the host, which shows nothing about what the network can reach.
What is configuration drift on a server fleet, and how do you find and deal with it? Where would you refuse to auto-correct it?
Sample Answer
Direct answer
Configuration drift is the gap that opens between what a server is supposed to be configured as (the declared, version-controlled desired state) and what it actually is, because someone or something changed it outside that process. A hotfix typed on one box during an incident, a package that rewrote a config file, a vendor installer, an auto-scaling replica built from an older image: after a few months no two "identical" servers are identical. You find drift by comparing actual state to desired state on a schedule and you deal with it by either reverting the server to the declared state (making it converge: bringing the live state back into line with the declared state) or adopting the change into the declaration, never by leaving it undocumented. You should refuse to auto-correct wherever a silent revert can cause an outage, destroy evidence, or overrule a human who is mid-incident.
Why it matters
Drift breaks three things at once: reproducibility (you cannot rebuild a server and get the same result), security (the hardened setting someone loosened to "just get it working" stays loosened), and troubleshooting (the one node with a different sysctl (a kernel setting, such as a network buffer size) is the one with the odd latency). It also invalidates audit evidence, because a scan from last quarter says nothing about today.
Finding it: four detection methods
| Method | What it compares | Real example |
|---|---|---|
| Configuration-management dry run | declared state vs live host, no change made | ansible-playbook site.yml --check --diff |
| Package verification | installed files vs what the package shipped | rpm -V <pkg>, dpkg --verify <pkg> |
| Benchmark scan | live settings vs a baseline profile | OpenSCAP or CIS-CAT (benchmark scanners) on a schedule |
| File integrity monitoring (FIM: tools that compute a checksum of each watched file and alert when it changes) | file hashes now vs a recorded baseline | AIDE (an open-source file integrity checker), or a commercial FIM |
Two of these, run in test containers:
An Ansible dry run (--check --diff) after someone edited a managed SSH drop-in file on the host. The declaration is a one-task play that owns the whole file:
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Write the drop-in (sshd -t checks the candidate before it replaces the file)
ansible.builtin.copy:
dest: /etc/ssh/sshd_config.d/00-hardening.conf
content: |
# Managed by Ansible. Local edits are overwritten.
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
validate: /usr/sbin/sshd -t -f %s
The host's copy of the file had PasswordAuthentication yes. Nothing is changed by the dry run. --check means "report what you would change, change nothing", and --diff prints the file differences. Read the diff like a patch: lines starting with - are what the server has now, lines starting with + are what the declaration would write, and unmarked lines are unchanged context:
TASK [Write the drop-in (sshd -t checks the candidate before it replaces the file)] ***
--- before: /etc/ssh/sshd_config.d/00-hardening.conf
+++ after: /etc/ssh/sshd_config.d/00-hardening.conf
@@ -1,4 +1,4 @@
# Managed by Ansible. Local edits are overwritten.
PermitRootLogin no
-PasswordAuthentication yes
+PasswordAuthentication no
KbdInteractiveAuthentication no
Package verification after changing a packaged file's permissions (chmod 666 /etc/passwd) on AlmaLinux 9, and appending a line to /etc/bash.bashrc on Ubuntu:
$ rpm -V setup
.M....... c /etc/passwd <- M: mode differs from the package's
$ dpkg --verify bash
??5?????? c /etc/bash.bashrc <- 5: checksum differs from the package's
Reading the first column: rpm -V prints nine characters, one per test, in the order Size, Mode, digest (checksum), Device, symLink, User, Group, Time, caPabilities. A . means that test passed, a letter or digit means it failed, and ? means the test could not be performed. So .M....... says only the Mode (permissions) differs, and ??5?????? from dpkg --verify says the checksum differs, while the ? marks are tests dpkg did not perform (it stores checksums rather than modes or owners). An unchanged file prints nothing, and on Ubuntu dpkg --verify also prints lines starting with missing for files absent from the image, such as documentation trimmed from a container; those are not drift. The c marks a configuration file, which administrators are expected to edit, so these tools tell you a file differs, not whether the difference is wrong. That judgement needs the declared state.
A dry run only catches drift in what you have declared. Undeclared drift (a new listening service, a new local user, a new cron job) is found by the baseline scan, the FIM, and by comparing inventories (listening ports, local accounts, installed packages) across hosts of the same role and flagging the outlier.
Dealing with it: a decision, not a reflex
For each finding, ask who is right, the declaration or the server:
- The server is wrong (accidental edit, failed update): revert it, and record that it happened.
- The server is right (a fix that should be permanent): change the declared state through the normal review process, so every other server converges to it. Reverting would reintroduce the bug.
- Nobody knows: do not guess. Open a ticket to the owner and leave it, flagged, until answered.
Then shrink the cause: reduce who can log in and change things by hand, make changes through pipelines, rebuild from images (an immutable setup means servers are never changed after they are built: nothing edits a server in place, and replacing an instance discards any hand edit), and run the dry run on a schedule with the result going to a dashboard (the count of changed items per host, trending down).
Where I would refuse to auto-correct
| Situation | Why an automatic revert is dangerous |
|---|---|
| A host with an open incident or a change in progress | The "drift" may be the responder's mitigation. A revert reopens the problem. Mark the host as under change hold, with an expiry. |
| Settings whose change needs a restart or a live reconnect (database parameters, cluster membership, network and firewall rules, SSH daemon settings) | The correction itself can cause the outage or cut the admin's own session. These go through a staged, validated rollout. |
| Stateful data and application state (database files, queues, certificates in use) | Config tools converge configuration, not data; "correcting" can discard state. |
| Security-relevant surprises (a new authorized SSH key, a new local administrator, a changed audit configuration, a modified system binary) | This may be a compromise. Reverting destroys evidence. Preserve the host's state, alert the security team, then remediate. |
| Hosts whose declared state is itself unreliable (the declaration is stale or untested) | Auto-reverting enforces a wrong definition at scale, quickly. |
| Anything that spans many hosts at once with one wrong value | A bad declaration pushed by an auto-correct loop is a fleet-wide outage; limit with batch sizes (the first host, then 25%, and so on) and automatic stop on failure. |
The rule I apply: auto-correct only settings that are low-risk, idempotent (re-applying the correction when nothing is wrong changes nothing) and cheap to verify (file permissions, a banner, a sysctl value (a kernel setting), a package present); detect-and-alert on everything else.
Trade-offs
- Correcting every few minutes keeps hosts clean but fights incident responders and hides the human process problem that created the drift. Correcting daily with alerts on repeated offenders surfaces the cause.
- A strict "any difference is drift" policy drowns teams in noise from files that are meant to differ per host (hostnames, certificates, machine IDs). Declare those as per-host variables or exclude them explicitly, with a reason.
Design a patch cadence for a company with about 500 mixed Windows and Linux servers, three-tier web applications and a small DBA team. What does the monthly cycle look like and what are your target timelines?
Sample Answer
Direct answer
Run a monthly cycle anchored on the second Tuesday (when Microsoft normally publishes its monthly security updates), push it through four rings (staged groups of servers that receive the update one group after another, each group proving the update safe for the next) that grow from about 4% of the estate to all 500 servers, put hard timelines on severity, and keep a separate emergency track for actively exploited flaws. Windows follows the Microsoft release date; Linux packages arrive continuously, so Linux follows the same ring calendar rather than its own, which keeps the DBA team's workload predictable.
Assumptions I am making (change them if the facts differ): about 500 servers, a three-tier web application (web, application, database), redundant pairs for most web and application hosts, a small team of database administrators (DBAs) who must be present for database restarts.
The monthly cycle (November 2026 as the worked calendar)
Release day is the second Tuesday, 2026-11-10. The ring plan below was computed from that date, and the hosts add up to 500.
| Ring | Contents | Hosts | When | Date |
|---|---|---|---|---|
| 0 | Lab and canary hosts | 20 | Release day +1 | Wed 2026-11-11 |
| 1 | Non-production plus one node of every production tier | 60 | +3 | Fri 2026-11-13 |
| 2 | One member of each redundant production pair | 170 | +8 | Wed 2026-11-18 |
| 3 | The other node of each Ring 2 pair (170, database primaries included) plus all single-instance hosts and the partners of the Ring 1 production nodes (80 together) | 250 | +11 | Sat 2026-11-21 |
Where the ring sizes come from. They follow the shape of the estate, not a formula. Ring 0 is about 4% of the estate (20 of 500), small enough that a bad update harms little. Ring 1 adds 60, so 80 hosts (16%) have patched, and it holds non-production plus one node of every production tier (web, application, database) so each tier meets the update early. Ring 2 patches one node of each redundant pair, 170 hosts, bringing the total to 250 (50%). Ring 3 is what is left by construction: the other node of each of those 170 pairs (a partner is the second half of a pair whose first half patched in Ring 2) plus 80 more hosts (the single-instance hosts and the partners of the production nodes that patched in Ring 1), which makes 250 (the 170 and 80 split is illustrative). The running totals are 20, 80, 250 and 500, and 20 + 60 + 170 + 250 = 500.
A canary is a host patched first so that a bad update shows itself there while little depends on it; Ring 0 is the canary ring.
Ring 3 is the largest on purpose: by the time it runs, three earlier rings have already exercised every patch on every kind of host. Sunday 2026-11-22 is held as reserve in case Ring 3 spills over.
Between the rings, a gate (a checkpoint that must pass before the next ring may start): the next ring starts only if the previous ring has had its health checks green for at least 24 hours, no incident is attributed to the update, and failed installs share no common error. One failing gate pauses the cycle, which is cheaper than a failed Ring 3.
Target timelines by severity (my recommended policy, not an external standard)
| Class | Target | Calendar result for the November cycle |
|---|---|---|
| Actively exploited, or critical on an internet-facing host | 72 hours via the emergency track (below), using a reduced ring order | Within 3 days of confirmation |
| Critical | 14 days from release | By Tue 2026-11-24; the ring plan finishes on day 11, so it meets this with 3 days to spare |
| Important | 30 days from release | By Thu 2026-12-10 |
| Low and optional | Next cycle | Rolled into December |
The emergency track, as an example. Suppose a flaw in the web server software is confirmed as exploited on Thursday 2026-11-12 at 09:00, and the affected hosts are the internet-facing ones (illustrative: 40 of the 500, in pairs). The normal calendar is set aside and only the affected hosts are patched, in the same order of caution but with shorter waits:
| When | What | Gate before the next step |
|---|---|---|
| Thu 13:00 | the canary hosts that run the affected software | health checks green for 2 hours (instead of 24) |
| Thu 17:00 | one node of each internet-facing pair | health checks green until Friday morning |
| Fri 09:00 | the other node of each pair | health checks green |
If the last step finishes by Friday 12:00, that is 45 hours before the 72-hour limit (Sunday 2026-11-15 09:00), so a failed step still leaves time to retry. The rest of the estate follows the normal rings, with this update already in place.
Check on the arithmetic: 14 days after 2026-11-10 is 2026-11-24, and 30 days after is 2026-12-10, both computed from the date, not estimated. The severity classes and day counts are decisions for the business to own; if a regulation or contract sets a shorter period for your data, that period replaces mine.
What each cycle contains, in order
- Day 0: release lands; the patch lead reads the release notes and the vendor's list of known issues, and assigns each update a severity and a ring plan.
- Day 0 to 1: pre-checks on every host: free disk space, backups completed, snapshot taken for VMs.
- Rings 0 to 3 as above, each with the same ordered runbook: take one node out of the load balancer, patch, reboot if required, run health checks, put it back, then the next node. Never both nodes of a pair together.
- Databases (small DBA team): replicas first, then fail over, then patch the old primary, so the DBAs perform one controlled failover instead of an outage. Database hosts are never in Ring 0 to 2 as primaries, but their replicas are, so database patching is exercised early.
- Day 14 and day 30: compliance review against the timelines, with a named owner for every host that is behind.
Linux and Windows together
Windows hosts are driven by the central update tooling and follow the table directly. For Linux, pull fixes weekly into an internal repository snapshot (your own copy of the distribution's package repository), freeze the snapshot at the Ring 0 date, and let every later ring install from that same frozen snapshot, so Ring 3 gets exactly what Ring 0 tested rather than whatever has been published since.
Measures and rollback
- Success measure: the percentage of hosts patched within the target for their severity, reported per ring, with exceptions listed by owner. Exceptions need an expiry date.
- Rollback readiness: VM snapshots before patching for most hosts, a documented uninstall path tested on Ring 0, and for databases a verified backup before the primary is touched.
- Pause criteria: repeated install failure with the same error on two or more hosts, any health check failure on a production node, or a vendor advisory withdrawing an update.
Trade-offs
A longer deferral between rings lowers the chance of installing a bad update and raises the time an exposed host stays unpatched; the 72 hour emergency track exists precisely so the normal cycle can stay cautious. A Saturday Ring 3 uses the quietest load of the week and gives the DBAs one planned day for failovers, but it costs weekend staff time, so agree time off in lieu in advance.
Write the Ansible tasks that enforce your SSH daemon hardening settings idempotently, restart the service only when something actually changed, and confirm the result before the play can strand you.
Sample Answer
Direct answer
Put the settings in a drop-in file that sshd reads first, write it with the copy module and a validate: command so a bad file never replaces a good one, attach a handler that reloads the service so it runs only when the file really changed, then force that handler to run immediately and prove, from the controller and over a second, brand-new SSH connection, that the automation account can still log in while Ansible's original connection is held open as the way back. Before touching anything, refuse to continue if the account Ansible logs in with has no authorized key, since turning passwords off is the step that strands you. Run the play in small batches that stop on the first failure.
Terms used in the play
- Controller: the machine you run
ansible-playbookfrom. Inventory: the list of hosts and their connection details;linux_serversbelow is a group name from it. - Play and task: a play maps a set of hosts to an ordered list of tasks; a task calls one module (a unit of work such as
copy,statorcommand). - Handler: a task that runs only when another task tells it (
notify) that something changed. ansible_user: the inventory variable naming the account Ansible logs in to each host with.delegate_to: localhost: run this one task on the controller instead of on the target host.- SSH connection reuse: by default Ansible opens one SSH connection to each host and keeps it open for the whole play (the SSH options
ControlMasterandControlPersist;ControlPathis the socket file that shares it), so later tasks do not log in again.
The play
---
- name: Harden the SSH daemon without stranding the play
hosts: linux_servers
become: true
gather_facts: true
serial: [1, "25%"]
max_fail_percentage: 0
vars:
sshd_service: "{{ 'ssh' if ansible_facts['os_family'] == 'Debian' else 'sshd' }}"
sshd_dropin: /etc/ssh/sshd_config.d/00-hardening.conf
sshd_settings:
PermitRootLogin: "no"
PasswordAuthentication: "no"
KbdInteractiveAuthentication: "no"
PubkeyAuthentication: "yes"
X11Forwarding: "no"
MaxAuthTries: "3"
LoginGraceTime: "30"
tasks:
- name: Look up the account this play logs in with
ansible.builtin.getent:
database: passwd
key: "{{ ansible_user }}"
- name: Check that account has an authorized_keys file before passwords go away
ansible.builtin.stat:
path: "{{ getent_passwd[ansible_user][4] }}/.ssh/authorized_keys"
register: login_keys
- name: Stop here if key login is not already possible
ansible.builtin.assert:
that:
- login_keys.stat.exists
- login_keys.stat.size > 0
fail_msg: "{{ ansible_user }} has no authorized_keys; refusing to disable password login"
- name: Apply the hardening drop-in and prove it works
block:
- name: Write the drop-in (sshd -t checks the candidate before it replaces the file)
ansible.builtin.copy:
dest: "{{ sshd_dropin }}"
content: |
# Managed by Ansible. Local edits are overwritten.
{% for key, value in sshd_settings.items() %}{{ key }} {{ value }}
{% endfor %}
owner: root
group: root
mode: "0644"
validate: /usr/sbin/sshd -t -f %s
notify: Reload sshd
- name: Read the effective configuration sshd will use
ansible.builtin.command: /usr/sbin/sshd -T
register: sshd_effective
changed_when: false
check_mode: false
- name: Fail if any setting is overridden by an earlier file
ansible.builtin.assert:
that:
- (item.key | lower ~ ' ' ~ item.value | lower) in sshd_effective.stdout_lines
fail_msg: "{{ item.key }} is not {{ item.value }} in the effective config"
quiet: true
loop: "{{ sshd_settings | dict2items }}"
- name: Reload sshd now, not at the end of the play
ansible.builtin.meta: flush_handlers
- name: Prove a brand-new login works while the old connection is still open
ansible.builtin.command:
cmd: >-
ssh {{ ansible_ssh_common_args | default('') }}
-o BatchMode=yes -o ControlMaster=no -o ControlPath=none -o ConnectTimeout=10
{{ ('-i ' ~ ansible_ssh_private_key_file) if ansible_ssh_private_key_file is defined else '' }}
-p {{ ansible_port | default(22) }}
{{ ansible_user }}@{{ ansible_host | default(inventory_hostname) }} true
delegate_to: localhost
become: false
changed_when: false
check_mode: false
rescue:
- name: Remove our drop-in so the host returns to its previous behaviour
ansible.builtin.file:
path: "{{ sshd_dropin }}"
state: absent
notify: Reload sshd
- name: Reload sshd with the drop-in gone
ansible.builtin.meta: flush_handlers
- name: Fail this host loudly
ansible.builtin.fail:
msg: "SSH hardening failed on {{ inventory_hostname }} and was rolled back"
handlers:
- name: Reload sshd
ansible.builtin.service:
name: "{{ sshd_service }}"
state: reloaded
Reading the play in order
- Header.
become: trueruns tasks as root through sudo.serial: [1, "25%"]andmax_fail_percentage: 0set the batching, explained below.varsholds the service name (sshorsshdby OS family), the drop-in path and the settings as a dictionary. getentasks the host's account database for the login account. On a test host with the account set torootit returned the list["x", "0", "0", "root", "/root", "/bin/bash"]: the password placeholder, user id, group id, description, home directory and shell. Index 4 counts from zero, sogetent_passwd[ansible_user][4]is the home directory (/rootthere), and the next task looks for.ssh/authorized_keysinside it.statandassertcheck that file exists and is not empty, and stop the play before any change if not.block: everything inside is attempted as a unit; if any task in it fails, therescuelist runs instead.copywith the template: the line{% for key, value in sshd_settings.items() %}{{ key }} {{ value }}followed by{% endfor %}loops over the dictionary and writes oneKey valueline per setting. Rendered on a test host with two settings it produced exactly these lines after the comment:PermitRootLogin noandMaxAuthTries 3.validatechecks the candidate file, andnotifyqueues the handler only if the file changed.sshd -Tprints the effective configuration with lower-case keywords.changed_when: falsestops this read-only command being reported as a change, andcheck_mode: falsemakes it run even under--check.- The
assertloop runs once per setting. ForPermitRootLogin: "no"the expressionitem.key | lower ~ ' ' ~ item.value | lowerbuilds the textpermitrootlogin no(~joins strings,| lowerlower-cases), and the assertion is that this exact line appears in the list of output lines fromsshd -T. If an earlier file setPermitRootLogin yes, the linepermitrootlogin yesappears instead, the text is missing, and the task fails. flush_handlersruns the queued reload now. The login test runs thesshcommand on the controller.rescueundoes the change and fails the host.
Why each piece is there
- Drop-in, not an edit of
sshd_config. The OpenSSH manual says anIncludepulls in files "in lexical order" and that "for each keyword, the first obtained value will be used". The distributionsshd_configincludes/etc/ssh/sshd_config.d/*.confnear the top (line 12 on the Ubuntu 24.04 test image, line 15 on AlmaLinux 9), so a file named00-hardening.confis read before the vendor's own drop-ins (AlmaLinux ships50-redhat.conf) and wins. Managing a whole file we own is also what makes the task idempotent (running it a second time changes nothing): the same content produces no change. validate: /usr/sbin/sshd -t -f %s.copywrites the candidate to a temporary path, runs the command with%sreplaced by that path, and replaces the real file only if it exits 0.sshd -tchecks "the validity of the configuration file and sanity of the keys". An invalid value never reaches/etc/ssh.- Why validation is not enough: the
sshd -Tassertion. The temporary file is checked alone, so a conflict with another file is invisible to it.sshd -Tprints the effective configuration (lower-case keyword, then value), and theassertcompares every setting we declared with whatsshdwould really use. It reads files from disk, so it works before the reload and is the guard against the "an earlier file wins" case. - Both
PasswordAuthenticationandKbdInteractiveAuthentication. They are separate switches (the second is the current name ofChallengeResponseAuthentication, a deprecated alias), and both default toyes, so disabling only one leaves a way to be asked for a password. notifyplusmeta: flush_handlers. A handler runs only if the notifying task reportedchanged, which gives "restart only when something changed". The default is to run handlers at the end of the play; flushing runs it now, so the proof happens while the play still has a working connection to fall back on.state: reloadedmakessshdre-read its configuration (the manual describes SIGHUP, the hang-up signal, as makingsshdre-execute itself with its original options) rather than stopping the daemon.- A fresh login from the controller, with the old connection still open. Ansible keeps one SSH connection open and reuses it (the
ControlPersistoption keeps that connection alive between tasks), so a "ping" after the reload would run over the old, already authenticated session and prove nothing. Thecommandtask runs a separatesshprocess on the controller (delegate_to: localhost,ControlPath=noneso it cannot share the master connection (the long-lived connection Ansible opened),BatchMode=yesso it fails instead of prompting) using the same host, user, port, key and extra SSH arguments as the inventory. Because it does not touch Ansible's own connection, that connection is still alive if the new login is refused, and therescuesection can still reach the host to undo the change. (The alternative,meta: reset_connectionfollowed bywait_for_connection, also proves a fresh login, but if the login fails there is no connection left to roll back over.) block/rescue. Any failure inside the block (validation, effective-config mismatch, failed new login) removes our drop-in, reloads, and fails the host loudly, so the host goes back to its previous behaviour instead of staying half-configured.serial: [1, "25%"]andmax_fail_percentage: 0. The first batch is one host (the canary); later batches are 25% of the inventory.max_fail_percentageapplies per batch, and at 0 any failure in a batch stops later batches. I verified that: with four hosts,serial: [1, "50%"]and one failure in the second batch, the fourth host never ran withmax_fail_percentage: 0and did run without it.- Service name.
sshon Debian and Ubuntu,sshdon the RHEL family; thesshd_servicevariable picks one from the OS family.
Results from a test run
The play ran against a real sshd over real SSH (a key-authenticated account with sudo, on 127.0.0.1) in an Ubuntu 24.04 container. That container has no systemd, so the reload handler used the init-script service manager there; on a systemd host the same task uses systemd.
RUN 1: PLAY RECAP target : ok=9 changed=2 failed=0 rescued=0
RUN 2: PLAY RECAP target : ok=8 changed=0 failed=0 rescued=0 (no handler ran)
$ sshd -T | grep -E '^(permitrootlogin|passwordauthentication|maxauthtries|logingracetime|x11forwarding) '
logingracetime 30
maxauthtries 3
permitrootlogin no
passwordauthentication no
x11forwarding no
Before the first run, the same host reported logingracetime 120, maxauthtries 6, passwordauthentication yes, x11forwarding yes.
Four deliberate failures:
| Injected fault | What happened |
|---|---|
PermitRootLogin maybe | copy failed with failed to validate and unsupported option "maybe"; no file was written; rescue ran; host failed |
a file 00-aaa-cloud.conf containing PasswordAuthentication yes | the assert failed on that setting; rescue removed our drop-in and reloaded; host failed |
a valid setting that locks the automation account out (AllowUsers nobody) | validation and the effective-config assert both passed, the reload ran, the fresh login from the controller was refused, and rescue then removed the drop-in and reloaded over the old connection; a re-run afterwards logged in normally |
the login account's authorized_keys removed | the pre-check assertion stopped the play before any change: deploy has no authorized_keys; refusing to disable password login |
Complexity and edge cases
- Work per host is constant (a handful of tasks, one file, one
sshd -T). Wall-clock time depends on the batch plan: for 100 hosts,serial: [1, "25%"]gives batches of 1, 25, 25, 25 and 24, which is five batches. - The login test proves the automation account can log in the way the inventory says it does. A human using a different key, or a
Matchrule that affects only some source addresses, is a different path; for hosts with such rules, add a second test task for that path. If the controller reaches hosts through a bastion or a different connection plugin, thesshcommand must be adapted to match (a bastion inansible_ssh_common_argscarries over). - The authorized-keys check proves a key file exists, not that the key matches the one in use. The login that follows the reload is the real proof; the pre-check only prevents the obvious foot-gun.
- A host with a console or out-of-band access (cloud serial console, hypervisor console) is the recovery path if all else fails; know where it is before the run.
- Settings not included here (
AllowGroups, ciphers and MACs) are deliberate omissions: each can lock out legitimate users or break older clients, so each gets its own tested change.
Unlock Full Question Bank
Get access to all 16 System and Endpoint Hardening interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.