Top 10 Best Linux Security Tips

Linux security requires a multi-layered approach combining system hardening, proper configuration, and proactive monitoring. In this comprehensive guide, you'll learn ten essential security practices that form the foundation of a robust Linux security posture.

QuantumBytz Editorial Team
January 17, 2026
Share:
Illustration of Linux security featuring the Tux penguin beside a digital padlock and glowing circuit patterns, symbolizing secure Linux systems, encryption, and cybersecurity protection.

Top 10 Best Linux Security Tips: A Complete Guide to Securing Your Linux System

Introduction

Linux security requires a multi-layered approach combining system hardening, proper configuration, and proactive monitoring. In this comprehensive guide, you'll learn ten essential security practices that form the foundation of a robust Linux security posture. These techniques will help you protect your systems against common attack vectors, secure network communications, and maintain system integrity through proper access controls and monitoring.

By implementing these security measures, you'll significantly reduce your system's attack surface while maintaining optimal performance and functionality.

Prerequisites

Before implementing these security configurations, ensure you have:

  • Root or sudo access to your Linux system
  • Basic command-line proficiency
  • computing" title="Understanding Quantum Supremacy: What It Means for Enterprise Computing" class="internal-link">supremacy-enterprise-computing" title="Understanding Quantum Supremacy: What It Means for Enterprise Computing" class="internal-link">Understanding of Linux file permissions and user management
  • Familiarity with text editors like vim or nano
  • Network connectivity for package installations
  • Backup of critical system configurations

Overview

Linux security encompasses multiple domains: access control, network security, system hardening, monitoring, and incident response. Each security tip addresses specific vulnerabilities while working together to create a comprehensive defense strategy. These practices are applicable across major Linux distributions including Ubuntu, CentOS, RHEL, and Debian.

The security measures covered range from fundamental practices like securing SSH access to advanced techniques such as implementing mandatory access controls with SELinux or AppArmor.

Step-by-Step Guide

1. Secure SSH Configuration

SSH is often the primary remote access vector, making its security configuration critical for system protection.

Start by editing the SSH daemon configuration:

sudo nano /etc/ssh/sshd_config

Implement these essential SSH security settings:

# Change default port to reduce automated attacks
Port 2022

# Disable root login
PermitRootLogin no

# Limit user access
AllowUsers username1 username2
AllowGroups ssh-users

# Disable password authentication (use keys only)
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey

# Reduce login grace time
LoginGraceTime 30

# Limit connection attempts
MaxAuthTries 3
MaxSessions 2

# Disable X11 forwarding if not needed
X11Forwarding no

# Use strong ciphers and key exchange algorithms
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group16-sha512
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com

Generate and deploy SSH keys:

# On client machine
ssh-keygen -t ed25519 -b 4096 -C "your_email@domain.com"

# Copy public key to server
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ip -p 2022

Restart SSH service and test connectivity:

sudo systemctl restart sshd
sudo systemctl enable sshd

2. Configure and Optimize Linux Firewall

A properly configured firewall provides the first line of defense against network-based attacks.

Using UFW (Uncomplicated Firewall):

# Enable UFW
sudo ufw enable

# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH on custom port
sudo ufw allow 2022/tcp

# Allow specific services
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 25/tcp

# Allow from specific IP ranges
sudo ufw allow from 192.168.1.0/24 to any port 22

# Limit SSH connections to prevent brute force
sudo ufw limit 2022/tcp

# Check status
sudo ufw status verbose

Using iptables for Advanced Configuration:

# Create iptables rules file
sudo nano /etc/iptables/rules.v4

# Basic iptables ruleset
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]

# Allow loopback traffic
-A INPUT -i lo -j ACCEPT

# Allow established connections
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Allow SSH with rate limiting
-A INPUT -p tcp --dport 2022 -m conntrack --ctstate NEW -m recent --set
-A INPUT -p tcp --dport 2022 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
-A INPUT -p tcp --dport 2022 -j ACCEPT

# Allow HTTP/HTTPS
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

# Drop invalid packets
-A INPUT -m conntrack --ctstate INVALID -j DROP

# Log dropped packets
-A INPUT -j LOG --log-prefix "iptables-dropped: " --log-level 4
-A INPUT -j DROP

COMMIT

Apply iptables rules:

sudo iptables-restore < /etc/iptables/rules.v4
sudo systemctl enable netfilter-persistent

3. Implement Strong User Account Security

User account management forms the foundation of system access control.

Create secure user accounts:

# Create user with specific home directory permissions
sudo useradd -m -d /home/username -s /bin/bash username
sudo chmod 750 /home/username

# Set strong password policy
sudo nano /etc/security/pwquality.conf

Configure password quality requirements:

# Minimum password length
minlen = 12

# Require mixed case, numbers, and special characters
minclass = 4
maxrepeat = 2
maxsequence = 3

# Dictionary check
dictcheck = 1

# Password history
remember = 5

Set account lockout policies:

sudo nano /etc/security/faillock.conf
# Lock account after failed attempts
deny = 5

# Lockout duration (seconds)
unlock_time = 900

# Audit interval
audit

# Log failed attempts
silent

Configure sudo access properly:

sudo visudo
# Allow specific commands only
username ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/systemctl status nginx

# Require password re-entry
Defaults:username timestamp_timeout=0

# Log all sudo commands
Defaults logfile="/var/log/sudo.log"
Defaults log_input, log_output

4. Enable and Configure System Auditing

System auditing provides visibility into system activities and potential security violations.

Install and configure auditd:

sudo apt install auditd audispd-plugins
sudo systemctl enable auditd

Configure audit rules:

sudo nano /etc/audit/rules.d/audit.rules
# Delete all existing rules
-D

# Buffer size
-b 8192

# Failure mode (0=silent 1=printk 2=panic)
-f 1

# Monitor file access
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/group -p wa -k group_changes
-w /etc/sudoers -p wa -k sudoers_changes

# Monitor system calls
-a always,exit -F arch=b64 -S adjtimex,settimeofday,clock_settime -k time_change
-a always,exit -F arch=b32 -S adjtimex,settimeofday,stime,clock_settime -k time_change

# Monitor login/logout events
-w /var/log/lastlog -p wa -k logins
-w /var/log/wtmp -p wa -k session
-w /var/log/btmp -p wa -k session

# Monitor privilege escalation
-a always,exit -F arch=b64 -S setuid,setgid,setreuid,setregid -k privilege_escalation
-a always,exit -F arch=b32 -S setuid,setgid,setreuid,setregid -k privilege_escalation

# Monitor network configuration changes
-a always,exit -F arch=b64 -S sethostname,setdomainname -k network_modifications
-a always,exit -F arch=b32 -S sethostname,setdomainname -k network_modifications

# Make rules immutable
-e 2

Restart auditd and verify configuration:

sudo systemctl restart auditd
sudo auditctl -l

5. Secure Nginx with Best Practices

Web server security is crucial for protecting web applications and preventing common attacks.

Configure secure Nginx settings:

sudo nano /etc/nginx/nginx.conf
# Hide nginx version
server_tokens off;

# Security headers configuration
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;

# Rate limiting
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

# SSL/TLS configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;

Create a secure server block:

sudo nano /etc/nginx/sites-available/secure-site
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;
    
    # SSL certificate paths
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    
    # Rate limiting
    limit_req zone=login burst=5 nodelay;
    limit_conn addr 10;
    
    # Disable unnecessary HTTP methods
    if ($request_method !~ ^(GET|HEAD|POST)$) {
        return 405;
    }
    
    # Block common attack patterns
    location ~* /(wp-admin|admin|phpmyadmin) {
        deny all;
    }
    
    # Secure file upload handling
    location ~* \.(php|jsp|asp|sh|py|pl|exe)$ {
        deny all;
    }
    
    # Main location block
    location / {
        try_files $uri $uri/ =404;
        
        # Additional security headers for this location
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    }
    
    # Error pages
    error_page 403 404 /error.html;
    location = /error.html {
        internal;
    }
}

6. Implement ModSecurity Web Application Firewall

ModSecurity provides application-layer protection against web-based attacks.

Install ModSecurity for Nginx:

sudo apt install nginx-module-modsecurity

Load the module in nginx.conf:

load_module modules/ngx_http_modsecurity_module.so;

Configure ModSecurity:

sudo mkdir -p /etc/nginx/modsecurity
sudo nano /etc/nginx/modsecurity/modsecurity.conf
# Enable ModSecurity
SecRuleEngine On

# Request body handling
SecRequestBodyAccess On
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
SecRequestBodyInMemoryLimit 131072
SecRequestBodyLimitAction Reject

# Response body handling
SecResponseBodyAccess On
SecResponseBodyMimeType text/plain text/html text/xml application/json
SecResponseBodyLimit 524288
SecResponseBodyLimitAction ProcessPartial

# File uploads
SecTmpDir /tmp/
SecDataDir /var/cache/modsecurity/
SecUploadDir /var/cache/modsecurity/upload/

# Debug logging
SecDebugLog /var/log/nginx/modsecurity_debug.log
SecDebugLogLevel 0

# Audit logging
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
SecAuditLogParts ABDEFHIJZ
SecAuditLogType Serial
SecAuditLog /var/log/nginx/modsecurity_audit.log

# OWASP Core Rule Set
Include /etc/nginx/modsecurity/owasp-crs/*.conf

Download and configure OWASP Core Rule Set:

cd /etc/nginx/modsecurity/
sudo wget https://github.com/coreruleset/coreruleset/archive/v3.3.4.tar.gz
sudo tar -xzf v3.3.4.tar.gz
sudo mv coreruleset-3.3.4 owasp-crs
sudo cp owasp-crs/crs-setup.conf.example owasp-crs/crs-setup.conf

Enable ModSecurity in Nginx virtual host:

server {
    # ... other configuration ...
    
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
    
    # ... rest of configuration ...
}

7. Configure Automatic Security Updates

Keeping the system updated is crucial for maintaining security against known vulnerabilities.

Configure unattended upgrades on Debian/Ubuntu:

sudo apt install unattended-upgrades apt-listchanges
sudo dpkg-reconfigure -plow unattended-upgrades

Configure automatic updates:

sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-security";
    "${distro_id}:${distro_codename}-updates";
};

# Automatically reboot if necessary
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";

# Email notifications
Unattended-Upgrade::Mail "admin@example.com";
Unattended-Upgrade::MailOnlyOnError "true";

# Remove unused dependencies
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Remove-New-Unused-Dependencies "true";

# Logging
Unattended-Upgrade::SyslogEnable "true";
Unattended-Upgrade::SyslogFacility "daemon";

For CentOS/RHEL, configure yum-cron:

sudo yum install yum-cron
sudo nano /etc/yum/yum-cron.conf
[commands]
update_cmd = security
update_messages = yes
download_updates = yes
apply_updates = yes

[emitters]
system_name = production-server
emit_via = email
email_from = root@localhost
email_to = admin@example.com
email_host = localhost

[base]
debuglevel = -2
mdpolicy = group:main

8. Implement File Integrity Monitoring

File integrity monitoring detects unauthorized changes to critical system files.

Install and configure AIDE (Advanced Intrusion Detection Environment):

sudo apt install aide

Initialize AIDE database:

sudo aideinit
sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

Configure AIDE rules:

sudo nano /etc/aide/aide.conf
# Define what to check
All = p+i+n+u+g+s+m+S+md5+sha1+sha256+rmd160+tiger+haval+gost+crc32+acl+xattrs+selinux

# Define directories and files to monitor
/boot                   All
/bin                    All
/sbin                   All
/lib                    All
/lib64                  All
/opt                    All
/usr                    All
/etc                    All

# Exclude log files and temporary directories
!/var/log
!/var/spool
!/var/run
!/tmp
!/proc
!/sys
!/dev

# Monitor specific configuration files
/etc/passwd             All
/etc/shadow             All
/etc/group              All
/etc/sudoers            All
/etc/ssh/sshd_config    All

Create automated AIDE checking:

sudo nano /usr/local/bin/aide-check.sh
#!/bin/bash

LOGFILE="/var/log/aide-check.log"
EMAIL="admin@example.com"

# Run AIDE check
/usr/bin/aide --check > $LOGFILE 2>&1

# Check if there are changes
if [ $? -ne 0 ]; then
    # Send email notification
    mail -s "AIDE Alert: File integrity violations detected on $(hostname)" $EMAIL < $LOGFILE
fi

# Rotate logs
if [ -f "$LOGFILE.old" ]; then
    rm "$LOGFILE.old"
fi

if [ -f "$LOGFILE" ]; then
    mv "$LOGFILE" "$LOGFILE.old"
fi

Schedule regular AIDE checks:

sudo crontab -e
# Run AIDE check daily at 3 AM
0 3 * * * /usr/local/bin/aide-check.sh

9. Secure Network Services and Ports

Minimize attack surface by securing or disabling unnecessary network services.

Scan and identify running services:

# Check listening ports
sudo netstat -tlnp
sudo ss -tlnp

# Check enabled services
sudo systemctl list-unit-files --type=service --state=enabled

Disable unnecessary services:

# Common services that may not be needed
sudo systemctl disable bluetooth
sudo systemctl disable cups
sudo systemctl disable avahi-daemon
sudo systemctl disable rpcbind

# Stop services immediately
sudo systemctl stop bluetooth cups avahi-daemon rpcbind

Secure remaining services with systemd restrictions:

sudo mkdir -p /etc/systemd/system/nginx.service.d/
sudo nano /etc/systemd/system/nginx.service.d/security.conf
[Service]
# Security restrictions
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/log/nginx /var/cache/nginx /run
PrivateTmp=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictRealtime=true
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM

Configure TCP Wrappers for additional service protection:

sudo nano /etc/hosts.allow
# Allow SSH from specific networks
sshd: 192.168.1.0/24
sshd: 10.0.0.0/8

# Allow local connections
ALL: 127.0.0.1
sudo nano /etc/hosts.deny
# Deny all other connections
ALL: ALL

10. Enable SELinux or AppArmor Mandatory Access Control

Mandatory Access Control provides additional security layers beyond traditional DAC permissions.

For RHEL/CentOS (SELinux):

Check SELinux status:

getenforce
sestatus

Set SELinux to enforcing mode:

sudo nano /etc/selinux/config
SELINUX=enforcing
SELINUXTYPE=targeted

Common SELinux management commands:

# Check context of files
ls -Z /var/www/html/

# Set proper contexts
sudo setsebool -P httpd_can_network_connect 1
sudo setsebool -P httpd_can_network_relay 1

# Restore default contexts
sudo restorecon -Rv /var/www/html/

# View SELinux denials
sudo ausearch -m avc -ts recent

For Ubuntu/Debian (AppArmor):

Check AppArmor status:

sudo aa-status

Install additional profiles:

sudo apt install apparmor-profiles apparmor-utils

Put profiles in enforce mode:

sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx
sudo aa-enforce /etc/apparmor.d/usr.sbin.mysqld

Create custom AppArmor profile:

sudo nano /etc/apparmor.d/usr.local.bin.custom-app
#include <tunables/global>

/usr/local/bin/custom-app {
  #include <abstractions/base>
  #include <abstractions/nameservice>

  # Allow execution
  /usr/local/bin/custom-app mr,

  # Allow specific file access
  /etc/custom-app/** r,
  /var/lib/custom-app/** rw,
  /var/log/custom-app/** w,
  
  # Network access
  network inet tcp,
  network inet udp,

  # Deny everything else
  deny /home/** rw,
  deny /root/** rw,
}

Load and enforce the profile:

sudo apparmor_parser -r /etc/apparmor.d/usr.local.bin.custom-app
sudo aa-enforce usr.local.bin.custom-app

Verification

Verify your security implementations with these checks:

SSH Security Verification:

# Test SSH configuration
sudo sshd -t

# Verify SSH is listening on custom port
sudo netstat -tlnp | grep :2022

# Test key-based authentication
ssh -p 2022 username@localhost

Firewall Verification:

# Check UFW status
sudo ufw status numbered

# Test iptables rules
sudo iptables -L -n -v

Service Security Verification:

# Verify disabled services
sudo systemctl is-enabled bluetooth cups avahi-daemon

# Check listening services
sudo ss -tlnp | grep -E ':(22|80|443|25)'

Audit System Verification:

# Check audit daemon status
sudo systemctl status auditd

# Verify audit rules
sudo auditctl -l

# Test audit logging
sudo ausearch -k passwd_changes

File Integrity Verification:

# Manual AIDE check
sudo aide --check

# Verify AIDE database
ls -la /var/lib/aide/

Troubleshooting Common Issues

SSH Connection Issues:

If SSH connections fail after configuration changes:

# Check SSH daemon status
sudo systemctl status sshd

# Review SSH logs
sudo tail -f /var/log/auth.log

# Test configuration without restarting
sudo sshd -t

# Emergency access via console if locked out
sudo systemctl restart sshd

Firewall Blocking Services:

If legitimate traffic is blocked:

# Temporarily disable UFW
sudo ufw --force reset

# Check iptables rules causing issues
sudo iptables -L -n --line-numbers

# Remove specific iptables rule
sudo iptables -D INPUT 3

SELinux/AppArmor Denials:

If applications fail due to MAC policies:

# For SELinux - check audit logs
sudo ausearch -m avc -ts recent

# Set SELinux to permissive temporarily
sudo setenforce 0

# For AppArmor - check logs
sudo dmesg | grep -i apparmor

# Put profile in complain mode
sudo aa-complain /etc/apparmor.d/profile-name

Performance Issues After Security Changes:

If system performance degrades:

# Check system load
top
htop

# Monitor audit overhead
sudo auditctl -s

# Reduce audit rules if necessary
sudo auditctl -D

# Check ModSecurity logs for excessive blocking
tail -f /var/log/nginx/modsecurity_audit.log

Best Practices

Regular Security Maintenance:

  • Review security logs weekly
  • Update security configurations quarterly
  • Test backup and recovery procedures monthly
  • Conduct security assessments annually

Monitoring and Alerting:

  • Set up centralized logging with rsyslog or journald
  • Configure email alerts for critical security events
  • Monitor failed authentication attempts
  • Track privilege escalation activities

Documentation and Change Management:

  • Document all security configurations
  • Maintain change logs for security modifications
  • Test changes in non-production environments first
  • Create rollback procedures for each security control

Principle of Least Privilege:

  • Grant minimum necessary permissions
  • Use role-based access controls where possible
  • Regularly audit user permissions and access
  • Remove unused accounts and services promptly

Defense in Depth:

  • Implement multiple security layers
  • Don't rely on single security controls
  • Plan for security control failures
  • Maintain offline backups of critical data

Key Takeaways

• SSH security forms the foundation of remote access protection - disable root login, use key-based authentication, and change default ports • Firewall configuration should follow default-deny policies with specific allow rules for required services only • Strong user account security includes complex passwords, account lockout policies, and proper sudo configuration • System auditing with auditd provides essential visibility into system activities and potential security violations • Web server security requires multiple layers including secure SSL/TLS configuration, security headers, and rate limiting • ModSecurity Web Application Firewall adds crucial protection against application-layer attacks and OWASP Top 10 vulnerabilities • Automatic security updates ensure systems remain protected against known vulnerabilities without manual intervention • File integrity monitoring with AIDE detects unauthorized changes to critical system files and configurations • Network service hardening involves disabling unnecessary services and implementing systemd security restrictions • Mandatory Access Control through SELinux or AppArmor provides additional security beyond traditional file permissions

QuantumBytz Editorial Team

The QuantumBytz Editorial Team covers cutting-edge computing infrastructure, including quantum computing, AI systems, Linux performance, HPC, and enterprise tooling. Our mission is to provide accurate, in-depth technical content for infrastructure professionals.

Learn more about our editorial team