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 small Linux web server serves only HTTPS to the public and takes SSH from a few admins. Design its host firewall policy, show the ruleset, and explain how you would test it and make it survive a reboot without cutting your own session.
Sample Answer
Direct answer
Use the kernel's own packet filter, nftables, on the server with a default-deny inbound policy: accept packets that belong to connections already allowed, accept loopback, accept a minimal set of ICMP, accept TCP 443 from anywhere, accept TCP 22 only from a named set of admin addresses, and drop everything else. Do not filter outbound for this host unless there is a reason (see the trade-off below). Test the file for syntax before applying it, apply it with a timed automatic rollback armed, confirm from a second, new session before cancelling the rollback, and make it permanent by putting it in the file the distribution's nftables service loads at boot.
If the host is already managed with ufw or firewalld, use that tool and express the same policy in it. Two firewall managers writing rules on one host is the failure to avoid.
Policy
| Traffic | Decision | Why |
|---|---|---|
| Inbound packets of an already-established or related connection | accept (first rule) | replies to the server's own outbound requests, and your existing SSH session, keep working while rules change |
Inbound packets in connection-tracking state invalid | drop | not part of any valid connection |
| Loopback interface | accept | local services talk to each other over it |
| ICMP and ICMPv6 error messages (destination-unreachable, time-exceeded, parameter-problem, packet-too-big) | accept | path MTU discovery (how hosts learn the largest packet that fits along the path) and error reporting fail without them. RFC 4890 section 4.3.1 says Destination Unreachable (all codes), Packet Too Big, Time Exceeded code 0 and Parameter Problem codes 1 and 2 must not be dropped, and section 4.3.2 says Time Exceeded code 1 and Parameter Problem code 0 normally should not be dropped; the ruleset accepts every code of all four types |
| ICMPv6 neighbour discovery (neighbour solicitation and advertisement, router advertisement) | accept | IPv6 hosts use them to find the other hosts on the link and the default gateway; blocking them breaks IPv6 on this host |
| Echo request (ping), IPv4 and IPv6 | accept, limited to 5 per second | lets monitoring and humans check reachability, with a cap on abuse |
| TCP 443 | accept from anywhere | the service this host exists to provide |
| TCP 22 | accept only from admin_v4 / admin_v6 sets | SSH exposed to the internet is the most attacked port; a handful of known addresses removes that exposure |
| Anything else inbound | drop (policy drop) | default deny: a service nobody planned for is not reachable by accident |
| Forwarding | drop | this is a server, not a router |
| Outbound | accept (see below) |
The firewall runs in the input hook of the server itself, so every packet addressed to the host passes it before any local program sees it. It complements, and does not replace, a cloud security group or a perimeter firewall: the host firewall is what still protects the server from other machines on the same network that have already been compromised.
The ruleset
#!/usr/sbin/nft -f
# Host firewall for a public HTTPS server with SSH from a few admin addresses.
# Replace only our own table, so rules from other tools (Docker, fail2ban) survive.
table inet filter
delete table inet filter
table inet filter {
set admin_v4 {
type ipv4_addr
elements = { 10.77.0.10, 10.77.0.11 }
}
set admin_v6 {
type ipv6_addr
elements = { fd00:77::10 }
}
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
ct state invalid drop
iifname "lo" accept
# IPv6 does not work without neighbour discovery
icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert, destination-unreachable, packet-too-big, time-exceeded, parameter-problem } accept
icmp type { destination-unreachable, time-exceeded, parameter-problem } accept
icmp type echo-request limit rate 5/second accept
icmpv6 type echo-request limit rate 5/second accept
tcp dport 443 accept
tcp dport 22 ip saddr @admin_v4 accept
tcp dport 22 ip6 saddr @admin_v6 accept
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}
Reading the ruleset, line by line
| Line | What it means |
|---|---|
table inet filter | A table is a named container for chains and sets. The family inet makes one table cover IPv4 and IPv6 together; filter is only the table's name |
set admin_v4 { type ipv4_addr; elements = { ... } } | A named list of addresses. Rules refer to it as @admin_v4, so the allowed admins live in one place |
chain input { | A chain is an ordered list of rules. Packets are checked against the rules from top to bottom |
type filter hook input priority filter; policy drop; | type filter: this chain accepts or drops packets. hook input: attach it where packets addressed to this host arrive (forward is for packets passing through, output for packets the host sends). priority filter: the order among chains on the same hook; filter is the standard name for priority 0. policy drop: a packet that reaches the end without being accepted is dropped |
ct state established,related accept | ct is connection tracking, the kernel's memory of each flow. A packet that belongs to a connection already allowed (a reply, or a related error message) is accepted straight away, which is why this rule comes first |
ct state invalid drop | Packets that fit no known connection are dropped |
iifname "lo" accept | iifname is the input interface name. lo is the loopback interface, used by programs on this host talking to each other |
icmpv6 type { nd-neighbor-solicit, ... } accept | Accept the listed ICMPv6 message types: neighbour discovery (nd-...) plus the error types |
icmp type echo-request limit rate 5/second accept | Accept ping requests only while fewer than 5 per second arrive; the excess does not match this rule, falls through to the end and meets policy drop |
tcp dport 443 accept | dport is the destination port: anyone may connect to HTTPS |
tcp dport 22 ip saddr @admin_v4 accept | Port 22 and the source address (saddr) is in the set. The ip6 saddr line does the same for IPv6 |
chain forward / chain output | forward drops everything (not a router); output is policy accept, so outbound is unfiltered |
Each term in the policy table has a line that implements it:
| Policy row | Ruleset line |
|---|---|
| connection tracking (replies keep working) | ct state established,related accept and ct state invalid drop |
| path MTU discovery | packet-too-big in the icmpv6 line, destination-unreachable in the icmp line |
| neighbour solicitation and advertisement | nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert in the icmpv6 line |
| SSH from admins only | the two tcp dport 22 ... saddr @admin_... lines |
Notes on the file:
- The first two lines of the table section (
table inet filterthendelete table inet filter) make the file re-loadable: the first creates the table if it does not exist (so the delete never fails), the second removes it, and the definition that follows rebuilds it. Only this table is replaced, so tables created by other tools (Docker's, fail2ban's) are left alone.flush rulesetwould wipe those too. I loaded the file onto an empty ruleset, then again onto the existing table, and it succeeded both times; a tableinet othercreated beforehand survived. - The family
inetcovers IPv4 and IPv6 in one table, so there is no forgotten IPv6 path with no rules. The two address sets are separate because the address types differ. The example addresses are a documentation-style private range (10.77.0.0/24) and a unique-local IPv6 address; replace them with your admin or bastion addresses. - Sets can be changed without reloading the file:
nft add element inet filter admin_v4 '{ 10.77.0.99 }'adds an address. To make it permanent, add it to the file as well, or the next reload forgets it. ct stateis connection tracking: the kernel remembers each flow, which is why one rule accepts all replies.
Test it before trusting it
-
Syntax check without applying:
nft -c -f /etc/nftables.confparses the file and reports errors without changing the running ruleset. -
Behaviour test from outside, using throwaway containers. This needs Docker on a Linux machine. Three containers share one Docker network: a server with the ruleset loaded and listeners on 22, 443 and 8080, one probe at an admin address and one at an address that is not in the set (the network, names and addresses are illustrative):
bash# setup, run from a directory holding web-fw.nft (the ruleset above), echo_server.py, server.sh and probe.sh docker network create --subnet 10.77.0.0/24 fw-test-net docker run -d --name fw-server --network fw-test-net --ip 10.77.0.2 --cap-add NET_ADMIN \ -v "$PWD":/w ubuntu:24.04 bash /w/server.sh docker run -d --name fw-admin --network fw-test-net --ip 10.77.0.10 -v "$PWD":/w ubuntu:24.04 sleep 300 docker run -d --name fw-other --network fw-test-net --ip 10.77.0.50 -v "$PWD":/w ubuntu:24.04 sleep 300 # wait for the server to finish installing and loading (about 30 seconds), then probe from each client docker exec fw-admin bash /w/probe.sh docker exec fw-other bash /w/probe.sh # cleanup docker rm -f fw-server fw-admin fw-other && docker network rm fw-test-net--cap-add NET_ADMINlets the server container change its own firewall; the clients do not need it. The echo server is a few lines of Python that listens on port 22 and sends back whatever it receives:python# echo_server.py import socket s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("0.0.0.0", 22)) s.listen() while True: c, _ = s.accept() while True: d = c.recv(100) if not d: break c.sendall(d)bash# server.sh (runs in the server container: Ubuntu 24.04) apt-get update -qq && apt-get install -y -qq nftables python3 > /dev/null python3 /w/echo_server.py & # echo server on TCP 22 for p in 443 8080; do python3 -m http.server "$p" --bind 0.0.0.0 > /dev/null 2>&1 & done nft -c -f /w/web-fw.nft && nft -f /w/web-fw.nft wait # keep the container (and the listeners) alive # probe.sh (runs in each client container; the server is 10.77.0.2) for p in 22 443 8080; do timeout 2 bash -c "exec 3<>/dev/tcp/10.77.0.2/$p" 2>/dev/null \ && echo "port $p open" || echo "port $p blocked/timeout" doneReading the probe:
/dev/tcp/HOST/PORTis not a real file but a bash feature, andexec 3<>/dev/tcp/10.77.0.2/22makes bash try to open a TCP connection to that address and port as file descriptor 3. If the connection is accepted the command succeeds, so&&prints "open". A dropped packet gets no reply, so the attempt hangs untiltimeout 2kills it after 2 seconds and||prints "blocked/timeout". A closed port that is not firewalled would answer at once with a refusal and print the same blocked message. Without the finalwaitthe script ends, the container exits and every probe prints blocked/timeout. With it, the probes printed exactly the table below.Probe from port 22 port 443 port 8080 admin address 10.77.0.10 open open blocked/timeout other address 10.77.0.50 blocked/timeout open blocked/timeout This confirms all three decisions: the public service is reachable by everyone, SSH only by the admin set, and an unplanned port by nobody.
-
Check that reloading does not drop a live session. A client at an admin address opens a TCP session to port 22, the server's ruleset is reloaded with
nft -fwhile the session is open, and the client sends again:python# session_client.py <server-ip> import socket, sys, time s = socket.create_connection((sys.argv[1], 22), timeout=5) s.sendall(b"before"); print("echo 1:", s.recv(100)) time.sleep(6) # the server reloads its ruleset during this pause s.sendall(b"after-reload"); print("echo 2:", s.recv(100))Output:
echo 1: b'before'thenecho 2: b'after-reload'. The established-connection rule is what carries the session across the reload.
Applying it on a real host without cutting yourself off
Two ways lock-outs happen: a typo in the admin address set, and rules that load fine but block the path you are using. Guard against both:
# 1. save our own table so it can be put back (or removed again if it did not exist)
{ echo 'table inet filter'; echo 'delete table inet filter'; nft list table inet filter 2>/dev/null; } > /root/fw-before.nft
# 2. arm a rollback in 2 minutes (systemd transient timer)
systemd-run --unit=fw-revert --on-active=2min /usr/sbin/nft -f /root/fw-before.nft
# 3. validate, then apply
nft -c -f /etc/nftables.conf && nft -f /etc/nftables.conf
# 4. from a SECOND terminal, open a new SSH connection from an admin address
# and request the HTTPS page from outside; only then cancel the rollback:
systemctl stop fw-revert.timer
Reading step 1: the curly braces form a brace group, which runs the three commands one after the other and lets one > send their combined output to a single file. The file therefore starts with table inet filter (create the table if it is missing, so the next line cannot fail) and delete table inet filter (remove it), followed by nft list table inet filter (the current definition of that table in loadable form, or nothing if there is no such table). Loading the file later first removes our table and then re-creates the old one if there was one. Only our own table is touched, which matches how the ruleset file itself is loaded. In step 2, systemd-run --on-active=2min schedules that load to run once, 2 minutes from now.
If the new rules strand you, you do nothing and the timer restores the old behaviour in 2 minutes. The saved file begins with the create-then-delete pair because loading a file does not remove rules that are already present; I checked that loading an empty file left the new rules in place, that the saved file removed the table again when none existed beforehand, and that, when one did exist, adding a rule and then loading the saved file brought back exactly the saved rules. I did not save the whole ruleset with flush ruleset because that is not safe on a host that also runs Docker: nft list ruleset prints the iptables-nft compatibility tables too, and in a test container nft -f refused to load them back with unsupported xtables compat expression. A file loads as one transaction, so that error would have meant the revert changed nothing and the lock-out stayed in place, and a successful flush would also have wiped the other tools' tables that the ruleset file takes care to leave alone. systemd-run --on-active= creates a transient timer, and with --unit= the timer is named fw-revert.timer; the revert command itself was not run here, because the test containers have no systemd. Keep out-of-band access (a cloud serial console or hypervisor console) ready, since it is the only route back if even the timer fails.
Surviving a reboot
On Debian and Ubuntu the nftables package ships nftables.service, whose ExecStart is /usr/sbin/nft -f /etc/nftables.conf, so the file above goes in /etc/nftables.conf and systemctl enable nftables makes it load at boot. On the RHEL family the service loads /etc/sysconfig/nftables.conf instead (in the AlmaLinux 9 package, whose ExecStart is /sbin/nft -f /etc/sysconfig/nftables.conf, that file ships with the sample include commented out), so use include there or put the rules in that file. To test persistence without waiting for a reboot, run nft flush ruleset from a console session and then systemctl restart nftables and list the ruleset; then do one real reboot in a maintenance window, with console access open, before calling it done.
Trade-offs and what would change the design
- Outbound
accept: a web server that can reach anywhere makes data theft and reverse shells easier after a compromise. The alternative is an outbound allow-list (DNS, time sync, package repositories, the specific APIs the application calls). I would take that for a server holding sensitive data, and accept the maintenance cost (every new dependency is a ticket). For a small server whose compromise has limited blast radius, accept-all outbound plus egress monitoring is a defensible choice. - SSH allow-list versus a bastion or VPN: if admins have changing addresses, an allow-list becomes constant churn and lock-outs. Allow SSH only from the bastion's address instead, and control who can use the bastion.
- Rate-limiting echo and new connections is a convenience, not a security boundary. Real denial-of-service protection happens upstream.
- Containers on the same host (Docker, Kubernetes) add their own rules and forwarding behaviour. The scoped
delete tableapproach avoids deleting them, but you must test the combination.
Pitfalls
- Putting
ct state established,related acceptafter the SSH rule, or omitting it, and cutting off the session when the policy loads. - Forgetting IPv6: an IPv4-only ruleset leaves the host wide open over IPv6 if it has an address, which is why the table is
inet. - Setting
policy dropon the input chain before confirming the ICMPv6 neighbour-discovery rules, so the host loses its default gateway and drops off the network. - Testing only from inside the host, which shows nothing about what the network can reach.
A new Windows server has just been provisioned and should have your organisation's hardening baseline applied through Group Policy and local hardening scripts. How do you verify automatically that it really applied, which commands and logs do you inspect, and how do noncompliant hosts get surfaced to the team?
Sample Answer
Direct answer
Do not trust "the Group Policy Object (GPO) is linked" or "the script exited 0". Verify the effective state on the host, automatically, in four layers, and report centrally:
- Did policy process? Look at the Group Policy Operational event log and run
gpresultto see which GPOs applied or were denied. - Is the setting actually in effect? Query the live value with the tool that owns it (firewall profile, registry,
auditpol, SMB configuration) and compare with the expected value. - Did the local hardening script finish? Check a run record that the script writes at the end (version, exit code, time), not just the scheduler's "task succeeded".
- Surface the result. Each host emits a JSON result with a status per setting; a collector aggregates them and the team gets a list of non-compliant hosts, with "not yet applied" and "deliberately excepted" shown separately from "wrong".
Layer 1: did Group Policy process, and what applied
Run these on the host from an elevated prompt (or remotely through your management tooling):
gpupdate /force /target:computer
gpresult /scope computer /h C:\Temp\gp-computer.html /f
gpresultreports the Resultant Set of Policy (RSoP), the combined outcome of every GPO that applies to the computer. It needs an output option./hwrites an HTML report and/foverwrites an existing file;/rprints a summary to the console and/vor/zprint more detail. The report lists the GPOs that applied and those that were denied, with the reason. Two common reasons: a security filter (a setting on the GPO that limits it to named computers or groups, so a server outside them is denied) and a Windows Management Instrumentation (WMI) filter (a query about the machine, such as its OS version, that must return true for the GPO to apply). How to read it for a new server: find the hardening GPO by name. If it sits under the applied list, policy reached the host. If it sits under the denied list, the stated reason tells you whether the server is in the wrong group or OU, or failed a filter. If it appears in neither, the GPO is not linked above the server's OU. Archive the report as evidence for a failed host.- The event log
Microsoft-Windows-GroupPolicy/Operationalrecords the processing. A client-side extension (CSE) is the part of Windows that applies one family of Group Policy settings (security settings, firewall, advanced audit and so on); each runs separately, so one can fail while the others succeed. Event 4016 marks a client-side extension starting and 5016 marks it completing successfully, so a healthy processing run shows a 4016 and a 5016 pair per extension, and a 4016 with no later 5016 means that extension did not finish.Get-WinEventprints events with the columnsTimeCreated,Id,LevelDisplayNameandMessage; the extension's name is in theMessagetext. Warnings and errors in the System log (for example 1129, no network path to a domain controller, or 1058, the policy files could not be read from the domain controller) explain why policy did not process. - Clock skew matters: Microsoft's guidance notes that a difference of more than five minutes between a computer and its domain controller can stop the computer authenticating, so a new server with a wrong clock gets no policy.
w32tm /resyncfixes it. - A success event does not prove the setting is in effect. For the advanced audit extension, event 5016 can carry the return status
E_PENDING(a Windows status meaning "not finished yet") by design: an asynchronous thread was started to apply the audit settings, so the event says only that processing began. Check the Security-Audit-Configuration-Client Operational log (under Applications and Services Logs, Microsoft, Windows) and, more importantly, read the live audit policy withauditpolas in Layer 2.
Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-GroupPolicy/Operational'; Id = 5016 } -MaxEvents 5
Layer 2 and 3: check the live state and the local script
The script below runs on the host (from a scheduled task, a remoting call or your endpoint management tool). It checks a baseline of eight items covering six kinds of evidence, and writes a JSON result:
#requires -Version 5.1
[CmdletBinding()]
param(
[datetime]$ProvisionedAtUtc = [datetime]::MinValue,
[int]$GraceMinutes = 120,
[int]$MaxGpoAgeHours = 24,
[string]$RunRecordPath = 'C:\ProgramData\Hardening\last-run.json',
[string]$OutputPath = (Join-Path $env:TEMP 'baseline-result.json')
)
$Baseline = @{
Version = '2026.10'
Checks = @(
@{ Id = 'fw-domain-on'; Type = 'Firewall'; Profile = 'Domain'; Expected = 'True' }
@{ Id = 'fw-public-on'; Type = 'Firewall'; Profile = 'Public'; Expected = 'True' }
@{ Id = 'tls10-server'; Type = 'Registry'
Path = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server'
Name = 'Enabled'; Expected = '0' }
@{ Id = 'smb1-off'; Type = 'Smb'; Property = 'EnableSMB1Protocol'; Expected = 'False' }
@{ Id = 'smb-sign-req'; Type = 'Smb'; Property = 'RequireSecuritySignature'; Expected = 'True'
Exception = @{ Ticket = 'CHG-1042'; Approver = 'secops'; Expires = '2026-12-31' } }
@{ Id = 'audit-proc-create'; Type = 'Audit'; Category = 'Detailed Tracking'
Subcategory = 'Process Creation'; Expected = 'Success' }
@{ Id = 'local-script-ran'; Type = 'RunRecord'; Expected = '2026.10' }
@{ Id = 'gpo-fresh'; Type = 'GpoFresh'; Expected = 'True' }
)
}
function Get-ObservedValue {
param($Check)
switch ($Check.Type) {
'Firewall' { [string](Get-NetFirewallProfile -Name $Check.Profile -PolicyStore ActiveStore).Enabled }
'Registry' {
if (-not (Test-Path -LiteralPath $Check.Path)) { '<missing>' }
else {
$props = Get-ItemProperty -LiteralPath $Check.Path -ErrorAction Stop
if ($props.PSObject.Properties.Name -contains $Check.Name) { [string]$props.($Check.Name) } else { '<missing>' }
}
}
'Smb' { [string](Get-SmbServerConfiguration).($Check.Property) }
'Audit' {
$rows = auditpol /get /category:"$($Check.Category)" /r |
ConvertFrom-Csv -Header Machine, Target, Subcategory, Guid, Inclusion, Exclusion
$row = $rows | Where-Object Subcategory -match $Check.Subcategory | Select-Object -First 1
if (-not $row) { throw "subcategory $($Check.Subcategory) not in auditpol output" }
[string]$row.Inclusion
}
'RunRecord' {
if (-not (Test-Path -LiteralPath $RunRecordPath)) { '<missing>' }
else { [string](Get-Content -LiteralPath $RunRecordPath -Raw -ErrorAction Stop | ConvertFrom-Json).BaselineVersion }
}
'GpoFresh' {
$since = (Get-Date).AddHours(-$MaxGpoAgeHours)
$ev = Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-GroupPolicy/Operational'; Id = 5016; StartTime = $since } -MaxEvents 1 -ErrorAction SilentlyContinue
[string][bool]$ev
}
}
}
function Resolve-CheckStatus {
param($Check, [string]$Observed, [string]$ErrorText, [datetime]$Now, [datetime]$ProvisionedAtUtc, [int]$GraceMinutes)
if ($ErrorText) { return @{ Status = 'Unknown'; Note = $ErrorText } }
$ok = if ($Check.Type -eq 'Audit') { $Observed -match $Check.Expected } else { $Observed -eq $Check.Expected }
if ($ok) { return @{ Status = 'Compliant'; Note = '' } }
$ex = $Check.Exception
if ($ex -and ([datetime]$ex.Expires).Date -ge $Now.Date) {
return @{ Status = 'Excepted'; Note = "$($ex.Ticket) approved by $($ex.Approver) until $($ex.Expires)" }
}
if (($Now - $ProvisionedAtUtc).TotalMinutes -lt $GraceMinutes) {
return @{ Status = 'Pending'; Note = 'inside the post-provisioning grace window' }
}
$note = if ($ex) { "exception $($ex.Ticket) expired $($ex.Expires)" } else { '' }
return @{ Status = 'NonCompliant'; Note = $note }
}
function Invoke-Baseline {
$now = [datetime]::UtcNow
$results = foreach ($c in $Baseline.Checks) {
$obs = $null; $err = $null
try { $obs = Get-ObservedValue -Check $c } catch { $err = $_.Exception.Message }
$r = Resolve-CheckStatus -Check $c -Observed $obs -ErrorText $err -Now $now -ProvisionedAtUtc $ProvisionedAtUtc -GraceMinutes $GraceMinutes
[pscustomobject]@{ id = $c.Id; expected = $c.Expected; observed = $obs; status = $r.Status; note = $r.Note }
}
$doc = [pscustomobject]@{
host = $env:COMPUTERNAME; baselineVersion = $Baseline.Version
checkedAtUtc = $now.ToString('o'); results = @($results)
}
$doc | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $OutputPath -Encoding UTF8
if ($results | Where-Object status -eq 'NonCompliant') { exit 1 }
if ($results | Where-Object status -in 'Unknown', 'Pending') { exit 2 }
exit 0
}
Invoke-Baseline
What each kind of check does:
| Check | Source of truth | Expected value (example) |
|---|---|---|
Firewall | Get-NetFirewallProfile -PolicyStore ActiveStore, the effective policy summed over all GPOs and local rules | profile enabled |
Registry | Get-ItemProperty on the Schannel protocol key (Enabled of the Transport Layer Security 1.0 server role) | 0 |
Smb (Server Message Block, the Windows file-sharing protocol) | Get-SmbServerConfiguration properties EnableSMB1Protocol and RequireSecuritySignature | False and True |
Audit | auditpol /get /category:"Detailed Tracking" /r parsed as CSV; the Process Creation row must include Success | Success |
RunRecord | last-run.json written by the hardening script at the end of a successful run, holding BaselineVersion | 2026.10 |
GpoFresh | an event 5016 in Microsoft-Windows-GroupPolicy/Operational within the last 24 hours (an example threshold) | True |
The local hardening script must write the run record only after all its steps succeed, for example { "BaselineVersion": "2026.10", "ExitCode": 0, "FinishedUtc": "..." }. A missing or older record means the script did not finish or an old baseline version ran. A record, registry key or registry value that does not exist yet is not a failed check: the script reports the observed value <missing>, which is a mismatch like any other, so it goes through the exception and grace-window rules below. That is exactly what a server on which Group Policy has not yet processed looks like. Pass -ProvisionedAtUtc (from the asset inventory) so the grace window can work; its default of the minimum date value switches the grace window off.
What the collected evidence looks like
The auditpol report. With /r, auditpol prints CSV with six columns: machine name, policy target, subcategory, subcategory GUID, inclusion setting and exclusion setting (the Microsoft Learn description of the report format). The script supplies those six names itself with ConvertFrom-Csv -Header, so the printed header line becomes the first parsed row, which is harmless because the filter Where-Object Subcategory -match 'Process Creation' skips it. Illustrative rows for a host called WEB01, parsed on PowerShell 7:
Machine Subcategory Inclusion
------- ----------- ---------
Machine Name Subcategory Inclusion Setting
WEB01 Process Creation Success
WEB01 Process Termination No Auditing
The check reads the Inclusion value of the Process Creation row, here Success, which matches the expected Success. A row reading No Auditing would be NonCompliant.
An exception as a record. In the baseline, an exception is a small hash table attached to the check, with a ticket, an approver and an expiry date. This is the smb-sign-req check from the script:
@{ Id = 'smb-sign-req'; Type = 'Smb'; Property = 'RequireSecuritySignature'; Expected = 'True'
Exception = @{ Ticket = 'CHG-1042'; Approver = 'secops'; Expires = '2026-12-31' } }
The result file the collector receives. baseline-result.json has one entry per check. This illustrative example for WEB01 uses four of the eight checks and was produced by running the script's own Resolve-CheckStatus function on PowerShell 7 with a fixed clock; the observed values are made up to show each status:
{
"host": "WEB01",
"baselineVersion": "2026.10",
"checkedAtUtc": "2026-10-05T12:00:00.0000000Z",
"results": [
{ "id": "fw-domain-on", "expected": "True", "observed": "True", "status": "Compliant", "note": "" },
{ "id": "smb1-off", "expected": "False", "observed": "True", "status": "NonCompliant", "note": "" },
{ "id": "smb-sign-req", "expected": "True", "observed": "False", "status": "Excepted", "note": "CHG-1042 approved by secops until 2026-12-31" },
{ "id": "audit-proc-create", "expected": "Success", "observed": "Success", "status": "Compliant", "note": "" }
]
}
(The script writes it with ConvertTo-Json, which prints each field on its own line; it is compacted here.) The collector only needs the host and the status of each entry: this host would be listed as NonCompliant because of smb1-off, with the excepted SMB signing counted separately. The script's exit code for this host would be 1, since one item is non-compliant.
Distinguishing "not yet applied" from "deliberately excepted"
The function Resolve-CheckStatus assigns one of five statuses to each check. The rules, in order:
- Observed value equals expected:
Compliant. - Not equal, and the check carries an exception (ticket, approver, expiry date) that has not expired:
Excepted, with the ticket in the note. - Not equal, no valid exception, and the host was provisioned less than the grace period ago (120 minutes here, an example):
Pending. Group Policy and first-boot scripts need time, and flagging every new server red in its first minutes trains the team to ignore the report. - Not equal otherwise:
NonCompliant. If an exception existed but expired, the note says so. - The check itself failed (for example access denied, or a malformed run record):
Unknownwith the error text, never a pass. A key, value or record that simply does not exist is not a failure of the check; it is a mismatch with observed value<missing>and follows rules 2 to 4.
The script exits 1 for any non-compliant item and 2 when only Unknown or Pending items remain, so a pipeline can gate a server's promotion into production on exit code 0.
The decision function was executed on PowerShell 7 with fixed times. Save the script as Test-HardeningBaseline.ps1 and the harness below as t.ps1 in the same folder, then run pwsh -NoProfile -File t.ps1. The harness loads the function from the saved script:
$e=$null;$t=$null
$ast=[System.Management.Automation.Language.Parser]::ParseFile("$PWD/Test-HardeningBaseline.ps1",[ref]$t,[ref]$e)
"parse errors: $($e.Count)"
foreach($f in $ast.FindAll({param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Resolve-CheckStatus'},$true)){ Invoke-Expression $f.Extent.Text }
$now=[datetime]'2026-10-05T12:00:00Z'
$prov=[datetime]'2026-10-05T10:30:00Z' # 90 min before
$old=[datetime]'2026-10-04T10:30:00Z'
$ex=@{Ticket='CHG-1042';Approver='secops';Expires='2026-12-31'}
$exOld=@{Ticket='CHG-0001';Approver='secops';Expires='2026-09-30'}
function show($label,$r){ '{0,-34} {1,-13} {2}' -f $label,$r.Status,$r.Note }
show 'match' (Resolve-CheckStatus -Check @{Type='Smb';Expected='True'} -Observed 'True' -ErrorText $null -Now $now -ProvisionedAtUtc $old -GraceMinutes 120)
show 'audit contains Success' (Resolve-CheckStatus -Check @{Type='Audit';Expected='Success'} -Observed 'Success and Failure' -ErrorText $null -Now $now -ProvisionedAtUtc $old -GraceMinutes 120)
show 'mismatch, valid exception' (Resolve-CheckStatus -Check @{Type='Smb';Expected='True';Exception=$ex} -Observed 'False' -ErrorText $null -Now $now -ProvisionedAtUtc $old -GraceMinutes 120)
show 'mismatch, 90 min old host' (Resolve-CheckStatus -Check @{Type='Smb';Expected='True'} -Observed 'False' -ErrorText $null -Now $now -ProvisionedAtUtc $prov -GraceMinutes 120)
show 'mismatch, expired exception' (Resolve-CheckStatus -Check @{Type='Smb';Expected='True';Exception=$exOld} -Observed 'False' -ErrorText $null -Now $now -ProvisionedAtUtc $old -GraceMinutes 120)
show 'mismatch, no exception' (Resolve-CheckStatus -Check @{Type='Smb';Expected='True'} -Observed 'False' -ErrorText $null -Now $now -ProvisionedAtUtc $old -GraceMinutes 120)
show 'check threw' (Resolve-CheckStatus -Check @{Type='Smb'} -Observed $null -ErrorText 'access denied' -Now $now -ProvisionedAtUtc $old -GraceMinutes 120)
Output:
parse errors: 0
match Compliant
audit contains Success Compliant
mismatch, valid exception Excepted CHG-1042 approved by secops until 2026-12-31
mismatch, 90 min old host Pending inside the post-provisioning grace window
mismatch, expired exception NonCompliant exception CHG-0001 expired 2026-09-30
mismatch, no exception NonCompliant
check threw Unknown access denied
The missing-record branch of the collection code was executed on PowerShell 7 with a run-record path that does not exist (save the harness as t3.ps1 next to the script and run pwsh -NoProfile -File t3.ps1):
$e=$null;$t=$null
$ast=[System.Management.Automation.Language.Parser]::ParseFile("$PWD/Test-HardeningBaseline.ps1",[ref]$t,[ref]$e)
"parse errors: $($e.Count)"
$RunRecordPath = Join-Path $PWD 'no-such-last-run.json'
foreach($f in $ast.FindAll({param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -in 'Get-ObservedValue','Resolve-CheckStatus'},$true)){ Invoke-Expression $f.Extent.Text }
$now = [datetime]'2026-10-05T12:00:00Z'
$check = @{ Id = 'local-script-ran'; Type = 'RunRecord'; Expected = '2026.10' }
$obs = Get-ObservedValue -Check $check
"observed with no run record: $obs"
foreach ($age in 10, 600) {
$r = Resolve-CheckStatus -Check $check -Observed $obs -ErrorText $null -Now $now -ProvisionedAtUtc $now.AddMinutes(-$age) -GraceMinutes 120
'{0,3}-minute-old host: {1}' -f $age, $r.Status
}
parse errors: 0
observed with no run record: <missing>
10-minute-old host: Pending
600-minute-old host: NonCompliant
The rest of the collection of live values (Get-NetFirewallProfile, auditpol, registry and SMB queries, including the registry branch, which uses the same Test-Path pattern) needs a Windows host, so that part was parse-checked and its cmdlets verified against Microsoft Learn, not executed.
Surfacing noncompliant hosts
- Each host writes
baseline-result.json; an agent or scheduled task ships it to a central store (a file share, a SIEM (security information and event management) index or a database), keyed by host name. - A daily report lists hosts by status:
NonCompliantfirst with the failing check ids, thenUnknown(the host could not be evaluated, which includes a host that stopped reporting), thenPendingolder than a few hours, and a count of active exceptions with their expiry dates. - Alerts go to the owning team's queue with the host, the failing check, the expected and observed values, and a link to the stored
gpresultreport. - Reconcile the list against the asset inventory: a server with no result at all is an alert in its own right.
- Trend the numbers: percentage compliant per baseline version, mean time from provisioning to compliant, and exceptions nearing expiry.
Pitfalls
- Reading GPO status from the Group Policy Management Console instead of the host: it shows what is linked, not what applied.
- Treating event 5016 as proof for audit settings (see the
E_PENDINGnote above). - A grace window that never closes: always compute
Pendingfrom the provisioning time and let it expire. - Exceptions without an expiry date become permanent.
- Checking only the registry value that a GPO sets: another source may override it later, so also check the effective state where a tool offers one (the firewall ActiveStore,
auditpol).
A critical remote code execution flaw is being exploited in the wild and a vendor patch exists. How does your team get from the advisory to every host patched, and what protects you in the gap?
Sample Answer
Direct answer
Treat it as an emergency change with two parallel tracks that start at once: close the gap (reduce exposure now with mitigations while the patch is prepared) and close the hole (patch every vulnerable host, internet-facing first, through compressed rings). A third track runs alongside because the flaw is being exploited: assume some hosts may already be compromised and look for evidence going back to when exploitation started, not when we heard about it. Verification is an independent check that no host still runs the vulnerable version, and I close the incident only after mitigations have been unwound deliberately and the hunt has finished.
Advisory to every host patched, step by step
- Confirm it applies to us. Read the vendor advisory: which product, versions and configurations are affected, and whether exploitation requires a specific feature. Query the inventory and scanner for hosts that run it. This is the first place a poor inventory shows: if you cannot list affected hosts within the hour, that is the first lesson.
- Declare an emergency change. Name an incident lead and a change approver who can approve out of normal cycle, open a channel, and agree a status cadence. Pre-agreed emergency change rules exist so this is minutes, not days.
- Rank the exposure. Internet-facing first, then hosts reachable from partner networks or user networks, then isolated hosts. The same ranking decides patch order.
- Apply mitigations immediately where you can, per exposure (see the next section).
- Patch a canary in hours, not weeks. A canary is a small first group of hosts, like the canary in the mine, that gets the change before everyone else so a problem shows up on a few machines. Apply the vendor patch to a handful of hosts that represent each affected role, check health, and use that evidence to authorise the wider push. An emergency changes the soak time, not the existence of a test.
- Roll out in compressed rings (groups of hosts patched one group after another), internet-facing hosts first even if they are in the later ring. Keep the ability to halt.
- Hunt for compromise. Search logs and endpoint telemetry for the exploit's known indicators from the date exploitation began, using the vendor and public reporting, up to now. Patching closes the door but does not evict someone already inside. Indicators of compromise (IOCs) are observable traces of an attack, such as file hashes, IP addresses, domain names or process names; the vendor and public reporting publish them. Beyond the published list, look for typical evidence, and know where each kind lives:
| Evidence | Where to look |
|---|---|
| New accounts | Windows: Security log event 4720 (a user account was created). Linux: getent passwd compared with the last known list, and the authentication log |
| Unexpected child processes of the vulnerable service (for example a web server launching a shell) | The EDR process tree. Windows Security event 4688 (a new process was created), which includes the parent process name and, if the "Include command line in process creation events" policy is on, the command line |
| New scheduled tasks or cron entries | Windows: Security event 4698 (a scheduled task was created). Linux: crontab -l, /etc/cron.d, and systemd timers |
| Outbound connections to new destinations | Firewall, proxy and DNS logs; on a host, ss -tnp for live connections |
- Verify. Re-scan with an authenticated scan (the scanner logs in to each host and reads installed versions, instead of guessing from outside) and query installed versions directly; reconcile against the host list from step 1; chase every host that did not report. Confirm required restarts happened.
- Unwind and learn. Remove temporary mitigations on purpose (a forgotten block rule is its own outage), record the timeline, and fix whatever slowed you (inventory, approval, rings).
What protects you in the gap
| Protection | How it helps | Limit |
|---|---|---|
| Disable or restrict the vulnerable feature or service | Removes the attack path entirely if the vendor documents a workaround | May break a function; confirm with the service owner |
| Restrict network reach (firewall rule, take the service off the internet, allow only known source ranges) | Attacker cannot reach the vulnerable port | Blocks legitimate users too; works only if the flaw is network-reachable |
| Virtual patch: a WAF or intrusion prevention rule that blocks the exploit pattern for this flaw (a WAF is a web application firewall sitting in front of the web application so all requests pass it) | Buys time without touching the host | Only as good as the signature; attackers vary payloads, so it is a delay not a fix |
| Detection tuned to the exploit: EDR (endpoint detection and response) and log rules for the known indicators | Catches successful exploitation quickly | Detects, does not prevent |
| Reduce what a compromise yields: rotate credentials the host could read, tighten service-account rights | Limits blast radius (how much an attacker who gets in can reach and damage) if exploitation already happened | Needs prior least-privilege work to be fast |
Choose by what the flaw needs: a remotely reachable network flaw gets the network restriction first; a flaw in an optional feature gets the feature disabled. I never rely on a single row: restrict reach and add detection at minimum.
Worked example
Suppose the advisory covers a web application server product, exploitation is unauthenticated over HTTPS, and the inventory shows 40 affected hosts: 6 internet-facing, 14 reachable from the corporate network, 20 internal job-runner hosts. Hour 0 to 2: confirm the list, declare the emergency change, put the 6 internet-facing hosts behind an allow-list or WAF rule. Hours 2 to 6: patch 2 canaries drawn from the 40 (one internet-facing host and one internal job-runner host) and run the application's health checks. Then in stages: the other 5 internet-facing hosts, then the 14 reachable from the corporate network, then the remaining 19 internal job-runner hosts. The count reconciles: 2 + 5 + 14 + 19 = 40. In parallel, start the hunt on the 6 exposed hosts from the first public exploitation date. If an authenticated scan afterwards finds 39 hosts at the fixed version, the one missing host is found by reconciling the scan against the step-1 list, which is why that list is kept.
Trade-offs and pitfalls
- Speed versus safety: an emergency patch that breaks the service turns a security incident into an availability incident. Canary evidence is how you justify going fast.
- Mitigations create false confidence. A WAF rule is not a patch and should carry an expiry.
- Declaring victory at "patch deployed". The hosts that did not report, and the hosts already compromised, are the risk that remains.
- Assuming the clock starts at the advisory. Exploitation may have started earlier, so the hunt window starts at the first reported exploitation.
A business-critical internal application depends on an old protocol version your baseline forbids, and it cannot be upgraded for six months. How do you contain the risk on the hosts involved while it stays up, and how do you stop the exception becoming permanent?
Sample Answer
Direct answer
Keep the forbidden protocol alive only on the one service that needs it, shrink who can reach that service to a named list of clients, wrap the process so a compromise of it goes nowhere, and record the whole arrangement as an exception with an owner and a hard expiry date that a script checks every night. The exception becomes permanent when nobody is forced to look at it, so the design goal is that the expiry date is enforced by the system, not remembered by a person.
The running example below is a billing application that still needs TLS 1.0 (an obsolete version of the Transport Layer Security protocol) on port 8443, approved on 2026-11-01 for six months, so it expires 2027-04-30. Network segmentation would add another layer, but the controls below work on the host itself, so they hold even if the network enforces nothing.
Step 1: Contain the risk on the host
| Layer | What it does | Where it sits |
|---|---|---|
| Scoped weakness | The legacy setting lives in this one application's own listener config, never in host-wide crypto settings. Every other service on the box keeps the baseline. | Application config |
| Host firewall allow-list | Only the two known client addresses may reach port 8443. Everyone else is dropped and logged. | The host's own packet filter, on the input path, so any packet addressed to this host must pass it |
| Service sandbox | The process runs as a dedicated unprivileged user, cannot gain privileges, sees a read-only filesystem except its data directory, and can only talk to listed addresses. | systemd unit |
| Reduced exposure | Remove every package, shell, compiler and unused listener the app does not need. Disable remote admin paths that are not required. | Host build |
| Watching | Dropped attempts are logged, and the vulnerability scanner finding is linked to the exception ID. | Logging and scanner |
Host firewall (nftables, the Linux packet filter). Rules run top to bottom and the first match decides, so the allow rule comes before the drop. The policy stays accept so only port 8443 is restricted and nothing else on the host changes:
table inet legacy_app {
set allowed_clients {
type ipv4_addr
elements = { 10.20.4.11, 10.20.4.12 }
}
chain input {
type filter hook input priority 0; policy accept;
tcp dport 8443 ip saddr @allowed_clients accept
tcp dport 8443 counter log prefix "legacy-app-denied " drop
}
}
Loaded with nft -f legacy.nft and then listed with nft list table inet legacy_app, the ruleset is accepted and prints back as:
table inet legacy_app {
set allowed_clients {
type ipv4_addr
elements = { 10.20.4.11, 10.20.4.12 }
}
chain input {
type filter hook input priority filter; policy accept;
tcp dport 8443 ip saddr @allowed_clients accept
tcp dport 8443 counter packets 0 bytes 0 log prefix "legacy-app-denied " drop
}
}
Reading the listing: the source said priority 0, and nft prints it back as priority filter, its name for 0 (the ordinary position for filtering rules among other chains on the same hook). hook input means the chain sees packets addressed to this host. ip saddr @allowed_clients matches a source address in the named set. counter packets 0 bytes 0 was added by the word counter in the drop rule: it is a tally that starts at zero and increments each time a packet matches that rule, so it is how you see denied attempts. log prefix "legacy-app-denied " writes a kernel log line with that tag for each match, and drop discards the packet silently.
That shows the syntax loads and the rules are in the order intended; it does not prove live traffic behaviour, so after deployment send a test connection from an allowed and a non-allowed host and confirm the drop counter moves only for the second. Persist the rules through the host's normal nftables configuration so they survive a reboot.
Service sandbox (systemd unit; once the program named in ExecStart exists on disk the file passes systemd-analyze verify with no output, because verify also checks that path and prints a "not executable" error while it is missing; a deliberately misspelled directive is reported, so the check does catch typos):
[Unit]
Description=Legacy billing app (TLS 1.0 exception, expires 2027-04-30)
[Service]
ExecStart=/opt/legacy-app/bin/server
User=legacyapp
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=/var/lib/legacy-app
ProtectHome=yes
PrivateTmp=yes
CapabilityBoundingSet=
RestrictAddressFamilies=AF_INET AF_UNIX
IPAddressAllow=10.20.4.11 10.20.4.12 10.20.9.0/28
IPAddressDeny=any
$ systemd-analyze verify /etc/systemd/system/bad.service
/etc/systemd/system/bad.service:7: Unknown key name 'NoNewPrivilegez' in section 'Service', ignoring.
Why each line: ProtectSystem=strict mounts the whole filesystem read-only except the paths named in ReadWritePaths; an empty CapabilityBoundingSet= removes every Linux capability from the process (Linux splits the powers of the root user into separate units called capabilities, such as CAP_NET_ADMIN for changing firewall and network settings and CAP_SYS_ADMIN for mounting filesystems, so a process with none of them cannot do any of those root-only things even if it is compromised); NoNewPrivileges=yes stops it gaining privilege through execve() (the system call that starts a program), for example by launching a setuid program (a program that runs with its owner's rights); IPAddressAllow/IPAddressDeny filter both incoming and outgoing packets of the service, with the allow list checked first, so IPAddressDeny=any plus an allow list is a default-deny. The 10.20.9.0/28 entry stands for the application's own database or dependency range; add the local resolver too if the app needs one. This is a second, independent layer: if someone edits the nftables rules, the unit still limits where the process can talk.
Step 2: Stop the exception becoming permanent
- A written exception record: ID, host, control being waived, compensating controls (the table above), business owner, technical owner, approver, and an expiry date. The expiry is the vendor's committed upgrade date, not an open "until fixed".
- Expiry that fails loudly. A nightly job reads the exception register and exits non-zero for any expired row, which opens a ticket and pages the owner.
- Checkpoints on the project, not only on the exception. At the midpoint (2027-01-31) the upgrade must have a test build in hand; if it does not, the business owner and the approver meet to decide, with the real dates, whether to fund an alternative.
- Renewal is harder than the first approval. One extension of at most 30 days, signed by a more senior approver than the original, with the reason the date slipped written down. A second extension is a new exception.
- Scanner and baseline linkage. The scanner suppression for this host carries the exception ID and the same expiry, so when the exception lapses the finding reappears on its own.
Register and checker (bash, run with the date pinned so the result is repeatable). The register is the CSV file shown after the script, one exception per row. The billing exception was approved on 2026-11-01, so the check below is pinned to 2026-11-05, a few days after approval:
#!/usr/bin/env bash
# Fail (exit 1) if any approved exception has passed its expiry date.
set -euo pipefail
today=${TODAY:-$(date +%F)}
rc=0
while IFS=, read -r id host control expires owner; do
[[ $id == id ]] && continue
if [[ $expires < $today ]]; then
printf 'EXPIRED %s host=%s control=%s expired=%s owner=%s\n' "$id" "$host" "$control" "$expires" "$owner"
rc=1
fi
done < "${1:?usage: check-exceptions.sh exceptions.csv}"
exit "$rc"
id,host,control,expires,owner
EX-101,billing01,legacy-tls,2027-04-30,jlee
EX-102,billing02,legacy-tls,2026-09-30,jlee
EX-103,hr07,smb1,2026-12-31,mpatel
$ TODAY=2026-11-05 ./check-exceptions.sh exceptions.csv
EXPIRED EX-102 host=billing02 control=legacy-tls expired=2026-09-30 owner=jlee
$ echo $?
1
Only EX-102 is reported because its date is before the pinned day; the other two have later dates. The comparison works because ISO dates (YYYY-MM-DD) sort the same alphabetically as chronologically. A row whose expiry equals the checked day is not yet reported (the test is "earlier than today"), and it is reported the following day.
Reading the checker, line by line:
| Line | What it does |
|---|---|
set -euo pipefail | Stop on any failed command (-e), treat an unset variable as an error (-u), and count a pipeline as failed if any stage fails (-o pipefail) |
today=${TODAY:-$(date +%F)} | Use the TODAY environment variable if set (that is how the run above is pinned); otherwise ask date for today in YYYY-MM-DD form |
rc=0 | Remember the exit code to return: 0 means no expired rows |
while IFS=, read -r id host control expires owner; do | Read the file one line at a time. Setting IFS=, makes a comma the field separator, so a line like EX-102,billing02,legacy-tls,2026-09-30,jlee is split into the five named variables; -r stops backslashes being interpreted |
[[ $id == id ]] && continue | The first line of the CSV is the header, where the first field is literally id; skip it |
[[ $expires < $today ]] | Inside [[ ]] the < compares the two strings alphabetically, which is correct for ISO dates |
printf 'EXPIRED ...', rc=1 | Print one line per expired row and remember that the run must fail |
done < "${1:?usage: ...}" | The < feeds the file named by the first argument into the loop. ${1:?message} stops the script with that usage message if no argument was given |
exit "$rc" | Exit 0 if nothing expired, 1 otherwise, so a scheduler or pipeline can open a ticket on failure |
Trade-offs and pitfalls
- Allow-list over "monitor only". Monitoring tells you after the fact; the allow-list means a compromised neighbour on the same network segment still cannot open a session to the weak listener.
- Do not lower host-wide settings to make the app work. That silently weakens every other service and is the usual way a "temporary" exception spreads.
- A compensating control is not a fix. It reduces the likelihood of exploitation; the exception record must say that residual risk remains and who accepted it.
- What would change the plan: if the vendor cannot commit to a date at all, treat it as a replacement project, not an exception; if clients are too many to list, the allow-list loses value and the risk acceptance must be escalated rather than quietly widened.
You have just deployed a Windows Server that will run IIS for an internal business application. What hardening steps do you apply to the host and the web role after installation, covering the host firewall, service accounts and application pool identities, patching, and a configuration baseline? How would you notice later that it has been misconfigured or compromised?
Sample Answer
Direct answer
Harden in this order: patch the server before it takes traffic, shrink what is installed, close the network path to the one port and the one source network that need it, give the application the least privilege it can run with, tighten what the web server accepts and sends, then apply and verify a configuration baseline (a documented list of required settings). Afterwards, detect trouble with three feeds: configuration drift checks, web and security logs forwarded off the host, and endpoint protection alerts. This web server stays a domain member server and is not a domain controller.
Step by step
| Step | Action | How you know it worked |
|---|---|---|
| 1. Patch | Bring the OS, the .NET runtime and the IIS (Internet Information Services, the Windows web server) components fully up to date through the organization's patch server before opening the firewall to users | Windows Update Agent scan shows no applicable critical or security updates |
| 2. Remove unused role services | List the installed Web Server role services, uninstall the ones the application does not use (for example WebDAV publishing or FTP if present), and use -Remove to delete the payload so nobody re-enables them casually | Get-WindowsFeature listing matches the approved list |
| 3. Host firewall | Firewall on in all three profiles, default inbound action Block, allow only HTTPS from the application's client network and management from the admin network, log blocked traffic | Get-NetFirewallProfile -PolicyStore ActiveStore and the rule's address filter |
| 4. TLS | Disable legacy Transport Layer Security (TLS) protocol versions in Schannel (the Windows TLS provider) and control cipher suites through the cipher suite order, not by editing registry keys by hand | Registry value read-back, then an external TLS scan |
| 5. Identities | One application pool per application, running as the default ApplicationPoolIdentity; content read-only for that identity | The w3wp.exe process owner (Task Manager, or the Common Information Model (CIM) query below) is the pool's own identity, and the access control list (ACL) shows only intended grants |
| 6. Request filtering | Limit verbs, URL length, file extensions and suppress the server header | Request filtering settings in the site's web.config |
| 7. Logging | Keep IIS logs, enable process-creation auditing and forward everything to a collector | Test events arrive at the collector |
| 8. Baseline | Apply the organization's baseline (for example a Center for Internet Security (CIS) Benchmark profile for this Windows Server version, or the vendor's security baseline) through Group Policy and keep IIS configuration as files under source control | The commands in the verification table below, run on a schedule |
Commands
# 1. Review installed Web Server role services, then remove what the application does not need
Get-WindowsFeature | Where-Object { $_.Installed -and $_.Name -like 'Web-*' } |
Select-Object Name, DisplayName
Uninstall-WindowsFeature -Name $unneeded -WhatIf # $unneeded = names chosen from the list above
Uninstall-WindowsFeature -Name $unneeded -Remove # -Remove also deletes the feature files
# 2. Host firewall: on for every profile, inbound default Block, HTTPS only from the application subnet
Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled True -DefaultInboundAction Block `
-LogBlocked True -LogFileName '%SystemRoot%\System32\LogFiles\Firewall\pfirewall.log'
New-NetFirewallRule -DisplayName 'IIS HTTPS from app subnet' -Direction Inbound -Action Allow `
-Protocol TCP -LocalPort 443 -RemoteAddress 10.20.0.0/24 -Profile Domain
# 3. TLS 1.0 off for the server role (a service or application restart may be needed)
$p = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server'
New-Item -Path $p -Force | Out-Null
New-ItemProperty -Path $p -Name Enabled -Value 0 -PropertyType DWord -Force | Out-Null
# 4. One application pool per application, default identity, read-only content
& "$env:windir\system32\inetsrv\appcmd.exe" set AppPool HrApp -processModel.identityType:ApplicationPoolIdentity
icacls D:\sites\hr\content /grant "IIS AppPool\HrApp:(OI)(CI)RX"
# 5. Verification
Get-NetFirewallProfile -PolicyStore ActiveStore | Select-Object Name, Enabled, DefaultInboundAction
Get-NetFirewallRule -DisplayName 'IIS HTTPS from app subnet' | Get-NetFirewallAddressFilter
Get-CimInstance Win32_Process -Filter "Name = 'w3wp.exe'" |
ForEach-Object { $o = Invoke-CimMethod -InputObject $_ -MethodName GetOwner; "$($o.Domain)\$($o.User)" }
Reading the less obvious pieces: w3wp.exe is the IIS worker process, the program that runs one pool's application code. In icacls ... /grant "IIS AppPool\HrApp:(OI)(CI)RX", IIS AppPool\HrApp is the pool's virtual account (an automatically managed identity with no password that does not appear in the user list), (OI) object inherit means files inside get the entry, (CI) container inherit means subfolders get it, and RX is read and execute. A security identifier (SID) is the unique ID Windows stores in an ACL in place of the name. In the TLS snippet, New-Item -Force creates the registry key for TLS 1.0 on the server side if it is missing, and New-ItemProperty ... -Name Enabled -Value 0 -PropertyType DWord writes the 32-bit number 0, which tells Schannel that this protocol version is off.
Notes on the commands:
- Firewall. The profile defaults on a computer are enabled and inbound Block, so the explicit settings document the intent and protect against a changed profile. Only the rule you add admits traffic, and its
-RemoteAddressaccepts a subnet in CIDR form. The subnet10.20.0.0/24is a placeholder for the application's client network. The firewall sits on the server itself, so it applies whatever network device is in front of it; a rule for the admin network (remote management) is added the same way with its own port and source. - Role services.
Uninstall-WindowsFeaturedoes not accept wildcards in-Name, so the names come from the review listing. Run with-WhatIffirst. Removing the payload with-Removemeans a later reinstall needs an installation source. - TLS. Schannel protocol settings live under
...\SCHANNEL\Protocols\<protocol>\Serverand the DWORDEnabledset to0disables that version. Microsoft documents that disabling versions can break interoperability, and that services may need a restart to pick the change up, so first inventory the clients of this internal application. Control cipher suites with the cipher suite order (Group Policy or the TLS PowerShell commands), not registry edits. - Identities. Since IIS 7.5 a new pool defaults to
ApplicationPoolIdentity, a virtual account namedIIS AppPool\<pool name>with its own security identifier, so permissions can be granted to one application only. Do not useLocalSystem(extensive privileges) orNetworkService(shared with other services, so a compromise of one can tamper with the others). If the application must reach a database or file share, the pool identity authenticates on the network as the computer account (DOMAIN\SERVER$), so grant that account the access on the remote side. Example: the pool onWEB01reads\\FS01\hr-reports.FS01has never heard of the localIIS AppPool\HrApp; it sees a request from the domain account of the machine,CORP\WEB01$(the trailing$marks a machine account), so the share and NTFS permissions onFS01must grantCORP\WEB01$, on that folder only. Every pool onWEB01shares that network identity, which is why one application that needs its own network identity gets a managed service account (a domain account whose password Active Directory rotates automatically). The managed service account is configured as the pool's custom identity. Grant the pool read and execute on the content folder only, and write only to the specific folders the application must write to (uploads, temporary files), with no execute permission there.
Request filtering and the server header
Request filtering is built in and rejects bad requests before application code runs. A web.config fragment (from the IIS documentation pattern) that denies directory traversal and alternate data streams, denies unlisted file extensions and verbs, and limits URL and query string lengths:
<configuration>
<system.webServer>
<security>
<requestFiltering removeServerHeader="true">
<denyUrlSequences>
<add sequence=".." />
<add sequence=":" />
</denyUrlSequences>
<fileExtensions allowUnlisted="false" />
<requestLimits maxUrl="2048" maxQueryString="1024" />
<verbs allowUnlisted="false" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
Line by line: removeServerHeader="true" stops IIS announcing itself in the Server response header. denyUrlSequences rejects any URL containing .. (walking up out of the web root) or : (which can address an alternate data stream, extra hidden content attached to an NTFS file name). fileExtensions allowUnlisted="false" and verbs allowUnlisted="false" mean only the extensions and HTTP verbs you list are accepted. maxUrl="2048" and maxQueryString="1024" reject URLs longer than 2048 characters and query strings longer than 1024.
Because allowUnlisted="false" rejects everything not listed, add fileExtensions and verbs entries for what the application uses (for example .aspx and GET, POST, or PUT and DELETE for a REST API) or the application breaks. removeServerHeader requires IIS 10 on Windows Server version 1709 or later. Hiding the header removes a convenience for scanners but is not a security boundary.
Patching after day one
Patching has three parts: the OS and IIS through the patch server on a ring schedule (test server first, then production), the .NET runtime and IIS modules through the same channel, and the application's own libraries through its release pipeline. Check each cycle with an automated scan (a Windows Update Agent search such as (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher().Search("IsInstalled=0 and Type='Software'").Updates.Count, where 0 is the passing result) and keep an emergency path for out-of-band fixes.
How you notice a misconfiguration or compromise later
- Configuration drift. A scheduled check compares live settings with the baseline and reports to a central location (the verification table below lists the checks). Add file integrity monitoring (a tool that records a hash of each watched file and alerts when the hash changes) on
applicationHost.config, eachweb.configand the web root, so a new.aspxfile in an upload folder or a changed configuration raises an alert. - Web logs forwarded off the host. Request filtering returns HTTP 404 with a specific substatus when it blocks something:
404.5URL sequence denied,404.6verb denied,404.7file extension denied,404.11double-escaped URL,404.14URL too long. A burst of these from one source is scanning or an attack attempt, and a sudden stop of logs is also a signal. - Security log. Turn on Audit Process Creation (Advanced Audit Policy, Detailed Tracking) and the policy "Include command line in process creation events". Event 4688 then records the command line of every new process. The command line can contain secrets and is readable by anyone who can read the Security log, so restrict that access. A shell or scripting host started on an internal web server at the time of web requests is worth an alert. Also alert on a new service, a new scheduled task, or a new member of the local Administrators group.
- Endpoint protection. The endpoint protection or EDR (endpoint detection and response) agent reports malware detections and, where it records them, parent and child process chains.
- Forwarding. Send IIS logs and the Security log to a central collector as events happen (Windows Event Forwarding or an agent), so an attacker on the host cannot erase the evidence after the fact.
- Outside-in checks. A weekly external TLS and configuration scan confirms what clients really see.
Verification table
Every row in the baseline has a command that proves it:
| Setting | Required value | Verify with |
|---|---|---|
| Firewall profiles | Enabled, default inbound Block | Get-NetFirewallProfile -PolicyStore ActiveStore | Select-Object Name, Enabled, DefaultInboundAction |
| HTTPS inbound rule | Port 443, remote address is the app subnet only | Get-NetFirewallRule -DisplayName 'IIS HTTPS from app subnet' | Get-NetFirewallAddressFilter |
| Role services | Only the approved list installed | Get-WindowsFeature | Where-Object { $_.Installed -and $_.Name -like 'Web-*' } compared with the approved list |
| TLS 1.0 server | Enabled is 0 | Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server' -Name Enabled |
| Pool identity | Worker process runs as the pool's virtual account | the Get-CimInstance Win32_Process owner query above |
| Content permissions | Pool has read and execute only | icacls D:\sites\hr\content |
| Command-line auditing | Audit Process Creation and the command-line policy enabled | auditpol /get /category:"Detailed Tracking" and a test event in the Security log |
What a correct result looks like (described from the commands' documented properties, not run, because they need a Windows host):
Get-NetFirewallProfile -PolicyStore ActiveStore: three rows (Domain, Private, Public), each withEnabledTrue andDefaultInboundActionBlock. A False or an Allow in any row is wrong.Get-NetFirewallRule ... | Get-NetFirewallAddressFilter: the remote address lists only the application subnet.Anymeans the rule admits everyone.- The
Get-CimInstance Win32_Processowner query: prints the pool's own virtual account, withHrAppafter theIIS APPPOOLprefix.SYSTEMorNETWORK SERVICEmeans the pool is running under a broader identity. icacls D:\sites\hr\content: an entry forIIS AppPool\HrAppending in(RX), and no(F),(M)or(W)for it.auditpol /get /category:"Detailed Tracking": the Process Creation line shows Success (or Success and Failure).No Auditingis wrong.
Pitfalls
- Locking down request filtering with
allowUnlisted="false"without listing what the application needs causes a production outage that looks like an application bug. - Disabling TLS versions without checking the clients breaks an internal client that is still on an old stack.
- A firewall rule that allows HTTPS from "Any" source makes the hardening cosmetic; the source network is the control.
- Logs kept only on the web server are lost when that server is compromised.
- A baseline that is applied once and never rechecked drifts within months; the recurring check is part of the control.
Unlock Full Question Bank
Get access to all 21 System and Endpoint Hardening interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.