Loading content...
Vulnerability management addresses known weaknesses. But what about the attack surface that exists simply because systems ship with insecure defaults—unnecessary services running, permissive configurations enabled, legacy protocols active?
Security Hardening is the practice of proactively configuring systems to minimize attack surface before vulnerabilities even appear. It transforms the question from "How do we fix what's broken?" to "How do we ensure there's less to break in the first place?"
Consider a fresh operating system installation:
Each unnecessary component is potential attack surface. Each permissive default is a misconfiguration waiting to be exploited. Hardening systematically addresses these before they become incidents.
By the end of this page, you will understand hardening philosophy and the principle of minimization, master CIS Benchmarks and DISA STIGs as hardening standards, implement practical hardening for Linux and Windows systems, develop automated hardening pipelines, and balance security restrictions with operational requirements.
Hardening is guided by the principle of minimization: every component, service, permission, and protocol that isn't explicitly required for the system's function should be removed or disabled.
Core Hardening Principles
1. Minimal Installation Install only packages and components required for the system's role. A web server doesn't need a C compiler. A database server doesn't need a GUI.
2. Disable Unnecessary Services Every running service increases attack surface. If a service isn't actively used, disable it. If it's needed occasionally, start it on-demand rather than at boot.
3. Restrict Permissions Apply the principle of least privilege to file permissions, process capabilities, and network access. Default to deny; explicitly permit only what's needed.
4. Secure Defaults Replace vendor defaults with secure configurations. Default passwords, example configurations, and debug settings must be changed.
5. Enable Logging and Auditing Comprehensive logging enables detection and forensics. Hardening includes ensuring sufficient logging for security-relevant events.
6. Remove or Protect Management Interfaces Administrative interfaces (SSH, RDP, web consoles) are high-value targets. Restrict network access, require strong authentication, and consider removing if not needed.
| Standard | Source | Coverage | Use Case |
|---|---|---|---|
| CIS Benchmarks | Center for Internet Security | OS, applications, cloud | Industry standard, audit-ready |
| DISA STIGs | Defense Information Systems Agency | DoD systems | US Government compliance |
| NIST SP 800-123 | National Institute of Standards | Server hardening | Federal guidance |
| Microsoft Security Baselines | Microsoft | Windows, Office, Edge | Windows environments |
| OpenSCAP | Red Hat/NIST | Automated compliance | Linux automation |
Linux hardening encompasses kernel parameters, service configuration, file permissions, and authentication settings. The following demonstrates key hardening areas.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
#!/bin/bash# Linux Security Hardening Script# Based on CIS Benchmark recommendations set -euo pipefailecho "=== Linux Security Hardening ===" # === Kernel Hardening (sysctl) ===cat > /etc/sysctl.d/99-hardening.conf << 'EOF'# Network hardeningnet.ipv4.conf.all.send_redirects = 0net.ipv4.conf.default.send_redirects = 0net.ipv4.conf.all.accept_source_route = 0net.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.all.log_martians = 1net.ipv4.icmp_echo_ignore_broadcasts = 1net.ipv4.tcp_syncookies = 1 # Kernel hardening kernel.randomize_va_space = 2kernel.kptr_restrict = 2kernel.dmesg_restrict = 1kernel.yama.ptrace_scope = 2kernel.core_uses_pid = 1kernel.sysrq = 0 # File system hardeningfs.suid_dumpable = 0fs.protected_hardlinks = 1fs.protected_symlinks = 1EOFsysctl -p /etc/sysctl.d/99-hardening.conf # === Disable Unnecessary Services ===SERVICES_TO_DISABLE="avahi-daemon bluetooth cups rpcbind nfs-serverautofs vsftpd telnet.socket rsh.socket rlogin.socket"for svc in $SERVICES_TO_DISABLE; do systemctl disable --now "$svc" 2>/dev/null || truedone # === SSH Hardening ===cat > /etc/ssh/sshd_config.d/hardening.conf << 'EOF'PermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesPermitEmptyPasswords noX11Forwarding noMaxAuthTries 3ClientAliveInterval 300ClientAliveCountMax 2AllowTcpForwarding noAllowAgentForwarding noProtocol 2Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.comMACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.comEOFsystemctl reload sshd # === File Permission Hardening ===chmod 600 /etc/shadow /etc/gshadowchmod 644 /etc/passwd /etc/groupchmod 700 /rootchmod 600 /etc/ssh/sshd_configfind /var/log -type f -exec chmod 640 {} ; # === Remove SUID/SGID where unnecessary ===chmod u-s /usr/bin/newgrp 2>/dev/null || truechmod u-s /usr/bin/chsh 2>/dev/null || truechmod u-s /usr/bin/chfn 2>/dev/null || true # === Password Policy ===cat >> /etc/security/pwquality.conf << 'EOF'minlen = 14dcredit = -1ucredit = -1ocredit = -1lcredit = -1maxrepeat = 3EOF # === Enable Audit Logging ===cat > /etc/audit/rules.d/hardening.rules << 'EOF'-w /etc/passwd -p wa -k identity-w /etc/shadow -p wa -k identity-w /etc/sudoers -p wa -k actions-a always,exit -F arch=b64 -S execve -F euid=0 -k privilegedEOFaugenrules --load echo "Hardening complete. Reboot recommended."Windows hardening leverages Group Policy, security baselines, and PowerShell for configuration. Microsoft provides Security Baselines that implement CIS and DISA recommendations.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
# Windows Security Hardening Script# Based on CIS Benchmarks and Microsoft Security Baselines Write-Host "=== Windows Security Hardening ===" -ForegroundColor Cyan # === Disable Unnecessary Services ===$servicesToDisable = @( 'RemoteRegistry', 'Fax', 'XboxGipSvc', 'XblAuthManager', 'XblGameSave', 'XboxNetApiSvc', 'WSearch')foreach ($svc in $servicesToDisable) { Set-Service -Name $svc -StartupType Disabled -ErrorAction SilentlyContinue Stop-Service -Name $svc -Force -ErrorAction SilentlyContinue} # === Disable SMBv1 ===Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart # === Enable Windows Defender Features ===Set-MpPreference -DisableRealtimeMonitoring $falseSet-MpPreference -PUAProtection EnabledSet-MpPreference -EnableControlledFolderAccess Enabled # === Configure Windows Firewall ===Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled TrueSet-NetFirewallProfile -Profile Public -DefaultInboundAction Block # === Disable Remote Desktop (if not needed) ===Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' ` - Name "fDenyTSConnections" -Value 1 # === Password Policy via Security Policy ===# Minimum length 14, history 24, complexity enabledsecedit /export /cfg C:\Windows\Temp\secpol.cfg (Get - Content C: \Windows\Temp\secpol.cfg) - replace` 'MinimumPasswordLength = \d+', 'MinimumPasswordLength = 14' | ` Set- Content C: \Windows\Temp\secpol.cfgsecedit / configure / db C: \Windows\Security\local.sdb / cfg C: \Windows\Temp\secpol.cfg # === Enable Audit Policies === auditpol / set / category: "Logon/Logoff" / success: enable / failure: enableauditpol / set / category: "Account Logon" / success: enable / failure: enableauditpol / set / category: "Privilege Use" / success: enable / failure: enableauditpol / set / category: "System" / success: enable / failure: enable # === Credential Guard(Windows 10 / 11 Enterprise) ===# Enable Virtualization Based Security$regPath = "HKLM:\SYSTEM\CurrentControlSet\Control\DeviceGuard"Set - ItemProperty - Path $regPath - Name "EnableVirtualizationBasedSecurity" - Value 1Set - ItemProperty - Path $regPath - Name "RequirePlatformSecurityFeatures" - Value 1 Write - Host "Hardening complete. Restart required." - ForegroundColor GreenManual hardening verification doesn't scale. Automated compliance tools continuously validate that systems remain hardened and drift hasn't occurred.
OpenSCAP is the industry-standard tool for automated SCAP (Security Content Automation Protocol) compliance checking on Linux.
1234567891011121314151617181920212223242526
#!/bin/bash# Automated Compliance Checking with OpenSCAP # Install OpenSCAPdnf install openscap- scanner scap - security - guide - y # List available profilesoscap info / usr / share / xml / scap / ssg / content / ssg - rhel8 - ds.xml # Run CIS Level 1 Server benchmark scanoscap xccdf eval \ --profile xccdf_org.ssgproject.content_profile_cis_server_l1 \ --results scan - results.xml \ --report scan - report.html \ /usr/share / xml / scap / ssg / content / ssg - rhel8 - ds.xml # Generate remediation script for failed checksoscap xccdf generate fix \ --profile xccdf_org.ssgproject.content_profile_cis_server_l1 \ --output remediate.sh \ scan - results.xml # Apply remediations(review first!)# chmod + x remediate.sh && ./ remediate.sh echo "Scan complete. Review scan-report.html"| Tool | Platform | Standards Supported | Deployment |
|---|---|---|---|
| OpenSCAP | Linux | CIS, DISA STIG, PCI-DSS | Open source, CLI |
| Microsoft SCT | Windows | CIS, Microsoft baselines | Free, GPO integration |
| Chef InSpec | Cross-platform | Custom, CIS profiles | Open source, CI/CD |
| Ansible Hardening | Cross-platform | CIS, custom | Open source, agentless |
Beyond OS hardening, individual applications require their own security configurations. Web servers, databases, and common services all have hardening requirements.
123456789101112131415161718192021222324
# Nginx Security Hardeningserver_tokens off; # TLS Configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers ECDHE - ECDSA - AES128 - GCM - SHA256: ECDHE - RSA - AES128 - GCM - SHA256;ssl_prefer_server_ciphers on;ssl_session_timeout 1d;ssl_session_cache shared: SSL: 50m;ssl_stapling on;ssl_stapling_verify on; # Security Headersadd_header X - Frame - Options "SAMEORIGIN" always;add_header X - Content - Type - Options "nosniff" always;add_header X - XSS - Protection "1; mode=block" always;add_header Content - Security - Policy "default-src 'self'" always;add_header Strict - Transport - Security "max-age=31536000" always; # Rate limitinglimit_req_zone $binary_remote_addr zone = api: 10m rate = 10r / s; # Disable unnecessary methods if ($request_method!~ ^ (GET | HEAD | POST)$ ) { return 405; } Modern infrastructure requires hardening beyond traditional OS configurations. Containers and cloud resources have their own attack surfaces.
12345678910111213141516171819202122232425262728293031
# Hardened Container Image ExampleFROM alpine: 3.19 AS base # Use specific, non - latest tags# Run as non - root userRUN addgroup - g 1000 appgroup && \ adduser - u 1000 - G appgroup - D appuser # Minimal package installationRUN apk add--no - cache ca - certificates && \ rm - rf /var/cache/apk/* # Copy only what's neededCOPY --chown=appuser:appgroup ./app /app # Read-only filesystem friendlyWORKDIR /appUSER appuser # No shell for production# Remove if not needed: RUN rm /bin/sh # Health checkHEALTHCHECK --interval=30s --timeout=3s \ CMD wget -q --spider http://localhost:8080/health || exit 1 # Explicit exposed portsEXPOSE 8080 # Non-root, minimal privilegesENTRYPOINT ["/app/server"]Security hardening introduces operational challenges that must be carefully managed.
| Challenge | Description | Mitigation |
|---|---|---|
| Application Breakage | Hardening may break applications expecting permissive configs | Test in staging; implement gradually; maintain exception process |
| Configuration Drift | Systems drift from hardened state over time | Automated compliance scanning; infrastructure as code |
| Operational Friction | Restrictions slow troubleshooting | Document exceptions; provide break-glass procedures |
| Legacy Systems | Old systems can't meet modern standards | Risk-accept with compensating controls; plan upgrades |
| Scale | Thousands of systems to harden | Automation, golden images, configuration management |
Security hardening proactively reduces attack surface before adversaries discover vulnerabilities. It transforms systems from permissive defaults to secure configurations that minimize risk. Let us consolidate the essential principles.
Module Complete
You have now completed the Security Best Practices module, covering:
Together, these practices form the operational foundation of secure systems.
You now understand security hardening: the philosophy of minimization, practical implementation for Linux and Windows, automated compliance verification, and application/container hardening. Combined with the previous pages on least privilege, defense in depth, patching, and vulnerability management, you have a comprehensive toolkit for building and maintaining secure operating system environments.