🔒Security & Privacy⭐ Featured

Secure your Ubuntu 24.04 installation: Complete Security Hardening Guide

Comprehensive step-by-step guide to hardening Ubuntu 24.04 LTS with SSH security, UFW firewall, fail2ban, AppArmor 4.0, kernel hardening, and advanced security measures for production servers.

Published January 16, 2025
8 min read
By Toolsana Team

Ubuntu 24.04 LTS "Noble Numbat" brings impressive security improvements, but a fresh installation still needs proper hardening to face real-world threats. After managing Ubuntu servers in production for years, I've learned that security is about creating layers of protection that work together seamlessly.

This guide walks you through securing your Ubuntu 24.04 system from initial setup to advanced hardening. Whether you're running a home server or production infrastructure, these techniques will significantly strengthen your security posture.

Getting Started with System Updates

Before diving into security configurations, let's ensure your system is up to date. This initial step addresses any vulnerabilities discovered since your installation media was created.

sudo apt update && sudo apt upgrade -y
sudo apt install ufw fail2ban unattended-upgrades apt-listchanges

These packages form your security foundation: UFW for firewall management, fail2ban for intrusion prevention, and unattended-upgrades for automatic security updates.

Creating a Secure SSH Setup

One of the most critical steps is setting up secure SSH access. Instead of using your default user account, let's create a dedicated SSH user following the principle of least privilege.

sudo adduser sshuser
sudo usermod -aG sudo sshuser

Now switch to this new user and set up SSH key authentication. This is far more secure than password-based login:

su - sshuser
mkdir -p ~/.ssh && chmod 700 ~/.ssh

Generate your SSH key pair on your local machine (not the server):

ssh-keygen -t ed25519 -C "your-email@example.com"
ssh-copy-id -i ~/.ssh/your-key-name.pub sshuser@your-server-ip

Test the key-based authentication before proceeding. Once confirmed working, it's time to harden the SSH configuration itself.

Hardening SSH Configuration

Open the SSH configuration file and make these essential changes:

sudo nano /etc/ssh/sshd_config

Here's what needs to be configured for security:

PermitRootLogin no
PasswordAuthentication no
AllowUsers sshuser
ClientAliveInterval 300
ClientAliveCountMax 2
MaxAuthTries 3
MaxSessions 2

These settings disable root login, force key-based authentication, restrict access to your SSH user only, and automatically disconnect idle sessions. The MaxAuthTries setting limits failed login attempts, while MaxSessions prevents resource exhaustion from too many concurrent connections.

Test your configuration before restarting:

sudo sshd -t
sudo systemctl restart ssh

Always keep your current SSH session open while testing to avoid locking yourself out.

Setting Up UFW Firewall

Ubuntu's UFW makes firewall management straightforward. Before enabling it, configure the basic rules to avoid accidentally blocking yourself:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

If you changed your SSH port, adjust accordingly. For additional security, you can limit SSH connections to prevent brute force attacks:

sudo ufw limit ssh
sudo ufw enable

Check your firewall status to confirm everything is working:

sudo ufw status verbose

Configuring Fail2ban Protection

Fail2ban monitors your log files and automatically blocks IPs showing malicious behavior. Start by copying the default configuration:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

Configure the essential settings in the DEFAULT section:

[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
destemail = your-email@example.com

[sshd]
enabled = true

If you're running web services, enable additional jails for comprehensive protection. For Apache or Nginx servers, enable the respective jails by setting enabled = true in their sections.

Start and enable the service:

sudo systemctl enable fail2ban
sudo systemctl start fail2ban
sudo fail2ban-client status

Automating Security Updates

Keeping your system updated is perhaps the most important ongoing security task. Configure unattended upgrades to handle security updates automatically:

sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

Ensure these lines are uncommented for security updates:

"${distro_id}:${distro_codename}-security";

Configure the update behavior:

Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Mail "your-email@example.com";
Unattended-Upgrade::MailOnlyOnError "true";

Set the update frequency:

sudo nano /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

Test your configuration with a dry run:

sudo unattended-upgrades --dry-run --debug

Leveraging AppArmor 4.0

Ubuntu 24.04 includes AppArmor 4.0, which provides mandatory access control to limit application capabilities. Check your current AppArmor status:

sudo aa-status

Most profiles should be in "enforce" mode for maximum security. Install additional profiles for better coverage:

sudo apt install apparmor-utils apparmor-profiles apparmor-profiles-extra

If applications aren't working correctly due to AppArmor restrictions, check the logs rather than disabling protection:

sudo dmesg | grep -i apparmor
sudo journalctl -f | grep -i apparmor

For troubleshooting, you can put problematic profiles in complain mode temporarily:

sudo aa-complain /path/to/profile

Kernel Security Hardening

The Linux kernel has numerous security parameters that can be tuned to resist various attacks. Edit the kernel parameters file:

sudo nano /etc/sysctl.conf

Add these security-focused settings:

# IP spoofing protection
net.ipv4.conf.default.rp_filter=1
net.ipv4.conf.all.rp_filter=1

# Disable ICMP redirects
net.ipv4.conf.all.accept_redirects=0
net.ipv4.conf.default.accept_redirects=0
net.ipv6.conf.all.accept_redirects=0
net.ipv6.conf.default.accept_redirects=0

# SYN flood protection
net.ipv4.tcp_syncookies=1

# Disable source routing
net.ipv4.conf.all.accept_source_route=0
net.ipv6.conf.all.accept_source_route=0

# Additional hardening
kernel.dmesg_restrict=1
net.ipv4.conf.all.log_martians=1
net.ipv4.icmp_ignore_bogus_error_responses=1

Apply these changes immediately:

sudo sysctl -p

Strengthening User Account Security

Review all user accounts with shell access and remove unnecessary ones:

cat /etc/passwd | grep -E "/bin/(bash|sh)$"

Configure password policies by editing the PAM configuration:

sudo nano /etc/pam.d/common-password

Find the line containing pam_unix.so and add complexity requirements:

password [success=1 default=ignore] pam_unix.so obscure sha512 minlen=12 lcredit=-1 ucredit=-1 dcredit=-1 ocredit=-1

Set password aging policies for your users:

sudo chage -M 90 -m 7 -W 14 sshuser

This sets a maximum password age of 90 days, minimum age of 7 days between changes, and 14-day warning period before expiration.

Setting Up Two-Factor Authentication

For additional security, implement two-factor authentication for SSH access. Install the Google Authenticator PAM module:

sudo apt install libpam-google-authenticator

Configure it for your SSH user:

google-authenticator

Answer "y" to time-based tokens, "y" to update your .google_authenticator file, "y" to disallow multiple uses, "n" to skip rate limiting, and "y" to enable time skew.

Edit the PAM SSH configuration:

sudo nano /etc/pam.d/sshd

Add this line:

auth required pam_google_authenticator.so

Update the SSH configuration to enable challenge-response authentication:

sudo nano /etc/ssh/sshd_config

Set:

ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive

Restart SSH and test the two-factor authentication from a new session.

System Monitoring and Auditing

Install and configure audit logging for comprehensive system monitoring:

sudo apt install auditd audispd-plugins
sudo systemctl enable auditd

Configure basic audit rules:

sudo nano /etc/audit/rules.d/audit.rules

Add these essential monitoring rules:

# Monitor authentication events
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/group -p wa -k group_changes

# Monitor sudo usage
-w /etc/sudoers -p wa -k sudoers_changes
-w /var/log/sudo.log -p wa -k sudo_log_changes

# Monitor SSH configuration
-w /etc/ssh/sshd_config -p wa -k ssh_config_changes

Restart auditd to apply the rules:

sudo systemctl restart auditd

Install additional security tools for regular system auditing:

sudo apt install lynis rkhunter chkrootkit

Run periodic security scans:

sudo lynis audit system
sudo rkhunter --check
sudo chkrootkit

Network Security Enhancements

For additional network protection, consider implementing DDoS protection and rate limiting. Configure connection tracking limits:

sudo nano /etc/sysctl.conf

Add these network security parameters:

# Connection tracking
net.netfilter.nf_conntrack_max = 2000000
net.netfilter.nf_conntrack_tcp_timeout_established = 7440
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120

# Rate limiting
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216

If you're running web services, configure rate limiting in your web server to complement fail2ban protection.

Regular Maintenance and Monitoring

Security is an ongoing process, not a one-time setup. Create a regular maintenance routine that includes:

Check system updates weekly, review fail2ban logs monthly, audit user accounts quarterly, and update your security configurations as needed. Set up log monitoring with tools like logwatch to receive daily security summaries:

sudo apt install logwatch
sudo nano /etc/cron.daily/00logwatch

Configure logwatch to email you daily reports of security-relevant events.

Backup Security Considerations

Don't forget to secure your backup strategy. If you're using automated backups, ensure they're encrypted and stored securely. Consider using tools like restic or duplicity for encrypted, deduplicated backups:

sudo apt install restic

Set up encrypted backups to remote storage with proper access controls and regular restore testing.

Conclusion

Securing Ubuntu 24.04 requires a layered approach combining system hardening, access controls, monitoring, and regular maintenance. The configurations outlined here provide a solid foundation for most environments, but remember that security needs vary based on your specific use case.

Start with the essential steps like SSH hardening, firewall configuration, and automatic updates, then gradually implement additional measures like two-factor authentication and comprehensive auditing. Regular monitoring and maintenance ensure your security posture remains strong against evolving threats.

Remember, security is not a destination but a journey. Stay informed about new vulnerabilities, keep your systems updated, and regularly review your security configurations to maintain robust protection for your Ubuntu 24.04 installations.

Share this post: