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 security update requires a library upgrade that will break a business-critical application until the app is rebuilt. How do you work with the application owner and delivery team to get the patch out safely?
Sample Answer
Direct answer
Treat it as a risk decision shared with the application owner, not a ticket to push. First establish how exposed the vulnerable library really is. Then pick the fastest safe control that cuts that exposure now (a compensating control), and agree a dated plan to rebuild the application on the fixed library, with a tested rollback and an expiry on any exception. The application owner decides the business timing. You and the security team decide what risk is acceptable in the meantime, and both sign the exception.
Step 1: Size the exposure with the owner (day 0)
Terms: a CVE is a numbered public vulnerability record; CVSS is the severity score attached to it; the KEV catalog is the US CISA list of vulnerabilities known to be exploited in the wild; an SBOM (software bill of materials) is the list of components inside an application.
Ask these questions in this order, because each answer changes the plan:
- Is the vulnerable component actually present and loaded? Use the SBOM or a dependency scan. A copy that is on disk but never loaded is lower risk than one on the request path.
- Is the vulnerable code path reachable (can an attacker's input actually get to the flawed code)? Example: an XML library is flawed only in how it handles external entity declarations. If the app uses it to read its own fixed configuration file and never accepts XML from anyone else, the flaw is not reachable. If the app has an /import endpoint that hands an uploaded XML file straight to that parser, it is reachable.
- Who can reach the application: internet, partner network, or internal only?
- Is it on the KEV list or is a public exploit available? If yes, the time you can wait shrinks sharply. To check, search the CVE id in the CISA KEV catalog page, or read its JSON feed. This script, run in a Python container, looks up Log4Shell (CVE-2021-44228):
import json, urllib.request
url = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
catalog = json.load(urllib.request.urlopen(url))["vulnerabilities"]
for item in catalog:
if item["cveID"] == "CVE-2021-44228":
print(item["cveID"], item["vendorProject"], item["product"], item["dateAdded"])
Output it printed:
CVE-2021-44228 Apache Log4j2 2021-12-10
The line reads: CVE id, vendor and product, and the date CISA added it. A CVE that is not in the catalog prints nothing.
5. What does the application touch (payments, personal data) and what is the cost of an hour of downtime?
Step 2: Choose a stopgap that matches the exposure
| Option | Use when | Cost / limit |
|---|---|---|
| Turn off or block the vulnerable feature (config flag, route block) | Feature is optional | Business loses that feature |
| Restrict network reach (allow-list, move behind VPN) | Attack needs network access | Breaks legitimate external users |
Web application firewall (WAF) rule or virtual patch in front of the app (a rule that recognises the exploit's request pattern, for example a request body containing an XML <!ENTITY declaration, and blocks it before it reaches the app; the app itself is unchanged, hence 'virtual') | Exploit pattern is known and HTTP-borne | Bypassable; covers only the traffic that passes the WAF |
| Vendor backport or patched build of the old major version | Vendor offers one | Needs vendor support contract |
| Run the fixed library in a shimmed or side-by-side deployment (a shim is a thin adapter that translates the old library's calls into the new library's; side-by-side means the new library runs next to the old one, for example in a separate process, and only the exposed function is routed to it) | Break is a small API change | Engineering effort, own testing |
| Accept the risk temporarily | Low reachability, internal only | Needs a named approver and an expiry date |
Commit to the least disruptive control that genuinely closes the attack path, not the one that merely looks like a control. A WAF rule on an internal-only path does nothing if the attacker is already inside.
Step 3: Agree the delivery plan with the delivery team
- Set the milestones on a calendar with owners: rebuild on the new library, regression test, staging soak, production release. Example for a 21-day exception: day 0 exposure review and stopgap live; day 7 rebuilt build in staging; day 14 test sign-off; day 21 production release. The exception expires on day 21 and must be renewed by the approver, not silently extended.
- Release the way you would any risky change: canary (a small slice of traffic first) then widen, with the previous build kept deployable so rollback is a redeploy, not a rebuild.
- Test what actually breaks: the API changes between library versions, serialization formats (how data is written out as bytes or text, such as stored JSON or cached objects: a new version may write a date or field name differently, so data saved by the old build fails to load or other services cannot read it), and any behaviour the application relied on. Contract tests (automated tests that check each caller still gets the requests and responses it expects from the changed service) against dependants catch the downstream break.
- Keep a record: who accepted the residual risk, which compensating control is in place, and the date it is verified.
Worked example
An in-house billing service uses an XML library whose fix exists only in the next major version, which changes class names. The service is reachable only from the corporate network, and the vulnerable parser is used for one optional import feature. Decision: disable the import endpoint (stopgap, removes the reachable path), restrict the service to its three calling subnets, record a 21-day exception signed by the application owner and the security lead, and run the library upgrade on the delivery team's sprint. If the vulnerability turned out to be on the public request path and on the KEV list, the same facts would flip the plan: take the service out of public reach or pull a WAF block in within hours, and treat the rebuild as an emergency release.
Trade-offs and pitfalls
- Do not bypass the owner and force the upgrade: a broken business-critical app costs more than most delayed patches, and you lose trust for the next request.
- Do not accept "we will get to it" without a date: an exception with no expiry is a permanent unpatched system.
- Verify the stopgap works: test that the blocked path is actually blocked (try the exploit-shaped request in staging) instead of assuming.
- Look beyond this app: scan every other application using the same library so the one fix does not leave five siblings exposed.
How does patching change when hosts are immutable images rather than long-lived mutable servers? Describe a strategy that keeps OS, runtime and application layers current without losing control of rollout.
Sample Answer
Direct answer
With immutable images you never patch a running host. Patching becomes a rebuild: apply the update while building a new, versioned image, test that image, publish it, and replace hosts with it in waves. Rollback is replacing hosts with the previous image version. Control moves from "which servers did we reach tonight" to "which image version is each host running, and how fast is the fleet converging on the newest one".
A long-lived mutable server (a server you log in to and update in place) accumulates drift: two servers that started identical end up with different package sets after partial or failed updates. An immutable host cannot drift because nobody changes it after launch.
Three layers, three triggers
A host image is built from layers, and each layer has its own trigger and owner.
| Layer | What it contains | What triggers a rebuild | Typical owner |
|---|---|---|---|
| OS | Kernel, system libraries (for example OpenSSL), base packages | Vendor security release, plus a scheduled rebuild so the base never goes stale | Platform team |
| Runtime | JVM (Java virtual machine), Node.js, Python or .NET runtime and its system dependencies | New runtime patch release, end of support for a runtime version | Platform team with application teams |
| Application | Your code and its library dependencies | Normal release pipeline, dependency updates | Application team |
Each layer is built on the one below, so a change to a lower layer forces a rebuild and retest of everything above it. That is the real cost of immutability: a one-package OS fix means rebuilding the application images that sit on top. The answer is automation. A new base image publication automatically opens a build of every dependent image, runs the same tests, and produces candidate images without a person starting each build.
The patch pipeline
- Build from a pinned source. Build the base image from a dated snapshot of the vendor package repository, not "whatever is newest right now". The same inputs then give the same image, and a failed build can be reproduced.
- Record a manifest. Store the full package list and versions with every image. The question "is the fix for vulnerability X in production?" becomes a query over manifests and over "which image version does each host run", not a login to every host.
- Gate the image. Run automated tests on the image itself: it boots, the service starts, a smoke test passes, listening ports match what is expected. A vulnerability scan and signature check belong here as build gates. A signature check verifies, with the publisher's key, that the image was produced by your pipeline and not altered afterwards; the trusted registry is the image store your pipeline alone can write to. The fleet only launches images that pass both.
- Publish a version. Tag with something sortable, for example the build date plus a counter (
base-2026.10.05.1). Never move a floatinglatesttag, because then "which version is this host on" has no answer. - Roll out by replacement. Replace hosts in waves, with health checks deciding whether each wave may continue.
A manifest and the query over it, executed in a debian:12-slim container (the package names and versions are what that container printed; the "fixed" versions are illustrative thresholds, and 99.0 is an impossible version used to show a failing answer):
$ dpkg-query -W -f='${Package} ${Version}\n' bash coreutils > manifest-base-2026.10.05.1.txt
$ cat manifest-base-2026.10.05.1.txt
bash 5.2.15-2+b13
coreutils 9.1-1
$ ver=$(awk '$1=="bash"{print $2}' manifest-base-2026.10.05.1.txt)
$ dpkg --compare-versions "$ver" ge 5.0 && echo "bash $ver >= 5.0: image has the fix"
bash 5.2.15-2+b13 >= 5.0: image has the fix
$ dpkg --compare-versions "$ver" ge 99.0 || echo "bash $ver < 99.0: image is missing the fix"
bash 5.2.15-2+b13 < 99.0: image is missing the fix
The manifest is a plain list of package and version, stored beside the image base-2026.10.05.1. The question "is the fix in production?" becomes: for each image version in use, compare the manifest's version with the fixed version (dpkg --compare-versions does the version ordering), then count the hosts per image version. "Pinned snapshot" means the build reads packages from a copy of the repository frozen at a date, and a floating latest tag is a label that is moved to point at newer images, so it stops naming one specific image.
Rollout with control: a worked example
Take a stateless web tier (hosts that keep no data that must survive replacement) of 40 hosts in one fleet group. Amazon EC2 Auto Scaling (Amazon's service that keeps a group of virtual servers at a set size) has a feature called instance refresh that replaces the servers in a group with new ones in waves. It is one concrete mechanism; any orchestrator that replaces hosts in waves works the same way. Its documented settings map to the controls you want:
- Minimum healthy percentage: how much of the desired capacity must stay in service. The documented default is 90 percent when no instance maintenance policy exists. At 90 percent of 40, at least 36 hosts must stay healthy, so at most 4 are replaced at a time.
- Checkpoints (
CheckpointPercentages): points where the refresh pauses so you can verify before continuing. With checkpoints[10, 50, 100]on 40 hosts, the pauses come when 4 hosts (10 percent), 20 hosts (50 percent) and 40 hosts (100 percent) are on the new image. At 4 hosts per wave that is after wave 1, wave 5 and wave 10. - Checkpoint delay: how long to wait at a checkpoint. The documented default is one hour.
- Instance warmup: how long a new host has to finish initializing before the next replacement. The refresh does not move on the moment a new host is healthy; it waits out the warmup first. With 40 hosts and a 90 percent minimum, up to 4 hosts are taken out, their 4 replacements launch, and only after those replacements pass their health checks and finish the warmup does the next batch of 4 begin. A longer warmup therefore stretches every one of the 10 waves, and the minimum healthy percentage is what caps how many hosts may be out at once while that happens.
- Auto rollback is disabled by default, so turn it on and connect it to an Amazon CloudWatch alarm (AWS's monitoring service) on error rate or latency if you want the refresh to undo itself.
The first checkpoint is your canary (a small first group that receives the change before everyone else): 4 of 40 hosts take real traffic on the new image while you compare their error rate and latency with the other 36. The comparison is only meaningful if the canary hosts see the same kind of traffic as the rest, so judge it on rates (errors per request) and not on raw counts.
Keeping the layers current without losing control
- Cadence: rebuild the base on a schedule (for example monthly) even when no urgent fix exists, so hosts are never far behind. Add a maximum host age, for example 30 days, after which a host is replaced regardless. Both are example policies; choose them from your risk tolerance.
- Emergency path: a critical vulnerability goes through the same pipeline with tighter checkpoints, not through logging in to hosts. A manual hotfix on a live host defeats the model, so if one is ever applied, tag the host for replacement within a stated number of hours.
- Measure convergence: report the percentage of hosts on the current image and the age of the oldest host. A fleet stuck at 70 percent means the rollout is blocked, not that patching is done.
- State lives elsewhere: databases, uploads and sessions must sit on managed services or attached volumes, because replacement discards the host's local disk. Hosts that cannot meet this (a stateful database node) are patched with a failover pattern: patch the replica, promote it, then patch the old primary.
Scanning and signing are controls on the pipeline above: they are gates before publish, so a host can only ever launch an image that passed them. If the hosts are containers on an orchestrator, the same rule applies one level up: the image tag is the unit you version, and the orchestrator's rolling update takes the place of the instance refresh.
Trade-offs and pitfalls
| Choice | Benefit | Cost or risk |
|---|---|---|
| Rebuild the whole image for a one-package fix | Tested artifact, atomic rollback | Build capacity, and a slower path for a single urgent package |
| Unpinned package repository during build | Always newest | Builds are not reproducible, so a bad image cannot be recreated |
| Weak health checks ("port is open") | Fast rollouts | A broken image passes every wave and reaches 100 percent |
| Very short checkpoint delay | Quick completion | Slow failures (memory leak, cache warm-up) appear after the canary is declared good |
| Keeping old images | Fast rollback | Storage cost and old vulnerable images that must be blocked from launching |
What would change the recommendation: for a small fleet of stateful, licensed or hardware-bound servers, in-place patching with rings and a tested rollback (snapshot or replica failover) can be cheaper than building an image pipeline. The immutable model pays off when hosts are interchangeable and the fleet is large enough that drift is the dominant risk.
Write an Ansible play that applies security updates on Ubuntu hosts, records whether the kernel was upgraded, and reboots only in that case. It must be idempotent and safe to run against production.
Sample Answer
Direct answer
Install only the security origins with unattended-upgrade (Ubuntu's tool that installs only updates from the origins listed in its configuration), compare the installed kernel image packages before and after, set a fact kernel_upgraded from that comparison, and call ansible.builtin.reboot only when the fact is true. Make it safe for production with serial (a few hosts per batch) and max_fail_percentage: 0 (stop the rollout on the first failure), make check mode a read-only preview, and make a second run change nothing (that property is called idempotence: running the play again on an already-patched host reports no change). The playbook below was run in an Ubuntu 24.04 container to verify each of those properties, with one stand-in explained afterwards.
The playbook
---
- name: Apply Ubuntu security updates and reboot only after a kernel upgrade
hosts: "{{ target_hosts | default('ubuntu_prod') }}"
become: true
serial: "{{ batch_size | default(1) }}"
max_fail_percentage: 0
vars:
# Versioned kernel image packages (linux-image-6.8.0-45-generic), not the
# linux-image-generic meta package, which keeps one name across upgrades.
kernel_package_regex: '^linux-image-[0-9]'
tasks:
- name: Snapshot installed packages before the upgrade
ansible.builtin.package_facts:
manager: apt
- name: Remember the kernel images (name=version) installed before the upgrade
ansible.builtin.set_fact:
kernels_before: "{{ ansible_facts.packages | dict2items
| selectattr('key', 'match', kernel_package_regex)
| map(attribute='key') | sort
| map('extract', ansible_facts.packages) | map('first') | map(attribute='version')
| zip(ansible_facts.packages | dict2items
| selectattr('key', 'match', kernel_package_regex)
| map(attribute='key') | sort) | map('reverse') | map('join', '=') | list }}"
- name: Install the tool that restricts upgrades to the security origins
ansible.builtin.apt:
name: unattended-upgrades
state: present
update_cache: true
cache_valid_time: 3600
- name: Preview what would be upgraded (check mode only, changes nothing)
ansible.builtin.command: unattended-upgrade --dry-run --verbose
register: security_preview
changed_when: false
check_mode: false
when:
- ansible_check_mode
- "'unattended-upgrades' in ansible_facts.packages"
- name: Apply security updates (origins come from Allowed-Origins in 50unattended-upgrades)
ansible.builtin.command: unattended-upgrade --verbose
register: security_run
changed_when: "'Packages that will be upgraded' in security_run.stdout"
when: not ansible_check_mode
- name: Snapshot installed packages after the upgrade
ansible.builtin.package_facts:
manager: apt
- name: Record whether a new kernel image arrived
ansible.builtin.set_fact:
kernels_after: "{{ ansible_facts.packages | dict2items
| selectattr('key', 'match', kernel_package_regex)
| map(attribute='key') | sort
| map('extract', ansible_facts.packages) | map('first') | map(attribute='version')
| zip(ansible_facts.packages | dict2items
| selectattr('key', 'match', kernel_package_regex)
| map(attribute='key') | sort) | map('reverse') | map('join', '=') | list }}"
- name: Decide
ansible.builtin.set_fact:
kernel_upgraded: "{{ (kernels_after | difference(kernels_before)) | length > 0 }}"
- name: Report the decision per host
ansible.builtin.debug:
msg: "{{ inventory_hostname }} kernel_upgraded={{ kernel_upgraded }} before={{ kernels_before }} after={{ kernels_after }}"
- name: Reboot only when a kernel was upgraded in this run
ansible.builtin.reboot:
reboot_timeout: 900
msg: "Rebooting after kernel upgrade (Ansible)"
when:
- kernel_upgraded | bool
- not ansible_check_mode
tags: reboot
Inventory used for the test (inventory.ini):
[ubuntu_prod]
localhost ansible_connection=local
Run it as ansible-playbook -i inventory.ini security-updates.yml -e batch_size=2 against real hosts: two hosts per batch, and a failed host stops later batches.
Reading the kernel-detection chain
package_facts fills ansible_facts.packages with a dictionary: each key is a package name and each value is a list of installed versions. The long expression in kernels_before (and the identical one in kernels_after, which runs after the upgrade) turns that dictionary into a list of name=version strings for kernel images only. Read it one filter at a time, using illustrative package data (a kernel image, the linux-image-generic meta package that keeps one name across upgrades, and an unrelated package; the versions are made up). Each stage below was run with ansible-core 2.16.3 in an Ubuntu 24.04 container:
| Filter stage | What it does | Result on the illustrative data |
|---|---|---|
dict2items | turns the dictionary into a list of {key, value} pairs so it can be filtered | three pairs: linux-image-6.8.0-45-generic, linux-image-generic, openssl |
selectattr('key', 'match', kernel_package_regex) | keeps pairs whose name matches ^linux-image-[0-9], which means "starts with linux-image- followed by a digit" | the meta package and openssl are dropped |
map(attribute='key') | sort | takes just the names and sorts them so both lists use one order | ['linux-image-6.8.0-45-generic'] |
map('extract', ansible_facts.packages) then map('first') then map(attribute='version') | looks each name up in the dictionary, takes the first (usually only) installed entry, and reads its version | ['6.8.0-45.45'] |
zip(<the same sorted names>) | pairs each version with its name | [['6.8.0-45.45', 'linux-image-6.8.0-45-generic']] |
map('reverse') | map('join', '=') | list | flips each pair to name first and joins with = | ['linux-image-6.8.0-45-generic=6.8.0-45.45'] |
The names are listed twice in the expression because zip needs a second copy of the sorted name list to pair against. The final value on this data was ['linux-image-6.8.0-45-generic=6.8.0-45.45'].
Why name=version pairs and not just names: a new kernel normally arrives as a new package name (...-52-generic), but a rebuilt package can keep its name with a new version, and the pair catches both. difference returns the items of the first list that are not in the second. After an upgrade that installs a second kernel, with illustrative lists, ['linux-image-6.8.0-52-generic=6.8.0-52.53', 'linux-image-6.8.0-45-generic=6.8.0-45.45'] | difference(['linux-image-6.8.0-45-generic=6.8.0-45.45']) printed ['linux-image-6.8.0-52-generic=6.8.0-52.53']: one new pair, so its length is above zero and kernel_upgraded is true. If nothing new arrived the difference is empty and the length is 0.
In the playbook, changed_when: "'Packages that will be upgraded' in security_run.stdout" means Ansible reports the task as changed only when that phrase appears in the tool's output, which unattended-upgrade prints when it is about to upgrade packages.
Why each part is built this way
Security updates only. Ubuntu's unattended-upgrade reads Allowed-Origins (a setting in /etc/apt/apt.conf.d/50unattended-upgrades that lists which package sources it may install from). On the Ubuntu 24.04 image it printed Allowed origins are: o=Ubuntu,a=noble, o=Ubuntu,a=noble-security, o=UbuntuESMApps,a=noble-apps-security, o=UbuntuESM,a=noble-infra-security, and Initial blacklist: was empty, so kernels are not excluded by default. On the same fresh image, apt-get -s dist-upgrade (a simulation) listed libaudit1 coming from noble-updates, while unattended-upgrade reported No packages found that can be upgraded unattended: updates that exist only in the general updates pocket were left alone (a pocket is one of an Ubuntu release's update channels: noble is the release as shipped, noble-security the security fixes, noble-updates the other bug fixes). The alternative of apt with upgrade: dist and default_release: noble-security is weaker, because apt's target-release option raises the priority of that suite for packages that have a candidate in it; it does not exclude the other suites.
Detecting a kernel upgrade. A new kernel arrives as a new package whose name carries the version (for example linux-image-6.8.0-45-generic), while the linux-image-generic meta package keeps its name. The play records name=version pairs for packages matching ^linux-image-[0-9] before and after, and kernel_upgraded is true when the after-list contains a pair the before-list lacks. It uses package_facts, which reads the package database, instead of parsing text output.
Reboot only in that case. The reboot task has two conditions, kernel_upgraded | bool and not ansible_check_mode. ansible.builtin.reboot waits until the host answers again; it compares /proc/sys/kernel/random/boot_id (a random ID the kernel generates at each boot, so a new value proves the machine really restarted) before and after to prove that a real reboot happened, and reboot_timeout: 900 gives the host 900 seconds to come back (the default is 600).
Safe against production.
seriallimits the batch, so capacity is never fully removed.max_fail_percentage: 0aborts the play when any host in a batch fails, so one bad host stops the rollout. When this was tried with three hosts,serial: 1and a failure on the second host, the third host was never run.- Check mode (
--check) must not change anything. Here the apply task is skipped under check mode and a separate task runsunattended-upgrade --dry-run(markedcheck_mode: falseso that it really runs, andchanged_when: false) to preview what would happen. That preview only runs whenunattended-upgradeswas already installed when the play started (the package facts from before the install decide this): on a bare host a check-mode run reports the install as the pending change and skips the preview instead of failing, because the command does not exist until the real run installs it. - The kernel decision is taken after the upgrade from facts, so it does not depend on the text output of the upgrade tool.
Verification that was actually run
The container has no kernel packages, so the printed output below shows a different package where a real run shows a kernel image. The substitution, in full:
| Real run | Test in the container |
|---|---|
kernel_package_regex is ^linux-image-[0-9] | overridden on the command line to ^libssl3t64$, so the OpenSSL library package is the one tracked (the \$ is shell escaping for the end-of-name anchor) |
| a security update installs a new kernel image | libssl3t64 is first downgraded to its release version, so the security update upgrades it |
before and after list linux-image-...=... pairs | they list libssl3t64=... pairs, as the output shows |
| the reboot task runs when the decision is true | it is skipped with --skip-tags reboot, because a container cannot reboot |
In detail: libssl3t64 was downgraded to its release version (3.0.13-0ubuntu3), and the play was run with kernel_package_regex overridden to ^libssl3t64$, so the security update of that package plays the role of a kernel upgrade. The reboot task itself was not executed (a container cannot reboot); --skip-tags reboot was used in the run where the decision was true, and the when condition produced the skip in the other runs.
apt-get install -y ansible-core sudo python3-apt unattended-upgrades
apt-get install -y --allow-downgrades libssl3t64=3.0.13-0ubuntu3 openssl=3.0.13-0ubuntu3
ansible-playbook -i inventory.ini security-updates.yml --syntax-check
ansible-playbook -i inventory.ini security-updates.yml --check -e "kernel_package_regex='^libssl3t64\$'" \
| grep -E "TASK \[(Preview|Apply|Report|Reboot)|Packages that|kernel_upgraded|skipping|changed=|fatal"
dpkg-query -W libssl3t64
TASK [Preview what would be upgraded (check mode only, changes nothing)] *******
TASK [Apply security updates (origins come from Allowed-Origins in 50unattended-upgrades)] ***
skipping: [localhost]
TASK [Report the decision per host] ********************************************
"msg": "localhost kernel_upgraded=False before=['libssl3t64=3.0.13-0ubuntu3'] after=['libssl3t64=3.0.13-0ubuntu3']"
TASK [Reboot only when a kernel was upgraded in this run] **********************
skipping: [localhost]
localhost : ok=9 changed=0 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0
libssl3t64:arm64 3.0.13-0ubuntu3
Check mode changed nothing: the package is still at the old version. Now the real run, then a second run:
ansible-playbook -i inventory.ini security-updates.yml -e "kernel_package_regex='^libssl3t64\$'" --skip-tags reboot \
| grep -E "TASK \[(Preview|Apply|Report|Reboot)|kernel_upgraded|skipping|changed="
ansible-playbook -i inventory.ini security-updates.yml -e "kernel_package_regex='^libssl3t64\$'" \
| grep -E "TASK \[(Apply|Report|Reboot)|kernel_upgraded|skipping|changed="
TASK [Preview what would be upgraded (check mode only, changes nothing)] *******
skipping: [localhost]
TASK [Apply security updates (origins come from Allowed-Origins in 50unattended-upgrades)] ***
TASK [Report the decision per host] ********************************************
"msg": "localhost kernel_upgraded=True before=['libssl3t64=3.0.13-0ubuntu3'] after=['libssl3t64=3.0.13-0ubuntu3.16']"
localhost : ok=9 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
skipping: [localhost]
TASK [Apply security updates (origins come from Allowed-Origins in 50unattended-upgrades)] ***
TASK [Report the decision per host] ********************************************
"msg": "localhost kernel_upgraded=False before=['libssl3t64=3.0.13-0ubuntu3.16'] after=['libssl3t64=3.0.13-0ubuntu3.16']"
TASK [Reboot only when a kernel was upgraded in this run] **********************
skipping: [localhost]
localhost : ok=9 changed=0 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0
The first run reports changed=1 and kernel_upgraded=True, so on a real host the reboot would run. The second run reports changed=0, kernel_upgraded=False and skips the reboot, which is what idempotent means here: running it again on a patched host does nothing.
Edge cases and limits
- A run that dies between the upgrade and the reboot leaves the new kernel installed but not running. The next run sees no new kernel package and does not reboot. Cover this with a separate check that compares the running kernel (
ansible_facts.kernel) with the newest installed image, and alert on hosts that differ. - The same happens if the machine's own automatic updates installed the kernel earlier in the day, before this play took its first snapshot.
- A stateless web tier can be rebooted in batches; a database primary should not. Use
serial: 1, patch standbys first, and fail over deliberately before touching a primary. Drain hosts from the load balancer before the reboot, as for any rolling change. unattended-upgradetakes the package manager lock and can fail if another apt process is running; the task fails loudly and, withmax_fail_percentage: 0, stops the rollout, which is the safe outcome.- Complexity: one pass over the installed-package list per snapshot, so the work grows with the number of installed packages per host and linearly with the host count, divided by the batch size.
Write a PowerShell approach that checks patch compliance across a list of Windows servers: find missing critical and security updates, collect KB numbers, and produce a summary report. How do you handle credentials, timeouts and throttling, and make results accurate across different OS versions?
Sample Answer
Direct answer
Run a Windows Update Agent (WUA, the component Windows uses to scan for updates) search on each server through PowerShell remoting, return the missing critical and security updates with their KB (Knowledge Base article) numbers, convert each server's answer into one row with a status of Compliant, NonCompliant or Unknown, and write the rows to a timestamped CSV. Run the scan on the target itself so it decides applicability for its own OS build, which is what makes one script accurate across Windows Server versions. An unreachable or failed host is Unknown, never Compliant.
Why this design
| Concern | Choice | Reason |
|---|---|---|
| Finding missing updates | WUA search IsInstalled=0 and Type='Software' and IsHidden=0 inside Invoke-Command | WUA returns only updates that apply to that machine and are not installed, so servers on different OS versions each get their own correct answer |
Not Get-HotFix | Used only for spot checks of one KB | Get-HotFix uses the Win32_QuickFixEngineering class, which returns only updates supplied by Component-Based Servicing (the Windows servicing stack) and not those from the Windows Update site or Windows Installer, so an empty result proves little |
| Critical and security filter | An update counts if MsrcSeverity is set to any of its four ratings (Critical, Important, Moderate or Low, the Microsoft Security Response Center rating, so a Low-rated security fix counts too) or its category name contains Critical or Security | A security fix carries a severity rating whatever its level; the category check covers the Critical update classification. An optional preview update has no severity and the category Updates, so it is not counted |
| KB numbers | KBArticleIDs joined as KB<number> | Documented IUpdate property |
| Restart state | Microsoft.Update.SystemInfo RebootRequired | A server with a pending restart is not yet protected, so the flag has its own RebootPending column and a Compliant row with RebootPending True should be alerted on (the status itself reflects missing updates only). Microsoft's WUA remote-use page lists ISystemInformation among the interfaces not available to remote callers, so confirm on your own servers that this read inside the remoting session returns a value; the script's [bool] cast turns a null read into False |
| Credentials | Default is the caller's own Kerberos identity (the domain's ticket-based authentication); optional -Credential; no passwords in the script and no CredSSP (a mechanism that delegates your credentials to the remote host) | Run it from a jump host (a hardened administration server that you connect through, so the credentials live in one controlled place) under a dedicated service account. WUA over a remote connection requires administrator rights on the target (Microsoft's documentation says the remote caller must be an administrator), so scope that account to servers and keep its credentials in a vault |
| Timeouts | New-PSSessionOption -OpenTimeout (milliseconds, default 180000 which is 3 minutes) bounds connecting; Wait-Job -Timeout bounds the whole scan | OperationTimeout is not a limit on how long a command runs, so a hung scan needs the job timeout |
| Throttling | Invoke-Command -ThrottleLimit, default 32 concurrent connections | Each scan contacts the update source; the limit also protects the WSUS (Windows Server Update Services) server from a thundering herd (many machines contacting one server at the same moment). WSUS is deprecated by Microsoft: it receives no new features but is still supported for production use. Lower the limit if the update server struggles |
| Output | ConvertTo-ComplianceRow creates the same shape for every outcome | One CSV regardless of what failed |
The script
#requires -Version 5.1
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$ComputerListPath,
[pscredential]$Credential,
[int]$ThrottleLimit = 32,
[int]$ConnectTimeoutSec = 30,
[int]$JobTimeoutSec = 900,
[string]$OutputDir = '.'
)
# Runs ON each target. Uses the Windows Update Agent, so applicability is decided per OS build.
$ScanBlock = {
$session = New-Object -ComObject Microsoft.Update.Session
$searcher = $session.CreateUpdateSearcher()
$result = $searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$updates = foreach ($u in $result.Updates) {
[pscustomobject]@{
KB = (@(foreach ($k in $u.KBArticleIDs) { "KB$k" }) -join ',')
Title = $u.Title
Severity = [string]$u.MsrcSeverity
Categories = (@(foreach ($c in $u.Categories) { $c.Name }) -join ';')
}
}
[pscustomobject]@{
OS = $os.Caption
Build = $os.BuildNumber
SearchResultCode = [int]$result.ResultCode
RebootRequired = [bool](New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired
Updates = @($updates)
}
}
function ConvertTo-ComplianceRow {
param(
[Parameter(Mandatory)][string]$ComputerName,
$Scan,
[string]$Failure,
[string]$ScannedAt = [datetime]::UtcNow.ToString('o')
)
$row = [ordered]@{
ComputerName = $ComputerName; Status = 'Unknown'; MissingCount = $null
MissingKBs = ''; RebootPending = $null; OS = ''; Build = ''; Reason = ''
ScannedAt = $ScannedAt
}
if ($Failure -or $null -eq $Scan) {
$row.Reason = if ($Failure) { $Failure } else { 'no result returned' }
}
elseif ($Scan.SearchResultCode -ne 2) {
$row.Reason = "WUA search result code $($Scan.SearchResultCode)"
}
else {
$missing = @($Scan.Updates | Where-Object { $_.Severity -or $_.Categories -match 'Critical|Security' })
$row.Status = if ($missing.Count -gt 0) { 'NonCompliant' } else { 'Compliant' }
$row.MissingCount = $missing.Count
$row.MissingKBs = (($missing | Where-Object KB | ForEach-Object KB | Sort-Object -Unique) -join ',')
$row.RebootPending = $Scan.RebootRequired
$row.OS = $Scan.OS; $row.Build = $Scan.Build
}
[pscustomobject]$row
}
$computers = Get-Content -LiteralPath $ComputerListPath |
ForEach-Object { $_.Trim() } |
Where-Object { $_ -and -not $_.StartsWith('#') } |
Sort-Object -Unique
$icm = @{
ComputerName = $computers
ScriptBlock = $ScanBlock
ThrottleLimit = $ThrottleLimit
SessionOption = New-PSSessionOption -OpenTimeout ($ConnectTimeoutSec * 1000)
AsJob = $true
ErrorAction = 'SilentlyContinue'
}
if ($Credential) { $icm.Credential = $Credential } # default: the caller's own Kerberos identity
$job = Invoke-Command @icm
$null = Wait-Job -Job $job -Timeout $JobTimeoutSec
$seen = @{}
$rows = @(foreach ($child in $job.ChildJobs) {
$name = $child.Location
$seen[$name.ToLowerInvariant()] = $true
if ($child.State -eq 'Completed') {
$scan = Receive-Job -Job $child -ErrorAction SilentlyContinue | Select-Object -First 1
ConvertTo-ComplianceRow -ComputerName $name -Scan $scan
}
else {
$why = if ($child.JobStateInfo.Reason) { $child.JobStateInfo.Reason.Message } else { "job state $($child.State)" }
ConvertTo-ComplianceRow -ComputerName $name -Failure $why
}
})
foreach ($c in $computers) {
if (-not $seen.ContainsKey($c.ToLowerInvariant())) {
$rows += ConvertTo-ComplianceRow -ComputerName $c -Failure 'no job was created'
}
}
Stop-Job -Job $job -ErrorAction SilentlyContinue
Remove-Job -Job $job -Force -ErrorAction SilentlyContinue
$stamp = [datetime]::UtcNow.ToString('yyyyMMddTHHmmssZ')
$rows | Sort-Object ComputerName |
Export-Csv -NoTypeInformation -Path (Join-Path $OutputDir "patch-compliance-$stamp.csv")
$rows | Group-Object Status | Select-Object Name, Count | Format-Table -AutoSize
if ($rows | Where-Object Status -eq 'NonCompliant') { exit 1 }
if ($rows | Where-Object Status -eq 'Unknown') { exit 2 }
exit 0
Exit codes: 1 if any server is non-compliant, 2 if none is non-compliant but some are unknown, 0 when every server is compliant, so a scheduler can alert on any non-zero code.
Reading the script
The search result code. The Windows Update Agent reports how its search ended as an OperationResultCode. Microsoft Learn defines six values: 0 not started, 1 in progress, 2 succeeded, 3 succeeded with errors (the results might be incomplete), 4 failed, 5 aborted. The line elseif ($Scan.SearchResultCode -ne 2) therefore reads "unless the search fully succeeded, do not trust the list of updates". That matters because an empty list from a failed search looks exactly like an empty list from a healthy server. Any code other than 2 produces Unknown with the code in the Reason column, and in the demo below the synthetic code 3 shows that even "succeeded with errors" is not accepted as a clean answer.
How the per-server rows are collected.
Invoke-Command @icmwithAsJob = $truereturns immediately with one parent job. PowerShell creates one child job per target computer, and each child runs$ScanBlockon that computer. All children run at once, up toThrottleLimitat a time.Wait-Job -Timeout $JobTimeoutSecblocks until every child has finished or 900 seconds have passed, whichever comes first. This is why the scan runs as a job: a remote command has no built-in run-time limit, so without a job one hung server would hold the whole script forever. When the timeout passes, children that are stillRunningstay in that state.foreach ($child in $job.ChildJobs)visits each child.$child.Locationis the computer name it ran on. ACompletedchild is read withReceive-Job, which returns what the script block output (the one object withOS,Build,SearchResultCode,RebootRequired,Updates). Any other state (Failed,Runningbecause it timed out) becomes anUnknownrow whose reason is the job's failure message orjob state Running.- The
$seenhash table records every name that produced a child job, and the finalforeach ($c in $computers)adds anUnknownrow for any listed host with no child job at all (for example, a name that did not resolve), so the CSV has exactly one row per input line. Stop-JobandRemove-Jobclean up anything still running.
Making results accurate
- Not applicable versus missing. The search lists updates that apply to this machine and are not installed. An update meant for a different OS version, or already replaced by a newer one, does not appear (superseded updates are excluded unless
IncludePotentiallySupersededUpdatesis set). Do not build one master KB list and test every server against it, because that reports false gaps on servers where a KB is not applicable. - Which source answered. By default the search uses the update source the machine is configured for: the WSUS server if configured, otherwise Microsoft Update or Windows Update. "Missing" therefore means missing from what that source offers. An update your patch server has not yet synchronized or approved will not show up as missing. For a vendor-side view set
ServerSelectionto Windows Update. For disconnected hosts, WUA can scan offline against Microsoft's signedWsusscn2.cabpackage. Microsoft's documentation describes that package as covering security-related updates only, so an offline scan answers "which security updates are missing" and not "everything missing", and the package must be refreshed as new updates are released. Microsoft's offline-scan sample demonstrates the API and is documented as not production code and not supported. - Unreachable hosts. Connection failures, timeouts and search failures all become
Unknownwith a reason. The script also adds anUnknownrow for any listed host that never produced a job, so the row count equals the input list. - Different OS versions. The row records the OS caption and build, so a gap that appears on one build only is visible when you sort the CSV.
Verified output of the row logic
The remote and WUA parts need Windows and live servers, so they were parse-checked and their cmdlets and parameters checked against Microsoft Learn, not executed. The row-conversion function was executed on PowerShell 7 with synthetic scan results. Save the script as Get-PatchCompliance.ps1 and the harness below as parse.ps1 in the same folder and run pwsh -NoProfile -File parse.ps1; the harness loads the function from the saved script:
$e=$null;$t=$null
$ast=[System.Management.Automation.Language.Parser]::ParseFile("$PWD/Get-PatchCompliance.ps1",[ref]$t,[ref]$e)
"parse errors: $($e.Count)"
$fn=$ast.FindAll({param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst]},$true)
foreach($f in $fn){ Invoke-Expression $f.Extent.Text }
$ts='2026-10-05T02:00:00.0000000Z'
$scanA=[pscustomobject]@{OS='Windows Server 2019 Datacenter';Build='17763';SearchResultCode=2;RebootRequired=$true;Updates=@(
[pscustomobject]@{KB='KB5001';Title='Cumulative Update';Severity='Critical';Categories='Security Updates'},
[pscustomobject]@{KB='KB5002';Title='Optional preview';Severity='';Categories='Updates'},
[pscustomobject]@{KB='KB5003';Title='.NET security';Severity='Important';Categories='Security Updates'})}
$scanB=[pscustomobject]@{OS='Windows Server 2022 Standard';Build='20348';SearchResultCode=2;RebootRequired=$false;Updates=@(
[pscustomobject]@{KB='KB5002';Title='Optional preview';Severity='';Categories='Updates'})}
$scanC=[pscustomobject]@{OS='';Build='';SearchResultCode=3;RebootRequired=$false;Updates=@()}
@(
ConvertTo-ComplianceRow -ComputerName srv-a -Scan $scanA -ScannedAt $ts
ConvertTo-ComplianceRow -ComputerName srv-b -Scan $scanB -ScannedAt $ts
ConvertTo-ComplianceRow -ComputerName srv-c -Scan $scanC -ScannedAt $ts
ConvertTo-ComplianceRow -ComputerName srv-d -Failure 'Connecting to remote server srv-d failed' -ScannedAt $ts
) | Format-Table ComputerName,Status,MissingCount,MissingKBs,RebootPending,Reason -AutoSize | Out-String -Width 200
Output:
parse errors: 0
ComputerName Status MissingCount MissingKBs RebootPending Reason
------------ ------ ------------ ---------- ------------- ------
srv-a NonCompliant 2 KB5001,KB5003 True
srv-b Compliant 0 False
srv-c Unknown WUA search result code 3
srv-d Unknown Connecting to remote server srv-d failed
srv-a has three applicable updates, but the optional preview (KB5002, no severity, category Updates) is not counted, so two are missing. srv-b has only the optional preview, so it is compliant. srv-c returned search result code 3 (succeeded with errors, so its list might be incomplete), and srv-d could not be reached, so both are Unknown.
Scheduling and where results land
Run the script daily from a scheduled task or pipeline job on the jump host under the service account. It writes patch-compliance-<UTC timestamp>.csv to a controlled evidence location (a write-once store if the report is used as audit evidence), and the same rows can be shipped to a database or SIEM (security information and event management system) for trend lines. Keep every file: the history shows when a server went out of compliance and how long it took to recover.
When to prefer WSUS or Configuration Manager reports
Use the management platform's own reports (WSUS reporting or Microsoft Configuration Manager, often shortened to ConfigMgr, compliance reports) as the system of record for the managed fleet. The clients report their state continuously, no remoting or administrator credentials are needed for the reading, the data scales to thousands of machines and the history is built in. Use this script as an independent cross-check (does the console agree with what the machine says?), for servers outside the management platform, for a quick post-incident sweep, and for small or disconnected environments. A host that the console shows as compliant while the script shows missing updates needs investigation: either its client is not reporting correctly or the two are looking at different update sources.
Pitfalls
- Treating "no updates found" as compliant when the search itself failed. The script checks the search result code and reports
Unknown. - Running the search against a WSUS server that has no approvals yet: everything looks compliant.
- Sending the full results of thousands of hosts through one remoting session without a throttle, which overloads the update server.
- Storing a plaintext password to avoid a prompt. Use the caller's identity or a vault.
You need to move a fleet of Linux servers to key-only SSH logins. How do you roll it out without locking anyone out (including yourself), and what happens when a key is lost or leaked?
Sample Answer
Direct answer
Roll out key-only SSH in stages and prove each stage before the next one can lock anyone out: first deploy and test keys while passwords still work, then disable passwords on a small ring of hosts (a first group of servers that you change before the rest), then widen. Never close the session you are working in until a second, fresh session has logged in under the new rules. Keep an out-of-band way in (cloud serial console or management controller) and a sealed break-glass credential. For lost or leaked keys, remove the key from every host centrally, and for a leaked key also add it to a revocation list, then review who used it. Short-lived SSH certificates reduce the whole problem because they expire on their own.
Rollout, in order
- Inventory who logs in and how. People, automation accounts, deployment pipelines, monitoring, backup agents and anything that connects with a password in a script. Anything you miss is what breaks.
- Create keys and distribute public keys centrally. Each person has their own key pair (a private key that never leaves their machine, protected by a passphrase or a hardware token, and a public key that goes on servers). Distribute public keys from configuration management so one change updates the whole fleet. Automation accounts get their own keys, restricted to the commands they need. On each server, the public keys allowed to log in as a given user are listed in that user's
~/.ssh/authorized_keysfile, one key per line, and configuration management writes that file for you. - Prove key login while passwords still work. For each person, force a key-only attempt, for example
ssh -o PreferredAuthentications=publickey -o PasswordAuthentication=no user@host, and require it to succeed before anything is disabled. Track the result per person. The two-ooptions each remove a fallback:PreferredAuthentications=publickeymakes the client offer only a key, andPasswordAuthentication=nostops it from ever asking for a password. If the key does not work, the command fails instead of quietly falling back to a typed password, which is exactly the failure you need to see before passwords are switched off. - Watch for the file-permission trap. sshd refuses keys when the home directory or key file has loose permissions (the setting that controls this is
StrictModes). Reproduced in anubuntu:24.04container, withalice's key installed and her home directory then made world-writable:
$ chmod 777 /home/alice
$ ssh -p 2222 -o PreferredAuthentications=publickey alice@127.0.0.1 true
alice@127.0.0.1: Permission denied (publickey,password).
exit=255
sshd log: Authentication refused: bad ownership or modes for directory /home/alice
The client message is generic; only the server log names the cause, so check the server log first when a key "stops working". In the same test, the working login was logged as Accepted publickey for alice from 127.0.0.1 port 43584 ssh2: ED25519 SHA256:Fu25x/6yi..., which records the key's fingerprint and is what you search when you need to know who used a key.
5. Disable passwords with a drop-in, and check the order. The main sshd_config contains an Include line, a directive that tells sshd to read every file matching a pattern (here the sshd_config.d directory) at that point as if their lines were pasted in. The server reads those included files first, and for each keyword "the first obtained value will be used" (sshd_config man page), with files read in alphabetical order. A vendor file named 50-... that says PasswordAuthentication yes silently beats your 99-hardening.conf. Demonstrated in a container:
$ cat /etc/ssh/sshd_config.d/50-vendor.conf
PasswordAuthentication yes
$ cat /etc/ssh/sshd_config.d/99-hardening.conf
PasswordAuthentication no
PermitRootLogin no
KbdInteractiveAuthentication no
$ sshd -t && echo "syntax ok"
syntax ok
$ sshd -T | grep -E '^(passwordauthentication|permitrootlogin|kbdinteractiveauthentication) '
permitrootlogin no
passwordauthentication yes
kbdinteractiveauthentication no
$ mv /etc/ssh/sshd_config.d/99-hardening.conf /etc/ssh/sshd_config.d/00-hardening.conf
$ sshd -T | grep -E '^(passwordauthentication|permitrootlogin|kbdinteractiveauthentication) '
permitrootlogin no
passwordauthentication no
kbdinteractiveauthentication no
sshd -t only checks syntax and said "ok" while the effective setting was still insecure. sshd -T prints the effective configuration and is the check that matters. Turn off KbdInteractiveAuthentication as well as PasswordAuthentication: its default is yes, so leave it on only if you use it deliberately.
6. Apply to a pilot ring, with a safety net. (A ring is a group of hosts changed together: the pilot ring is the first and smallest, and each later ring is larger.) Validate (sshd -T), reload sshd (the unit is ssh.service on Ubuntu; check the name on other distributions), keep your current session open, and log in from a second terminal. Only when that works do you close the first. Existing connections survive a reload, which is what makes the safety net work. Do the pilot hosts first: one of each distribution and role.
7. Widen in rings and then enforce the setting through configuration management so it cannot drift back.
8. Remove password-based automation found in step 1 before the ring that contains it.
Optionally, AuthenticationMethods can require more than one method in sequence (for example key plus a second factor) for the admin tier.
Lockout-proofing, including yourself
| Failure | Prevention | Recovery |
|---|---|---|
| Typo makes sshd refuse to start | sshd -t before reload; configuration management validates before install | Out-of-band console |
| Your own key is missing or wrong on a host | Step 3 test per person before disabling passwords | Console, or the break-glass credential |
Loose permissions on ~/.ssh | Management sets owner and modes; step 4 check | Server log names the cause |
| Everyone's key lives only on one laptop | Each person has a second registered key (hardware token) | Admin adds a new key via management |
| The central distribution system itself is down | Break-glass key sealed and tested | Use it, then rotate it |
When a key is lost or leaked
- Lost (laptop gone, not known to be stolen): remove the public key from the central key list so the next configuration run removes it from every host's
authorized_keys, and issue a new key. A passphrase or hardware token makes this an inconvenience instead of an incident. - Leaked or stolen without protection: treat it as compromise. Remove it from the key list, and add it to a revocation list so hosts refuse it even before the removal propagates.
ssh-keygen -k -f <file> <key.pub>builds a key revocation list (KRL);RevokedKeys <file>in sshd configuration makes the server refuse listed keys, andssh-keygen -Q -f <file> <key.pub>tests a key against the list. Demonstrated in the container:
$ ssh-keygen -k -f /etc/ssh/revoked_keys /home/alice/.ssh/id_ed25519.pub
Revoking from /home/alice/.ssh/id_ed25519.pub
$ echo "RevokedKeys /etc/ssh/revoked_keys" > /etc/ssh/sshd_config.d/10-revoked.conf
$ sshd -t
$ ssh-keygen -Q -f /etc/ssh/revoked_keys /home/alice/.ssh/id_ed25519.pub
/home/alice/.ssh/id_ed25519.pub (alice@12511479e91a): REVOKED
$ ssh -p 2222 alice@127.0.0.1 true
alice@127.0.0.1: Permission denied (publickey).
exit=255
(The container's sshd was restarted after the file was added, which is why the new server process applied it.) Then search logs for that key's fingerprint across the window since the key was last known to be safe, rotate anything that account could reach, and rotate the host-side secrets it could have read.
-
Certificates: if you sign short-lived user certificates from an SSH certificate authority (
ssh-keygen -s <ca_key> -I <id> -n <principals> -V <validity> <key.pub>), servers trust the CA instead of individual keys, a lost certificate stops working at its expiry, and you do not need to touchauthorized_keyson every host. This is the better long-term design above a few dozen hosts, at the cost of running and protecting the CA key.A worked example with illustrative names, run in an
ubuntu:24.04container. The CA is just an ordinary key pair kept somewhere very safe, andalice_key.pubis Alice's public key:
$ ssh-keygen -s ca -I alice-laptop-2026-10 -n alice,deploy -V +8h alice_key.pub
Signed user key alice_key-cert.pub: id "alice-laptop-2026-10" serial 0 for alice,deploy valid from 2026-10-06T08:22:00 to 2026-10-06T16:23:25
$ ssh-keygen -L -f alice_key-cert.pub
alice_key-cert.pub:
Type: ssh-ed25519-cert-v01@openssh.com user certificate
Key ID: "alice-laptop-2026-10"
Valid: from 2026-10-06T08:22:00 to 2026-10-06T16:23:25
Principals:
alice
deploy
Reading the command: -s ca is the CA private key that signs; -I alice-laptop-2026-10 is the key identity, a free-text label stored in the certificate and written to the server's log whenever the certificate is used, so make it say who and when; -n alice,deploy lists the principals, the login names this certificate may log in as (a certificate for alice cannot log in as root); -V +8h sets the validity window, here eight hours from now (the start is backdated by about a minute to tolerate clock differences); the last argument is the public key being signed, and the result is written next to it as alice_key-cert.pub. ssh-keygen -L prints what a certificate contains. On the server, one line, TrustedUserCAKeys /etc/ssh/ca.pub, tells sshd to accept any unexpired certificate signed by that CA for a listed principal; sshd -t accepted that line in the same container.
Trade-offs
Key-only logins remove password guessing but make the key the whole security story, so private keys need a passphrase or hardware token and a rotation habit. Root login is set to no here: the default value prohibit-password still lets root in with a key, whereas no refuses root entirely, so administrators come in as themselves and use sudo, which keeps a per-person audit trail.
Unlock Full Question Bank
Get access to all 47 System and Endpoint Hardening interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.