Linux Hardening (Ubuntu)
This guide applies to an Ubuntu Server running on Akamai (Linode). However, similar methods can be used on all Debian-based Linux distributions. All instructions are completed within the terminal.
Navigation:
- Update Management
- Accounts and Authentication
- Firewall Configuration
- Intrusion Prevention System
- Remove Unnecessary Services
- Restrict File Permissions
- Logging
- Kernel Hardening
- Security Tools
Update Management
Apply and Enable Security Updates
Before starting, make sure your system is up to date:
sudo apt update && sudo apt upgrade -y
sudo apt autoremove -y
Enable automatic security updates:
sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure unattended-upgrades
Accounts and Authentication
Disable Root Access
An easy step to take to reduce brute-force attack success is to disable SSH logins as root.
Open and edit the SSH configuration:
sudo nano /etc/ssh/sshd_config
Look for the line containing PermitRootLogin, and set it to no:
PermitRootLogin no
Press CTRL+O to save, then CTRL+X to exit.
SSH Access
If SSH is not yet installed, update and install it:
sudo apt update && sudo apt install openssh-server -y
Set the service to start on boot:
sudo systemctl enable --now ssh
Confirm the SSH server is now running:
sudo systemctl status ssh
You will now allow SSH access by editing the configuration file:
sudo nano /etc/ssh/sshd_config
Locate the line containing PasswordAuthentication. Ensure the line does not have a # at the beginning:
PasswordAuthentication yes
Press CTRL+O to save, then CTRL+X to exit.
Restart the SSH service to ensure these changes take effect:
sudo systemctl restart ssh
Securing SSH
Using SSH key authentication replaces traditional password access with a pair of cryptographic keys. This includes a public key stored on the server and a private key stored securely on your local machine.
On your local PC, not the Ubuntu Server, open your terminal or PowerShell. Use a new tab if you are currently connected via SSH. Generate your public and private keys:
ssh-keygen -t ed25519 -C "your_email@example.com"
The method for copying the public key to your server will depend on your local operating system. The examples below assume you are using the default file name and location for the generated keys.
Copy the key to your server (Linux):
ssh-copy-id username@your-server-ip
Copy the key to your server (Powershell):
type $env:USERPROFILE\.ssh\id_ed25519.pub | ssh username@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Copy the key to your server (Mac Terminal):
cat ~/.ssh/id_ed25519.pub | ssh username@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Test your access. Open a new tab in your terminal or PowerShell on your local PC. Then run the following:
ssh username@your-server-ip
You should no longer be prompted for a password. Now that you have confirmed the key-based login is working, disable password logins on your Ubuntu server:
sudo nano /etc/ssh/sshd_config
Locate the line containing PasswordAuthentication. Set the option to no:
PasswordAuthentication no
Locate the line containing PubkeyAuthentication. Remove the # if it is present, and ensure the option is set to yes:
PubkeyAuthentication yes
Press CTRL+O to save, then CTRL+X to exit.
Restart the SSH service to ensure these changes take effect:
sudo systemctl restart ssh
Hardening SSH
This configuration will place restrictions on how users can connect via SSH, significantly reducing the surface area for brute-force attacks. You will ensure the server only uses the secure version 2 protocol, limits the number of authentication attempts, limits the amount of time available to connect, only allows specific users, and uses a nonstandard port number.
Open the SSH configuration file:
sudo nano /etc/ssh/sshd_config
If the line for Protocol is present, set it to:
Protocol 2
Locate the line for MaxAuthTries, and set it to:
MaxAuthTries 3
Locate the line for LoginGraceTime, and set it to:
LoginGraceTime 30
Locate the line for AllowUsers. If it is missing, add it to the bottom and set it to:
AllowUsers username
Locate the line for Port, and change it to an available port of your choosing:
Port ##
Press CTRL+O to save, then CTRL+X to exit.
Add a firewall rule for the new port:
sudo ufw allow ##
Restart the SSH service to ensure these changes take effect:
sudo systemctl restart ssh
Be mindful that you will now need to define your custom port number when connecting to the Ubuntu Server via SSH. For example, this can be done using the command below:
ssh username@your-server-ip -p port-number
Remove Unnecessary Access to Sudo
This step is part of enforcing the principle of least privilege. By doing this, you will reduce the amount of damage that can be caused by a compromised account, or from user error, such as sudo rm -rf /. This step also simplifies the process of tracking which account ran privileged commands.
See a list of currently active sudo users:
grep '^sudo:' /etc/group
Remove sudo access for users where it is not required:
sudo deluser username sudo
Once all users have been removed, confirm your updated access list:
grep '^sudo:' /etc/group
Firewall Configuration
Set Default Configuration
This will establish a secure-by-default baseline for your Ubuntu server. You can choose to expand upon these settings later.
Reject all incoming connection attempts:
sudo ufw default deny incoming
Allow the server to initiate connections to external sources:
sudo ufw default allow outgoing
Allow SSH access:
sudo ufw allow ssh
Activate the previously set rules:
sudo ufw enable
Intrusion Prevention System
Install IPS
Intrusion Prevention Systems can protect you from both manual and automated attacks. They work by scanning service logs for malicious patterns, then automatically updating firewall rules to block the associated IP addresses. In this example, I am utilizing the Fail2Ban open-source IPS.
Install Fail2Ban:
sudo apt install fail2ban
Enable Fail2Ban:
sudo systemctl enable fail2ban
Start Fail2Ban:
sudo systemctl start fail2ban
Confirm Fail2Ban is running:
sudo systemctl status fail2ban
Using Fail2Ban
After your server is up and live, you can use the following commands to view actions taken by Fail2Ban.
List banned IPs:
sudo fail2ban-client banned
List active jails:
sudo fail2ban-client status
List IPs in a specific jail:
sudo fail2ban-client status jailname
Ban an IP:
sudo fail2ban-client set jailname banip ip-address
Unban an IP:
sudo fail2ban-client set jailname unbanip ip-address
View recent logs:
sudo tail -f /var/log/fail2ban.log
Whitelist specific IPs:
sudo nano /etc/fail2ban/jail.local
Locate the [DEFAULT] line. Then add the following below it:
ignoreip = 127.0.0.1/8 ::1 ip-address
Press CTRL+O to save, then CTRL+X to exit.
Restart the Fail2Ban service to ensure these changes take effect:
sudo systemctl restart fail2ban
Remove Unnecessary Services
System Services
Before jumping in and removing services, it is easier to see which services are currently available. To do this, run:
systemctl list-units --type=service --no-pager
You will see a long list of available services. Not all of these services are needed. If you are also using Linode, you can find a full list of services here. In this case, you will disable the below services by running:
sudo systemctl disable --now \
console-setup.service \
keyboard-setup.service \
plymouth-quit.service \
plymouth-quit-wait.service \
plymouth-read-write.service \
setvtrgb.service \
getty@tty1.service \
serial-getty@ttyS0.service \
cloud-init.service \
cloud-config.service \
cloud-final.service \
cloud-init-local.service
Verify the services are now disabled:
systemctl list-unit-files --state=disabled --no-pager
Now you need to mask the services so that they cannot be easily re-enabled:
sudo systemctl mask \
console-setup.service \
keyboard-setup.service \
plymouth-quit.service \
plymouth-quit-wait.service \
plymouth-read-write.service \
setvtrgb.service \
getty@tty1.service \
serial-getty@ttyS0.service \
cloud-init.service \
cloud-config.service \
cloud-final.service \
cloud-init-local.service
Verify the services are now masked:
systemctl list-unit-files --no-pager | grep masked
Network Services
An important hardening step is to reduce the number of entry points into your server. Each running network service can be utilized by an attacker as an entry point, which is why it is best to remove anything that is not absolutely necessary for normal operation.
Check running services:
sudo ss -tulnp
Block an unnecessary service:
sudo systemctl disable --now service-name
Mask an unnecessary service:
sudo systemctl mask service-name
Confirm the service status has been updated:
sudo systemctl status service-name
Restrict File Permissions
Restricting file permissions is critical to ensure system integrity and data integrity. This step also follows the principle of least privilege by preventing unauthorized users from accessing sensitive data and/or modifying critical system files.
Start by listing the files where others have write permissions:
sudo find / -path /proc -prune -o -type f -perm -o+w -print
If you see any entries that should not be openly writable, set permissions:
sudo chmod 640 entry
Then set ownership:
sudo chown root:shadow entry
Logging
Checking your logs regularly is essential to monitoring your server security status. Fail2Ban log checks were covered above.
You can also check your system logs:
sudo journalctl
Check your authentication logs:
sudo tail -f /var/log/auth.log
You can also send your logs to a SIEM like Wazuh.
Kernel Hardening
It is important to adjust permissive settings in the kernel to be more restrictive. The kernel has unrestricted access to your system resources and hardware. This makes it the highest-value target for an attacker.
Create a custom Kernel configuration module:
sudo nano /etc/sysctl.d/99-custom.conf
Ensure IP forwarding is disabled:
net.ipv4.ip_forward=0
net.ipv6.conf.all.forwarding=0
Prevent IP spoofing by ensuring packets are only accepted if they arrive on the same interface they would be sent from:
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.default.rp_filter=1
Prevent attackers from redirecting your traffic by sending forged routing information:
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
Enable SYN cookie protection to protect against SYN flood DoS-style attacks:
net.ipv4.tcp_syncookies=1
Disable dmesg for non-root users:
kernel.dmesg_restrict=1
Press CTRL+O to save, then CTRL+X to exit.
Apply your changes:
sudo sysctl --system
Add a kernel hardening module:
sudo nano /etc/sysctl.d/99-kernel-hardening.conf
Hide kernel memory addresses from non-root users:
kernel.kptr_restrict=2
Disable non-root access to kernel performance monitoring:
kernel.perf_event_paranoid = 3
Protect against advanced memory exploits:
net.core.bpf_jit_harden = 2
Press CTRL+O to save, then CTRL+X to exit.
Apply your changes:
sudo sysctl --system
Security Tools
ClamAV
ClamAV is an open-source antivirus toolkit used to detect trojans, viruses, malware, etc. It can be used both for on-demand scanning and live protection. The logs can also be viewed in your SIEM, such as Wazuh.
Installation
Update your system:
sudo apt update && sudo apt upgrade -y
Install ClamAV:
sudo apt install clamav clamav-daemon -y
Manually update virus definitions:
sudo systemctl stop clamav-freshclam
sudo freshclam
sudo systemctl start clamav-freshclam
Check your current definition update date:
freshclam -V
Enable and start services:
sudo systemctl enable --now clamav-daemon
sudo systemctl enable --now clamav-freshclam
Perform a test scan:
clamscan -r /home
To only see infected files:
sudo clamscan -ri /home
Configuration
Configure your instance by modifying the configuration file:
sudo nano /etc/clamav/clamd.conf
Ensure data stays within the local system:
LocalSocket /var/run/clamav/clamd.ctl
Automatically delete the old socket file if the server crashes:
FixStaleSocket true
Set a maximum single file scan size to prevent massive files from freezing the CPU:
MaxFileSize 100M
Set a maximum total file size, such as when scanning ZIP directories, to save on memory usage:
MaxScanSize 200M
Specify where the daemon writes its activity and detection reports:
LogFile /var/log/clamav/clamav.log
Add a date and time to every entry in the log file:
LogTime true
Press CTRL+O to save, then CTRL+X to exit.
Restart the daemon to apply the updates:
sudo systemctl restart clamav-daemon
Automation
Create a cron job to automate daily scans:
sudo crontab -e
Add the below, adjusting the time to match an appropriate time for your project:
0 2 * * * clamscan -r / --exclude-dir="^/sys" --exclude-dir="^/proc" --exclude-dir="^/dev" -i --log=/var/log/clamav/daily_scan.log
Press CTRL+O to save, then CTRL+X to exit.
Verify your line was added to cron:
sudo crontab -l
Rootkit Hunter
RKHunter is an open-source tool that looks for signs an attacker has already compromised the system. System integrity is verified by performing file hash comparisons, rootkit signature scanning, a search for suspicious properties, and network checks. Logs can also be sent to your SIEM, such as Wazuh.
Installation
Update your system:
sudo apt update && sudo apt upgrade -y
Install RKHunter:
sudo apt install rkhunter -y
When prompted for mail server configuration type, select no configuration. It is more secure to have your SIEM pull the logs than it is to have an email server running just to email you updates.
You will need to allow RKHunter to check for version and signature updates. To do this, open and edit the configuration file:
sudo nano /etc/rkhunter.conf
Allow the list of mirrors to be updated:
UPDATE_MIRRORS=1
Allow tools to use any available mirror:
MIRRORS_MODE=0
Allow RKHunter to run its default tools:
WEB_CMD=""
Press CTRL+O to save, then CTRL+X to exit.
Verify the installation:
sudo rkhunter --versioncheck
Update definitions:
sudo rkhunter --update
Set a baseline snapshot:
sudo rkhunter --propupd
Run a scan:
sudo rkhunter --check --sk --report-warnings-only
You can also check the log for warnings:
sudo grep Warning /var/log/rkhunter.log
Note any false positives for the configuration steps below.
Configuration
Open and edit the configuration file:
sudo nano /etc/rkhunter.conf
Enable checking if root logins are disabled:
ALLOW_SSH_ROOT_USER=no
Enable flagging if SSH protocol 1 is enabled:
ALLOW_SSH_PROT_V1=0
Whitelist the which command:
SCRIPTWHITELIST=/usr/bin/which
Whitelist your false positives. Hidden files were found in this example:
ALLOWHIDDENFILE=/etc/.updated
ALLOWHIDDENFILE=/etc/.resolv.conf.systemd-resolved.bak
Press CTRL+O to save, then CTRL+X to exit.
Set a baseline snapshot:
sudo rkhunter --propupd
Run a new scan to check if everything is working as expected:
sudo rkhunter --check --sk --report-warnings-only
Automation
Set up a cron job to automatically scan at specified time intervals:
sudo crontab -e
Add the below line to run a scan daily at 3 AM:
0 3 * * * /usr/bin/rkhunter --check --sk --report-warnings-only
Press CTRL+O to save, then CTRL+X to exit.
Verify your line was added to cron:
sudo crontab -l
Lynis
Lynis is an open-source security auditing tool. It performs system scans to detect vulnerabilities, misconfigurations, and compliance issues. Suggestions are provided to improve security.
Installation
Update your system:
sudo apt update && sudo apt upgrade -y
Install Lynis:
sudo apt install lynis -y
Run the audit:
sudo lynis audit system
Once the scan completes, you will be provided with a Hardening Index Score. On a newly configured server, you should expect to be between 60 and 70. Work through the report, starting with issues highlighted in red. Then move on to issues highlighted in yellow. Decide which risks should be mitigated immediately and which can be accepted risks.
Automation
If the data needs to be monitored via a SIEM, such as Wazuh, you can set the audit to run intermittently.
Set up a cron job to automatically run the audit at specified time intervals:
sudo crontab -e
Add the below to run an audit every 3 days at 4 AM:
0 4 */3 * * /usr/local/bin/lynis audit system --cronjob --quiet --report-file /var/log/lynis-report.dat
Press CTRL+O to save, then CTRL+X to exit.
Verify your line was added to cron:
sudo crontab -l
Now that your hardening baselin setup is complete, challenge yourself to get an audit score of 75 or higher!