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 handed a freshly provisioned Linux server that will host a production web service. How do you bring it to a secure baseline before it takes traffic, and how do you make that work repeatable rather than a one-off?
Sample Answer
Direct answer
I treat the first hour of a server's life as the cheapest time to harden it: it carries no traffic, no one depends on it, and a mistake costs a rebuild rather than an outage. In order, I patch it, remove or disable everything the service does not need (accounts, packages, listening ports), lock down remote access (key-only SSH, scoped sudo, default-deny firewall), set safe kernel and file permission defaults, turn on logging that leaves the host, and then prove the result with commands and a scanner. To make it repeatable I never do any of that by hand on the real server: the steps live in an image build and in configuration management (a tool such as Ansible that describes the desired state and applies it idempotently, meaning a second run changes nothing), and a scheduled run reports drift (a host that no longer matches the desired state).
The point of every step is to shrink the attack surface: the set of things an attacker can reach or abuse. An assessor looking at the host should see few open ports, few accounts that can log in, and no weak defaults left to find.
The eight steps, why each matters, and how I check it
| # | Step | Why it matters | How I check it |
|---|---|---|---|
| 1 | Apply pending security updates, then reboot if a kernel or libc (the C standard library nearly every program uses) changed | A fresh image is usually weeks old; known flaws are the easiest way in | On Ubuntu, apt list --upgradable should list nothing security-related afterwards |
| 2 | Accounts and sudo: remove unused accounts, give every person their own login, grant sudo to named commands rather than blanket root | Shared or unused accounts destroy accountability and widen the attack surface; narrow sudo limits what a stolen account can do | sudo -l -U <user> shows exactly what each person may run |
| 3 | SSH: keys only, no root login, no password or keyboard-interactive login | Password guessing against an internet-facing port is constant background noise | sshd -T prints the effective settings the daemon will use |
| 4 | Network exposure: stop services that are not part of the web service, then default-deny inbound with the firewall allowing only 443 and an admin source range | A port nobody listens on cannot be attacked | ss -tln before and after: only expected sockets remain |
| 5 | Kernel network parameters via a sysctl drop-in (sysctl reads and sets kernel settings; a drop-in is a small file in /etc/sysctl.d/ that is loaded at boot) | Stops the host honouring redirects (messages telling it to send traffic through a different router, which an attacker on the network can forge to divert traffic) and source-routed packets (packets that dictate their own path, which can steer around filtering), and logs impossible source addresses (a packet arriving from outside that claims a source such as 127.0.0.1 is almost certainly spoofed; the kernel calls these martians and the setting is log_martians) | Read each value back with sysctl -n <name> |
| 6 | File permissions: least-privilege owners and modes on the app tree, no world-writable files, review of setuid files (programs that run with their owner's rights) | A writable file in the wrong place turns a small bug into code execution | find listings (below) return nothing unexpected |
| 7 | Logging and audit: ship auth and system logs to a central collector, add audit rules for changes to /etc/ssh, /etc/sudoers.d and the account files | Logs kept only on the compromised host can be erased by the attacker | Generate a test event with logger and find it on the collector; make a test edit and find the audit record |
| 8 | File integrity: record a baseline of hashes for system binaries and /etc with a tool such as AIDE, check on a schedule | Detects a changed binary or config that no patch or ticket explains | A scheduled run that alerts on changes outside patch windows |
Repeatable: the same decisions as code
sshd reads the files in /etc/ssh/sshd_config.d/ in alphabetical order and, for each setting, the first value it finds wins. That is why the file is named 00-hardening.conf: it sorts before vendor or cloud-image drop-ins such as 50-cloud-init.conf, so its values cannot be overridden by them. The play's become: false means it does not escalate to root with sudo, because in the test container it already runs as root; on real hosts the play would use become: true.
This playbook was executed with ansible-core 2.16.3 inside an ubuntu:24.04 container (root, ansible-playbook baseline.yml). It writes the SSH drop-in, a validated sudoers rule and the sysctl drop-in, then fails the run if the effective SSH configuration is not what was intended.
- hosts: localhost
connection: local
become: false
tasks:
- name: sshd hardening drop-in (read first because of the 00 prefix)
ansible.builtin.copy:
dest: /etc/ssh/sshd_config.d/00-hardening.conf
mode: "0644"
content: |
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
- name: sudoers rule for the deploy user, syntax-checked before install
ansible.builtin.copy:
dest: /etc/sudoers.d/deploy-webapp
mode: "0440"
validate: /usr/sbin/visudo -cf %s
content: |
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart webapp
- name: kernel network hardening drop-in
ansible.builtin.copy:
dest: /etc/sysctl.d/90-hardening.conf
mode: "0644"
content: |
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.log_martians = 1
- name: refuse to continue if the effective sshd config is not what we intend
ansible.builtin.command: /usr/sbin/sshd -T
register: eff
changed_when: false
failed_when: "'passwordauthentication no' not in eff.stdout"
Run output (first run, then second run on the same host):
TASK [sshd hardening drop-in (read first because of the 00 prefix)] ************
changed: [localhost]
TASK [sudoers rule for the deploy user, syntax-checked before install] *********
changed: [localhost]
TASK [kernel network hardening drop-in] ****************************************
changed: [localhost]
TASK [refuse to continue if the effective sshd config is not what we intend] ***
ok: [localhost]
localhost : ok=5 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
--- second run
localhost : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
The check task runs sshd -T, which refuses to start with "Missing privilege separation directory: /run/sshd" on a host where the SSH service has never run; on a real server ssh.service creates that directory, and in the bare test container it was created first with mkdir -p /run/sshd. The recap line says ok=5 although the play lists four tasks: Ansible runs an automatic Gathering Facts step first (it collects details about the host), and that counts as the fifth. In the first run three tasks changed something and the fourth only read the result, which is why it shows ok and changed=3. changed=0 on the second run is the idempotence proof. The sysctl file only takes effect once the settings are loaded (sysctl --system reads every system directory, -p reads one file), which I did not run because a container does not let you change host kernel settings. The kernel's own documentation (ip-sysctl) gives tcp_syncookies a default of 1 and rp_filter a default of 0; on the test kernel the defaults read back as rp_filter = 0, tcp_syncookies = 1, accept_redirects = 0, send_redirects = 1 and accept_source_route = 0, which is why the drop-in sets send_redirects explicitly rather than trusting the default.
Reverse-path filtering (rp_filter, which drops packets whose source address would not be routed back out the same interface) is deliberately not in the drop-in. Strict mode is correct for a single-homed web server but breaks hosts with asymmetric routing, and the kernel uses the larger of the all and per-interface values (the kernel documentation: "The max value from conf/{all,interface}/rp_filter is used"; the values are 0 off, 1 strict, 2 loose), so setting all to strict cannot be undone for one interface, and I decide it per host class. Asymmetric routing means replies leave by a different network interface than the one the request arrived on. Illustrative case: a server has a public interface and a management interface, and a request from a monitoring system arrives on the management interface while the server's default route sends replies via the public one. Strict mode checks "would I send a reply to this source out of the interface it came in on?", answers no, and silently drops the request.
File permissions on the application tree, as run in the same kind of container (users webapp and deploy created first):
$ chmod 750 /srv/app; chmod 2770 /srv/app/shared
$ setfacl -m u:deploy:rx /srv/app
$ getfacl -p /srv/app
# file: /srv/app
# owner: webapp
# group: webapp
user::rwx
user:deploy:r-x
group::r-x
mask::r-x
other::---
$ stat -c '%A %U:%G %n' /srv/app /srv/app/shared
drwxr-x--- webapp:webapp /srv/app
drwxrws--- webapp:webapp /srv/app/shared
$ touch /srv/app/oops; chmod 666 /srv/app/oops
$ find /srv -xdev -type f -perm -0002 -print
/srv/app/oops
The s in drwxrws--- is the setgid bit on a directory, so files created inside inherit the directory's group. The ACL (access control list, a per-user permission beyond owner, group and other) lets deploy read the tree without joining the webapp group, and other has no access at all. The find line is the audit: any file under the application tree that anyone can write is a finding. find /usr/bin -xdev -type f -perm -4000 lists setuid files; on the test image it printed chfn, chsh, gpasswd, mount and newgrp among others, and the review question is whether each is expected for this server's role.
Steps 4, 7 and 8 as commands
These three steps are not part of the playbook above; each was run in an ubuntu:24.04 container. The firewall needs --cap-add NET_ADMIN to run there.
Step 4, default-deny inbound with ufw (Ubuntu's firewall front end), allowing SSH only from an illustrative admin range (203.0.113.0/24 is a documentation address block) and 443 from anywhere:
ufw default deny incoming
ufw default allow outgoing
ufw allow from 203.0.113.0/24 to any port 22 proto tcp
ufw allow 443/tcp
ufw enable
ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp ALLOW IN 203.0.113.0/24
443/tcp ALLOW IN Anywhere
443/tcp (v6) ALLOW IN Anywhere (v6)
Run over an SSH session, ufw enable first asks "Command may disrupt existing ssh connections. Proceed with operation (y|n)?"; the rule for port 22 above is added before enabling so that your own session survives the prompt. Read the table as: anything inbound that has no row is dropped; port 22 answers only the admin range; 443 answers everyone, on IPv4 and IPv6.
Step 7, audit rules. Create /etc/audit/rules.d/50-hardening.rules (the augenrules tool merges every file in that directory into /etc/audit/audit.rules, which auditd, the Linux audit daemon, loads):
-a always,exit -F arch=b64 -F dir=/etc/ssh -F perm=wa -F key=ssh_config
-a always,exit -F arch=b64 -F dir=/etc/sudoers.d -F perm=wa -F key=sudoers
-a always,exit -F arch=b64 -F path=/etc/passwd -F perm=wa -F key=accounts
-a always,exit -F arch=b64 -F path=/etc/shadow -F perm=wa -F key=accounts
Each line says: always log, on exit from a system call, when a file in this directory (dir=) or this exact file (path=) is written to or has its attributes changed (perm=wa: w is write, a is attribute change; r and x exist too), and tag the record with a key so ausearch -k ssh_config finds it later. Running augenrules in the container merged the file into /etc/audit/audit.rules; loading rules into a kernel was not possible there, so the test edit that produces an audit record needs a real host. Shipping logs off the host (the other half of step 7) is done with your log forwarder, such as rsyslog or a vendor agent; logger "test" then proves the path.
Step 8, file integrity with AIDE (Advanced Intrusion Detection Environment). Illustrative minimal setup, using a throwaway configuration file that watches one directory and records permissions, owner, group, size and SHA-256 hash:
# /tmp/aide.conf
database_in=file:/tmp/aide.db
database_out=file:/tmp/aide.db.new
database_new=file:/tmp/aide.db.new
report_url=stdout
Rules = p+u+g+s+sha256
/srv/demo Rules
aide -c /tmp/aide.conf --init builds the baseline database as aide.db.new; copy it to aide.db (the file named by database_in) to make it the baseline, then aide -c /tmp/aide.conf --check compares the disk with it and a clean run exits 0. After echo "more text" >> /srv/demo/app.conf (the file held hello plus a newline, 6 bytes), the check printed the following, abridged: the real report also has dashed section headings, shows the new SHA-256 value beside the old one, and ends with a block of database checksums.
AIDE found differences between database and filesystem!!
Summary:
Total number of entries: 2
Added entries: 0
Removed entries: 0
Changed entries: 1
Changed entries:
f > ... H : /srv/demo/app.conf
Detailed information about changes:
File: /srv/demo/app.conf
Size : 6 | 16
The summary counts entries added, removed and changed; the detail block shows the stored value on the left of | and the current value on the right (the file grew from 6 to 16 bytes, and its SHA-256 differs as well). The exit status is a sum: 1 if files were added, 2 if removed, 4 if changed, so this run exited 4 and a clean run exits 0, which makes it easy to alert on from a schedule.
Worked example: attack surface before and after
Before step 4 a default image running only SSH listens on one port. On the test container, with sshd started on port 2222, ss -tln printed:
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 128 0.0.0.0:2222 0.0.0.0:*
LISTEN 0 128 [::]:2222 [::]:*
On a real web host the target list is explicit: SSH (restricted by the firewall to the bastion or admin range) and 443. Anything else that appears in ss -tln after provisioning (a database listening on all interfaces, a metrics agent, a leftover test service) is either bound to localhost, firewalled, or removed. That before and after listing is also what I hand a security assessor.
Trade-offs and pitfalls
- Developer workflow. Developers lose "just sudo to root and fix it". The fix is to give them what they actually do as named sudo rules (restart the service, read its logs), to deploy through the pipeline instead of by hand, and to give them a read-only way to see logs. Pushing back on blanket root is easier when the three commands they need work on day one.
- Emergency access. Key-only SSH plus a firewall can lock out the people who must fix an incident. Keep an out-of-band path (cloud serial console or the server's management controller) and a documented break-glass credential that is sealed, audited and rotated after use. Test it before you need it.
- Hardening that breaks the app. Apply the baseline to a staging host built from the same image, run the application's smoke tests, and only then promote the image. A baseline that is only ever tested on production eventually causes an outage.
- One-off hand edits. A hardened server that someone then tweaks by hand drifts. Either rebuild instead of editing, or have configuration management revert and report the change.
- File integrity is noisy until it is told about patch windows: baseline after patching, and alert on changes outside them.
You have 300 pending patches this month and capacity for a fraction of them across a mixed Windows and Linux estate. How do you decide what goes first?
Sample Answer
Direct answer
I do not rank 300 patches by CVSS score (the Common Vulnerability Scoring System, a 0 to 10 measure of how severe a flaw is in the abstract). I rank them by how likely they are to hurt us this month: first evidence the flaw is being exploited, then whether the vulnerable thing is reachable by an attacker, then how much the host matters, then what already protects it, and last the cost and risk of the patch itself. That gives four tiers. The top tiers fill the capacity; everything else is deferred on purpose, with an owner and a date, and the ranking is re-run weekly because exploitation news changes it.
Signals
| Signal | What it tells you | Source |
|---|---|---|
| Known exploited | Attackers are using this flaw now | CISA's Known Exploited Vulnerabilities (KEV) catalog, which CISA says organisations should use as an input to vulnerability prioritisation; vendor advisories stating active exploitation |
| Likelihood of exploitation | Statistical estimate of exploitation soon | EPSS (Exploit Prediction Scoring System, from FIRST), a 0 to 1 probability that a published CVE will be exploited in the wild in the next 30 days |
| Severity | How bad it is if it works | CVSS base score; useful for tie-breaks, poor as the primary sort because it ignores whether anyone is exploiting it |
| Exposure | Can an attacker reach it? | Internet-facing, reachable from partner networks, internal only, isolated. "Reachable" means an attacker's traffic can actually get to the vulnerable service |
| Asset value | What the host holds or controls | Domain controllers, identity systems, database servers, jump hosts rank above test boxes |
| Compensating controls | Does something already block exploitation? | WAF (web application firewall) rule, network segmentation (splitting the network into zones with firewalls between them, so a host in one zone cannot be reached from the others), feature disabled, EDR (endpoint detection and response) with blocking enabled for that technique. A compensating control is any such measure that blocks the same attack when you cannot patch yet; detection-only coverage shortens response but blocks nothing, so it does not count |
| Patch cost and risk | Effort, downtime, chance of regression | Reboot needed, vendor warns of known issues, cluster failover required |
A CVE (Common Vulnerabilities and Exposures) identifier is just the public name of one flaw; one patch commonly fixes many CVEs, so I rank patches by the worst CVE they contain.
Tier rules
| Tier | Rule | Target |
|---|---|---|
| P0 | Known exploited AND the vulnerable component is present on an internet-facing host or a critical host | Out-of-band, within days, ahead of the normal ring schedule |
| P1 | Known exploited on internal hosts, OR high EPSS or critical CVSS on an internet-facing or critical host | This monthly cycle, first rings |
| P2 | High or critical CVSS on internal, non-critical hosts (a compensating control puts the patch at the back of the tier), or moderate flaws on exposed hosts | Next cycle unless EPSS or KEV changes |
| P3 | Low severity, no exploitation evidence, isolated or low-value hosts | Routine bundle, quarterly |
The numeric cut-off for "high EPSS" is a team decision that should be written down and revisited; one defensible way is to set it from how many patches you can absorb in a cycle rather than from a magic number.
Worked example with the numbers shown
Month backlog: 300 patches across Windows and Linux. Triage with the rules above gives:
| Tier | Patches |
|---|---|
| P0 | 12 |
| P1 | 41 |
| P2 | 97 |
| P3 | 150 |
| Total | 300 |
Capacity this month, from the team's test and reboot-window budget: 60 patches. Illustrative derivation: the test lab can validate 15 patches a week, and the month has 4 weeks, so 15 x 4 = 60 patches can be tested. There are 4 reboot windows a month and each can absorb 25 patches, so 4 x 25 = 100 can be rebooted. Capacity is the smaller of the two limits, which is 60, set by testing. P0 and P1 together are 12 + 41 = 53, which fills 53 of the 60 slots. The remaining 7 go to the top of P2, chosen by asset value (domain controllers and identity servers first). Deferred: 97 - 7 = 90 P2 patches plus 150 P3 patches = 240, and 60 + 240 = 300. Each deferred patch has a recorded reason, an owner and a review date, and the 240 are re-scored every week. If a P2 CVE lands on the KEV list on the 12th, it is re-tiered that day instead of waiting for the next cycle: P0 if it sits on an internet-facing or critical host, otherwise P1 under the rules above (known exploited on internal hosts).
Two illustrative patches show how the signals combine. Patch A fixes a remote code execution flaw in a web server component. It is on the KEV list (exploited now) and the component is installed on an internet-facing host, so it meets both halves of the P0 rule (known exploited, and present on an internet-facing host), and CVSS and EPSS are not needed to decide. Patch B fixes a privilege escalation flaw in a desktop library. It has a CVSS score of 8.8 (high), is not on the KEV list, has a low EPSS probability (say 0.02, a 2 percent chance of exploitation in the next 30 days), and is installed only on internal, non-critical hosts, behind a segment boundary with no route from the internet. No P0 or P1 rule matches, because it is not known exploited and it is not on an internet-facing or critical host. The P2 rule does (high CVSS on internal, non-critical hosts), so it is P2, and the segmentation (a compensating control) places it behind other P2 patches for the leftover slots, which are chosen by asset value; otherwise it waits for the next cycle.
Notice that capacity is the number of patches the team can safely test and reboot, not the number the tools can install. Grouping patches that need the same reboot, for example a kernel and its libraries together on Linux or the monthly cumulative update on Windows, raises effective capacity without raising risk.
Mixed Windows and Linux
Do not keep two ranked lists. Put both into one backlog with the same tier rules, then split by operating system only at scheduling time because the mechanics differ: Windows patches arrive in a monthly cumulative bundle, so you choose rings and timing, whereas Linux fixes arrive per package and can be selected individually, so you can pull a single critical package forward. Third-party applications on either platform go into the same ranking.
Pitfalls
- Sorting by CVSS alone sends the team after unexploited "critical" flaws while an exploited "medium" stays open.
- Ranking by CVE count per patch rewards bundles, not risk.
- Treating deferred items as accepted: deferral without an owner and date is how a backlog becomes permanent.
- Trusting scanner severity for a flaw in a component that is installed but never loaded; check reachability before spending an emergency slot.
- Using EPSS as an on/off switch. It is a probability, so a low score reduces priority but does not make a KEV-listed flaw safe.
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.
Why does patching fall apart without an accurate asset inventory, and how do you build and keep one that covers servers, VMs and software dependencies?
Sample Answer
Direct answer
You can only patch what you know exists, and you can only prioritise what you know the version of. Without an accurate inventory the patching programme reports a healthy percentage over the hosts it can see, while the hosts it cannot see (forgotten virtual machines (VMs), test boxes that became production, a container image with an old library inside) stay vulnerable and nobody is accountable for them. A good inventory is built from several independent sources, reconciled against each other every day, and covers three layers: hosts (physical or virtual machines), the software installed on them, and the dependencies packaged inside applications.
Why patching falls apart without it
- Blind spots are invisible in the metric. "98% patched" is computed over hosts that report. A host that never reported is not in the denominator. In a patch console this shows up as devices whose compliance state is Unknown. For example, Microsoft Configuration Manager (the on-premises tool many Windows estates use to deploy updates) reports each update on each machine as Required (needed, not yet installed), Not Required (does not apply), Installed or Unknown. Unknown means the site server (the central Configuration Manager server that stores the results) has received no state message, the small status report a machine's client sends after it scans, so it cannot say anything about that machine. Treat Unknown as a defect to chase, not a footnote.
- You cannot answer "are we exposed?" quickly. When a critical flaw in a library is announced, the first question is "which hosts run version X?". With no software inventory that answer takes days of manual checking.
- Operating-system patching does not touch everything. A Python virtual environment, a vendored library, or a container image carries its own copy of a dependency (a library the software relies on). The OS package manager never updates it.
- Ownership is unknown. A vulnerable host with no named owner never gets a window agreed.
How to build and keep it accurate
Three layers, each with a source that is not the thing being inventoried:
| Layer | Authoritative sources | What you record |
|---|---|---|
| Hosts and VMs | Platform export: the listing from the hypervisor (the software that runs virtual machines on a physical server) or the cloud provider's API, directory and DHCP/DNS records, a periodic network discovery scan | Name, address, OS and version, environment, owner, last time seen |
| Installed software | An agent or scheduled job on the host that lists packages (dpkg-query on Debian-family, rpm -qa on Red Hat-family, the Windows installed-update and software lists) | Package, version, collection time |
| Dependencies inside applications | Lock files and a software bill of materials (SBOM, a machine-readable list of components in a build) generated in the build pipeline | Component, version, which application and which build |
Why several sources: the platform export (the hypervisor or cloud listing) is complete but knows nothing about software; the agent (a small program installed on each host that reports what it finds) knows software but only for hosts that have the agent. Comparing the two finds the hosts without an agent, which is exactly the blind-spot set.
Collection script (bash, one tab-separated row per package or dependency, with host, OS, kind, name, version and a UTC timestamp):
#!/usr/bin/env bash
# Emit one TSV line per installed OS package and per Python dependency on this host.
set -euo pipefail
host=$(hostname -s)
collected=$(date -u +%FT%TZ)
os=$(. /etc/os-release && printf '%s %s' "$ID" "$VERSION_ID")
dpkg-query -W -f='${binary:Package}\t${Version}\n' |
awk -F'\t' -v h="$host" -v o="$os" -v t="$collected" \
'{print h "\t" o "\tos-package\t" $1 "\t" $2 "\t" t}'
if command -v pip3 >/dev/null; then
pip3 list --format=freeze 2>/dev/null |
awk -F'==' -v h="$host" -v o="$os" -v t="$collected" \
'NF==2 {print h "\t" o "\tpython-dep\t" $1 "\t" $2 "\t" t}'
fi
Reading the script: dpkg-query -W -f='...' lists every installed package using the format string (${binary:Package} is the name, ${Version} the version, \t a tab). The output is piped (|) into awk, a line-by-line text tool. -F'\t' tells awk the input fields are separated by tabs, -v h="$host" hands the shell variable host to awk as h, and {print h "\t" o ...} prints each line again with the host, OS, kind, name, version and timestamp joined by tabs. The Python half works the same way, except pip3 list --format=freeze prints name==version, so -F'==' splits on the double equals, and NF==2 keeps only lines that really have two fields.
I ran this in an Ubuntu 24.04 container after installing python3-pip (a stock image has no pip3, so the Python branch is skipped and the script prints only the operating-system package rows, 92 in my run); with pip present it printed 235 rows, of which these are examples (columns: host, OS, kind, name, version, UTC collection time; the host column is the container's ID):
d3b8cd2a0685 ubuntu 24.04 os-package bash 5.2.21-2ubuntu4 2026-10-06T08:21:45Z
d3b8cd2a0685 ubuntu 24.04 os-package apt 2.8.3 2026-10-06T08:21:45Z
d3b8cd2a0685 ubuntu 24.04 python-dep pip 24.0 2026-10-06T08:21:45Z
Each row carries a collection timestamp so stale data is visible.
The daily reconciliation compares the platform export (the complete list of machines that exist, from the hypervisor or cloud) with the list of hosts that reported inventory in the last 24 hours:
#!/usr/bin/env bash
platform=$1 reported=$2
echo "In platform export but never reported inventory (unpatched blind spots):"
comm -23 <(sort -u "$platform") <(sort -u "$reported") | sed 's/^/ /'
echo "Reported inventory but absent from platform export (shadow or stale records):"
comm -13 <(sort -u "$platform") <(sort -u "$reported") | sed 's/^/ /'
Reading it: comm compares two sorted files and prints three columns: lines only in the first file, lines only in the second, and lines in both. The numbers are the columns to suppress: -23 hides columns 2 and 3, leaving only the lines found in the platform export alone (hosts that exist but never reported); -13 hides columns 1 and 3, leaving only the lines found in the reported list alone (hosts that report but nobody registered). <(sort -u "$platform") is process substitution: bash runs the command and gives comm its sorted, de-duplicated output as if it were a file. sed 's/^/ /' puts two spaces at the start of every line for readability.
With a platform export of web01 web02 app01 db01 db02 batch07 and reports from web01 web02 app01 db01 legacy-ftp, it prints:
In platform export but never reported inventory (unpatched blind spots):
batch07
db02
Reported inventory but absent from platform export (shadow or stale records):
legacy-ftp
Two blind spots (batch07, db02) get an owner and a deadline to install the agent or be decommissioned; legacy-ftp is a host nobody registered, which is usually the more dangerous finding.
Keeping it accurate (the part that decays)
- Make registration automatic. New VMs are created from templates that install the agent and tag an owner; no tag, no network access in production.
- Freshness rule. A host with no check-in for 24 hours is flagged; seven days means investigate and either fix or retire it.
- Join inventory to the vulnerability data. The inventory is only useful when the scanner and the patch tool use the same host identity.
- Measure the inventory itself: the percentage of platform-listed hosts that reported in the last 24 hours, and the count of unowned hosts. Both should trend towards 100% and zero.
Trade-offs
An agent gives rich data but needs deployment and upkeep; an agentless scan (one run from the network, with nothing installed on the host) is quick to start but shallow. Start with the platform-export reconciliation (cheap, finds blind spots immediately), then add the agent, then add build-time SBOMs for the dependency layer, which is the hardest and most valuable last step.
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.
Unlock Full Question Bank
Get access to all 14 System and Endpoint Hardening interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.