thelinuxvault guide

Optimizing Linux Security: A Guide to Secure Defaults

Linux is renowned for its robust security, but **default configurations**—shipped with most distributions to prioritize usability—often leave gaps that attackers can exploit. From weak password policies to unnecessary open ports, these "out-of-the-box" settings are designed for convenience, not defense. *Secure defaults* are pre-configured settings that prioritize security from the start, reducing attack surfaces and minimizing risk before an incident occurs. This guide will walk you through actionable steps to harden a Linux system by enforcing secure defaults across critical areas: user authentication, file permissions, network services, kernel configuration, and more. Whether you’re managing a personal server or an enterprise fleet, these practices will help you build a resilient foundation against modern threats.

Table of Contents

  1. Understanding Secure Defaults
  2. User Account & Authentication Security
  3. File System Permissions & Ownership
  4. Network Security Hardening
  5. Package Management & Software Security
  6. Kernel Hardening
  7. Logging & Monitoring
  8. Automation & Compliance
  9. Conclusion
  10. References

1. Understanding Secure Defaults

Secure defaults are pre-configured settings that inherently reduce risk by:

  • Following the principle of least privilege (users/services have only the permissions needed).
  • Disabling unnecessary features (e.g., unused services, kernel modules).
  • Enabling protective measures (e.g., encryption, logging, access controls).

Unlike reactive measures (e.g., patching after a breach), secure defaults act as a proactive barrier, making exploitation harder even if vulnerabilities exist.

2. User Account & Authentication Security

User accounts are often the first target for attackers. Hardening authentication prevents unauthorized access and privilege escalation.

2.1 Password Policies

Enforce strong, unique passwords using PAM (Pluggable Authentication Modules), the system that controls Linux authentication.

Configure /etc/login.defs (system-wide password settings):

# Set minimum password length to 12 characters
PASS_MIN_LEN 12
# Require password change every 90 days
PASS_MAX_DAYS 90
# Prevent password reuse (last 5 passwords)
PASS_WARN_AGE 7

Strengthen PAM Rules (edit /etc/pam.d/common-password):
Add pam_pwquality to enforce complexity (e.g., uppercase, numbers, symbols):

password    requisite     pam_pwquality.so retry=3 minlen=12 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1
  • ucredit=-1: Require at least 1 uppercase letter.
  • dcredit=-1: Require at least 1 digit.

2.2 Disable Root SSH Access

Never allow direct root login via SSH. Instead, use sudo for administrative tasks.

Edit /etc/ssh/sshd_config:

PermitRootLogin no
# Allow only specific users (e.g., "admin")
AllowUsers admin

Restart SSH: systemctl restart sshd.

2.3 SSH Key Authentication

Replace password-based SSH with key-based authentication, which is far more secure.

Generate SSH Keys (on your local machine):

ssh-keygen -t ed25519 -C "[email protected]"  # Ed25519 is more secure than RSA

Copy Keys to the Server:

ssh-copy-id admin@your-server-ip

Disable Password SSH (edit /etc/ssh/sshd_config):

PasswordAuthentication no
ChallengeResponseAuthentication no

2.4 Two-Factor Authentication (2FA)

Add an extra layer with 2FA using libpam-google-authenticator.

Install and Configure:

sudo apt install libpam-google-authenticator  # Debian/Ubuntu
google-authenticator  # Run as the user; scan QR code with Google Authenticator app

Update PAM for SSH (edit /etc/pam.d/sshd):

auth required pam_google_authenticator.so

Update SSHD Config (enable challenge-response):

ChallengeResponseAuthentication yes  # Required for 2FA prompts

2.5 Account Lockout

Prevent brute-force attacks by locking accounts after failed login attempts.

Use pam_faillock (edit /etc/pam.d/common-auth):

auth    required    pam_faillock.so preauth silent audit deny=5 unlock_time=900
auth    [success=1 default=ignore]      pam_unix.so
auth    [default=die]   pam_faillock.so authfail audit deny=5 unlock_time=900
  • deny=5: Lock after 5 failed attempts.
  • unlock_time=900: Unlock after 15 minutes (or use faillock --user <user> --reset to manually unlock).

3. File System Permissions & Ownership

Incorrect file permissions allow attackers to read sensitive data (e.g., /etc/shadow) or modify critical files (e.g., /etc/sudoers).

3.1 Secure Default Permissions

Use umask to set default permissions for new files/directories. The default umask 022 gives rw-r--r-- (644) for files and rwxr-xr-x (755) for directories—too permissive for sensitive data.

Set a stricter umask (edit /etc/profile for all users or ~/.bashrc for individuals):

umask 027  # New files: 640 (rw-r-----), directories: 750 (rwxr-x---)

3.2 Protect Critical Directories

Restrict access to system directories:

# /etc: Contains configs (e.g., passwd, sshd_config)
chmod 750 /etc  
chown root:root /etc  

# /home/<user>: User data (should be private)
chmod 700 /home/*  
chown <user>:<user> /home/<user>  

# /tmp: World-writable, but use tmpfs with noexec (prevent script execution)
# Edit /etc/fstab:
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0

3.3 Immutable Files

Prevent accidental/ malicious modification of critical files with chattr (change file attributes):

# Make /etc/passwd immutable (only root can modify with chattr -i)
chattr +i /etc/passwd  
chattr +i /etc/shadow  

4. Network Security Hardening

Networks are a prime attack vector. Secure defaults here involve firewalls, service restrictions, and encryption.

4.1 Firewalls

Block unauthorized network traffic with a firewall. Use ufw (Uncomplicated Firewall) for simplicity, or nftables (modern alternative to iptables).

UFW Setup:

# Enable UFW
ufw enable  
# Deny all incoming, allow all outgoing
ufw default deny incoming  
ufw default allow outgoing  
# Allow only essential ports (e.g., SSH, HTTP/HTTPS)
ufw allow 22/tcp   # SSH
ufw allow 443/tcp  # HTTPS  
ufw status verbose  # Verify rules

4.2 Disable Unused Services

Every running service is a potential target. Stop and disable unnecessary services (e.g., telnet, ftp, cups).

List running services (systemd systems):

systemctl list-unit-files --type=service --state=enabled

Disable a service:

systemctl disable --now cups  # Stop and disable CUPS (printing service)

4.3 Encrypt All Network Traffic

Use TLS/SSL for all services (web, email, SSH). For web servers (Nginx/Apache), enforce modern TLS protocols and ciphers.

Example Nginx TLS Config (/etc/nginx/conf.d/ssl.conf):

ssl_protocols TLSv1.3 TLSv1.2;  # Disable older protocols (TLSv1.0/1.1)
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

5. Package Management & Software Security

Outdated or untrusted software is a major source of vulnerabilities. Secure defaults here focus on verifying, updating, and minimizing software.

5.1 Use Official Repositories

Only install software from trusted sources (e.g., Debian/Ubuntu’s main repo, Red Hat’s official channels). Third-party repos (PPAs) increase risk—verify their GPG keys first.

Verify Repo GPG Keys (Debian/Ubuntu):

apt-key list  # List trusted keys
# Add a new key (e.g., for Docker):
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

5.2 Automatic Updates

Enable unattended security updates to patch vulnerabilities quickly.

Debian/Ubuntu: Install unattended-upgrades:

apt install unattended-upgrades  
dpkg-reconfigure -plow unattended-upgrades  # Enable automatic updates

Red Hat/CentOS: Use dnf-automatic:

dnf install dnf-automatic  
systemctl enable --now dnf-automatic.timer

5.3 Minimize Installed Software

Remove unused packages to reduce attack surface:

# Debian/Ubuntu: List and remove orphaned packages
apt autoremove --purge  
# Red Hat/CentOS: Remove unused dependencies
dnf autoremove

6. Kernel Hardening

The Linux kernel is the core of the OS—hardening it prevents low-level exploits (e.g., buffer overflows, privilege escalation).

6.1 Secure GRUB Bootloader

GRUB (Grand Unified Bootloader) controls kernel startup. Restrict access and disable risky features.

Edit /etc/default/grub:

# Disable kernel debugging and kexec (allows loading new kernels)
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nokaslr=0 kexec-disable=1"
# Require password to edit GRUB menu (prevent kernel parameter tampering)
GRUB_PASSWORD=your_encrypted_password  # Generate with `grub-mkpasswd-pbkdf2`

Update GRUB: update-grub (Debian/Ubuntu) or grub2-mkconfig -o /boot/grub2/grub.cfg (Red Hat).

6.2 Enable Security Modules

Use AppArmor or SELinux to restrict program behavior (e.g., prevent a web server from reading /etc/shadow).

AppArmor (easier for beginners, path-based rules):

  • Enable profiles for critical services (e.g., Apache, SSH):
    aa-enforce /etc/apparmor.d/usr.sbin.apache2  # Enforce Apache profile

SELinux (more powerful, label-based rules, default on RHEL/CentOS):

  • Set to enforcing mode:
    setenforce 1  # Temporary
    sed -i 's/SELINUX=permissive/SELINUX=enforcing/' /etc/selinux/config  # Permanent

6.3 Sysctl Hardening

Tweak kernel parameters via /etc/sysctl.conf or /etc/sysctl.d/ to disable risky features.

Example /etc/sysctl.d/security.conf:

# Enable ASLR (Address Space Layout Randomization)
kernel.randomize_va_space=2
# Disable IPv4 forwarding (if not a router)
net.ipv4.ip_forward=0
# Block ICMP redirects (prevents MITM attacks)
net.ipv4.conf.all.accept_redirects=0
net.ipv6.conf.all.accept_redirects=0
# Disable core dumps (prevent attackers from analyzing process memory)
fs.suid_dumpable=0

Apply changes: sysctl -p /etc/sysctl.d/security.conf.

7. Logging & Monitoring

Without logging, you won’t detect breaches. Secure defaults ensure comprehensive logging and alerting.

7.1 Centralized Logging

Aggregate logs from multiple systems using tools like ELK Stack (Elasticsearch, Logstash, Kibana) or Graylog for easier analysis.

Configure rsyslog (default Linux logging daemon) to forward logs:

# Edit /etc/rsyslog.conf to send logs to a central server
*.* @@central-log-server:514  # TCP forwarding

7.2 Audit File/System Changes

Use auditd to track critical events (e.g., file modifications, user logins).

Example Audit Rule (edit /etc/audit/rules.d/audit.rules):

# Log changes to /etc/passwd
-w /etc/passwd -p wa -k passwd_changes
# Log sudo commands
-a always,exit -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295 -k sudo_usage

Restart auditd: systemctl restart auditd.

7.3 Block Brute-force Attacks with fail2ban

fail2ban monitors logs for repeated failed login attempts and blocks the attacker’s IP.

Install and Configure fail2ban:

apt install fail2ban  # Debian/Ubuntu
# Enable SSH protection (edit /etc/fail2ban/jail.local)
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600  # Ban for 1 hour

8. Automation & Compliance

Manually enforcing secure defaults across multiple systems is error-prone. Use automation and compliance tools to scale.

8.1 Ansible for Secure Defaults

Ansible playbooks automate configuration (e.g., setting sshd_config, sysctl rules).

Example Ansible Task (enforce SSH key-only auth):

- name: Disable password authentication in SSHD
  lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^PasswordAuthentication'
    line: 'PasswordAuthentication no'
  notify: restart sshd

8.2 Compliance Scanning with OpenSCAP

OpenSCAP checks systems against security benchmarks (e.g., CIS, NIST) and generates reports.

Scan with OpenSCAP:

oscap xccdf eval --profile cis-server-level1 --results scan.xml /usr/share/xml/scap/ssg/content/ssg-debian11-ds.xml

9. Conclusion

Optimizing Linux security with secure defaults is a continuous process. By hardening user accounts, file permissions, networks, and the kernel—then monitoring for anomalies—you create a resilient system that resists attacks. Regularly update your defaults to match new threats (e.g., emerging kernel vulnerabilities) and use automation to maintain consistency at scale.

10. References