Skip to content

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.

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) ALL when 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 pairs
PasswordAuthentication no
PubkeyAuthentication yes
# Disable empty passwords
PermitEmptyPasswords no
# Limit authentication attempts per connection to prevent brute-forcing
MaxAuthTries 3
# Disconnect idle sessions automatically (e.g., 5 minutes of inactivity)
ClientAliveInterval 300
ClientAliveCountMax 0
# Limit login access to specific authorized users or groups
AllowUsers sysadmin devops
# or
AllowGroups wheel sudo

After modifying, test configuration syntax before reloading the daemon:

Terminal window
sudo sshd -t
sudo systemctl reload sshd # or 'sudo systemctl reload ssh' on Debian/Ubuntu

38.3 SSH Authentication Deep Dive & Key Management

Section titled “38.3 SSH Authentication Deep Dive & Key Management”

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:

Terminal window
# Generate a new Ed25519 key pair with a descriptive comment
ssh-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:

Terminal window
# Option A: Automated installation
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server.example.com
# Option B: Manual installation on the server
mkdir -p ~/.ssh
echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5... admin@workstation" >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

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_ed25519

Now connect simply by running:

Terminal window
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 ─ │
  1. Wrong Username for the AMI/Image: Connecting as root or ubuntu when the image expects ec2-user, admin, or centos.
  2. 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.
  3. Missing from ~/.ssh/authorized_keys: The public key was not added to the target user’s ~/.ssh/authorized_keys file.
  4. Incorrect Permissions on the Server:
    • The user’s home directory must not be writable by group or others (chmod 755 /home/user).
    • ~/.ssh directory must be mode 700.
    • ~/.ssh/authorized_keys must be mode 600.
    • All files must be owned by the target user (chown -R user:user ~/.ssh).
  5. Windows Private Key Permission Error: On Windows with OpenSSH, you may encounter:
    WARNING: UNPROTECTED PRIVATE KEY FILE!
    Permissions for 'aws-key.pem' are too open.
    Fix via PowerShell (icacls):
    Terminal window
    icacls "C:\path\to\aws-key.pem" /inheritance:r
    icacls "C:\path\to\aws-key.pem" /grant:r "$($env:USERNAME):(R)" "NT AUTHORITY\SYSTEM:(F)" "BUILTIN\Administrators:(F)"

To see the exact point where SSH authentication fails:

Terminal window
ssh -vvv -i key.pem user@server.example.com

38.5 Special Permissions (SUID, SGID, Sticky)

Section titled “38.5 Special Permissions (SUID, SGID, Sticky)”

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.
Terminal window
# 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/binary
sudo chmod u-s /path/to/binary
  • Files: Executes with group permissions.
  • Directories: Files created inside inherit the parent directory’s group ownership rather than the creator’s primary group.
Terminal window
sudo chmod g+s /var/shared/devs

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).

Terminal window
sudo chmod +t /shared/scratch
Terminal window
# Force password expiration every 90 days with a 7-day warning
sudo chage -M 90 -m 1 -W 7 username
# Inspect password aging settings
sudo chage -l username

Defend against brute-force attacks by locking accounts after 5 failed attempts (configured in /etc/security/faillock.conf):

Terminal window
# View failed attempts
sudo faillock --user username
# Reset lock manually
sudo faillock --user username --reset
Terminal window
# Audit listening ports
sudo ss -tulpn
# Disable unneeded services
sudo systemctl stop cups bluetooth
sudo systemctl disable cups bluetooth
  • Debian / Ubuntu:
    Terminal window
    sudo apt install unattended-upgrades -y
    sudo dpkg-reconfigure -plow unattended-upgrades
  • RHEL / Alma / Rocky:
    Terminal window
    sudo dnf install dnf-automatic -y
    sudo 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:

Binds security profiles in /etc/apparmor.d/ directly to application paths:

Terminal window
# Check profile status
sudo 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/nginx

SELinux (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:

Terminal window
# 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 files
sudo restorecon -Rv /var/www/html

38.9 Production Security Baseline Checklist

Section titled “38.9 Production Security Baseline Checklist”
  1. Dedicated User Accounts: Never share ubuntu or ec2-user. Create personal user accounts with dedicated SSH keys.
  2. Disable Direct Root Login: Set PermitRootLogin no in sshd_config and elevate using sudo -i.
  3. Enforce Public Key Authentication: Set PasswordAuthentication no.
  4. Use Modern Key Cryptography: Default to ed25519 key pairs with local passphrases.
  5. Protect Key Permissions: Ensure ~/.ssh is 700, authorized_keys is 600, and Windows private keys are restricted via icacls.
  6. Automate Security Patches: Enable unattended-upgrades or dnf-automatic.
  7. 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!