🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Operating System Hardening for Linux and Windows

System SecurityđŸŸĸ Free Lesson

Operating System Security

Every application eventually rests on an operating system, and the OS is where abstract policy becomes concrete: a permission bit, a service that listens on a port, a kernel module nobody installed on purpose. Host hardening is the discipline of removing everything the machine does not need and proving that what remains behaves. It is unglamorous work with an excellent track record — a large share of successful intrusions follow an unpatched service, an over-privileged account or a forgotten debug interface rather than a zero-day exploit.

Start by deciding what the machine is for

Hardening cannot begin until the role is fixed. A public web server, a build runner, a domain controller and a developer laptop each need different controls, and a baseline written for one will either break or under-protect the others. Classify by exposure (internet-facing, internal, air-gapped), by data (what would leak if the host fell), and by role, then derive a baseline per class. Everything that is not required for the role gets disabled, uninstalled or firewalled — not "monitored just in case".

The measurement that matters is attack surface: how many services listen, how many accounts can log in, how many binaries can elevate, how quickly a critical patch lands. All four are scriptable, and all four should trend downward or meet a service level.

Hardening areaLinux checkWindows checkFailure it prevents
Listening servicesss -tulnGet-NetTCPConnection -State ListenForgotten admin panels exposed
Interactive accountsawk over /etc/passwdGet-LocalUserShared or dormant logins
Elevation rightsSUID files, sudoersGet-LocalGroupMember AdministratorsTrivial privilege escalation
Patch leveldnf check-updateGet-HotFixKnown-exploit compromise
Disk encryptionlsblk -o NAME,FSTYPEmanage-bde -statusData theft from lost hardware

Accounts and permissions on Linux

User accounts are the boundary that survives every other control failing. Keep interactive accounts individual and named — shared accounts destroy accountability the moment you need to know who deleted a table. Expire passwords on a schedule, require a minimum age so cycling cannot be gamed, and remove shell access from service accounts entirely.

# Create a service account with no login shell and an expiring password policy
sudo useradd --system --home-dir /opt/app --shell /usr/sbin/nologin appsvc
sudo chage -M 90 -m 7 -W 14 appsvc     # max 90 days, min 7 between changes, warn at 14

# Permission hygiene: find the holes that turn a low-priv foothold into root
find / -xdev -perm -4000 -type f 2>/dev/null          # SUID binaries
find / -xdev -perm -2000 -type f 2>/dev/null          # SGID binaries
find /etc /opt /srv -xdev -perm -0002 -type f 2>/dev/null   # world-writable files
find / -xdev -type d -perm -0002 2>/dev/null | grep -v -E '^/(proc|sys|tmp)'  # world-writable dirs

# Prove the fix: tighten a secret and check the result
sudo chmod 600 /opt/app/secrets.env
sudo chown root:appsvc /opt/app/secrets.env
stat -c '%a %U:%G %n' /opt/app/secrets.env

Numeric modes are worth memorizing because misreading them is the classic mistake: 755 gives the owner everything and everyone else read-and-execute, 644 gives everyone read, and 600 leaves the file readable only by its owner. When a secret is readable by others, every account on the box — including any service that gets compromised — can read it.

SSH: the most attacked service you run

SSH is the front door of nearly every server, and brute-force attempts against it start within minutes of an address becoming reachable. Configuration changes that pay for themselves: key-only authentication, no root password login, a restricted set of users and groups, a low MaxAuthTries, and rate limiting so credential stuffing becomes slow.

# /etc/ssh/sshd_config — apply, then validate before restarting
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers deploy ci-bot
MaxAuthTries 3
LoginGraceTime 20
X11Forwarding no
ClientAliveInterval 300
ClientAliveCountMax 2
# Always check before you reload, or you may lock yourself out
sshd -t && sudo systemctl reload sshd

# Add a second layer in front of it: connection rate limiting
sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication'   # confirm the live config
sudo nft add rule inet firewall input tcp dport 2222 ct state new limit rate 5/minute accept

Two operational notes. Never change a remote SSH config without a second session open, and confirm with sshd -t first — a typo in an AllowUsers line can terminate your connection on reload. Moving the port is cosmetic against a determined scanner, but it removes the automated noise from your logs.

Shrinking the running system

Every running service is code with bugs, an update cadence and a socket. The cheapest security win available is turning off what you do not use, and it is the step teams skip because disabling something feels riskier than leaving it — right up until the unused service is the one that gets exploited.

# See what is actually listening and who owns it
sudo ss -tulnp
sudo systemctl list-units --type=service --state=running

# Disable and remove attack surface you do not need
sudo systemctl disable --now cups bluetooth avahi-daemon
sudo systemctl mask debug-shell.socket              # emergency root shell must stay off

# Kernel and network sysctls: ignore redirects, enable sanity checks
cat <<'EOF' | sudo tee /etc/sysctl.d/99-hardening.conf
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.tcp_syncookies = 1
fs.suid_dumpable = 0
kernel.kptr_restrict = 2
EOF
sudo sysctl --system

On Windows the equivalent work is Group Policy and PowerShell: enforce a baseline through the Local Group Policy Editor or a domain GPO (account lockout thresholds, audit policy, drive encryption, firewall profiles), disable unused services such as Remote Registry and SMBv1, and confirm the result rather than assuming it.

# Enforce a firewall posture and verify it
Set-NetFirewallProfile -Profile Domain,Public,Private -DefaultInboundAction Block -DefaultOutboundAction Allow
New-NetFirewallRule -DisplayName "Allow HTTPS only" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow

# Close doors attackers use for local escalation and recon
Set-Service -Name RemoteRegistry -StartupType Disabled
Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart

# Confirm the actual state
Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction
Get-Service RemoteRegistry | Select-Object Name, Status, StartType
Get-LocalGroupMember -Group Administrators

Configuration management (Ansible, DSC, or your cloud's image pipeline) keeps these settings from drifting. A hardening script run once on a hand-built server is a snapshot; the same script in a pipeline is a control.

Boot integrity and full-disk encryption

Hardening that stops at the running kernel still trusts everything that loads before it. Secure Boot verifies that the bootloader and kernel are signed by trusted keys, which blocks rootkits that would otherwise intercept syscalls below your monitoring. Measured boot extends the idea by recording a chain of hashes that can be attested remotely, so a provisioning system can refuse to join a host whose boot state does not match the known-good measurement.

Full-disk encryption protects data when the physical device leaves your control — the lost laptop, the seized server drive, the retired disk in a recycling pile. LUKS on Linux and BitLocker on Windows both need deliberate key management: recovery keys escrowed where IT can reach them but attackers cannot, TPM binding so the disk unlocks only on that hardware, and a tested recovery procedure, because an unrecoverable encrypted volume is an outage you caused.

# LUKS setup and verification on Linux
sudo cryptsetup luksFormat --type luks2 /dev/nvme0n1p3
sudo cryptsetup open /dev/nvme0n1p3 cryptroot
sudo cryptsetup luksDump /dev/nvme0n1p3 | head -20
sudo blkid | grep crypt                    # confirm the mapping exists

# TPM-backed BitLocker with recovery key escrow (Windows, elevated PowerShell)
Manage-Bde -Protectors -Add C: -TPM
Backup-BitLockerKeyProtector -MountPoint C: -KeyProtectorId ((Get-BitLockerVolume C:).KeyProtector | Where-Object KeyProtectorType -eq 'Tpm').KeyProtectorId
Manage-Bde -Status C:

A control is only real when its state is measured. Feed encryption and Secure Boot status into the same compliance dashboard that tracks patch lag, so a machine that silently drifted out of baseline shows up within a day rather than at its next rebuild.

Patching without breaking production

Unpatched systems remain the most reliable way in, because the exploits are public, automated and often trivial. The operational problem is that patching competes with availability, so the fix is cadence plus process rather than heroics: a monthly maintenance window for non-critical updates, a defined emergency path that can ship a critical fix out of band, and asset inventory so you know what needs it.

Track mean time to patch as a metric, segmented by exposure. Internet-facing hosts deserve hours for critical vulnerabilities and a week at most for the rest; internal hosts get the monthly window. Where reboot is the obstacle, live patching or rolling restarts of a replicated service removes the objection. Test in a staging environment that mirrors production closely enough that a bad patch fails there, and keep a rollback plan that has actually been rehearsed.

Audit logging: knowing what happened

Logs are how a host testifies after the fact. Enable them before you need them — once an intrusion is suspected, retroactive logging tells you nothing. On Linux, auditd records changes to sensitive files and privilege use; on Windows, the Security event log records logon events, privilege use and policy changes when the right audit subcategories are enabled.

# Watch the files that indicate account or policy tampering
sudo auditctl -w /etc/passwd -p wa -k identity_change
sudo auditctl -w /etc/shadow -p wa -k identity_change
sudo auditctl -w /etc/sudoers -p wa -k sudoers_change
sudo auditctl -a always,exit -F arch=b64 -S execve -F euid=0 -k root_commands

# Query by key during an investigation
sudo ausearch -k identity_change --start today
sudo aureport --auth --summary | head

Ship logs off the host to a collector an attacker cannot wipe, keep clocks synchronized so timelines line up, and alert on the events that matter — failed logins in bursts, sudo by unexpected users, changes to identity files. A log that nobody reads is storage, not a control.

Common Mistakes

Hardening a server by hand and never codifying it

Fix: Put the baseline in configuration management so new builds inherit it and drift is detected automatically.

Running applications as root 'because permissions are confusing'

Fix: Create a dedicated unprivileged service account and grant it only the files and ports it needs.

Changing sshd_config over a single remote session

Fix: Validate with sshd -t, keep a second session open, and test key-based login before disconnecting.

Leaving default services and sample packages installed

Fix: Build minimal images; every package you do not use is code an attacker can exploit.

Collecting logs locally where the attacker can delete them

Fix: Forward to a central collector with restricted retention and alerting.

Best Practices

  • Define one hardening baseline per machine class and prove it with an automated compliance scan.
  • Measure listening ports, privileged accounts and patch lag weekly; treat regressions as incidents.
  • Use SSH keys from a managed CA or vault rather than copied key files with unknown provenance.
  • Apply sysctl and firewall hardening as versioned files reviewed in pull requests.
  • Rehearse reboots and rollbacks so patching is never blocked by fear of downtime.

Key Takeaways

  • Hardening starts with a declared machine role; everything not required for that role is removed, not monitored.
  • Permission bits and sudo rules decide how far a compromise travels — audit SUID binaries and world-writable files regularly.
  • SSH should be key-only, rate-limited and validated with sshd -t before any remote reload.
  • Running services define attack surface; disabling unused daemons and tightening sysctls is the cheapest control you own.
  • Patch speed is a measurable control: track mean time to patch separately for internet-facing and internal hosts.
  • Logs only become a control when they leave the host, keep good time, and trigger alerts someone acts on.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Cybersecurity Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement