0% found this document useful (0 votes)
116 views20 pages

Linux Hardening

The document provides recommendations to harden Linux endpoints against attacks by securing credentials, restricting access, protecting the kernel, and improving auditing. It recommends configuring kernel module signing, sysctl parameters, disabling new module loading, restricting SSH access, reviewing cron jobs and permissions, and enabling auditing tools like SELinux and AppArmor.

Uploaded by

Abdou Soudaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views20 pages

Linux Hardening

The document provides recommendations to harden Linux endpoints against attacks by securing credentials, restricting access, protecting the kernel, and improving auditing. It recommends configuring kernel module signing, sysctl parameters, disabling new module loading, restricting SSH access, reviewing cron jobs and permissions, and enabling auditing tools like SELinux and AppArmor.

Uploaded by

Abdou Soudaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

WHITE PAPER

LINUX ENDPOINT HARDENING TO PROTECT AGAINST


MALWARE AND DESTRUCTIVE ATTACKS
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 2

Contents
Background.......................................................................................................................................... 3

Platform Hardening............................................................................................................................. 4

Kernel Module Signing........................................................................................................... 4


Sysctl Configuration Parameters.......................................................................................... 4
Kernel Module Loading Enforcement.................................................................................... 5
SSH Attack Surface Reductions............................................................................................ 6
Cron Jobs Review and Permission Restrictions.................................................................... 7
SUID Executables.................................................................................................................. 7
Mounted Partitions Permissions Options.............................................................................. 8
SELinux................................................................................................................................. 9
AppArmor..............................................................................................................................11
Configure Iptables to Enforce Local Firewall Rules..............................................................12
Disable Unnecessary Services............................................................................................. 13
NFS Server Hardening..........................................................................................................14
File Integrity Monitoring (FIM)...............................................................................................14

Credential Hardening.......................................................................................................................... 15

Root Account Hardening....................................................................................................... 15


Identify and Protect Privileged Accounts............................................................................. 15
Strong Password Enforcement............................................................................................ 15
Interactive Logon Restrictions............................................................................................. 16

Auditing and Visibility......................................................................................................................... 17

System Auditing Configurations........................................................................................... 17


Log Execution Timestamps (Shell History)........................................................................... 18
Session Recording................................................................................................................ 18

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.

This document provides recommendations to protect Linux endpoints against adversary


techniques such as lateral movement, privilege escalation, and deploying rootkits or modified
kernel modules that possess either a malicious or destructive capability. Drovorub (https://
media.defense.gov/2020/Aug/13/2002476465/-1/-1/0/CSA_DROVORUB_RUSSIAN_GRU_
MALWARE_AUG_2020.PDF) is an example of a Linux malware toolset that includes a kernel
module rootkit that can be leveraged for command and control (C2) communications, file
download and upload capabilities, and the execution of arbitrary commands.

Similar to Windows-based architectures, security protections need to be aligned for Linux


endpoints to harden credentials, access methods, protect the kernel, and bolster auditing and
visibility of activities.
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 4

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.

TABLE 1. References to enable Secure Boot and Kernel Module Signing.

Linux Distributions Reference Links

Linux Kernel https://www.kernel.org/doc/html/v4.15/admin-guide/module-signing.html

Red Hat Enterprise Linux https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/managing_monitoring_and_


updating_the_kernel/signing-kernel-modules-for-secure-boot_managing-monitoring-and-updating-the-kernel

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

# Disables packet redirect sending


net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Does not accept source routing


net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Enables reverse path filtering


net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Disables IPv6 router advertisements


net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0

# Logs suspicious packets


net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# Controls the System Request debugging functionality of the kernel


kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename (useful for debugging
multi-threaded applications)
kernel.core_uses_pid = 1

# Enables TCP SYN Cookies


net.ipv4.tcp_syncookies = 1

# Enables SYN-flood protections


net.ipv4.tcp_synack_retries = 5

# Enables ExecShield protection


kernel.exec-shield = 2

# Enable full address space randomization


kernel.randomize_va_space = 2

FIGURE 1. Recommended sysctl configuration parameters.

Kernel Module Loading Enforcement


Within sysctl.conf, the Linux kernel can be configured to not allow for new modules to be loaded.

# Prevent new modules from loading


kernel.modules_disabled = 1

FIGURE 2. Setting to disable new kernel modules from loading using sysctl.

Another option for setting this configuration is referenced within Figure 3.

echo 1 > /proc/sys/kernel/modules_disabled

FIGURE 3. Setting to disable kernel module loading using /proc.


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 6

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

FIGURE 4. Example startup script to load trusted modules.

SSH Attack Surface Reductions


Secure Shell (SSH) is a commonly used method to access and AuthenticationMethods publickey,password
administer Linux endpoints. Adversaries often use SSH to gain
initial access, maintain persistence, and laterally move. FIGURE 5. Require both public key and password-based authentication.

Organizations should define policies and procedures to harden


• Host-based firewalls should be enforced to limit origination
SSH access methods for Linux endpoints. The following
addresses that can connect to the SSH service on an endpoint.
recommendations should be considered:
This is strongly recommended for any Linux endpoints that have
• Least privileged access should be enabled for all SSH- SSH services exposed to the Internet or untrusted locations.
accessible accounts and groups, especially for automated Iptables and nftables are Linux utilities that can be used to
processes and remote access. configure IP packet filtering and limit SSH access from a
• To limit SSH access to Linux endpoints for only authenticated specific set of systems.
non-root user accounts, set PermitRootLogin to "No" in the Alternatively, TCP wrappers could be used to implement packet
/etc/ssh/sshd_config file. filtering and limit origination systems that can access SSH
• Implement user or group level restrictions for SSH access services on Linux endpoints. TCP wrappers work by configuring
to Linux endpoints through AllowUser, AllowGroup, two files: /etc/hosts.allow and /etc/hosts.deny. It is
DenyUser, DenyGroup settings defined within the recommended to add “ALL” hosts to the hosts.deny file and only
/etc/ssh/sshd_config file. the specific authorized hosts to the hosts.allow file.

• 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.

The command referenced in Figure 6 can be used to list all the


cron jobs lon a Linux endpoint for a specific user: If the above command emits no output, then the system is
configured as recommended.

crontab -u <username> -l The command referenced in Figure 10 determines if the /etc/


cron.d directory has the correct permissions.

FIGURE 6. Listing Cronjobs for a user.


stat -c "%a %u %g" /etc/cron.d | egrep -v
The commands referenced in Figure 7 can be used to list all the ".00 0 0"
cron jobs configured on an endpoint:
FIGURE 10. Command to verify permissions of /etc/cron.d.

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.

ls -al <path of the binary> SUID Executables


SUID (set owner USER ID on execution) is a file permission that
can be configured so that files will execute under the permissions
FIGURE 8. Full permission listing for a binary.
of the file owner. Files with SUID permissions are often used
Additionally, cron job file permissions should be reviewed. Read by adversaries to escalate privileges and perform malicious
access to cron files could provide adversaries with the ability to activities on a system. Although there are legitimate reasons to
gain insight on jobs that run on the endpoint, and could provide a have a binary with SUID, it is important to identify and review SUID
method to gain unauthorized privileged access or create binaries binaries on a regular basis.
or modules that will “blend in” with expected activities. Write
access to cron files could provide unprivileged users with the Organizations should review all files on Linux endpoints that have
ability to elevate privileges. the SUID bit set. Checking SUID should be part of the regular
review process including post update/installation activity.
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 8

The commands referenced in Figure 12 can be used to search for SUID executables on a Linux endpoint.

find / -perm -u=s -type f 2>/dev/null


df --local -P | awk '{if (NR!=1) print $6}
find <partition> -xdev -type f -perm -4000

FIGURE 12. Commands to search for SUID executables.

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

TABLE 2. Recommended mount point options.

Mount Point Mount Options

/tmp nosuid, noexec, nodev

/home nodev

/dev/shm nosuid, noexec, nodev

/var defaults

/var/log defaults (nosuid, noexec, nodev – can be added)

/var/tmp nosuid, noexec, nodev

/var/log/audit defaults (nosuid, noexec, nodev – can be added)

Any Removable Media Partition nosuid, noexec, nodev


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 9

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

mount | grep /tmp


/usr/.tempdisk on /tmp type ext4 FIGURE 14. SELinux enforcement mode.
(rw,nosuid,nodev,noexec,relatime)
• Permissive: SELinux prints warnings instead of enforcing. All
FIGURE 13. Verifying the mount options for /tmp mount point.
actions will be logged to /var/log/audit/audit.log.

# Command to set SeLinux to Enforcing mode


The output from the mount command will display the currently sudo setenforce 0
mounted filesystems, the filesystem type the device is mounted
as, and the options that are utilized. # Parameters to add to the /etc/selinux/
config file
If the recommended options are not present for the mount SELINUX=permissive
point, then organizations should configure the file system
table (/etc/fstab) to add the recommended options for the
FIGURE 15. SELinux permissive mode.
associated mount points.

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

FIGURE 17. Autolabeling command.


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 10

SELinux Policies • Type / Domain: Logical grouping of objects (type) or processes


An SELinux policy is a set of rules that define the directories, (domain) to apply permissions.
files, and ports that can be accessed by a process or application. To change the SELinux context for objects or processes, the
SELinux polices can be created either automatically or manually. chcon command can be leveraged (Figure 21).

Targeted mode within the /etc/selinux/config file is the


chcon -t <type-name>_t <file path / name>
default mode for SELinux. In this mode, SELinux targets only
selected processes that exist in configured domains.
FIGURE 21. SELinux type modification command example.
SELinux Context
To make access control decisions, SELinux uses “context” to • Sensitivity: Defines multiple levels of security between level c0
identify the associated resources relevant to an application or and c3. This context is used only when the SELinux policy type is
process. Context is the collection of security related information set to MLS mode (non-default).
assigned to each object (e.g., directory, file, process, port).
SELinux Modules
SELinux uses modules to load permission configurations. To view
system_u:object_r:net_conf_t:s0 the list of loaded modules, the command referenced in Figure 22
can be leveraged.
FIGURE 18. SELinux context format.

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>

semanage login -a -s <SELinux-User> <account>


FIGURE 23. Commands to manage SELinux loaded modules.

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

FIGURE 20. SELinux role association command.


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 11

AppArmor The apparmor_parser command can be used to load a profile


AppArmor is another method to apply MAC for Ubuntu and SuSE into the kernel. It can also be used to reload a currently loaded
Linux systems. Unlike SELinux, with AppArmor, MAC rules for profile (-r option) after modifying it to have the changes take
applications are applied by file paths instead of within security effect (Figure 27).
contexts (labels). AppArmor works by profiling an application to
determine what an application needs to access, and the capabilities # reload a profile:
required to function as part of normal baselined operations. sudo apparmor_parser -r /etc/apparmor.d/
profile.name
AppArmor profiles can allow capabilities like network access, raw
socket access, and the permission to read, write, or execute files # reload all profiles:
based on matching paths. Profiles (stored in the /etc/apparmor.d sudo systemctl reload apparmor.service
directory) can also be configured and customized based upon
specific permissions required by an application. Profiles can run in FIGURE 27. Commands to reload an AppArmor profile.
“complain mode” or “enforce mode.”
• Enforce mode (default setting for the profiles that come with The /etc/apparmor.d/disable directory can be used along with
Ubuntu) prevents applications from taking restricted actions. the apparmor_parser -r option to disable a profile (Figure 28).
• Complain mode allows applications to take restricted actions
and creates a log entry recording the action within /var/log/ sudo ln -s /etc/apparmor.d/<profile.name> /
messages. etc/apparmor.d/disable/
sudo apparmor_parser -r /etc/
To install AppArmor, the command referenced in Figure 24 can
apparmor.d/<profile.name>
be leveraged.

FIGURE 28. Commands to disable an AppArmor profile.


sudo apt install apparmor
To disable AppArmor and unload the kernel module, the
FIGURE 24. Command to install AppArmor commands referenced in Figure 29 can be leveraged:

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

apparmor_status FIGURE 29. Commands to unload the AppArmor kernel module.

To re-enable AppArmor, the commands referenced in Figure 30


FIGURE 25. Command to verify if AppArmor is installed and configured.
can be leveraged.

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.

# all profiles For additional information about AppArmor, reference:


sudo aa-enforce /etc/apparmor.d/*
https://ubuntu.com/server/docs/security-apparmor

FIGURE 26. Command to verify if AppArmor is installed and configured.

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

Configure Iptables to Enforce Local Firewall Rules


Iptables is the local firewall enforcement control for Linux endpoints. Iptables configurations can be leveraged to control both
inbound and outbound layer 3 communications in Linux.

Figure 31 contains example commands to configure specific conditions using iptables in Linux.

# List iptables rules


sudo iptables -L -v -n

# Flush command to clean-up iptables rules


iptables –flush

# Modify the default chain policy to DROP (default = ACCEPT)


iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
# Note: When DROP is configured for both INPUT and OUTPUT, for every defined communication flow,
two (2) rules (one for incoming and one for outgoing) must be configured.

# Only allow Inbound SSH from a specific subnet


iptables -A INPUT -i eth0 -p tcp -s <XXX.XXX.XXX.XXX/XX> --dport 22 -m state --state
NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# Only allow Outbound SSH to a specific subnet


iptables -A OUTPUT -o eth0 -p tcp -d < XXX.XXX.XXX.XXX/XX> --dport 22 -m state --state
NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# Block a specific IP address Inbound


iptables -A INPUT -s <XXX.XXX.XXX.XXX> -j DROP

# Block a specific IP address Outbound


iptables -A OUTPUT -d <XXX.XXX.XXX.XXX> -j DROP

# Block a specific IP address and port Outbound


iptables -A OUTPUT -p tcp -d <XXX.XXX.XXX.XXX> --dport <XXXX> -j DROP

FIGURE 31. Example iptables configurations.

Once configured, iptables rules need to be saved using either of the commands referenced in Figure 32.

/sbin/service iptables save


/etc/init.d/iptables save

FIGURE 32. Commands to save iptables rules.

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/

• Uncomplicated Firewall (ufw) is available by default in Ubuntu distributions.


For additional details about ufw, reference https://wiki.ubuntu.com/
UncomplicatedFirewall

• Nftables is the default and recommended firewalling framework in Debian 10 and


later, and it replaces iptables. For additional details about nftables, reference
https://wiki.debian.org/nftables
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 13

Disable Unnecessary Services


Linux endpoints should be reviewed and hardened to protect against non-baselined services from being enabled and leveraged. To
see a listing of all enabled and running services on a Linux endpoint, the command service—status-all can be leveraged. Any running
services will have a “+” symbol associated (Figure 33).

[ + ] 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

FIGURE 33. Example output of running services.

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)

• rpcbind • smb (TCP/445)

• rsync • telnet (TCP/22)

• 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 sudo command allows users to run programs with


sudo cp /etc/pam.d/common-password /root/
the security privileges of another user. By default, sudo
sudo nano /etc/pam.d/common-password
runs commands with superuser privileges. Access to the
sudo privilege is managed through the /etc/sudoers # Edit parameters
file. Alternatively, file entries can also be created in the / password requisite pam_cracklib.so retry=1
etc/sudoers.d folder to provide sudo access to a user. minlen=15 ucredit=-1 lcredit=-1 dcredit=-1
Organizations should review the /etc/sudoers file and /etc/ ocredit=-1
sudoers.d folder to identify any groups that may have sudo
access. Membership to any groups that have sudo access should
FIGURE 38. Steps to enforce strong password requirements on a Linux endpoint.
be reviewed.

In RHEL, the group “wheel” has sudo access as part of the


default configuration. The command referenced in Figure 36
can be used to identify all the members of a group (e.g., “wheel”)
on a RHEL endpoint.

grep wheel /etc/group

FIGURE 36. Command to list all members of the wheel group.


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 16

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.

auth required pam_faillock.so preauth audit silent deny=5 unlock_time=900


auth [success=1 default=bad] pam_unix.so
auth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=900
auth sufficient pam_faillock.so authsucc audit deny=5 unlock_time=900

FIGURE 39. Enable Lockout for failed password attempts.

The setting referenced in Figure 40 will prevent root account lockout as a result of an account lockout configuration.

auth required /lib/security/$ISA/pam_tally.so onerr=fail no_magic_root

FIGURE 40. Configuration to protect root accountsa from lockout.

The setting referenced in Figure 41 will enforce that the sha512 hashing algorithm is used as part of the password storage configuration.

password sufficient pam_unix.so sha512

FIGURE 41. Configure usage of sha512 for password hashing.

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.

Interactive Logon Restrictions


Organizations should configure the shell field in the /etc/passwd file to “/sbin/nologin” for accounts that don’t require interactive
logons, which effectively disables shell access for an account (Figure 42).

usermod -s /sbin/nologin <user>

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

Auditing and Visibility


System Auditing Configurations Figure 43 provides sample auditd.conf configuration options
Organizations should review Linux endpoint auditing that reflect optimized settings for both logging and performance.
configurations present in the Linux Auditing System (AuditD) to These settings should be tested on a subset of Linux endpoints to
ensure that events and detections are recorded and available for ensure that they are optimized for the current environment.
review and analysis.

Linux Auditing System (Auditd) local_events = yes


AuditD is a feature for Linux endpoints that provides logging write_logs = yes
log_file = /var/log/audit/audit.log
of actions such as system calls, file access, authentication,
log_group = root
and other security-related events. When installed (sudo apt- log_format = RAW
install auditd) and enabled (sudo service auditd flush = INCREMENTAL
start), there are several types of security events that are freq = 50
recorded, such as: num_logs = 99
max_log_file = 50
• Modification to audit configurations and audit log files. max_log_file_action = ROTATE
• Changes to trusted databases (e.g., /etc/passwd). priority_boost = 4
disp_qos = lossy
• Auditing and monitoring /etc/passwd for write, append, and #dispatcher = /sbin/audispd
read actions (using auditctl). name_format = NONE
• Attempts to export information out of the system. ##name = mydomain
space_left = 524
• Changes to user authentication mechanisms (e.g., SSH) . space_left_action = EMAIL
• Modifications to user and group associations. verify_email = yes
action_mail_acct = root
• Login and logout events. admin_space_left = 256
• Unsuccessful unauthorized file access attempts. admin_space_left_action = SUSPEND
disk_full_action = SUSPEND
• Privileged commands being invoked. disk_error_action = SUSPEND
• File deletion events. use_libwrap = yes
##tcp_listen_port = XX
• Changes to privileged functions (e.g., sudoers). tcp_listen_queue = 5
• Kernel module loading and unloading. tcp_max_per_addr = 1
##tcp_client_ports = 1024-65535
• Auditing of all privileged functions. tcp_client_max_idle = 0
• File mount conditions. enable_krb5 = no
krb5_principal = auditd
• Locations of public/private keys (within the .ssh directory) ##krb5_key_file = /etc/audit/audit.key
distribute_network = no
While there are many benefits of enabling auditd, there are also
some potential performance impacts. Once configured, auditd
logs can quickly accumulate on an endpoint, so organizations FIGURE 43. Example auditd configuration settings.

should have a mechanism in place to forward audit logs to a log


aggregation tool or a SIEM. To enhance the performance of auditd,
it is recommended to configure the /etc/audit/auditd.conf
file to allow for the endpoint to have enough time to accumulate
the logs to forward off the endpoint, as well as ensuring that logs
are written to disk and not to the event buffer to protect against
overutilization of the userspace (Figure 43).
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 18

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.

Learn more at www.mandiant.com

Mandiant About Mandiant


11951 Freedom Dr, 6th Fl, Reston, VA 20190 Since 2004, Mandiant® has been a trusted partner to security-conscious
(703) 935-1700 organizations. Today, industry-leading Mandiant threat intelligence and
833.3MANDIANT (362.6342) expertise drive dynamic solutions that help organizations develop more
[email protected] effective programs and instill confidence in their cyber readiness.

©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

TABLE 2. Change log.

Version/Date Notes

1.0: March 15, 2022 Initial Document

You might also like