Linux Server Hardening
Hardening a Linux server is the process of enhancing its security and reducing its attack surface by applying various configurations, policies, and tools. A hardened Linux server is more resilient to cyber threats and less prone to compromise.
While Linux servers have been employed for specialized purposes over an extended period, it’s crucial to recognize that the default configuration of a freshly installed Linux server often exhibits a remarkably low level of security. This intentional design choice aims to maximize functionality and versatility during the initial setup phase. However, this approach necessitates the implementation of fundamental hardening tools before deploying the server in a production environment, where it will be exposed to potential threats and vulnerabilities.
We will delve deeply into the essential hardening techniques that every Linux server, regardless of its intended purpose, must implement. It’s vital to understand that these measures serve to minimize potential attack vectors, constituting best practices in the realm of server security. Crafting a tailored linux hardening strategy is imperative, one that takes into account the server’s specific role, operating environment, version, and other pertinent factors. This customization is pivotal in fortifying the server’s defense capabilities effectively.
15 Essential Linux Server Hardening Tips
Facilitate precise documentation of Linux host details
For each new Linux hardening task, it’s essential to craft a fresh document encompassing all checklist items outlined in this guide. Every implemented item should be diligently marked off within the document. Additionally, at the document’s outset, incorporate the following details regarding the Linux host:
- Hostname
- IP address
- MAC address
- Name of the individual conducting the hardening (usually yourself)
- Date
- Asset Number (In corporate settings, include the asset number designated by your organization for host identification)
System updates
Keeping a Linux server updated with the latest security patches and bug fixes is one of the simplest and most effective ways to harden its security. Regular system updates help prevent many common vulnerabilities and exploits from affecting the server. Utilize the package manager of your Linux distribution, such as apt, yum, or pacman, and execute commands like sudo apt update && sudo apt upgrade or sudo yum update to update the system.
Establish a new sudo user
For installing and setting up the server, the system administrator in the Linux operating system possesses system-wide privileges. To decrease the possibility that hackers may exploit this user's access and privileges, it must not be utilized to carry out routine server tasks. As a result, a new user must be established and granted the necessary rights to carry out standard server operations. Only certain administrators will be able to utilize this sudo user.
The command:
# adduser sam
(refer to Sam as your user name)
A password will be required. Put in a robust and lengthy password. The new user of the server should be added to the sudoers organization because it will require root-level access to carry out administrative tasks:
# usermod -aG sudo tom
Firewall configuration
Typically, firewalls are pre-installed on Linux servers that need to be manually activated. The following command can be used to enable the ufw firewalls that are used by Ubuntu servers:
# ufw enable
Secure BIOS
Each computer manufacturer utilizes a distinct set of keys to access BIOS mode, necessitating the configuration of an administrative password. To secure the BIOS:
- Set a BIOS password to prevent changes to security settings.
- Disable booting from external media devices (USB/CD/DVD) to prevent unauthorized access.
- Change default passwords or disable internal web server access on modern server motherboards.
Disable USB access
In critical systems, consider disabling USB usage on the Linux host to enhance security.
Configure and install a fail2ban firewall
For the purpose of preventing unauthorized network incoming and outgoing traffic to the server, the Fail2ban firewall is the most helpful option. A log-parsing application called Fail2ban keeps an eye on system logs for signs of an orchestrated attack on your Linode.
Fail2ban implements a new policy to iptables when using defined parameters that restrict the attacker's IP address for a predetermined period of time or irrevocably when malicious activity is discovered. Users can receive email notifications from Fail2ban that such an assault is taking place. This third-party firewall must be deployed individually. Following installation, it can be configured to prevent various types of undesired HTTP, SSH, and FTP traffic by making the necessary modifications in the file /etc/fail2ban/jail.local
# nano /etc/fail2ban/jail.local
Reduce service footprint
An essential step in fortifying a Linux server involves minimizing the number of running services. Services, which are background programs offering diverse functions like web hosting, databases, or email handling, aren’t all indispensable or actively utilized. Moreover, certain services may present security vulnerabilities or consume unnecessary resources. To streamline services, leverage tools like systemctl, service, or chkconfig to list, enable, disable, or halt services that are surplus to requirements.
Secure your data with encryption
Data encryption involves converting it into an unreadable format accessible only with a key or password. Implementing encryption can enhance the security of your Linux server by safeguarding sensitive or confidential information from unauthorized access, theft, or leakage. Utilize tools such as cryptsetup, dm-crypt, or LUKS to encrypt disks, partitions, or files, or employ SSL/TLS certificates to encrypt web traffic.
Configure SSH
Linux servers, including Red Hat distributions, arrive from the manufacturer with SH services. Secure Shell or Secure Socket Shell (SSH) experiences the majority of the outside attacks and as such its security is of the utmost importance. Numerous settings can be changed to improve security, but these are where we advise you to start:
- Port 22 is the standard SSH port. It is advised that you alter the default configurations because Port 22 is known to contain a number of vulnerabilities.
- It is essential to ascertain that the SSH cannot access the Root account. For this, the following command can help:
PermitRootLogn no
- A key based authentication system should be installed in this type of server to increase its security by replacing the traditional password based authentication system. All this can be configured from /etc/ssh/sshd_config
- Allow some specific users:
AllowUsers [Username]
When a user is trying to configure the SSH, this is really the beginning; there is indeed a lot more a user can do. Some businesses, for instance, include banners to ward off assailants and prevent them from continuing further.
You must ensure the following extra parameters are present in the "sshd config" file:
Protocol2
IgnoreRhosts to yes
HostbasedAuthentication no
PermitEmptyPasswords no
X11Forwarding no
MaxAuthTries 5
Ciphers aes128-ctr,aes192-ctr,aes256-ctr
ClientAliveInterval 900
ClientAliveCountMax 0
UsePAM yes
Finally, make sure that only root users have access to the sshd config file by setting its permissions to:
#chown root:root /etc/ssh/sshd_config
#chmod 600 /etc/ssh/sshd_config
To fully comprehend all the configurations in this file, a user can take a look at the SSH documentation for additional guidance, as this document contains detailed instructions and information on various topics.
Disk partitioning and Backup Management
Implementing disk partitioning and backup strategies is crucial for system availability and disaster recovery. Backups offer numerous benefits, safeguarding against system damage and OS update issues. For critical servers, it’s imperative to transfer backups offsite to prepare for potential disasters. Additionally, backup management is essential, including decisions on retention periods for old backups and the frequency of system backups (daily, weekly, etc.).
Partitions should be made for critical systems for the following:
- /
- /boot
- /usr
- /home
- /tmp
- /var
- /opt
Identify Open Ports
Ensuring the identification of open connections to the internet is paramount for maintaining security and network integrity. Monitoring open ports provides insights into network activity and communication patterns.
Automate the hardening of Linux by enabling SELinux
The linux kernel security mechanism known as Security-Enhanced Linux (SELinux) supports access control security policy. The SELinux can be configured in one of three ways:
- Disabled: Turned-off
- Prints cautions; permissive
- The policy is being upheld by enforcement.
To employ this system, the user needs to open the config file using a text editor:
#nano /etc/SELinux/config
Furthermore, it is essential to make sure that the policy is enforced:
SELINUX=enforcing
Free and Open Source Tools for Hardening
Open-source software typically offers greater transparency and customization compared to proprietary software. This enables security experts to more readily pinpoint vulnerabilities and create tailored solutions to address them. Moreover, hardening open-source tools are frequently free to use, broadening their accessibility to a diverse user base.
When using open source tools for hardening, it is from the world to help secure operating systems. Open source security is then employed for the practices, processes, and tools employed to secure and protect open-source software and the associated development and deployment environments.
Linux CIS Benchmark Hardening
The Center for Internet Security (CIS) Benchmarks established by the CIS Benchmark community for Linux, provide prescriptive guidance for establishing a secure configuration for Linux systems. CIS and the CIS Benchmark for operating systems offer best practices focused on technical configuration settings used to increase the security and cyber hygiene for OS Red Hat Enterprise Linux, SUSE Linux Enterprise Server, CentOS Linux, Amazon Linux, Debian Linux, Ubuntu Linux and more. Explore CIS Benchmark resources in their older versions of archived CIS Benchmarks in WorkBench.
Organizations can use the Linux hardening tools and scripts provided by CIS for manual hardening or the CIS hardened images. CIS Hardened Images refer to pre-configured virtual machine images designed to align with the rigorous security guidelines outlined in the corresponding CIS Benchmark for the respective operating system.
Linux CIS Benchmark Hardening settings provide a comprehensive approach to securing Linux systems and are continuously updated to address emerging threats and vulnerabilities. Additional Process Hardening settings in the Linux CIS Benchmark include:
1.5.1 Ensure core dump storage is disabled (Automated)
Remediation:
Edit /etc/systemd/coredump.conf and edit or add the following line:
Storage=none |
1.5.2 Ensure core dump backtraces are disabled (Automated)
Remediation:
Edit or add the following line in /etc/systemd/coredump.conf:
ProcessSizeMax=0 |
1.5.3 Ensure address space layout randomization (ASLR) is enabled (Automated)
Remediation:
Run the following script to set:
- kernel.randomize_va_space=2
#!/usr/bin/env bash { l_output=”” l_output2=”” l_parlist=”kernel.randomize_va_space=2″ l_searchloc=”/run/sysctl.d/*.conf /etc/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf /lib/sysctl.d/*.conf /etc/sysctl.conf $([ -f /etc/default/ufw ] && awk -F= ‘/^\s*IPT_SYSCTL=/ {print $2}’ /etc/default/ufw)” l_kpfile=”/etc/sysctl.d/60-kernel_sysctl.conf” KPF() { # comment out incorrect parameter(s) in kernel parameter file(s) l_fafile=”$(grep -s — “^\s*$l_kpname” $l_searchloc | grep -Pv — “\h*=\h*$l_kpvalue\b\h*” | awk -F: ‘{print $1}’)” for l_bkpf in $l_fafile; do echo -e “\n – Commenting out \”$l_kpname\” in \”$l_bkpf\”” sed -ri “/$l_kpname/s/^/# /” “$l_bkpf” done # Set correct parameter in a kernel parameter file if ! grep -Pslq — “^\h*$l_kpname\h*=\h*$l_kpvalue\b\h*(#.*)?$” $l_searchloc; then echo -e “\n – Setting \”$l_kpname\” to \”$l_kpvalue\” in \”$l_kpfile\”” echo “$l_kpname = $l_kpvalue” >> “$l_kpfile” fi # Set correct parameter in active kernel parameters l_krp=”$(sysctl “$l_kpname” | awk -F= ‘{print $2}’ | xargs)” if [ “$l_krp” != “$l_kpvalue” ]; then echo -e “\n – Updating \”$l_kpname\” to \”$l_kpvalue\” in the active kernel parameters” sysctl -w “$l_kpname=$l_kpvalue” sysctl -w “$(awk -F’.’ ‘{print $1″.”$2”.route.flush=1″}’ <<< “$l_kpname”)” fi } for l_kpe in $l_parlist; do l_kpname=”$(awk -F= ‘{print $1}’ <<< “$l_kpe”)” l_kpvalue=”$(awk -F= ‘{print $2}’ <<< “$l_kpe”)” KPF done } |
With hundreds of security settings in the benchmark to review and then run a remediation script for each operating system configured according to their role, version and environment can be labor intensive and often human error occurs and this is why automated hardening is recommended.
Automating Linux Hardening
For large-scale server infrastructure, manual hardening tools become impractical, leading many firms to overlook hardening efforts due to resource constraints and the risk of production outages. However, automation tools are essential for ensuring compliance with increasingly stringent hardening requirements and mitigating a wide range of attack techniques. Prior to implementation, thorough assessment of the impact of hardening activities on Linux servers is crucial. Yet, this testing process is often time-consuming and challenging, particularly in complex organizational environments with numerous interconnections.
By automating the Linux server hardening process using a tool like CalCom's Automated Server Hardening, the labor-intensive procedure may be completed for each server in about five minutes instead of five hours. In addition, the user would not experience any downtime when hardening, thanks to automation.