Debian Security Best Practices
Introduction
Debian is renowned for its stability and security in the Linux world. However, no system is inherently secure without proper configuration and maintenance. This guide introduces essential security practices for Debian systems, helping beginners understand how to protect their installations from common threats and vulnerabilities.
Security is not a one-time setup but an ongoing process. By implementing the practices outlined in this guide, you'll establish a strong security foundation for your Debian system and develop habits that contribute to maintaining that security over time.
Core Security Principles
Before diving into specific configurations, let's understand the fundamental principles of system security:
- Principle of Least Privilege: Grant only the permissions necessary for users and services to function
- Defense in Depth: Implement multiple layers of security
- Keep It Simple: Complex configurations can introduce security vulnerabilities
- Stay Updated: Security is an ongoing process, not a one-time setup
Keeping Your System Updated
Setting Up Automatic Updates
One of the most crucial security practices is keeping your system updated with the latest security patches.
# Install the unattended-upgrades package
sudo apt update
sudo apt install unattended-upgrades apt-listchanges
# Enable automatic updates
sudo dpkg-reconfigure -plow unattended-upgrades
This will create a basic configuration file at /etc/apt/apt.conf.d/20auto-upgrades
that enables automatic security updates.
Configuring Security Updates
Edit the configuration file to fine-tune your automatic update settings:
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
Ensure security updates are enabled by uncommenting the security line:
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}";
"${distro_id}:${distro_codename}-security";
// "${distro_id}:${distro_codename}-updates";
// "${distro_id}:${distro_codename}-proposed";
// "${distro_id}:${distro_codename}-backports";
};
Checking Update Status
Verify that automatic updates are working correctly:
sudo unattended-upgrade --dry-run --debug
Output will show which packages would be upgraded during a real run:
Initial blacklisted packages:
Starting unattended upgrades script
Allowed origins are: ['origin=Debian,codename=bookworm,label=Debian', 'origin=Debian,codename=bookworm,label=Debian-Security']
Checking: python3-software-properties (local=0.99.22, remote=0.99.22)
Checking: software-properties-common (local=0.99.22, remote=0.99.22)
No packages found that can be upgraded unattended and no pending auto-removals
Securing SSH Access
SSH (Secure Shell) is often the primary way to access servers remotely. Securing it is essential.
SSH Configuration Best Practices
Edit the SSH configuration file:
sudo nano /etc/ssh/sshd_config
Apply these recommended settings:
# Disable root login
PermitRootLogin no
# Disable password authentication (use SSH keys instead)
PasswordAuthentication no
# Limit user access
AllowUsers username1 username2
# Change default port (optional but adds security through obscurity)
Port 2222
# Limit login attempts
MaxAuthTries 3
# Enable strict mode
StrictModes yes
# Use strong encryption protocols
Protocol 2
After making changes, restart the SSH service:
sudo systemctl restart ssh
Setting Up SSH Key Authentication
Generate an SSH key pair on your client machine:
ssh-keygen -t ed25519 -C "[email protected]"
Copy the public key to your Debian server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ip
Now you can log in without a password:
ssh username@server_ip
Firewall Configuration
A properly configured firewall helps control incoming and outgoing network traffic.
Setting Up UFW (Uncomplicated Firewall)
UFW is a user-friendly interface for managing iptables. Install and configure it with:
# Install UFW
sudo apt update
sudo apt install ufw
# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (use your custom port if you changed it)
sudo ufw allow 22/tcp
# Allow other necessary services
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
# Enable the firewall
sudo ufw enable
Checking Firewall Status
Verify your firewall rules:
sudo ufw status verbose
Output example:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp ALLOW IN Anywhere
80/tcp ALLOW IN Anywhere
443/tcp ALLOW IN Anywhere
22/tcp (v6) ALLOW IN Anywhere (v6)
80/tcp (v6) ALLOW IN Anywhere (v6)
443/tcp (v6) ALLOW IN Anywhere (v6)
User Account Security
Properly managing user accounts is crucial for system security.
Creating Strong Password Policies
Install the libpam-pwquality package to enforce password policies:
sudo apt install libpam-pwquality
Edit the PAM configuration:
sudo nano /etc/pam.d/common-password
Add or modify the line with pam_pwquality.so:
password requisite pam_pwquality.so retry=3 minlen=12 difok=3 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 reject_username enforce_for_root
This configuration:
- Sets minimum password length to 12 characters
- Requires at least 1 uppercase, 1 lowercase, 1 digit, and 1 special character
- Prevents using parts of the username in the password
- Applies these rules to the root user as well
Managing Sudo Access
Review and restrict sudo access to only those who need it:
sudo visudo
Example of restricted sudo access:
# Allow specific commands for user "webadmin"
webadmin ALL=(ALL) /usr/bin/systemctl restart apache2, /usr/bin/systemctl restart nginx
File System Security
Securing your file system prevents unauthorized access to sensitive data.
Setting Proper File Permissions
Check and fix permissions for important directories:
# Set secure permissions for configuration files
sudo find /etc -type f -exec chmod 644 {} \;
# Set secure permissions for home directories
sudo chmod 750 /home/*
# Set secure permissions for system binaries
sudo find /usr/bin -type f -exec chmod 755 {} \;
Mounting Partitions with Security Options
Edit your /etc/fstab
file to add security options to mounted partitions:
sudo nano /etc/fstab
Add these options to enhance security:
# Example: Add noexec, nosuid, and nodev to /tmp
UUID=xxxxx-xxxxx /tmp ext4 defaults,noexec,nosuid,nodev 0 2
These options:
noexec
: Prevents execution of binaries on the partitionnosuid
: Ignores the SUID/SGID bits on executable filesnodev
: Prevents interpretation of character or block special devices
Monitoring and Logging
Proper monitoring helps detect potential security incidents.
Setting Up System Logging
Install and configure the rsyslog service:
sudo apt install rsyslog
sudo systemctl enable rsyslog
sudo systemctl start rsyslog
Configure log rotation to prevent logs from consuming all disk space:
sudo nano /etc/logrotate.conf
Example configuration:
# Rotate logs weekly
weekly
# Keep 4 weeks worth of logs
rotate 4
# Create new log files after rotation
create
# Compress old logs
compress
Installing and Configuring Fail2Ban
Fail2Ban helps protect against brute force attacks:
sudo apt install fail2ban
Create a custom jail configuration:
sudo nano /etc/fail2ban/jail.local
Example configuration for SSH protection:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
Start and enable Fail2Ban:
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
Check status with:
sudo fail2ban-client status sshd
Output example:
Status for the jail: sshd
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| `- Journal matches: _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
|- Currently banned: 0
|- Total banned: 0
`- Banned IP list:
Package Management Security
Ensuring the authenticity of packages is essential for system security.
Using Secure APT Sources
Only use official Debian repositories or trusted third-party repositories. Edit your sources list:
sudo nano /etc/apt/sources.list
Example of a secure sources.list file:
deb http://deb.debian.org/debian bookworm main contrib non-free-firmware
deb http://security.debian.org/debian-security bookworm-security main contrib non-free-firmware
deb http://deb.debian.org/debian bookworm-updates main contrib non-free-firmware
Verifying Package Integrity
Always verify the signatures of packages you download:
# Update the list of available packages and their versions
sudo apt update
# Install debian-keyring which contains the Debian developers' keys
sudo apt install debian-keyring
# Verify package signatures when installing
sudo apt install -V package_name
Security Auditing
Regular security audits help identify potential vulnerabilities.
Using Lynis for Security Auditing
Lynis is an open-source security auditing tool:
# Install Lynis
sudo apt install lynis
# Run a system audit
sudo lynis audit system
The output will provide a detailed security report with recommendations:
[+] Finalizing
--------------------------------------------------------------------------------
Tests finished at 2023-10-05 14:32:25
Lynis security scan details:
- Hardening index : 65 [################## ]
- Tests performed : 231
- Plugins enabled : 0
Want more details? Full report at:
- /var/log/lynis.log
- /var/log/lynis-report.dat
Regular Security Checks with Rkhunter
Rkhunter (Rootkit Hunter) scans for rootkits, backdoors, and local exploits:
# Install Rkhunter
sudo apt install rkhunter
# Update Rkhunter database
sudo rkhunter --update
# Perform a system check
sudo rkhunter --check
Example output:
System checks summary
=====================
File properties checks...
Required commands check failed
Files checked: 147
Suspect files: 0
Rootkit checks...
Rootkits checked : 492
Possible rootkits: 0
Applications checks...
All checks skipped
The system checks took: 1 minute and 13 seconds
Network Security
Securing network services reduces the attack surface of your system.
Disabling Unnecessary Network Services
Identify and disable unused network services:
# List all listening services
sudo ss -tulpn
# Disable an unnecessary service
sudo systemctl disable service_name
sudo systemctl stop service_name
Example of disabling the telnet service:
sudo apt purge telnetd
Implementing Network Access Controls
Configure TCP Wrappers to control access to network services:
sudo nano /etc/hosts.allow
Add rules to allow specific hosts:
# Allow SSH access only from specific IP addresses
sshd: 192.168.1.0/24
Then deny all other connections in /etc/hosts.deny
:
sudo nano /etc/hosts.deny
# Deny all other connections
ALL: ALL
System Hardening with Security Frameworks
Debian supports various security frameworks that can enhance system security.
Implementing AppArmor
AppArmor is a Mandatory Access Control (MAC) system:
# Install AppArmor
sudo apt install apparmor apparmor-utils apparmor-profiles
# Enable AppArmor at boot
sudo systemctl enable apparmor
sudo systemctl start apparmor
# Check status
sudo aa-status
Example output:
apparmor module is loaded.
20 profiles are loaded.
19 profiles are in enforce mode.
1 profiles are in complain mode.
0 processes have profiles defined.
0 processes are in enforce mode.
0 processes are in complain mode.
0 processes are unconfined but have a profile defined.
Setting Up SELinux (Alternative to AppArmor)
SELinux provides an alternative MAC framework:
# Install SELinux
sudo apt install selinux-basics selinux-policy-default
# Enable SELinux
sudo selinux-activate
# Reboot to apply changes
sudo reboot
After rebooting, check the SELinux status:
sudo sestatus
Example output:
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: default
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Memory protection checking: actual (secure)
Max kernel policy version: 31
Summary
Securing a Debian system requires a comprehensive approach that includes:
- Keeping your system updated with security patches
- Properly configuring SSH access
- Setting up and maintaining a firewall
- Implementing strong user account security
- Securing the file system
- Configuring monitoring and logging
- Using secure package management practices
- Performing regular security audits
- Securing network services
- Implementing security frameworks like AppArmor or SELinux
Security is an ongoing process, not a one-time setup. Regularly review your security practices and keep your knowledge up to date with the latest security recommendations for Debian.
Additional Resources
Practice Exercises
-
Basic Security Audit:
- Install and run Lynis on your system
- Address at least three security issues identified by the scan
-
SSH Hardening:
- Configure SSH to use key-based authentication
- Disable root login and password authentication
- Implement Fail2Ban to protect against brute force attacks
-
Firewall Configuration:
- Install and configure UFW
- Create rules to allow only necessary services
- Test your configuration to ensure it blocks unauthorized access
-
User Security:
- Review all user accounts on your system
- Implement strong password policies
- Configure proper sudo access restrictions
-
Security Monitoring:
- Set up log monitoring for important security events
- Configure automated alerts for suspicious activities
- Implement regular log review procedures
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)