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.
You are building deployment rings for patches across 5,000 servers. How do you define the rings, choose canary hosts, set soak times, and decide whether a patch is promoted or halted?
Sample Answer
Direct answer
A ring is a group of servers that receives a patch at the same time, ordered so that each ring is bigger and more important than the one before, with a waiting period (soak) between rings to let problems show up. The blast radius of a bad patch (how many servers it can hurt at once) is therefore limited to the ring it is in. For 5,000 servers I would use four rings: a canary ring of 25 hosts (0.5 percent), a first ring of 250 (5 percent), a second ring of 1,250 (25 percent) and a final ring of 3,475 (the rest). I pick canaries to be representative rather than convenient, set soak times that cover the workloads' real cycles, and promote only when written health criteria pass. A patch is halted automatically when a halt criterion trips, and the halt is owned by a named person who can also decide to resume.
The rings
| Ring | Hosts | Share of 5,000 | Cumulative | What goes in it |
|---|---|---|---|---|
| 0 Canary | 25 | 0.5% | 25 (0.5%) | Hosts chosen as described below; mostly non-production plus a few low-risk production |
| 1 Early | 250 | 5% | 275 (5.5%) | Non-critical production, staging, one member of each redundant pair (two servers doing the same job, so one can be patched while the other keeps serving) |
| 2 Broad | 1,250 | 25% | 1,525 (30.5%) | Most production, spread across data centres, availability zones (separate physical locations inside one cloud region) and clusters |
| 3 Final | 3,475 | 69.5% | 5,000 (100%) | The rest, including databases, domain controllers and anything with a strict change window |
The sizes sum to 5,000 (25 + 250 + 1,250 + 3,475) and were computed rather than estimated. Microsoft's Windows Update client policies (page "Configure Windows Update client policies" on learn.microsoft.com, formerly called Windows Update for Business) support the same idea for Windows clients: group devices with similar deferral periods into deployment or validation groups, defer quality updates by a number of days after release so a small pool is updated first, and pause quality updates for up to 35 days from a start date if a problem appears. Windows Server only gets the quality update policies from that service. For servers managed by other tooling, the same ring structure can be built from groups in your patch tool or from per-ring package repository snapshots.
Choosing canary hosts
A canary only helps if a bad patch would hurt it the way it would hurt production. Pick canaries by coverage, not by convenience:
- At least one host per operating system and major version, per hardware or hypervisor type, per major application role, and per network segment or region that has unique configuration (a different storage driver or agent version is a reason to add a canary).
- Include hosts that run the heaviest-used software on the box (a Java stack, a database, a web tier), so a library change shows up.
- Mostly non-production, plus a few real production hosts with low blast radius, because staging often lacks production's traffic and data.
- Never both members of a redundant pair, and never the only host of a role.
- Owners must have agreed in advance and have monitoring on.
Why 25 is not the whole answer. The chance a canary ring catches a defect depends on how many hosts the defect affects. If a patch breaks 1 percent of hosts (a specific hardware or driver combination), the chance that a random 25-host ring contains at least one broken host is 1 - 0.99^25 = 22.2 percent. The reasoning: "at least one broken" is the opposite of "none broken", so its probability is 1 minus the probability that none are. Each host is fine with probability 0.99, and with independent hosts all 25 are fine with probability 0.99^25 = 0.778 (0.7778 before rounding), so at least one is broken with probability 1 - 0.778 = 0.222. A random 250-host ring catches it with probability 1 - 0.99^250 = 91.9 percent. The same calculation for a 2 percent and a 5 percent defect, printed by this script (it assumes hosts are picked at random and independently):
for p in (0.01, 0.02, 0.05):
for k in (25, 250):
print(f"defect on {p:.0%} of hosts, ring of {k}: P(at least one broken host) = {1 - (1 - p) ** k:.1%}")
Reading the script: the outer loop takes each defect rate p (1, 2 and 5 percent of hosts broken); the inner loop takes each ring size k (25 and 250); (1 - p) ** k is the chance that all k hosts are fine; 1 - (1 - p) ** k is the chance that at least one is broken; the f"..." string formats p as a whole percent (:.0%) and the result to one decimal place (:.1%). Six combinations give six lines:
defect on 1% of hosts, ring of 25: P(at least one broken host) = 22.2%
defect on 1% of hosts, ring of 250: P(at least one broken host) = 91.9%
defect on 2% of hosts, ring of 25: P(at least one broken host) = 39.7%
defect on 2% of hosts, ring of 250: P(at least one broken host) = 99.4%
defect on 5% of hosts, ring of 25: P(at least one broken host) = 72.3%
defect on 5% of hosts, ring of 250: P(at least one broken host) = 100.0%
That is the reason ring 1 exists and the reason canaries must be chosen to cover the rare configurations on purpose instead of hoping random selection finds them.
Soak times
Soak must be at least as long as the shortest cycle that would reveal the problem. These are example values that I would set and justify per estate:
| Ring | Example soak before promotion | Reason |
|---|---|---|
| 0 | 24 hours | Covers a full daily cycle: a nightly scheduled job and morning peak |
| 1 | 48 hours | Covers a weekday spread, includes backups and scheduled jobs |
| 2 | 48 hours | Large enough population that rare errors surface |
| 3 | n/a (final) | Verification scan and watch period after completion |
Add time for monthly or quarterly workloads: if a billing or month-end job is the thing a patch could break, either include that system in an earlier ring and let one real run complete, or hold ring 3 for it deliberately. Patches that need a reboot are not "soaked" until the reboot has happened. Under these example values the happy-path campaign takes 24 + 48 + 48 = 120 hours of soak, which is 5 days, plus deployment time inside each ring; that is deliberately slower than an emergency track, and an emergency compresses soak (see the note at the end).
Promote or halt
Decide the criteria before the ring starts, write them down, and make them measurable. Example criteria (thresholds are a team choice and should come from your own baselines):
| Check | Promote when | Halt when |
|---|---|---|
| Install success | Almost all installs succeed and failures are explained | Failure rate in the ring exceeds a threshold you set in advance (example: 2 percent), or any failure pattern shared by one hardware or software type |
| Service health | Error rate and latency stay inside the baseline for the soak period | A sustained rise over baseline on any patched host, or a patched-host-only incident |
| Reboot and boot | Every host that rebooted came back | Any host that does not return, or boot time changes materially |
| Support signals | No tickets linked to the patch | Two or more independent reports with the same symptom |
| Security | Post-patch scan shows the target vulnerability gone | Scan still shows it (the patch did not apply) |
Halting means the orchestration stops sending the patch to later rings, and the decision is reversible. Pre-agree who may halt (the on-call engineer, without waiting for approval) and who may resume (the change owner). Prepare the rollback before the ring: a snapshot or image for virtual machines, the previous package version available in the repository, or a documented uninstall; and note which patches cannot be rolled back, because those need a longer soak and a rehearsal. After a halt, find the cause, exclude the affected configuration from the ring until fixed, and resume with the same criteria.
Worked example
A monthly operating-system patch. Day 0 evening: ring 0 (25 hosts) is patched, health stays inside baseline through the next 24 hours. Day 1 evening: ring 1 (250 hosts) is patched; on day 2, 7 of the 250 hosts show high disk latency, all of them using one storage driver version. The campaign halts. The halt fires under the service-health row of the criteria table (a sustained rise over baseline on patched hosts, all with the same storage driver), not under the install-failure row, because nothing failed to install. Seven hosts out of 250 is 2.8 percent, which is context for how large the affected group is, not the trigger: the 2 percent example threshold applies to install failures, and the service-health row halts on any patched host. Ring 2 and ring 3 never receive the patch: 1,250 + 3,475 = 4,725 hosts were protected from a problem that the 25 canaries alone did not reveal, since none of them used that driver (a case where coverage-based selection should be revised to add a host with that driver). Fix: update the driver, add a canary with that driver, re-run ring 1's affected hosts, then resume.
Failure modes and pitfalls
- Rings by convenience: all the canaries are the same VM template, so they cannot catch driver-specific or application-specific failures.
- Redundant pairs in one ring: both nodes down at once. Rule: at most one member of any redundant pair per ring.
- No halt authority: the person who sees the problem has to ask permission and the patch keeps rolling.
- Promotion by calendar instead of evidence: the soak ended, so everything proceeds, even though nobody looked.
- Skipping the ring structure for "urgent" patches. A genuine emergency compresses soak and shrinks ring 0 to a few hosts, but still keeps a canary and still keeps the halt.
Leadership asks how you know the patch programme is working. Which measures would you report, how is each calculated, and what would make a green dashboard misleading?
Sample Answer
Direct answer
Report a small set of measures that answer three questions: do we know every host (coverage), are hosts patched within the time we promised (compliance and speed), and what is still dangerous (exposure and exceptions). Compute each against the full asset inventory, not only against what the scanner saw. A dashboard turns misleading when the denominator shrinks, when averages hide a long tail, or when "installed" is counted although the patch is not yet active.
Measures and how each is calculated
| # | Measure | Calculation | Why leadership needs it |
|---|---|---|---|
| 1 | Inventory coverage | Hosts that reported scan data in the last 7 days / hosts in the authoritative inventory (the CMDB, configuration management database) | Everything else is only as good as this |
| 2 | Compliance within SLA | Hosts with no overdue patch for their severity / all hosts in inventory | The headline number |
| 3 | Time to patch | Days from patch release (or vulnerability published) to installed and active, per host; report median and 99th percentile (P99) by severity | Shows speed and the slow tail |
| 4 | Known-exploited exposure | Count of hosts with an open vulnerability on the CISA KEV catalog (Known Exploited Vulnerabilities) older than the SLA | Highest-risk subset |
| 5 | Patch failure rate | Failed or rolled-back patch installs / patch installs attempted | Quality of the programme itself |
| 6 | Open exceptions | Count, oldest age, and number past their expiry date | Risk accepted instead of fixed |
| 7 | Pending-reboot hosts | Hosts where the patch is installed but the reboot or restart is outstanding / hosts patched | Installed is not the same as protected |
An SLA (service-level agreement) here is the internal deadline per severity, for example critical within a number of days your policy sets.
Worked example: how a green number lies
Inventory has 1,000 servers. The scanner reaches 940 of them. Of those 940, 893 are within SLA.
- Coverage: 940 / 1,000 = 94.0 percent.
- Compliance the lazy way (against scanned hosts): 893 / 940 = 95.0 percent.
- Compliance the honest way (against inventory): 893 / 1,000 = 89.3 percent. The 60 unscanned hosts are unknown, and unknown must count as not compliant.
Now the tail. Take 100 hosts where 95 patched in 5 days and 5 took 90 days.
- Mean: (95 x 5 + 5 x 90) / 100 = 9.25 days.
- Median: 5 days.
- 99th percentile, nearest-rank method: sort the 100 values (95 values of 5 days, then 5 values of 90 days). The rank is 0.99 x 100 = 99, so take the 99th sorted value; positions 96 to 100 are all 90, so it is 90 days. (Computed in a Python container: rank 99, value 90, mean 9.25.)
A report showing only "mean 9.25 days" looks acceptable. The P99 and the list of those 5 hosts show where the real risk sits.
What makes a green dashboard misleading
- Shrinking denominator: hosts the scanner cannot reach, unregistered shadow servers, or hosts excluded as "exceptions" quietly leave the calculation.
- Averages instead of percentiles or the oldest age.
- Installed counted as patched while a reboot or service restart is pending.
- Scans that are unauthenticated or stale. An authenticated scan logs in to the host with a credential and reads its installed-package list; an unauthenticated scan only probes from the network (open ports, banners), so it cannot see a missing kernel update and often reports "no findings".
- OS patches only: third-party applications, language libraries and container images do not appear in an OS patch report.
- Severity re-rating: findings reclassified downward so they leave the SLA bucket.
- Exceptions that never expire.
Trade-offs and pitfalls
Do not report too many numbers: leadership remembers three. Lead with coverage, compliance against inventory, and known-exploited exposure, and keep the rest for the operating review. Pair every target with an owner. Test your dashboard by taking a known-unpatched host out of the scan scope and confirming the dashboard moves, because a number that cannot go red is not a measure.
Tell me about a time you introduced a hardening or secure-configuration change in production. How did you validate it, and what was your rollback plan?
Sample Answer
Direct answer
Tell a story with a clear arc: the risk that motivated the change, how you tested it on a small set before production, how you watched it afterwards, and a rollback that was written and rehearsed before the change. The sample below uses a real setting so you can see the shape. Use your own incident in its place.
Situation
Our file servers allowed unsigned SMB (Server Message Block, the Windows file-sharing protocol) traffic. Microsoft documents that unsigned SMB packets can be intercepted and modified in transit, and that on member servers the policy "Microsoft network server: Digitally sign communications (always)" is disabled by default, while it is enabled on domain controllers. Those are the long-standing defaults. Microsoft's SMB documentation says Windows 11 24H2 and Windows Server 2025 changed them (Windows 11 24H2 requires signing both outbound and inbound; Windows Server 2025 requires outbound signing, and Microsoft's pages differ on whether it also requires inbound), so on newer builds test what is actually enforced instead of assuming unsigned traffic is allowed. This story assumes older server builds that still accepted unsigned inbound SMB. Security asked us to require signing on the file servers.
What I did
- Wrote the change: set the policy to Enabled on a pilot OU (organizational unit, a folder of computers in Active Directory) containing two low-risk file servers.
- Identified who could break: older clients and appliances that cannot sign SMB. Microsoft's SMB signing page describes a connection to a server that does not support signing failing (for example with STATUS_INVALID_SIGNATURE), so by the same logic unsigned-only devices would lose access once signing is required. I inventoried clients before the change by turning on SMB signing auditing on the pilot servers for two weeks and listing each client that could not sign.
How the audit works, from Microsoft's SMB signing documentation: on a server build that has the setting (Microsoft documents these audit settings from Windows 11 24H2 and Windows Server 2025), run this in an elevated PowerShell session (or set the Group PolicyComputer Configuration\Administrative Templates\Network\Lanman Server\Audit client does not support signing):
Set-SmbServerConfiguration -AuditClientDoesNotSupportSigning $true
The server then writes an event for each client that connects without signing support to Event Viewer under Applications and Services Logs, Microsoft, Windows, SMBServer, Audit (the documentation lists event IDs 3021 and 3022 for that log). Reading the log after two weeks gives a client list; in this story it named two devices (illustrative names: nas-old-01 and copier-scan-02). If a server build lacks the setting, the fallback is the inventory of client operating systems and appliances plus a test connection from each type.
3. Validated: after enabling on the pilot, I tested from one current Windows 11 laptop, one older Windows 10 laptop, one Linux client mounting the share, and the two flagged devices: from each I opened the share by name, saved a file into it and read it back, so 'shares still opened' meant those three actions succeeded. I also watched file-copy performance. Microsoft's documentation says signing has limited impact on 1 Gb Ethernet but can matter more on faster networks, so I measured large copies on the pilot rather than assuming.
4. Wrote the rollback in advance: set the policy back to Disabled in the pilot GPO (Group Policy Object). Microsoft documents no restart requirement for this policy, so rollback is a policy change, not a reboot, and I confirmed that on the pilot before relying on it.
5. Rolled out in waves, with a communications note and a service-desk script for "cannot open share".
Result and lesson
The pilot surfaced two legacy devices that could not sign. We upgraded one and isolated the other on a separate share with a documented exception and an end date. Looking back, I would have run the audit first on every server group instead of just the pilot, and would have scheduled the first production wave away from month-end close.
Pitfalls
Do not say "no issues." A hardening story without a surprise sounds untested. Keep claims about numbers to what you measured. And say what you would do differently.
Your enterprise manages Windows patching with a mix of WSUS, ConfigMgr, Intune and Windows Update for Business. What is each good for, where do they fall short, and where does co-management make sense?
Sample Answer
Direct answer
WSUS is the on-premises distribution server for Microsoft updates, ConfigMgr (Configuration Manager) is the on-premises management system that uses WSUS and adds targeting, scheduling and reporting, Intune is the cloud management service, and Windows Update for Business (now called Windows Update client policies) is the set of client-side policies Intune or Group Policy applies. Co-management makes sense when one device population has a ConfigMgr history and cloud needs, so each workload can be assigned to the better tool.
Four names to keep straight: WSUS holds and hands out the updates (a server you run); ConfigMgr is the management system built on top of it; Intune is the cloud service; and Windows Update client policies (the new name for Windows Update for Business, a set of settings, not a server) are what Intune or Group Policy push to the device. An Intune update ring is those client policies packaged as one policy for one device group.
What each is good for and where it falls short
| Tool | Good for | Falls short |
|---|---|---|
| WSUS (Windows Server Update Services) | Central, on-premises control of which Microsoft updates reach computers on a network; PowerShell cmdlets for automation; LAN or offline-style networks | Microsoft says WSUS is deprecated and is no longer adding new features (still supported, with security and quality updates); it distributes Microsoft products only; you run the server |
| ConfigMgr | Collections, automatic deployment rules, maintenance windows, deadlines, compliance states, distribution points, third-party update integration options; detailed per-update reporting | Heavy infrastructure; its software update point is built on WSUS; internet-based clients need extra pieces such as a cloud management gateway (CMG, a ConfigMgr service hosted in Azure that lets ConfigMgr reach devices that are away from the corporate network) |
| Intune update rings | Cloud-managed deferral, deadline and restart settings; staged rings through device groups; pause and uninstall from the console; no on-premises update server | Needs devices to reach Microsoft and Intune endpoints, a licence, and Entra identity (Microsoft Entra ID is Microsoft's cloud identity service, formerly Azure AD); no content server of your own |
| Windows Update for Business (client policies) | The policy layer itself: deferral up to 365 days for feature updates and a shorter maximum for quality updates, pause, deadlines; settable by Group Policy or mobile device management (MDM, the enrolment channel through which a cloud service such as Intune pushes settings to a device) | Not a server product: devices fetch content themselves; Microsoft's overview lists Windows 10 and Windows 11 client editions, so plan server patching on other tooling |
Where co-management makes sense
Co-management means a device runs the ConfigMgr client and is enrolled in Intune at the same time. A workload is one area of management that can have either ConfigMgr or Intune as its authority: compliance policies, Windows Update policies, resource access, Endpoint Protection, device configuration, Office apps, client apps. The workload slider is the per-workload switch in the ConfigMgr console that moves that authority to Intune. ConfigMgr keeps every workload you have not switched, and you can pilot a workload on a separate collection (a group of devices) first.
Requirements to check first: devices must be Microsoft Entra joined or Entra hybrid joined (devices only registered with Entra are not supported), and Microsoft Entra ID P1 or P2 licensing (the paid tiers of Entra ID) is needed. The three device states differ like this:
- Entra joined: the organisation's Windows device is joined directly to Entra ID and the user signs in with a work account; no on-premises Active Directory is needed (Microsoft's device-identity overview lists organisation-owned Windows 10 and 11 devices here).
- Entra hybrid joined: the device is joined to your on-premises Active Directory and also registered with Entra ID, so it has both identities.
- Entra registered: typically a personal (bring-your-own) or mobile device that has had a work account added, without being joined to the organisation's directory. Co-management does not support this state.
Example estate: 4,000 laptops and 300 servers, on-premises Active Directory, ConfigMgr already installed.
| Population | Recommended patch channel | Reason |
|---|---|---|
| Laptops, hybrid joined | Co-manage; move the Windows Update policies workload to Intune rings, pilot on one collection first | Laptops leave the office, and rings plus deadlines work without a VPN |
| Servers | ConfigMgr with WSUS-backed software update point, with maintenance windows | Servers get only quality updates, need scheduled windows, and sit on the LAN |
| A small remote site with few devices and no ConfigMgr | WSUS alone, or Intune rings if devices are Entra joined | Avoids new infrastructure |
| Devices only registered with Entra, not joined | Keep on ConfigMgr or WSUS if they must be patched centrally | Not eligible for co-management |
Choosing
- Mostly cloud-connected clients and no ConfigMgr: Intune rings; add nothing else.
- Existing ConfigMgr, mixed estate: co-manage; move Windows Update policies first because it is one self-contained workload (one slider) that Microsoft lets you pilot on a separate collection before switching everyone.
- Servers and constrained networks: ConfigMgr or WSUS regardless of what laptops do.
Pitfalls
Two tools both setting update behaviour on one device cause conflicts; the workload slider exists so exactly one authority owns it. Declaring WSUS "dead" because of deprecation is wrong today, as it is supported, but ConfigMgr's software update point depends on it, so plan around Microsoft's lifecycle announcements instead of assuming either outcome. If you must tell the business one sentence: laptops go to the cloud first, servers stay on scheduled on-premises tooling, and the two meet through co-management.
Write a script that compares a security baseline for a Linux host (SSH settings, sysctl values, file modes, enabled services) against the host's current state and reports drift as a short human-readable summary plus machine-readable JSON. The baseline can have missing keys and per-setting defaults. How do you structure the comparison so that adding a new kind of check is easy?
Sample Answer
Direct answer
Read a JSON baseline, run one small check function per kind of setting (SSH, sysctl, file mode, service), compare each observed value with the expected one, and give every check one of four statuses: ok, drift, not_applicable or error (could not be evaluated). Print a short summary of the problems and write the full result as JSON. Adding a new kind of check means writing one function and registering it with a decorator: the loader, comparison engine, summary and JSON writer do not change. The script only reads (it opens files, calls os.stat, and runs the query systemctl is-enabled), so it never repairs anything.
Plain meanings of the terms. sshd is the SSH server and sshd_config its settings file. A sysctl value is a kernel setting, readable as a file under /proc/sys where the dots in the name become slashes (net.ipv4.ip_forward is /proc/sys/net/ipv4/ip_forward). A file mode such as 0640 means owner read and write, group read, others nothing. systemctl is the command line of the systemd service manager. A Match line in sshd_config starts a conditional block whose settings apply only to connections that match it.
Design decisions
| Decision | Choice | Reason |
|---|---|---|
| Baseline format | JSON with a defaults block and a checks list; every check has an id, a type and an expected value (or max_mode for file modes) | Defaults for severity and on_missing are stated once; any check can override them |
| Missing setting | Three outcomes: the check supplies a default (the daemon's documented default is then compared), or on_missing is not_applicable, or the setting counts as drift | A missing key is only drift when the baseline says the absence matters. For example PermitEmptyPasswords defaults to no in sshd_config(5), so an absent line is compliant when the baseline expects no |
| Expecting absence | "expected": "absent" | For something that should not exist (a telnet socket), a Missing result is the compliant outcome and is reported ok; if the thing exists, its state (for example enabled) is compared with absent and reported as drift |
| Extensibility | @check("kind") registry: a check function returns the observed value or raises Missing or CannotEvaluate | The engine never needs to know what a kind does |
| File modes | max_mode means "no more permissive than this", so 0600 passes a 0640 limit; exact expected is also supported | A file that is stricter than the baseline is not drift in most baselines |
| JSON schema | schema_version, host, summary counts, results list with fixed keys and a fixed status vocabulary, sorted keys, no timestamp | Stable output diffs cleanly and downstream tooling can rely on it; the collector adds the timestamp |
| Exit codes | 0 clean, 1 drift found, 2 nothing drifted but some checks could not run | A scheduler can alert on non-zero and tell the cases apart |
| Read-only | No writes except the report file the caller names | Detect only; remediation is a separate, reviewed step |
The script
Two Python constructs carry the design. CHECKS is a dictionary from a kind name to a function, and @check("sshd") above a function is a decorator: it runs CHECKS["sshd"] = check_sshd when the file loads, so registering a new kind is one line above its function. class Missing(Exception) and CannotEvaluate are custom error types: a check function signals "the thing is not there" or "I could not look" by raising one, and evaluate catches them in one place and turns them into statuses, so no check function needs to know about statuses.
#!/usr/bin/env python3
"""Read-only drift check of a Linux host against a JSON security baseline."""
import argparse
import json
import os
import socket
import subprocess
import sys
CHECKS = {}
def check(kind):
"""Register a check type. Adding a new kind of check means adding one function."""
def register(fn):
CHECKS[kind] = fn
return fn
return register
class Missing(Exception):
"""The thing being checked does not exist on this host."""
class CannotEvaluate(Exception):
"""The check could not run (tool absent, permission denied)."""
def norm(value):
return " ".join(str(value).split()).lower()
@check("sshd")
def check_sshd(spec, ctx):
path = ctx["root"] + spec.get("file", "/etc/ssh/sshd_config")
try:
with open(path, encoding="utf-8") as fh:
lines = fh.read().splitlines()
except FileNotFoundError:
raise Missing(path)
except PermissionError as exc:
raise CannotEvaluate(str(exc))
wanted = spec["key"].lower()
for line in lines:
parts = line.split(None, 1)
if not parts or parts[0].startswith("#"):
continue
word = parts[0].lower()
if word == "match":
break # keywords after Match are conditional, not global
if word == wanted and len(parts) == 2:
return parts[1].strip() # first value wins, as in sshd_config(5)
raise Missing(spec["key"])
@check("sysctl")
def check_sysctl(spec, ctx):
path = ctx["root"] + "/proc/sys/" + spec["key"].replace(".", "/")
try:
with open(path, encoding="utf-8") as fh:
return fh.read().strip()
except FileNotFoundError:
raise Missing(spec["key"])
except PermissionError as exc:
raise CannotEvaluate(str(exc))
@check("file_mode")
def check_file_mode(spec, ctx):
path = ctx["root"] + spec["path"]
try:
return format(os.stat(path).st_mode & 0o7777, "04o")
except FileNotFoundError:
raise Missing(path)
except PermissionError as exc:
raise CannotEvaluate(str(exc))
@check("service")
def check_service(spec, ctx):
try:
proc = subprocess.run(["systemctl", "is-enabled", spec["name"]],
capture_output=True, text=True, timeout=10)
except FileNotFoundError:
raise CannotEvaluate("systemctl not found")
except subprocess.TimeoutExpired:
raise CannotEvaluate("systemctl timed out")
state = (proc.stdout.strip().splitlines() or [""])[0]
if state == "not-found" or "No such file or directory" in proc.stderr:
raise Missing(spec["name"]) # systemd 255+ prints not-found; systemd 252 prints the error text
if not state:
raise CannotEvaluate(proc.stderr.strip() or "no output from systemctl")
return state
def compare(spec, actual):
if spec["type"] == "file_mode" and "max_mode" in spec:
extra = int(actual, 8) & ~int(spec["max_mode"], 8)
return extra == 0
return norm(actual) == norm(spec["expected"])
def evaluate(spec, defaults, ctx):
rec = {"id": spec["id"], "type": spec["type"],
"severity": spec.get("severity", defaults.get("severity", "medium")),
"expected": spec.get("expected", spec.get("max_mode")),
"actual": None, "status": None, "note": ""}
on_missing = spec.get("on_missing", defaults.get("on_missing", "drift"))
try:
fn = CHECKS[spec["type"]]
except KeyError:
rec["status"], rec["note"] = "error", "unknown check type"
return rec
try:
actual = fn(spec, ctx)
except Missing:
if spec.get("expected") == "absent":
rec["actual"], rec["status"], rec["note"] = "absent", "ok", ""
return rec
if "default" in spec: # setting absent: the program's documented default applies
actual = spec["default"]
rec["note"] = "absent, using stated default"
elif on_missing == "not_applicable":
rec["status"], rec["note"] = "not_applicable", "absent on this host"
return rec
else:
rec["status"], rec["note"] = "drift", "absent"
return rec
except CannotEvaluate as exc:
rec["status"], rec["note"] = "error", str(exc)
return rec
rec["actual"] = actual
rec["status"] = "ok" if compare(spec, actual) else "drift"
return rec
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("baseline")
ap.add_argument("--root", default="", help="prefix for file paths (testing)")
ap.add_argument("--host", default=socket.gethostname())
ap.add_argument("--json-out", required=True)
args = ap.parse_args(argv)
with open(args.baseline, encoding="utf-8") as fh:
baseline = json.load(fh)
defaults = baseline.get("defaults", {})
ctx = {"root": args.root}
results = [evaluate(s, defaults, ctx) for s in baseline["checks"]]
counts = {k: 0 for k in ("ok", "drift", "not_applicable", "error")}
for r in results:
counts[r["status"]] += 1
report = {"schema_version": 1, "host": args.host, "summary": counts,
"results": results}
with open(args.json_out, "w", encoding="utf-8") as fh:
json.dump(report, fh, indent=2, sort_keys=True)
fh.write("\n")
print(f"{args.host}: {counts['drift']} drift, {counts['ok']} ok, "
f"{counts['not_applicable']} n/a, {counts['error']} could not check")
for r in results:
if r["status"] in ("drift", "error"):
print(f" [{r['severity']}] {r['id']}: {r['status']} "
f"(expected {r['expected']}, actual {r['actual']}) {r['note']}".rstrip())
if counts["drift"]:
return 1
return 2 if counts["error"] else 0
if __name__ == "__main__":
sys.exit(main())
The baseline
{
"defaults": {"severity": "medium", "on_missing": "drift"},
"checks": [
{"id": "ssh-permit-root-login", "type": "sshd", "key": "PermitRootLogin", "expected": "no", "severity": "high"},
{"id": "ssh-password-auth", "type": "sshd", "key": "PasswordAuthentication", "expected": "no", "severity": "high"},
{"id": "ssh-empty-passwords", "type": "sshd", "key": "PermitEmptyPasswords", "expected": "no", "default": "no", "severity": "high"},
{"id": "ssh-x11-forwarding", "type": "sshd", "key": "X11Forwarding", "expected": "no", "default": "no", "severity": "low"},
{"id": "sysctl-ip-forward", "type": "sysctl", "key": "net.ipv4.ip_forward", "expected": "0"},
{"id": "sysctl-rp-filter", "type": "sysctl", "key": "net.ipv4.conf.all.rp_filter", "expected": "1"},
{"id": "sysctl-ipv6-ra", "type": "sysctl", "key": "net.ipv6.conf.all.accept_ra", "expected": "0", "on_missing": "not_applicable"},
{"id": "mode-shadow", "type": "file_mode", "path": "/etc/shadow", "max_mode": "0640", "severity": "high"},
{"id": "mode-sshd-config", "type": "file_mode", "path": "/etc/ssh/sshd_config", "max_mode": "0644"},
{"id": "mode-gshadow", "type": "file_mode", "path": "/etc/gshadow", "max_mode": "0640", "on_missing": "not_applicable"},
{"id": "svc-telnet", "type": "service", "name": "telnet.socket", "expected": "absent", "severity": "high"}
]
}
Each sshd check reads the global part of sshd_config. The OpenSSH manual states "Unless noted otherwise, for each keyword, the first obtained value will be used", so the parser returns the first occurrence of a keyword and ignores later duplicates (a few keywords accumulate instead, which is one more reason to prefer sshd -T for the effective answer). It stops at the first Match line because keywords after it only apply to matching connections. Include files are not followed. When you need the effective configuration including includes and Match evaluation, run sshd -T on the host and parse that instead. Executed in a debian:12-slim container with openssh-server installed (after mkdir -p /run/sshd and ssh-keygen -A), with an sshd_config holding PermitRootLogin yes, PasswordAuthentication=no, PermitRootLogin no and a Match User x block that sets PasswordAuthentication yes, the command sshd -T | grep -Ei '^(permitrootlogin|passwordauthentication|permitemptypasswords)' printed:
permitrootlogin yes
passwordauthentication no
permitemptypasswords no
The output is lowercase keyword value, the first PermitRootLogin wins, the Match block is not applied to the global value, and an unset keyword shows its built-in default. sshd also accepts = as the separator (PasswordAuthentication=no above), but the parser shown here splits on whitespace only, so a line written with = is read as missing; normalize the separator before comparing or use sshd -T.
Running it
The demo builds a throwaway directory tree that imitates a host, so the result is reproducible on any machine with Docker. Save drift_check.py, baseline.json and the script below in one directory (the demo script is named demo.sh):
set -u
R=/tmp/demo-root
mkdir -p $R/etc/ssh $R/proc/sys/net/ipv4/conf/all
cat > $R/etc/ssh/sshd_config <<'CFG'
# demo config
PermitRootLogin yes
PasswordAuthentication no
PermitRootLogin no
Match User backup
PasswordAuthentication yes
CFG
chmod 0644 $R/etc/ssh/sshd_config
echo 1 > $R/proc/sys/net/ipv4/ip_forward
echo 1 > $R/proc/sys/net/ipv4/conf/all/rp_filter
echo "root:*:19000:0:99999:7:::" > $R/etc/shadow; chmod 0644 $R/etc/shadow
python3 drift_check.py baseline.json --root $R --host demo-host --json-out report.json
echo "exit=$?"
cat report.json | head -40
docker run --rm -v "$PWD":/w -w /w python:3.12-slim sh demo.sh
Printed output (the script then prints the first lines of report.json, which are omitted here):
demo-host: 3 drift, 5 ok, 2 n/a, 1 could not check
[high] ssh-permit-root-login: drift (expected no, actual yes)
[medium] sysctl-ip-forward: drift (expected 0, actual 1)
[high] mode-shadow: drift (expected 0640, actual 0644)
[high] svc-telnet: error (expected absent, actual None) systemctl not found
exit=1
The summary counts (3 drift, 5 ok, 2 n/a, 1 could not check) add up to the 11 checks in the baseline, and the JSON summary object holds the same numbers: {'drift': 3, 'error': 1, 'not_applicable': 2, 'ok': 5}.
Reading the result:
ssh-permit-root-loginisdrifteven though a later line saysPermitRootLogin no: the first line wins.ssh-password-authisok: theMatch User backupblock that setsPasswordAuthentication yesis ignored by design because it only applies to that user.ssh-empty-passwordsandssh-x11-forwardingareokthrough the stated defaults (no), and the JSON records the noteabsent, using stated default.mode-shadowisdrift(0644is more permissive than the0640limit);mode-sshd-configpasses at0644.svc-telnetiserror: the container has nosystemctl, so the check reports that it could not run. It is not counted as compliant.sysctl-ipv6-raandmode-gshadowarenot_applicablebecause those paths are absent here and the baseline says absence is fine.
How the file-mode comparison works
compare checks that a file has no permission bit beyond the limit. ~limit flips every bit of the limit, and & keeps only bits that are set in both numbers, so actual & ~limit is the set of permission bits the file has that the limit does not allow. Zero means the file is within the limit. Executed in a python:3.12-slim container with the limit 0640 (the nine bits are owner rwx, group rwx, other rwx):
actual 0600 = 110000000 limit 0640 = 110100000 bits beyond limit = 000000000 -> ok
actual 0640 = 110100000 limit 0640 = 110100000 bits beyond limit = 000000000 -> ok
actual 0644 = 110100100 limit 0640 = 110100000 bits beyond limit = 000000100 -> drift
actual 0660 = 110110000 limit 0640 = 110100000 bits beyond limit = 000010000 -> drift
0644 fails because it adds the "other read" bit (the last 1 in the third line's beyond-limit column), and 0660 fails because it adds group write. 0600 passes because it only removes bits.
Adding a new kind of check
A check to confirm a line exists in a file is one function. The program below registers it and reuses main:
set -u
R=/tmp/demo-root
mkdir -p $R/etc
printf 'blacklist usb-storage\n' > $R/etc/modprobe-hardening.conf
cat > extra_check.py <<'PY'
import sys
import drift_check
from drift_check import check, Missing
@check("file_line")
def check_file_line(spec, ctx):
path = ctx["root"] + spec["path"]
try:
with open(path, encoding="utf-8") as fh:
lines = fh.read().splitlines()
except FileNotFoundError:
raise Missing(path)
return "present" if spec["line"] in lines else "absent"
sys.exit(drift_check.main())
PY
cat > extra.json <<'JSON'
{"checks": [
{"id": "usb-storage-blocked", "type": "file_line", "path": "/etc/modprobe-hardening.conf", "line": "blacklist usb-storage", "expected": "present"},
{"id": "cramfs-blocked", "type": "file_line", "path": "/etc/modprobe-hardening.conf", "line": "blacklist cramfs", "expected": "present", "severity": "low"}
]}
JSON
python3 extra_check.py extra.json --root $R --host demo-host --json-out extra-report.json
echo "exit=$?"
Output of that run:
demo-host: 1 drift, 1 ok, 0 n/a, 0 could not check
[low] cramfs-blocked: drift (expected present, actual absent)
exit=1
The first check passes because the file contains the line; the second reports drift. Nothing outside the new function and the baseline entries changed.
Complexity and edge cases
- Complexity: each check does constant work apart from I/O; an
sshdcheck readssshd_configonce per check, so N sshd checks over an L-line file cost O(N x L). Caching the parsed file per path makes it O(L + N) if the baseline grows large. - Edge cases handled: missing keys, missing files, unreadable files (reported as
error, not as pass), repeated keywords, comments, multi-value sysctl output (whitespace is normalized), a service that does not exist (newer systemd, 255 and later, printsnot-foundon stdout for an unknown unit; systemd 252, which Debian 12 ships, prints nothing on stdout andFailed to get unit file state for telnet.socket: No such file or directoryon stderr; both are treated as missing, which matters because without the second test an absent unit on a 252 host would be reported aserrorinstead of compliant), and an absent tool. - Not handled, and worth stating:
IncludeandMatchevaluation (usesshd -T), runtime sysctl values that differ from the persisted files in/etc/sysctl.d(add asysctl_persistedcheck kind to catch a setting that will revert at reboot), symlinks (os.statfollows them), and extended attributes or ownership (addownerchecks as another registered kind).
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.