38. Security Hardening
Security hardening is the continuous practice of reducing a system’s vulnerability surface area by disabling unused features, enforcing strict authentication, isolating processes, and applying the Principle of Least Privilege.
38.1 Core Security Principles
Section titled “38.1 Core Security Principles”Principle of Least Privilege (PoLP)
Section titled “Principle of Least Privilege (PoLP)”Every user, process, script, and container must operate with only the minimum privileges required to perform its task, and nothing more:
- Never run production applications or web servers as
root. - Do not grant blanket
sudo ALL=(ALL:ALL) ALLwhen restricted commands will suffice. - Disable interactive login for system service accounts:
Terminal window sudo usermod -s /sbin/nologin nginx - Lock inactive or terminated employee accounts:
Terminal window sudo usermod -L username# Unlock with:sudo usermod -U username
38.2 SSH Server Hardening (/etc/ssh/sshd_config)
Section titled “38.2 SSH Server Hardening (/etc/ssh/sshd_config)”SSH is the primary gateway for remote administration and the top target for automated brute-force attacks.
Production Hardened Directives (/etc/ssh/sshd_config)
Section titled “Production Hardened Directives (/etc/ssh/sshd_config)”# Disable direct root login (force login as normal user, then sudo)PermitRootLogin no
# Disable password authentication; enforce cryptographic SSH key pairsPasswordAuthentication noPubkeyAuthentication yes
# Disable empty passwordsPermitEmptyPasswords no
# Limit authentication attempts per connection to prevent brute-forcingMaxAuthTries 3
# Disconnect idle sessions automatically (e.g., 5 minutes of inactivity)ClientAliveInterval 300ClientAliveCountMax 0
# Limit login access to specific authorized users or groupsAllowUsers sysadmin devops# orAllowGroups wheel sudoAfter modifying, test configuration syntax before reloading the daemon:
sudo sshd -tsudo systemctl reload sshd # or 'sudo systemctl reload ssh' on Debian/Ubuntu38.3 SSH Authentication Deep Dive & Key Management
Section titled “38.3 SSH Authentication Deep Dive & Key Management”1. Generating Modern SSH Keys (ed25519)
Section titled “1. Generating Modern SSH Keys (ed25519)”Modern infrastructure has moved away from older 2048-bit RSA keys toward Ed25519 (an elliptic curve signature algorithm). Ed25519 keys are faster, mathematically superior, and much shorter:
# Generate a new Ed25519 key pair with a descriptive commentssh-keygen -t ed25519 -C "admin@workstation"This generates:
~/.ssh/id_ed25519: Private key (Secret! Never share, upload, or transmit).~/.ssh/id_ed25519.pub: Public key (Safe to copy to remote servers).
[!TIP] Always protect private keys with a passphrase. The passphrase encrypts the private key on disk so that if your laptop is stolen, an attacker cannot immediately use the key.
2. Installing Public Keys on a Remote Server
Section titled “2. Installing Public Keys on a Remote Server”While still authenticated with your initial key or password:
# Option A: Automated installationssh-copy-id -i ~/.ssh/id_ed25519.pub user@server.example.com
# Option B: Manual installation on the servermkdir -p ~/.sshecho "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5... admin@workstation" >> ~/.ssh/authorized_keyschmod 700 ~/.sshchmod 600 ~/.ssh/authorized_keys3. Client Configuration (~/.ssh/config)
Section titled “3. Client Configuration (~/.ssh/config)”Instead of typing lengthy IP addresses, ports, and key paths every time, configure shortcuts in your local ~/.ssh/config:
Host prod-node HostName 54.201.10.20 User devops Port 22 IdentityFile ~/.ssh/id_ed25519
Host db-internal HostName 10.0.1.50 User postgres ProxyJump prod-node IdentityFile ~/.ssh/id_ed25519Now connect simply by running:
ssh prod-node(This shortcut also works transparently with scp, rsync, and sshfs!)
38.4 Troubleshooting “Permission denied (publickey)”
Section titled “38.4 Troubleshooting “Permission denied (publickey)””The error Permission denied (publickey) means the SSH server refused the provided authentication tokens and terminated the connection before offering password authentication or a shell.
Client Server │ ─── 1. Connect (user@host) ────────► │ │ ◄── 2. Request Public Key Auth ───── │ │ ─── 3. Offer Key (id_ed25519) ─────► │ │ ◄── 4. REJECTED: Permission Denied ─ │The Top 5 Root Causes Checklist
Section titled “The Top 5 Root Causes Checklist”- Wrong Username for the AMI/Image: Connecting as
rootorubuntuwhen the image expectsec2-user,admin, orcentos. - Wrong Private Key Specified: The client offered a default key (
~/.ssh/id_rsa), but the server requires a different key specified via-i path/to/key.pem. - Missing from
~/.ssh/authorized_keys: The public key was not added to the target user’s~/.ssh/authorized_keysfile. - Incorrect Permissions on the Server:
- The user’s home directory must not be writable by group or others (
chmod 755 /home/user). ~/.sshdirectory must be mode700.~/.ssh/authorized_keysmust be mode600.- All files must be owned by the target user (
chown -R user:user ~/.ssh).
- The user’s home directory must not be writable by group or others (
- Windows Private Key Permission Error:
On Windows with OpenSSH, you may encounter:
Fix via PowerShell (WARNING: UNPROTECTED PRIVATE KEY FILE!Permissions for 'aws-key.pem' are too open.
icacls):Terminal window icacls "C:\path\to\aws-key.pem" /inheritance:ricacls "C:\path\to\aws-key.pem" /grant:r "$($env:USERNAME):(R)" "NT AUTHORITY\SYSTEM:(F)" "BUILTIN\Administrators:(F)"
Debugging with Verbose Mode (-v, -vvv)
Section titled “Debugging with Verbose Mode (-v, -vvv)”To see the exact point where SSH authentication fails:
ssh -vvv -i key.pem user@server.example.com38.5 Special Permissions (SUID, SGID, Sticky)
Section titled “38.5 Special Permissions (SUID, SGID, Sticky)”1. SUID (Set User ID) — Octal 4000
Section titled “1. SUID (Set User ID) — Octal 4000”Executes an application with the privileges of the file owner (typically root), rather than the user launching it.
- Legitimate example:
/usr/bin/passwd(requires root to update/etc/shadow). - Security Hazard: Unaudited SUID executables are the primary vector for local privilege escalation.
# Locate all SUID root binaries on the system:sudo find / -perm -4000 -type f -exec ls -la {} + 2>/dev/null
# Add or remove SUID:sudo chmod u+s /path/to/binarysudo chmod u-s /path/to/binary2. SGID (Set Group ID) — Octal 2000
Section titled “2. SGID (Set Group ID) — Octal 2000”- Files: Executes with group permissions.
- Directories: Files created inside inherit the parent directory’s group ownership rather than the creator’s primary group.
sudo chmod g+s /var/shared/devs3. Sticky Bit — Octal 1000
Section titled “3. Sticky Bit — Octal 1000”Ensures files inside a shared directory can only be deleted or renamed by the file owner, directory owner, or root (e.g. /tmp with mode 1777 / drwxrwxrwt).
sudo chmod +t /shared/scratch38.6 Password Policies & Account Lockout
Section titled “38.6 Password Policies & Account Lockout”# Force password expiration every 90 days with a 7-day warningsudo chage -M 90 -m 1 -W 7 username
# Inspect password aging settingssudo chage -l usernameAccount Lockout with PAM (faillock)
Section titled “Account Lockout with PAM (faillock)”Defend against brute-force attacks by locking accounts after 5 failed attempts (configured in /etc/security/faillock.conf):
# View failed attemptssudo faillock --user username
# Reset lock manuallysudo faillock --user username --reset38.7 Attack Surface Minimization
Section titled “38.7 Attack Surface Minimization”# Audit listening portssudo ss -tulpn
# Disable unneeded servicessudo systemctl stop cups bluetoothsudo systemctl disable cups bluetoothAutomated Security Updates
Section titled “Automated Security Updates”- Debian / Ubuntu:
Terminal window sudo apt install unattended-upgrades -ysudo dpkg-reconfigure -plow unattended-upgrades - RHEL / Alma / Rocky:
Terminal window sudo dnf install dnf-automatic -ysudo systemctl enable --now dnf-automatic.timer
38.8 Mandatory Access Control: SELinux vs AppArmor
Section titled “38.8 Mandatory Access Control: SELinux vs AppArmor”Traditional Linux security uses Discretionary Access Control (DAC): file permissions (rwx) defined at the owner’s discretion. If the nginx process is compromised, DAC allows an attacker to access anything nginx owns.
Mandatory Access Control (MAC) enforces kernel-level policy checks regardless of standard user permissions:
AppArmor (Debian / Ubuntu / SUSE)
Section titled “AppArmor (Debian / Ubuntu / SUSE)”Binds security profiles in /etc/apparmor.d/ directly to application paths:
# Check profile statussudo aa-status
# Place profile in complain mode (logs violations without blocking)sudo aa-complain /usr/sbin/nginx
# Place profile in enforce mode (strictly blocks unauthorized activity)sudo aa-enforce /usr/sbin/nginxSELinux (RHEL / Rocky / AlmaLinux / Fedora)
Section titled “SELinux (RHEL / Rocky / AlmaLinux / Fedora)”Uses Type Enforcement labels (user:role:type:level) attached to files, processes, and sockets:
# Check SELinux state (Enforcing, Permissive, Disabled)sestatus
# Temporarily toggle modes without rebooting:sudo setenforce 0 # Permissive (Log only)sudo setenforce 1 # Enforcing (Block and log)
# Inspect security context on files (-Z)ls -Z /var/www/html# e.g., system_u:object_r:httpd_sys_content_t:s0
# Restore default security context after copying filessudo restorecon -Rv /var/www/html38.9 Production Security Baseline Checklist
Section titled “38.9 Production Security Baseline Checklist”- Dedicated User Accounts: Never share
ubuntuorec2-user. Create personal user accounts with dedicated SSH keys. - Disable Direct Root Login: Set
PermitRootLogin noinsshd_configand elevate usingsudo -i. - Enforce Public Key Authentication: Set
PasswordAuthentication no. - Use Modern Key Cryptography: Default to
ed25519key pairs with local passphrases. - Protect Key Permissions: Ensure
~/.sshis700,authorized_keysis600, and Windows private keys are restricted viaicacls. - Automate Security Patches: Enable
unattended-upgradesordnf-automatic. - Always Test in a Secondary Terminal: When updating SSH or sudo configurations, always keep your current active terminal session open while testing in a new terminal window to prevent accidental lockouts!