Table of Contents
- Update and Patch Regularly
- Strengthen User Account Security
- Harden File and Directory Permissions
- Configure a Firewall
- Secure SSH Access
- Implement System Auditing and Intrusion Detection
- Harden the Linux Kernel
- Secure Applications and Services
- Enable Logging and Monitoring
- Backup and Disaster Recovery
- Conclusion
- References
1. Update and Patch Regularly
Why it matters: Outdated software is one of the top attack vectors. Vulnerabilities in the Linux kernel, libraries, or applications (e.g., OpenSSL, Apache) are frequently exploited by attackers. Regular updates patch these flaws before they can be weaponized.
How to implement:
- Automate updates: Use your distribution’s package manager to keep the system and installed software up-to-date.
- Debian/Ubuntu:
sudo apt update && sudo apt upgrade -y(for manual updates) or enableunattended-upgradesfor automation:sudo apt install unattended-upgrades sudo dpkg-reconfigure -plow unattended-upgrades # Enable automatic security updates - RHEL/CentOS/Rocky Linux:
sudo dnf update -yor usednf-automatic:sudo dnf install dnf-automatic sudo systemctl enable --now dnf-automatic.timer
- Debian/Ubuntu:
- Audit third-party software: Remove unused apps (e.g.,
sudo apt purge <package>) and avoid untrusted repositories (PPAs, RPM fusion).
2. Strengthen User Account Security
User accounts are often the weakest link. Compromised credentials can grant attackers unrestricted access.
Key steps:
-
Enforce strong passwords:
- Use
pam_pwqualityto enforce complexity (e.g., minimum length, mixed case, symbols). Edit/etc/security/pwquality.conf:minlen = 12 dcredit = -1 # Require at least 1 digit ucredit = -1 # Require at least 1 uppercase letter lcredit = -1 # Require at least 1 lowercase letter ocredit = -1 # Require at least 1 symbol - Set password expiration with
/etc/login.defs:PASS_MAX_DAYS 90 # Expire after 90 days PASS_MIN_DAYS 7 # No changes for 7 days PASS_WARN_AGE 14 # Warn 14 days before expiration
- Use
-
Limit
sudoprivileges:- Use
visudoto edit/etc/sudoersand restrict users to specific commands (avoidALL=(ALL) ALLfor non-admins):alice ALL=(ALL) /usr/bin/apt, /usr/bin/systemctl restart apache2 # Restrict Alice to apt and Apache restarts
- Use
-
Disable root login:
- For local access: Set
PermitRootLogin noin/etc/ssh/sshd_config(see Secure SSH Access). - For physical access: Use
sudo passwd -l rootto lock the root account (reversible withsudo passwd -u root).
- For local access: Set
-
Remove unused accounts:
- Audit accounts with
cat /etc/passwdand delete obsolete ones:sudo userdel -r <username>(the-rflag removes home directories).
- Audit accounts with
-
Enable Multi-Factor Authentication (MFA):
- Use
pam_google_authenticatororpam_u2f(for hardware keys like YubiKey). For SSH, addauth required pam_google_authenticator.soto/etc/pam.d/sshd.
- Use
3. Harden File and Directory Permissions
Incorrect file permissions can expose sensitive data (e.g., /etc/shadow, private keys) or allow privilege escalation.
Best practices:
-
Follow the principle of least privilege:
- Restrict read/write/execute access to only necessary users/groups. For example:
- User home directories:
chmod 700 /home/<user>(no access to others). - SSH keys:
chmod 600 ~/.ssh/id_rsa(read/write for owner only). - Sensitive configs:
/etc/sudoersshould have0440permissions.
- User home directories:
- Restrict read/write/execute access to only necessary users/groups. For example:
-
Secure critical system files:
- Use
chattrto make files immutable (prevents accidental/ malicious modification):
(Usesudo chattr +i /etc/passwd /etc/shadow /etc/sudoers # +i = immutablechattr -ito reverse when updates are needed.)
- Use
-
Set a strict
umask:- The
umaskdefines default permissions for new files. Edit/etc/profileor~/.bashrcto setumask 027(new files:640, directories:750).
- The
-
Audit permissions with
find:- Identify world-writable files (high risk):
find / -perm -0002 -type f 2>/dev/null # Ignore errors with 2>/dev/null
- Identify world-writable files (high risk):
4. Configure a Firewall
A firewall acts as a gatekeeper, blocking unauthorized network traffic. Linux offers powerful built-in tools for this.
Options:
-
UFW (Uncomplicated Firewall): Simple for beginners (default on Ubuntu):
sudo ufw default deny incoming # Block all incoming traffic sudo ufw default allow outgoing # Allow all outgoing traffic sudo ufw allow 22/tcp # Allow SSH (adjust port if needed) sudo ufw allow 443/tcp # Allow HTTPS sudo ufw enable # Start firewall on boot sudo ufw status verbose # Verify rules -
Firewalld: Dynamic firewall (default on RHEL/CentOS):
sudo firewall-cmd --set-default-zone=drop # Block incoming by default sudo firewall-cmd --add-service=ssh --permanent # Allow SSH sudo firewall-cmd --reload # Apply changes -
iptables: Advanced, low-level control (use for complex rules):
sudo iptables -P INPUT DROP # Default drop incoming sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Allow SSH sudo iptables-save > /etc/iptables/rules.v4 # Persist rules (Debian/Ubuntu)
Tips:
- Log dropped packets for auditing: Add
--log-prefix "FIREWALL DROP: "to iptables rules. - Use stateful rules: Allow established connections with
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT.
5. Secure SSH Access
SSH is the primary way to remote-manage Linux systems—making it a prime target for attackers.
Hardening steps:
-
Disable password authentication: Use SSH keys instead. Edit
/etc/ssh/sshd_config:PasswordAuthentication no PubkeyAuthentication yes -
Restrict SSH access:
PermitRootLogin no # No direct root login AllowUsers alice bob # Only allow specific users AllowGroups ssh-users # Or specific groups MaxAuthTries 3 # Lock after 3 failed attempts X11Forwarding no # Disable GUI forwarding (reduces attack surface) -
Use modern SSH protocol: Ensure
Protocol 2(only) is enabled (default in newer OpenSSH). -
Harden SSH key management:
- Use ED25519 keys (more secure than RSA):
ssh-keygen -t ed25519. - Protect keys with a passphrase (
ssh-keygen -pto add one later).
- Use ED25519 keys (more secure than RSA):
-
Block brute-force attacks with
fail2ban:- Install and enable
fail2banto ban IPs after repeated failed SSH attempts:
(Config insudo apt install fail2ban sudo systemctl enable --now fail2ban/etc/fail2ban/jail.local.)
- Install and enable
6. Implement System Auditing and Intrusion Detection
Even with firewalls and strong permissions, you need to detect breaches after they occur.
Tools to use:
-
auditd: Logs system events (file access, process execution, user actions).
- Install:
sudo apt install auditd(RHEL/CentOS: pre-installed). - Monitor sensitive files with rules in
/etc/audit/rules.d/audit.rules:-w /etc/passwd -p wa -k passwd_changes # Log write/append to passwd -w /usr/bin/sudo -p x -k sudo_exec # Log sudo execution - Search logs with
ausearch -k passwd_changes.
- Install:
-
File Integrity Monitoring (FIM): Detect unauthorized file changes with tools like:
- AIDE (Advanced Intrusion Detection Environment):
sudo apt install aide sudo aideinit # Generate baseline sudo aide --check # Compare current state to baseline - Tripwire or OSSEC: Enterprise-grade FIM with alerting.
- AIDE (Advanced Intrusion Detection Environment):
-
Lynis: A security auditing tool that scans for vulnerabilities:
sudo apt install lynis sudo lynis audit system # Generates a detailed report
7. Harden the Linux Kernel
The kernel is the core of the OS; hardening it reduces attack surface and mitigates exploits.
Key techniques:
-
Secure GRUB bootloader:
- Set a GRUB password to prevent tampering with boot options (e.g., single-user mode). Edit
/etc/grub.d/00_headerand runsudo update-grub. - Disable risky features in
/etc/default/grub:GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nousb noexec=nosuid" # Disable USB, noexec on /tmp
- Set a GRUB password to prevent tampering with boot options (e.g., single-user mode). Edit
-
Tweak
sysctlparameters:
Edit/etc/sysctl.confor/etc/sysctl.d/99-security.confto enable kernel protections:# Network hardening net.ipv4.conf.all.rp_filter=1 # Enable reverse path filtering net.ipv4.tcp_syncookies=1 # Mitigate SYN floods net.ipv4.icmp_echo_ignore_broadcasts=1 # Block broadcast pings # Memory protection kernel.randomize_va_space=2 # Enable ASLR (Address Space Layout Randomization) kernel.exec-shield=1 # Prevent execution of stack memoryApply changes with
sudo sysctl -p. -
Enable AppArmor/SELinux:
- AppArmor (default on Ubuntu): Enforces mandatory access control (MAC). Enable with
sudo aa-enforce /etc/apparmor.d/*. - SELinux (default on RHEL/CentOS): More strict than AppArmor. Set to
enforcingmode in/etc/selinux/config.
- AppArmor (default on Ubuntu): Enforces mandatory access control (MAC). Enable with
-
Disable unused kernel modules:
Blacklist unnecessary modules (e.g.,usb_storage,firewire) in/etc/modprobe.d/blacklist.conf:blacklist usb_storage blacklist firewire-core
8. Secure Applications and Services
Even a hardened OS is vulnerable if applications are misconfigured.
Best practices:
-
Minimize installed software: Use
dpkg -l(Debian) orrpm -qa(RHEL) to list packages and remove bloatware. -
Run services as non-root users:
- Web servers (Nginx/Apache): Configure to run as
www-dataorapache(not root). - Databases (MySQL/PostgreSQL): Use dedicated system users.
- Web servers (Nginx/Apache): Configure to run as
-
Secure web servers:
- Enable TLS 1.3 only (disable TLS 1.0/1.1). For Nginx, edit
/etc/nginx/nginx.conf:ssl_protocols TLSv1.3; ssl_prefer_server_ciphers on; - Add security headers (e.g.,
Strict-Transport-Security,X-Content-Type-Options).
- Enable TLS 1.3 only (disable TLS 1.0/1.1). For Nginx, edit
-
Container security:
- For Docker, run containers as non-root users and enable seccomp profiles:
docker run --user 1000:1000 --security-opt seccomp=default.json myimage
- For Docker, run containers as non-root users and enable seccomp profiles:
9. Enable Logging and Monitoring
Logs are critical for post-incident analysis. Centralized logging and real-time monitoring help detect breaches early.
Steps:
-
Centralize logs with rsyslog/Graylog:
- Configure
rsyslogto forward logs to a central server (e.g., Graylog, ELK Stack). Edit/etc/rsyslog.confto send logs to@central-log-server:514.
- Configure
-
Rotate logs to prevent disk bloat:
- Use
logrotate(configured in/etc/logrotate.conf). Set max log size and retention (e.g.,weekly,rotate 4).
- Use
-
Monitor with tools like Prometheus/Grafana:
- Track system metrics (CPU, memory, network) and set alerts for anomalies (e.g., sudden spikes in SSH failed logins).
-
Automate alerting: Use tools like
NagiosorZabbixto trigger alerts for critical events (e.g.,auditdlogs of/etc/passwdchanges).
10. Backup and Disaster Recovery
Even with perfect security, backups are your last line of defense against data loss (e.g., ransomware, hardware failure).
Backup best practices:
- Encrypt backups: Use tools like
borgbackuporrsync -e sshwith encrypted storage (e.g., LUKS-encrypted external drives). - Store backups offsite: Cloud storage (AWS S3, Backblaze) or physical media in a secure location.
- Test restores regularly: A backup is useless if you can’t restore from it.
- Automate backups: Use
cronjobs to runborg createorrsyncnightly. For example:# Cron job to backup /home daily at 2 AM 0 2 * * * /usr/bin/borg create --exclude-caches /backup/borg::$(date +%Y-%m-%d) /home
Conclusion
Securing Linux is a continuous process, not a one-time task. By combining these tips—from patching and user management to firewall rules and backups—you’ll create a layered defense that significantly reduces risk. Regularly audit your system with tools like lynis or aide, stay updated on new vulnerabilities, and adapt your strategy as threats evolve. Remember: the goal isn’t perfection, but resilience.