Linux Hardening
Linux Hardening
Contents
Background.......................................................................................................................................... 3
Platform Hardening............................................................................................................................. 4
Credential Hardening.......................................................................................................................... 15
Conclusion.......................................................................................................................................... 19
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 3
Background
The Linux operating system and supporting applications are becoming a prime target for
adversaries. Linux is used as the operating system backend for many components that
automate facets of critical infrastructure, on-premises and cloud-based technologies, and
Internet of Things (IoT) devices.
Platform Hardening
Kernel Module Signing
As of Linux kernel version 3.7, signed kernel modules using digital signatures can be leveraged to enhance the security of Linux by
preventing unsigned and untrusted modules from loading and running. Kernel module signing can be configured within the .config file as
part of the CONFIG_MODULE_SIG configuration parameters. This type of trust chaining for kernel modules works in parallel with UEFI
Secure Boot being enabled, which protects the bootloader and firmware.
Example methods which can be used to configure trust-chains and enforce kernel module signing are referenced in Table 1.
Ubuntu https://ubuntu.com/blog/how-to-sign-things-for-secure-boot
Fedora https://docs.fedoraproject.org/en-US/Fedora/23/html/System_Administrators_Guide/sect-signing-kernel-modules-for-
secure-boot.html
Gentoo https://wiki.gentoo.org/wiki/Signed_kernel_module_support
Oracle https://www.oracle.com/technical-resources/articles/linux/signed-kernel-modules.html
Debian https://wiki.debian.org/SecureBoot
Sysctl Configuration Parameters The /etc/sysctl.conf file can also be manually edited, with the
Sysctl.conf is the main kernel configuration file on Linux added or removed parameters being loaded upon executing the
systems. The sysctl -p command can be used to modify sysctl -p command.
kernel parameters at runtime, which will s`tore the configuration
Example parameters to include within the /etc/sysctl.conf
parameters within the /etc/sysctl.conf file.
file to harden a Linux endpoint are referenced in Figure 1.
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 5
# Disables IP forwarding
net.ipv4.ip_forward = 0
# Controls whether core dumps will append the PID to the core filename (useful for debugging
multi-threaded applications)
kernel.core_uses_pid = 1
FIGURE 2. Setting to disable new kernel modules from loading using sysctl.
To change this configuration back to the default setting, the kernel.modules_disabled setting can be configured back to “0” – and a
reboot will need to occur.
While this configuration can certainly reduce the attack surface from an adversary loading malicious kernels (e.g., rootkits), this can also
impact legitimate applications that would need to be loaded after the hardened configuration is enforced.
Note: Some modules are not loaded at boot time – and may be loaded as part of normalized system operations. To ensure that legitimate and authorized modules can still be
loaded, modules can be defined either within the /etc/modules-load.d file or within a startup script (Figure 4).
#!/bin/sh/
sleep <value>
insmod <module1> <module2> <module3>
echo 1 > /proc/sys/kernel/modules_disabled
• AuthenticationMethods configuration parameters in • If there is not a requirement to use X11 applications, set
the /etc/ssh/sshd_config file can be used to specify X11Forwarding to “No” in the /etc/ssh/sshd_config file.
authentication methods that can be utilized. Organizations • To limit the number of authentication attempts, set the
should consider defining more than one authentication method MaxAuthTries setting to “4” in the /etc/ssh/sshd_config file.
in order to enforce a type of multi-factor authentication (MFA)
• Set ClientAliveInterval between 300-900 seconds (5-
for accessing Linux endpoints.
15 minutes) in the /etc/ssh/sshd_config file and set
• Cryptographic public key-based authentication (PKI) should be ClientAliveCountMax to “1”.
configured along with a strong password to enable a form of
• To limit the risk of backdoor capabilities, set
MFA to harden authentication access to a Linux endpoint when
AllowTcpForwarding to “No” in the /etc/ssh/sshd_config
SSH is required.
file.
For this configuration, all users would need to create public
• To enhance auditing and visibility, set LogLevel to VERBOSE in
and private key pairs, and the keys would need to be added to
the in /etc/ssh/sshd_config file.
the endpoint before key-based authentication is enforced.
The example configuration (Figure 5) within the /etc/ssh/ • To disable accounts with empty passwords from being able to
sshd_config file will require a user to perform both password- login, set PermitEmptyPasswords to “No” in the /etc/ssh/
based and key-based authentication, enforcing a form of MFA sshd_config file.
for connecting to the endpoint.
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 7
Cron Jobs Review and Permission Restrictions The command referenced in Figure 9 determines if the /etc/
Cron jobs are used to set scheduled tasks on a Linux endpoint. crontab file has the correct permissions.
Cron jobs are often used by adversaries to establish a form
persistence or to elevate permissions by invoking processes or stat -c "%a %u %g" /etc/crontab | egrep -v
modules to run within the context of the system. Organizations ".00 0 0"
should review and enforce visibility for cron jobs configured on
Linux endpoints.
FIGURE 9. Command to verify permissions of /etc/crontab.
cat /etc/crontab
ls -al /etc/cron.d If the above command emits no output, then the system is
ls -al /etc/cron.hourly/ configured as recommended.
ls -al /etc/cron.daily/
ls -al /etc/cron.weekly The commands referenced in Figure 11 will restrict access for
ls -al /etc/cron.monthly/ non-root accounts to the /etc/crontab file and the /etc/
cron.d directory.
FIGURE 7. List all the cron jobs listed on a system.
The specific parameters associated with a cron job should also be chown root:root /etc/crontab
chmod og-rwx /etc/crontab
reviewed, including any binaries or modules that re configured for
chown root:root /etc/cron.d
execution, as these files should only be writable by the root user. chmod og-rwx /etc/cron.d
The full permissions for any executable files configured as part
of a cron job can be listed by using the command referenced in
FIGURE 11. Command to restrict read/write access to non-root accounts for cron
Figure 8. files and directory.
The commands referenced in Figure 12 can be used to search for SUID executables on a Linux endpoint.
The list of identified files should be reviewed for any binary that privileged programs or introducing potentially malicious
may allow a user to escalate privileges to root. Any file editor, software on the endpoint. Blocking the execution of binary files
compiler, or interpreter that can be used to read or overwrite a file and creation of setuid files can be done by using “noexec” and
should also be reviewed. If not required, SUID permissions should “nosuid” mount options.
be removed for identified files. • Temporary storage mount points are not intended to support
block or character special device files, and users should be
Mounted Partitions Permissions Options restricted from creating these filetypes. Executing character
Once an adversary gains a foothold on a compromised endpoint with or block special device filetypes from file systems increase
non-privileged access, as part of reconnaissance, an adversary may the opportunity for unprivileged users to elevate permissions.
look for partitions with weak or misconfigured permission settings Blocking the creation of special device filetypes can be
with the goal of executing binaries from storage locations for accomplished using the “nodev” mount option.
potential privilege escalation or lateral movement. • Directories (e.g., /var/log, /var/log/audit) where log
data is usually stored are recommended to have a separate
Organizations should review the existing configured options on
partition configured to protect against resource exhaustion
mount points and evaluate the following conditions: issues (where logs can significantly grow), is minimal, and the
• Temporary storage mount points (e.g., /tmp, /var/tmp, dev/ storage capacity is sized appropriately, creating a separate
shm, removable media), especially world-writable directories, partition can be planned at a later stage or during a scheduled
should be restricted from running executable binaries and maintenance window.
from creating setuid files to avoid non-root users executing
/home nodev
/var defaults
Focus should be aligned with the following options being assigned SELinux Modes
to temporary storage mount points (e.g., /tmp, /var/tmp, dev/ The configuration of SELinux is managed within the /etc/
shm, removable media): selinux/config file. Within the configuration file, SELinux can
• noexec: does not allow for direct execution of any binaries on be configured based upon the following modes:
the mounted filesystem.
• Enforcing: SELinux security policies are enforced for each
• nodev: does not interpret character or block special devices on system call. All actions will be logged to /var/log/audit/
the file system. audit.log.
• nosuid: does not allow set-user-identifier or set-group-
identifier bits to take effect.
# Command to set SeLinux to Enforcing mode
To verify what options a mounted filesystem is utilizing, the mount sudo setenforce 1
command can be leveraged. It is also possible to include the grep
# Parameters to add to the /etc/selinux/
command to limit the output for a particular mount point (Figure 13).
config file
SELINUX=enforcing
Note: If the mount points referenced in Table 2 do not exist, evaluate the feasibility • Disabled: No SELinux policies are loaded. No actions will be
to create another partition, mount it, and then apply the recommended options. logged
When modifying an existing folder (e.g., /var/log) it is advisable to bring the
system to emergency mode by ensuring that auditd is not running.
# Parameters to add to the /etc/selinux/
config file
SELinux SELINUX=disabled
SELinux is a Mandatory Access Control (MAC) security module for
Red Hat Enterprise Linux (RHEL) and CentOS. SELinux can control
FIGURE 16. SELinux disabled mode.
access based on labels assigned to files and processes. Labels
are configured in the form of user:role:type:level. Note: A system restart is required to switch between SELinux modes.
To verify if SELinux is installed and configured, the sestatus If SELinux is not already running in ”Enforcing” mode, it is
command can be leveraged. Additionally, the getenforce recommended to first configure SELinux in “Permissive” mode
command can be leveraged to determine the configuration state and ensure that autolabeling is enforced (Figure 17) upon reboot.
of SELinux.
touch /.autorelabel
sudo semodule -l
• The command ls –Z will display the SELinux security context files.
• The command ps –efZ will display the SELinux security context
FIGURE 22. Command to view the list of SELinux loaded modules.
for running processes.
• The command id –Z will display the SELinux security context The commands referenced in Figure 23 can be leveraged to
for users. control modules.
SELinux uses four context parameters that are enforced
by policies: # Disable a module
semodule -d <Module Name>
• Users: Every account, process, or application in Linux can be
linked to one “SELinux user” mapping. # Enable a module
To change a user association to a different SELinux user semodule -e <Module Name>
mapping, the command referenced in Figure 19 can be leveraged:
# Remove a module
semodule -r <Module Name>
FIGURE 19. SELinux user context change command. For additional information about SELinux, reference:
https://access.redhat.com/documentation/en-us/red_hat_
• Roles: Defines what an SELinux user can do with an object in enterprise_linux/7/html/selinux_users_and_administrators_
a specified domain or type. To check what domains or types guide/index
a specific role can access, the seinfo command can be
leveraged (Figure 20).
seinfo -<role>_r -x
To verify if AppArmor is running and configured, the command sudo systemctl stop apparmor.service
referenced in Figure 25 can be leveraged. sudo update-rc.d -f apparmor remove
For any profiles that are not configured for “enforce mode”, the
commands reference in Figure 26 can be leveraged. sudo systemctl start apparmor.service
sudo update-rc.d apparmor defaults
# specific profile
sudo aa-enforce /path/to/bin FIGURE 30. Commands to re-enable AppArmor.
Note: The aa-complain command can be substituted to change the profiles from
“enforce mode” to “complain mode”.
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 12
Figure 31 contains example commands to configure specific conditions using iptables in Linux.
Once configured, iptables rules need to be saved using either of the commands referenced in Figure 32.
The scope of ports and protocols to configure within iptables will Note: Linux distributions can use different firewall services and firewall
management tools. To avoid potential conflicts with the different services, it
vary based upon the intended use-case of the Linux endpoint.
is recommended to run only one firewall service on a Linux endpoint. Common
As a best-practice, the goal of an iptables configuration would modern firewall services and firewall management tools are noted below:
enforce a default chain policy of DENY, with only allow-list • RPM-based Linux distributions such as RHEL, CentOS, Fedora, SUSE and
OpenSUSE use firewalld by default. For additional details about firewalld,
communications configured bi-directionally.
reference https://firewalld.org/
[ + ] acpid
[ - ] alsa-utils
[ - ] anacron
[ + ] apparmor
[ + ] apport
[ - ] avahi-daemon
[ + ] bluetooth
[ - ] console-setup.sh
[ + ] cron
[ + ] cups
[ + ] cups-browsed
[ + ] dbus
[ + ] gdm3
[ - ] grub-common
[ - ] hwclock.sh
[ + ] irqbalance
[ + ] kerneloops
[ - ] keyboard-setup.sh
[ + ] kmod
[ + ] network-manager
[ + ] openvpn
[ - ] plymouth
[ - ] plymouth-log
[ - ] pppd-dns
[ + ] procps
[ - ] pulseaudio-enable-autospawn
[ - ] rsync
[ + ] rsyslog
[ - ] saned
[ - ] speech-dispatcher
[ - ] spice-vdagent
[ + ] udev
[ + ] ufw
[ + ] unattended-upgrades
[ - ] uuidd
[ + ] whoopsie
[ - ] x11-common
To disable a specific service, the command systemctl—now Note: The services listed above can be used legitimately, therefore the business
justification for the services to remain enabled should be considered. To reduce
disable <service-name> can be leveraged.
the attack surface of a Linux endpoint, if the services are not required for
operational purposes, they should be disabled. If the services cannot be disabled,
Common Linux endpoint services that can be abused by adversaries at a minimum, local firewall rules should be configured to restrict the scope of
and should be considered in-scope for disabling include: inbound access to Linux endpoints for some of the common protocols and ports
noted below.
• avahi-daemon • NFS (TCP & UDP/2049)
• NFS • rpcbind (TCP & UDP/111)
• smb
• telnet
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 14
NFS Server Hardening Once initialized, AIDE can be executed either manually (aide—
Network File Sharing (NFS) is a protocol that allows for directories check or the aide -c /etc/aide/aide.conf —check
and files to be shared with Linux clients over a network. commands) or as part of a scheduled (cron) job within /etc/
Configuration parameters for an NFS server are stored within the crontab. The output will identify files that have been added,
/etc/exports file. removed, or modified since AIDE was last initiated or ran.
Example output is included within Figure 34. For any added,
Best practices for hardening an NFS server to prevent against removed, or modified files, the output from AIDE will provide
unauthorized access to the file and directory contents include: additional context about the directory and file attributes.
• If directories must be mounted with the rw option (which allows
for both read and write requests on the NFS volume), to reduce
AIDE found differences between database and
risks of ransomware or data being overwritten in a malicious filesystem!!
manner. ensure that the volumes and directories are not world- Verbose level: 6
writable
• Leverage the showmount command to review all exported Summary:
Total number of entries: 286611
directories. If directories or paths that should not be
Added entries: 8
exportable are listed, restrictions can be defined within the
Removed entries: 4
/etc/exports file. Changed entries: 28
File Integrity Monitoring (FIM)
Modern Linux platforms can leverage the Advanced Intrusion FIGURE 34. Example AIDE output.
Detection Environment (AIDE) utility to create a database of
files to verify their integrity—and to identify any newly created, For additional information about AIDE, reference:
modified, or removed files. To generate an initial AIDE database to https://help.ubuntu.com/community/FileIntegrityAIDE
baseline the filesystem, the aide —init or aideinit commands
can be leveraged. https://access.redhat.com/documentation/en-us/red_hat_
enterprise_linux/7/html/security_guide/sec-using-aide
Note: AIDE initialization will check directories and files defined within the /etc/
aide.conf file. To include additional directories or files within the database, and to
change any parameters, the /etc/aide.conf file can be edited and modified.
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 15
Credential Hardening
Root Account Hardening Strong Password Enforcement
Organizations should not only limit the root account usage for Organizations should consider implementing mechanisms to
Linux endpoints, but also regularly review and monitor any root ensure strong passwords are used for all accounts on Linux
account usage in the environment and perform best-practices endpoints. The “Pam_cracklib.so” module can be used to
such as: check the strength of passwords.
• configuring a strong password.
The command referenced in Figure 37 can be used to install the
• enforcing a password rotation on a pre-defined interaval. libpam_cracklib module.
• setting a unique password for root accounts on all Linux
endpoints in the environment. $ sudo apt install libpam-cracklib
Identify and Protect Privileged Accounts
Organizations should review and document all accounts FIGURE 37. Command to install the libpam_cracklib module\.
configured on all Linux endpoints. All local accounts on a Linux
endpoint are listed in the files /etc/passwd and /etc/ After the installation has completed, the /etc/pam.d/common-
sudoers. Any modifications to content within these files should password file will need to be edited to enforce strong password
be reviewed to ensure that all accounts are authorized. requirements (Figure 38).
The UID (user identifier) value is used by Linux to identify a user. The available parameters for editing include:
Any user account that has the UID value set to 0 will have root
• retry=1 : Prompts user at most 1 time before returning with
privileges. Organizations should check and ensure that the only error. The default is also 1.
account configured on a Linux system with UID 0 is the default
• minlen=15 : The minimum acceptable size for the new password.
root account. The command referenced in Figure 35 can be used
to identify accounts that have a UID value set to 0. • ucredit=-1 : The password must contain at least 1 uppercase
characters.
cat /etc/passwd | awk -F: '($3 == 0) { print • lcredit=-1 : The password must contain at least 1 lowercase
$1 }' characters.
• dcredit=-12 : The new password must contain at least 12 digits.
FIGURE 35. Command to identify accounts with UID 0. • ocredit=-12 : The new password must contain at least 12 symbols.
The settings referenced in Figure 39 are recommended to enable password lockout for failed authentication attempts, where the
example enforces an account lockout after five (5) failed logon attempts.
The setting referenced in Figure 40 will prevent root account lockout as a result of an account lockout configuration.
The setting referenced in Figure 41 will enforce that the sha512 hashing algorithm is used as part of the password storage configuration.
Accounts that are inactive for a long period should be audited and disabled on a periodic basis. The lastlog command can be used to
identify the last login date for a specific account.
FIGURE 42. Command to set the shell for a user as /sbin/nologin for a specific account.
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 17
After the /etc/audit/auditd.conf file has been configured, Organizations should enable timestamps for the .bash_history
the next step to enhance visibility is to add additional rules to the file by configuring a “HISTTIMEFORMAT” variable on the
/etc/audit/rules.d/audit.rules file. Some examples of endpoint. The file “.bash_profile” in a user’s home directory
events that can be generated by auditd rules include, but are not can be used to configure this every time the user logs into the
limited to: endpoint (Figure 44).
• Reading, configuration, and monitoring of audit tools
• Standard kernel parameters, loading and unloading of modules echo 'export HISTTIMEFORMAT="%d/%m/%y %T "'
(including modprobe configuration), and kexec usage >> ~/.bash_profile
• Use of special files (e.g., attached block devices), mount
operations, and swap operations FIGURE 44. Command to configure $HISTTIMEFORMAT variable in a
.bash_profile file.
• Cron configurations
• Changes to users, groups, and passwords The default size of the history file is 1,000 lines. This means that
• Changes to Sudoers/root privileges, login information any commands that are older than last 1,000 commands will be
• Network events (e.g., hostname changes and connections) removed from the history file; therefore, it is recommended to
increase the file’s length. This can be configured by setting both
• Startup scripts and search paths
the HISTSIZE and HISTFILESIZE variables on a Linux endpoint.
• Service and system configurations The commands referenced in Figure 45 will configure variables
• Access to sensitive directories and binaries (e.g., /sbin) in a user’s bash profile, increasing the size of the history file to
• Process ID changes an unlimited value.
• Session initiation
echo 'export HISTSIZE= ' >> ~/.bash_profile
• Changes to sensitive access control levels (e.g., chmod >= 500)
echo 'export HISTFILESIZE= ' >> ~/.bash_
• Common reconnaissance, suspicious use of binaries (e.g., profile
Netcat, and code/data/process injections)
• Suspicious file access FIGURE 45. Commands to configure unlimited history file size for bash history.
The scope and type of rules required for auditing and visibility
Session Recording
purposes will be different for each organization. Pre-configured
Organizations should consider enabling user session recording.
rules for consideration are available from the following
User session recording enables the ability to record and play back
organizations:
user terminal sessions. All the recordings are captured and stored
• Center for Information Security (CIS) 1 in a text-based format in the system journal. This data can be
• Security Technical Implementation Guide (STIG) 2 used for auditing user sessions or performing forensics in case of
• Information Systems Security Organization (ISSO) a security incident.
• Controlled Access Protection Profile (CAPP) 3 For additional information for how to enable and configure
• Labeled Security Protection Profile (LSPP) 4 session recording, reference:
https://access.redhat.com/documentation/en-us/red_hat_
Log Execution Timestamps (Shell History)
enterprise_linux/8/html-single/recording_sessions/index
Linux systems store commands executed by a user in a user-
specific hidden “.bash_history” file located in each user’s http://manpages.ubuntu.com/manpages/bionic/man5/sssd-
home directory. This file can provide important information that session-recording.5.html
is useful when investigating and reviewing a Linux endpoint. A https://manpages.debian.org/testing/sssd-common/sssd-
limitation of the default shell history recording on Linux is that session-recording.5.en.html
the history file does not contain timestamps. The availability of
https://fedoraproject.org/wiki/ScreenCasting
timestamps being recorded within the .bash_history file can
provide significant contextual information for an investigation.
1 https://benchmarks.cisecurity.org/tools2/linux/CIS_CentOS_Linux_7_Benchmark_v1.1.0.pdf
2 https://github.com/linux-audit/audit-userspace/blob/master/rules/30-stig.rules
3 https://www.commoncriteriaportal.org/files/ppfiles/capp.pdf
4 https://www.commoncriteriaportal.org/files/ppfiles/lspp.pdf
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 19
Conclusion
Linux-focused exploitation attacks can pose a serious threat to organizations.
This whitepaper provides practical hardening guidance to protect against common
techniques used by threat actors to access and deploy malware or backdoors on Linux
endpoints. The guidance provided within this document is based on front-line expertise with
helping organizations prepare, contain, eradicate, and recover from incidents where Linux
endpoints have been targeted and impacted.
©2022 Mandiant, Inc. All rights reserved. Mandiant is a registered trademark of Mandiant, Inc. All other brands, products, or service
names are or may be trademarks or service marks of their respective owners. M-EXT-WP-US-EN-000422-01
W H I T E PA P E R | M A N D I A N T Linux Endpoint Hardening to Protect Against Malware and Destructive Attacks 20
Version/Date Notes