Linux is renowned for its robust security architecture, but even the most secure operating system can be compromised through misconfigurations, outdated software, or human error. As a Linux administrator, securing your systems is not a one-time task but an ongoing process of risk mitigation. This blog serves as a comprehensive checklist to help you fortify your Linux environment, covering foundational practices, advanced techniques, and actionable steps to protect against common threats. Whether you manage a single server or a fleet of machines, these guidelines will empower you to build a resilient security posture.
Table of Contents
- System Updates & Patch Management
- User Account Security
- Access Control: Hardening SSH
- File System Security
- Firewalls & Network Security
- Service Management
- Logging & Monitoring
- Vulnerability Scanning
- Encryption
- Advanced: SELinux & AppArmor
- Best Practices Checklist
- Conclusion
- References
1. System Updates & Patch Management
Outdated software is one of the most common attack vectors. Regularly updating your system ensures you receive critical security patches for vulnerabilities.
Why It Matters:
- Vulnerabilities in the Linux kernel, libraries, or applications are frequently discovered and patched by the open-source community. Delaying updates leaves systems exposed to exploits (e.g., Heartbleed, Shellshock).
Implementation:
For Debian/Ubuntu:
# Update package lists and upgrade installed packages
sudo apt update && sudo apt upgrade -y
# Upgrade to the latest stable release (optional)
sudo apt dist-upgrade -y
# Clean up old packages
sudo apt autoremove -y && sudo apt autoclean
For RHEL/CentOS/Rocky Linux:
# Update all packages
sudo dnf update -y
# For older CentOS (using yum)
sudo yum update -y
Automatic Updates:
Enable unattended updates to ensure patches are applied without manual intervention:
# Debian/Ubuntu: Install unattended-upgrades
sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure -plow unattended-upgrades # Enable automatic updates
# RHEL/CentOS: Use dnf-automatic
sudo dnf install dnf-automatic -y
sudo systemctl enable --now dnf-automatic.timer
2. User Account Security
Weak user account practices (e.g., shared accounts, weak passwords) are a leading cause of breaches. Enforce strict controls to limit risk.
Key Practices:
- Disable root login for interactive sessions (use
sudoinstead). - Enforce strong passwords (minimum length, complexity).
- Limit sudo access to essential users only.
- Remove dormant accounts and audit regularly.
Implementation:
Manage User Accounts:
# List all users
cut -d: -f1 /etc/passwd
# Delete dormant users (e.g., "olduser")
sudo userdel -r olduser # -r removes home directory
# Add a new user with sudo privileges
sudo adduser johndoe
sudo usermod -aG sudo johndoe
Enforce Password Policies with PAM:
Edit /etc/pam.d/common-password (Debian/Ubuntu) or /etc/pam.d/system-auth (RHEL/CentOS) to require strong passwords:
# Require 10+ characters, mixed case, numbers, and symbols
password requisite pam_cracklib.so minlen=10 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1
# Expire passwords after 90 days
password requisite pam_unix.so sha512 shadow remember=5 # Prevent reuse of last 5 passwords
Restrict sudo Access:
Edit the sudoers file with visudo (safe editing to avoid syntax errors):
sudo visudo
Add rules to allow only specific commands for users/groups:
# Allow johndoe to restart nginx without password
johndoe ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
3. Access Control: Hardening SSH
SSH (Secure Shell) is the primary method for remote access to Linux systems. Misconfigured SSH is a critical attack surface.
Critical Hardening Steps:
- Disable password-based authentication (use SSH keys).
- Disable root login over SSH.
- Restrict SSH access to trusted IPs (if possible).
- Use modern encryption algorithms.
Implementation:
Configure SSH (/etc/ssh/sshd_config):
Edit the SSH daemon config file:
sudo nano /etc/ssh/sshd_config
Apply these settings:
# Disable root login
PermitRootLogin no
# Disable password authentication (use keys only)
PasswordAuthentication no
ChallengeResponseAuthentication no
# Enable key-based authentication
PubkeyAuthentication yes
# Restrict users allowed to SSH (e.g., "johndoe" and "admin")
AllowUsers johndoe admin
# Limit SSH to specific IP ranges (e.g., 192.168.1.0/24)
# AllowUsers *@192.168.1.0/24 # Uncomment and adjust as needed
# Use strong ciphers (remove weak ones like CBC)
Ciphers [email protected],[email protected],[email protected]
# Restart SSH service to apply changes
sudo systemctl restart sshd # or ssh (Debian/Ubuntu)
Key-Based Authentication Setup:
On the client machine, generate an SSH key pair and copy it to the server:
# Generate key pair (ed25519 is preferred for security)
ssh-keygen -t ed25519 -C "johndoe@workstation" # Press Enter to accept defaults
# Copy public key to server (replace "johndoe" and "server_ip")
ssh-copy-id johndoe@server_ip
Verify SSH Hardening:
Test SSH access and audit the config:
# Check SSH daemon status
sudo systemctl status sshd
# Audit SSH configuration for weaknesses
sshd -T # Test configuration (look for "permitrootlogin no", "passwordauthentication no")
4. File System Security
Insecure file permissions or misconfigured file systems can expose sensitive data or allow privilege escalation.
Key Practices:
- Restrict permissions on critical files (e.g.,
/etc/passwd,/etc/shadow). - Use immutable files for sensitive configurations.
- Limit SUID/GUID binaries (reduce privilege escalation risks).
Implementation:
Check and Fix File Permissions:
# List permissions of critical files
ls -l /etc/passwd /etc/shadow /etc/sudoers
# Ensure /etc/shadow is readable only by root (permissions 0600)
sudo chmod 0600 /etc/shadow
# Set secure umask (default permissions for new files)
echo "umask 027" | sudo tee -a /etc/profile # 027: rwxr-x--- for directories, rw-r----- for files
Make Files Immutable:
Prevent accidental or malicious modification of critical files with chattr:
# Make /etc/resolv.conf immutable (prevents DNS hijacking)
sudo chattr +i /etc/resolv.conf
# Remove immutability (temporarily, if edits are needed)
sudo chattr -i /etc/resolv.conf
Audit SUID/GUID Binaries:
SUID binaries run with the owner’s privileges (e.g., root). Remove unnecessary ones:
# List all SUID/GUID binaries
find / -perm /6000 -ls 2>/dev/null
# Remove SUID bit from non-essential binaries (e.g., "telnet")
sudo chmod u-s /usr/bin/telnet
5. Firewalls & Network Security
A firewall acts as a barrier between your system and the network, blocking unauthorized traffic. Use it to allow only essential services.
Recommended Tools:
- UFW (Uncomplicated Firewall): Simplified frontend for
iptables(ideal for beginners). - nftables: Modern replacement for
iptables(more efficient, flexible).
Implementation with UFW:
# Install UFW (Debian/Ubuntu; pre-installed on most systems)
sudo apt install ufw -y
# Enable UFW and set default policies (deny incoming, allow outgoing)
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow essential services (SSH, HTTP, HTTPS)
sudo ufw allow 22/tcp # SSH (adjust port if changed earlier)
sudo ufw allow 80/tcp # HTTP (if running a web server)
sudo ufw allow 443/tcp # HTTPS
# Allow traffic from a trusted IP (e.g., office network 192.168.1.0/24)
sudo ufw allow from 192.168.1.0/24
# Enable UFW and verify rules
sudo ufw enable
sudo ufw status numbered # List rules with numbers for easy deletion
Advanced: nftables Example:
# Create a basic nftables rule set (block all except SSH/HTTP/HTTPS)
sudo nft add table inet filter
sudo nft add chain inet filter input '{ type filter hook input priority 0; policy drop; }'
sudo nft add rule inet filter input ct state related,established accept # Allow existing connections
sudo nft add rule inet filter input tcp dport { 22, 80, 443 } accept # Allow SSH/HTTP/HTTPS
sudo nft add rule inet filter input iif lo accept # Allow loopback traffic
# Save rules (persist across reboots)
sudo nft list ruleset | sudo tee /etc/nftables.conf
sudo systemctl enable --now nftables
6. Service Management
Unnecessary services (e.g., Telnet, FTP) increase your attack surface. Disable all non-essential services.
Implementation:
# List all running services
sudo systemctl list-unit-files --type=service --state=enabled
# Disable unused services (e.g., "cups" for printing, "telnet")
sudo systemctl disable --now cups
sudo systemctl disable --now telnet.socket
# Mask services to prevent accidental re-enabling (e.g., "ftp")
sudo systemctl mask vsftpd # Masked services cannot be started
7. Logging & Monitoring
Without logging, you cannot detect breaches or diagnose issues. Centralize and monitor logs to identify anomalies early.
Key Tools:
- rsyslog: Traditional system logging.
- journald: Systemd’s built-in logging (stores logs in binary format).
- Logrotate: Automatically rotate logs to prevent disk exhaustion.
Implementation:
View Logs with Journalctl:
# Show all logs (most recent first)
journalctl -xe
# Filter logs by service (e.g., "sshd")
journalctl -u sshd
# Show logs from the last hour
journalctl --since "1 hour ago"
Configure Log Rotation:
Edit /etc/logrotate.conf or files in /etc/logrotate.d/ to set rotation policies:
# Example: Rotate /var/log/auth.log daily, keep 7 days of logs
/var/log/auth.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0640 root adm
}
Centralized Logging (Optional):
For multi-server environments, forward logs to a central server (e.g., using rsyslog or tools like Graylog/ELK Stack).
8. Vulnerability Scanning
Proactively scan for vulnerabilities to identify and remediate issues before attackers exploit them.
Recommended Tools:
- Lynis: Open-source security auditing tool for Linux.
- OpenVAS: Full-featured vulnerability scanner (more advanced).
Lynis Audit Example:
# Install Lynis (Debian/Ubuntu)
sudo apt install lynis -y
# Run a security audit
sudo lynis audit system
# Review the report (look for "Suggestions" and "Warnings")
cat /var/log/lynis-report.dat
Output Tip: Lynis provides actionable fixes (e.g., “Harden /etc/hosts.allow” or “Enable process accounting”).
9. Encryption
Encrypt data at rest (e.g., disks) and in transit (e.g., network traffic) to protect against unauthorized access.
Data at Rest: LUKS Disk Encryption
Encrypt entire disks or partitions with LUKS (Linux Unified Key Setup):
# Install cryptsetup (LUKS tooling)
sudo apt install cryptsetup -y
# Encrypt a partition (e.g., /dev/sdb1)
sudo cryptsetup luksFormat /dev/sdb1 # WARNING: Erases data!
sudo cryptsetup open /dev/sdb1 encrypted_disk # Open the encrypted volume
sudo mkfs.ext4 /dev/mapper/encrypted_disk # Format the encrypted volume
sudo mount /dev/mapper/encrypted_disk /mnt/secure # Mount it
Data in Transit: SSL/TLS for Services
Ensure services like web servers (Nginx/Apache) use HTTPS with modern TLS:
# Install Certbot (for Let's Encrypt SSL certificates)
sudo apt install certbot python3-certbot-nginx -y
# Obtain and auto-configure SSL for Nginx
sudo certbot --nginx -d example.com
10. Advanced: SELinux & AppArmor
SELinux (Security-Enhanced Linux) and AppArmor are Mandatory Access Control (MAC) systems that restrict process actions beyond standard Unix permissions.
SELinux (RHEL/CentOS Default):
# Check SELinux status
sestatus
# Set to enforcing mode (recommended)
sudo setenforce 1
sudo sed -i 's/SELINUX=permissive/SELINUX=enforcing/' /etc/selinux/config # Persist across reboots
# Troubleshoot denials with audit2allow
sudo yum install policycoreutils-python-utils -y
sudo audit2allow -a # Generate allow rules from audit logs
AppArmor (Debian/Ubuntu Default):
# List AppArmor profiles
sudo aa-status
# Enable a profile for Nginx (enforce restrictions)
sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx
11. Best Practices Checklist
| Category | Action Items |
|---|---|
| System Updates | Run apt update && upgrade weekly; enable automatic updates. |
| User Security | Audit users monthly; enforce 10+ character passwords; limit sudo access. |
| SSH | Disable root login/password auth; use key-based auth; change default port. |
| Firewall | Allow only 22 (SSH), 80/443 (HTTP/HTTPS); block all other incoming traffic. |
| Files | Set /etc/shadow to 0600; make critical configs immutable with chattr +i. |
| Monitoring | Check logs daily with journalctl -u sshd; run Lynis audit monthly. |
| Encryption | Encrypt disks with LUKS; use Let’s Encrypt for SSL/TLS. |
12. Conclusion
Securing Linux is a continuous journey, not a destination. By following this checklist—from system updates and user controls to firewalls and encryption—you’ll significantly reduce your attack surface. Remember: security is layered; no single measure is sufficient. Regular audits, monitoring, and staying informed about new threats are critical to maintaining a robust defense.
Start small (e.g., harden SSH and enable a firewall), then gradually implement advanced controls like SELinux or vulnerability scanning. Your systems—and your organization—will thank you.