Gentoo Security Benchmark

Version 1.

This benchmarks helps people in improving their system configuration to be more resilient against attacks and vulnerabilities with little to no impact on the system functionality.

Applicable platforms

  • cpe:/o:gentoo:linux

Revision history

  • draft (as of 2011-11-23)

1. Introduction

Since years, Gentoo Linux has a Gentoo Security Handbook which provides a good insight in secure system configuration for a Gentoo systems. Although this is important, an improved method for describing and tuning a systems' security state has emerged: SCAP, or the Security Content Automation Protocol.

1.1. A little more about SCAP and OVAL

Within SCAP, NIST has defined some new standards of which XCCDF and OVAL are notably important in light of the guide you are currently using.

  • XCCDF (Extensible Configuration Checklist Description Format) is a specification language for writing security checklists and benchmarks (such as the one you are reading now)

  • OVAL (Open Vulnerability and Assessment Language) is a standard to describe and validate system settings


Thanks to the OVAL and XCCDF standards, a security engineer can now describe how the state of a system should be configured, how this can be checked automatically and even report on these settings. Furthermore, within the description, the engineer can make "profiles" of different states (such as a profile for a workstation, server (generic), webserver, LDAP server, ...) and reusing the states (rules) identified in a more global scope.

1.2. Using this guide

The guide you are currently reading is the guide generated from this SCAP content (more specifically, the XCCDF document) using openscap, a free software implementation for handling SCAP content. Within Gentoo, the package app-forensics/openscap provides the tools, and the following command is used to generate the HTML output:

### Command to generate this guide ###
# oscap xccdf generate guide scap-gentoo-xccdf.xml > output.html

Secondly, together with this XCCDF XML, you will also find an OVAL XML file. The two files combined allow you to automatically validate various settings as documented in the benchmark. Now, for Gentoo, no specific tests exist yet so we need to work around this a small bit.

Create a file called emerge-info-verbose in a working directory somewhere (say /var/tmp/genoval_output), do the same for the kernel configuration (but call the file kernel-config) and export the environment variable GENOVAL_SCRIPTOUTPUTDIR to this directory:
### Generate output for the tests ###
# mkdir /var/tmp/genoval_output
# export GENOVAL_SCRIPTOUTPUTDIR=/var/tmp/genoval_output
# emerge --info --verbose > /var/tmp/genoval_output/emerge-info-verbose
# zcat /proc/config.gz > /var/tmp/genoval_output/kernel-config

Now, to validate the tests, you can use the following commands:
### Testing the rules mentioned in the XCCDF document ###
# oscap xccdf eval --profile Gentoo-Default scap-gentoo-xccdf.xml

To generate a full report in HTML as well, you can use the next command:
### Testing the rules and generating an HTML report ###
# oscap xccdf eval --profile Gentoo-Default --results xccdf-results.xml --report report.html scap-gentoo-xccdf.xml

During the development of these security rules, we will try to include fix commands as well. These can be used by oscap to generate a script that automatically fixes the settings that have failed in the report (as long as this is possible in an unattended manner). However, be advised that this is experimental and you should definitely validate the fix script before you run it.

The following command can be used to generate the fix script:
### Generating a fix script ###
# scap xccdf generate fix --profile Gentoo-Default --result-id OSCAP-Test-Gentoo-Default xccdf-results.xml > fix.sh

The xccdf-results.xml file is generated from the previous command and the OSCAP-Test- prefix is mandatory (the rest is the name of the XCCDF profile).

Finally, this benchmark will suggest some settings which you do not want to enable. That is perfectly fine - even more, some settings might even raise eyebrows left and right. I'll try to document the reasoning behind the settings but you are free to deviate from them. If that is the case, you might want to disable the rules in the XCCDF document so that they are not checked on your system.

Also, the tests in the OVAL are not written with the intelligence that the tool is or is not installed. So a test that checks the content of sshd_config will fail (error actually) if the file doesn't exist. Although this can be made much more intelligent, this is not the scope of this document (yet).

1.3. Available XCCDF Profiles

As mentioned earlier, the XCCDF document supports multiple profiles. For the time being, two profiles are defined:

  • Gentoo-Default contains tests that are quick to validate

  • Gentoo-Default-Full contains all tests, including those that take a while (for instance because they perform full file system scans)

Substitute the profile information in the commands above with the profile you want to test on.

2. Before You Start

Before you start deploying Gentoo Linux and start hardening it, it is wise to take a step back and think about what you want to accomplish. Setting up a more secured Gentoo Linux isn't a goal, but a means to reach something. Most likely, you are considering setting up a Gentoo Linux powered server. What is this server for? Where will you put it? What other services will you want to run on the same OS? Etc.

2.1. Infrastructure Architecturing

When considering your entire IT architecture, many architecturing frameworks exist to write down and further design your infrastructure. There are very elaborate ones, like TOGAF (The Open Group Architecture Framework), but smaller ones exist as well.

A well written and maintained infrastructure architecture helps you position new services or consider the impact of changes on existing components. And the reason for mentioning such a well designed architecture in a hardening guide is not weird.

Security is about reducing risks, not about harassing people or making work for a system administrator harder. And reducing risks also means that you need to keep a clear eye out on your architecture and all its components. If you do not know what you are integrating, where you are putting it or why, then you have more issues to consider than hardening a system.

2.2. Mapping Requirements

When you design a service, you need to take both functional and non-functional requirements into account. That does sound like overshooting for a simple server installation, but it is not. Have you considered auditing? Where do the audit logs need to be sent to? What about authentication? Centrally managed, or manually set? And the server you are installing, will it only host a particular service, or will it provide several services?

When hosting multiple services on the same server, make sure that the server is positioned within your network on an acceptable segment. It is not safe to host your central LDAP infrastructure on the same system as your web server that is facing the Internet.

References

  1. IBM DeveloperWorks article on "Capturing Architectural Requirements". URL: <https://www.ibm.com/developerworks/rational/library/4706.html>.

2.3. Non-Software Security Concerns

From the next chapter onwards, we will only focus on the software side hardening. There are of course also non-software concerns that you should investigate.

References

  1. Site Security Handbook (RFC2196). URL: <https://www.rfc-editor.org/info/rfc2196>.

2.3.1. Physical Security

Make sure that your system is only accessible (physically) by trusted people. Fully hardening your system, only to have a malicious person take out the harddisk and run away with your confidential data is not something you want to experience.

When physical security cannot be guaranteed (like with laptops), make sure that theft of the device only results in the loss of the hardware and not of the data and software on it (backups), and also that the data on it cannot be read by unauthorized people. We will come back on disk encryption later.

References

  1. Data Center Physical Security Checklist (SANS, PDF). URL: <http://www.sans.org/reading_room/whitepapers/awareness/data-center-physical-security-checklist_416>.

2.3.2. Policies and Contractual Agreements

Create or validate the security policies in your organization. This is not only as a stick (against internal people who might want to abuse their powers) but also to document and describe why certain decisions are made (both architecturally as otherwise).

References

  1. Technical Writing for IT Security Policies in Five Easy Steps (SANS, PDF). URL: <http://www.sans.org/reading_room/whitepapers/policyissues/technical-writing-security-policies-easy-steps_492>.
  2. Information Security Policy Templates (SANS). URL: <https://www.sans.org/security-resources/policies/>.

3. Installation Configuration

Let's focus now on the OS hardening. Gentoo Linux allows you to update the system as you want after installation, but it might be interesting to consider the following aspects during installation if you do not want a huge migration project later.

3.1. Storage Configuration

Your storage is of utmost importance in any environment. It needs to be sufficiently fast, not to jeopardize performance, but also secure and manageable yet still remain flexible to handle future changes.

3.1.1. Partitioning

Know which locations in your file system structure you want on a different partition or logical volume. Separate locations allow for a more distinct segregation (for instance, hard links between different file systems) and low-level protection (file system corruption impact, but also putting the right data on the right storage media).

References

  1. Filesystem Hierarchy Standard. URL: <http://www.pathname.com/fhs/>.

3.1.1.1. /home Location

The /home location should be on its own partition, allowing the administrator to mount this location with specific options targetting the file systems' security settings or quota.

3.2. Use a Hardened Toolchain

When you install Gentoo, use the hardened stages and hardened toolchain. The hardened toolchain includes additional security patches, such as support for non-executable program stacks and buffer overflow detection.

During installation, make sure that the default hardened toolchain is selected, not one of the -hardenedno* as those are toolchains where specific settings are disabled. The -vanilla one is a toolchain with no hardened patches.

### Using the appropriate hardened toolchain ###
# gcc-config -l
 [1] x86_64-pc-linux-gnu-4.4.5 *
 [2] x86_64-pc-linux-gnu-4.4.5-hardenednopie
 [3] x86_64-pc-linux-gnu-4.4.5-hardenednopie.gcc-config-ref
 [4] x86_64-pc-linux-gnu-4.4.5-hardenednopiessp
 [5] x86_64-pc-linux-gnu-4.4.5-hardenednossp
 [6] x86_64-pc-linux-gnu-4.4.5-vanilla

4. System Settings

Within this chapter, we describe the (recommended) settings that can be adjusted relatively easily, even when a Gentoo installation has already been performed.

Table of Contents

4.1. Mounts and Mount Points

When mounting file systems, options can be presented that add or remove features from the mount point. Some of these options can be used to restrict actions taken or originating from the file system.

Mount options can be set in /etc/fstab in the fourth column.

### Setting mount options###
# vim /etc/fstab
[...]
tmpfs      /tmp      tmpfs      defaults,nosuid,noexec,nodev   0 0

Important mount options that are used later are:

  • nosuid will ignore SUID bits on binaries. If such a binary is encountered, it is executed as if it did not have the SUID bit set.

  • noexec will prevent direct execution of files or binaries from this partition.

  • nodev will ignore device files in this partition.


Even though these mount options can be worked around, it is a first line of defence against popular exploits and worms.

4.1.1. Temporary Files

The /tmp location is world writable, allowing for any service to put temporary files in it that are required during service operation.

This location should be a tmpfs file system (so that its content is cleared during shut down or reboot) and mounted with nosuid,noexec and nodev mount options (to reduce the impact when an exploit is attempted from within this location).

### Sample /etc/fstab line for /tmp ###
tmpfs   /tmp   tmpfs       defaults,nosuid,noexec,nodev     0 0

4.1.2. Home Directories

The /home location is used to host end user files. To reduce the risk of an exploit being launched, it is adviseable to mount this partition with the nosuid,nodev mount options.

### Sample /etc/fstab line for /home ###
/dev/mapper/volgrp-home   /home   ext4     noatime,nosuid,nodev,data=journal   0 2

4.1.3. Quota's

Most file systems support the notion of quotas - limits on the amount of data / files you are allowed to have on that particular file system.

To enable quotas, first configure your Linux kernel to include CONFIG_QUOTA.

Next, install the sys-fs/quota package.

### Installing quota ###
# emerge quota
Then add usrquota and grpquota to the partitions (in /etc/fstab) where you want to enable quotas on. For instance, the following snippet from /etc/fstab enables quotas on /var and /home.
### Example quota definition in /etc/fstab ###
/dev/mapper/volgrp-home  /home  ext4  noatime,nodev,nosuid,usrquota,grpquota  0 0
/dev/mapper/volgrp-var   /var   ext4  noatime,usrquota,grpquota               0 0
Finally, add the quota service to the boot runlevel.
### Adding quota to the boot runlevel ###
# rc-update add quota boot
Reboot the system so that the partitions are mounted with the correct mount options and that the quota service is running. Then you can setup quotas for users and groups.

References

  1. Managing Disk Usage with Quotas (LinuxHomeNetworking). URL: <http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch28_:_Managing_Disk_Usage_with_Quotas>.

4.2. Services

Services (daemons) are the primary reason for a server to exist. They represent the function of the server. For instance, a web server will run the apache2 or lighttpd service. A name server will run the named service.

In this benchmark, we will only focus on those services that are either default available on a Gentoo installation (like SSHd) or that are commonly used in Gentoo server architectures (like rsync). For the other services, I refer to other benchmarks.

References

  1. Center for Internet Security, host of many service benchmarks. URL: <http://www.cisecurity.org>.

4.2.1. Disable Unsafe Services

We recommend not to enable the following services unless absolutely necessary. These services use plain-text protocols and as thus unsafe to use on untrusted networks (like the Internet, but also internal networks).

  • Telnet service

  • FTP Service


It is recommended to substitute these services with their more secure counterparts (like sFTP, SSH, ...).

4.2.2. Require Single-User Boot to Give Root Password

When a system is booted in single user mode, some users might find it handy to immediately get a root prompt; others even have a specific bootloader entry to boot in single user mode.

It is important that, for a more secure server environment, even booting in single user mode requires the user to enter the root password. This is already done by default in Gentoo and is part of /etc/inittab's definition:

### Ensure sulogin is available for single user mode ###
su0:S:wait:/sbin/rc single
su1:S:wait:/sbin/sulogin

4.2.3. Properly Configure TCP Wrappers

With TCP wrappers, services that support TCP wrappers (or those started through xinetd) should be configured to only accept communication with trusted hosts. With the use of /etc/hosts.allo and /etc/hosts.deny, proper access control lists can be created.

More information on the format of these files can be obtained through man 5 hosts_access.

4.2.4. SSH Service

The SSH service is used for secure remote access towards a system, but also to provide secure file transfers.

4.2.4.1. Root Logon Through SSH Is Not Allowed

SSH should be configured so that the root user is not allowed to log on remotely. This can be accomplished by editing /etc/ssh/sshd_config and setting PermitRootLogin no as the default is "yes".

### Setting PermitRootLogin in /etc/ssh/sshd_config ###
PermitRootLogin no

4.2.4.2. Public Key Authentication Only

SSH should be configured to only allow authentication based on public/private keys. Password-based authentication is too weak; since SSH is used in 99% of the cases for administrative purposes, a leaked password can have major consequences.

Instead, public/private key authentication would require the adversary to have access to the private key and the passphraze with which the private key is protected.

Now, even leaked private keys have occurred (and will occur again), so it is important that the users know that the private key is not to be copied, and regular reviews of your audit logs is still mandatory.

### Using public key authentication ###
PubkeyAuthentication yes

4.2.4.3. Disable UsePAM for SSH

Although this is the default setting, I still find it important to mention it as many users tend to enable it. UsePAM should remain disabled, and this for the following reasons:

  • When enabled, the sshd daemon must run as root user. Without, sshd can leverage the capabilities offered through the kernel without requiring root privileges.

  • When enabled, public key authentication can be worked around, accepting regular password authentication again.

4.2.4.4. Only Allow Version 2

The SSH daemon should only allow version 2 connections. Although this is default for recent OpenSSH implementations, some users might still support version 1 in their configuration file.

The Protocol directive is used to specify which protocol versions are supported. If defined, it should only contain Protocol 2.

4.2.4.5. Only Allow Specific Groups to Log On

With the AllowUsers and AllowGroups you can fine-tune which accounts are allowed to log on through SSH.

4.2.4.6. Listen on Management Interface

If you have a multi-homed system (i.e. the system has multiple interfaces), only have SSHd running on those interfaces that you use for management tasks. This can be accomplished with the ListenAddress directive.

4.2.4.7. Use Privilege Separation

With privilege separation enabled, the SSH daemon has a tiny footprint running as root, whereas the rest of the application runs as an unprivileged process to deal with the incoming network traffic. This can be tuned with UsePrivilegeSeparation yes.

This is the default for OpenSSH.

4.2.4.8. Disable TCP Forwarding

SSH supports "tunneling", where packets are forwarded over a (partially) secure channel towards another location. If you do not need this, disable TCP forwarding through AllowTcpForwarding no.

4.2.4.9. Disable X11 Forwarding

SSH supports forwarding X11 packets, so X11 applications started on the remote system have their display shown on the client. If you do not need this, disable X11 forwarding through X11Forwarding no.

This is the default for OpenSSH.

4.2.4.10. Enable Strict Mode

When StrictModes yes is enabled, the SSH daemon will only allow a remote user to log on when some of the important files in that users' home directory have the proper privileges and ownership.

This is the default for OpenSSH.

4.2.5. Cron Service

A cron service is used to schedule tasks and processes on predefined times. Cron is most often used for regular maintenance tasks.

4.2.5.1. Only Allow Trusted Accounts Cron Access

Only allow trusted accounts to use cron. You should list trusted accounts in /etc/cron.allow.

4.2.6. At Service

The at service allows users to execute a task once on a given time. Unlike cron, this is not scheduled repeatedly - once executed, the task is considered completed and at will not invoke it again.

4.2.6.1. Only Allow Trusted Accounts At Access

Only allow trusted accounts to use at. You should list trusted accounts in /etc/at.allow.

4.2.7. NTP Service

With NTP, systems can synchronise their clocks, ensuring correct date and time information. This is important as huge clock drift could cause misinterpretation of log files or even unwanted execution of commands.

4.2.7.1. Synchronise The System Clock

Synchronise your systems' clock with an authorative NTP server, and use the same NTP service for all your systems.

You can accomplish this by regularly executing ntpdate, but you can also use a service like net-misc/ntp's ntpd.

4.3. Portage Settings

The package manager of any system is a very important tool. It is responsible for handling proper software deployments, but also offers features that should not be neglected, like security patch roll-out.

For Gentoo, the package manager offers a great deal of flexibility (as that is the goal of Gentoo anyhow). As such, good settings for a more secure environment within Portage (assuming that you use Portage as package manager) are important.

4.3.1. USE Flags

USE flags in Gentoo are used to tune the functionality of many components and enable or disable features.

For a well secured environment, there are a couple of USE flags that should be set in a global manner. These USE flags are

  • pam to enable Pluggable Authentication Modules support

  • tcpd for TCP wrappers support

  • ssl for SSL/TLS support

Pluggable Authentication Modules are a powerful mechanism to manage authentication, authorization and user sessions. Applications that support PAM can be tuned to the liking of the organization, leveraging central authentication, password policies, auditing and more.

With TCP wrappers, services can be shielded from unauthorized access on host level. It is an access control level mechanism which allows you to identify allowed (and denied) hosts or network segments on application level.

Finally, leveraging Secure Sockets Layer (or the standardized Transport Layer Security) allows applications to encrypt network communication or even implement a client-certificate based authentication mechanism.

You should set the USE flags globally in /etc/make.conf.

### Setting the USE flag in /etc/make.conf ###
USE="... pam tcpd ssl"

4.3.2. Fetching Signed Portage Tree

Gentoo Portage supports fetching signed tree snapshots using emerge-webrsync. This is documented in the Gentoo Handbook, but as it is quite easy, here you can find the instructions again:

### Using emerge-webrsync with GPG signatures ###
# mkdir -p /etc/portage/gpg
# chmod 0700 /etc/portage/gpg
# gpg --homedir /etc/portage/gpg --keyserver subkeys.pgp.net --recv-keys 0x239C75C4
# gpg --homedir /etc/portage/gpg --edit-key 0x239C75C4 trust
After this, you can edit /etc/make.conf:
### Editing make.conf for signed portage trees ###
FEATURES="webrsync-gpg"
PORTAGE_GPG_DIR="/etc/portage/gpg"
SYNC=""

4.4. Kernel Configuration

The Linux kernel should be configured using a sane security standard in mind. When using grSecurity, additional security-enhancing settings can be enabled.

4.4.1. Use grSecurity

grSecurity is a set of kernel patches that provides additional countermeasures against popular exploit methods and common vulnerabilities. Although the patchset is not part of the mainstream Linux kernel sources, Gentoo offers grSecurity through the hardened-sources kernel package.

References

  1. grSecurity Homepage. URL: <https://grsecurity.net>.
  2. Gentoo grSecurity v2 Guide. URL: <http://www.gentoo.org/proj/en/hardened/grsecurity.xml>.

4.4.1.1. Use PaX

With PaX, additional protection against memory corruption bugs and exploits is enabled. We recommend to enable the following settings:

  • Use legacy ELF header marking (CONFIG_PAX_EI_PAX) and Use ELF program header marking (CONFIG_PAX_PT_PAX_FLAGS) so that you can enable/disable PaX settings on a per-binary basis.

  • Enforce non-executable pages (CONFIG_PAX_NOEXEC) to disable allocation of memory that is both executable (contains runnable code) and writeable. Write- and executable pages are risky as it allows attackers to introduce code (through overflows or other methods) in memory and then execute that code. However, the downside is that there are still applications (or drivers) that depend on RWX memory.

  • Segmentation based non-executable pages (CONFIG_PAX_SEGMEXEC) or Paging based non-executable pages (CONFIG_PAX_PAGEEXEC) will support the non-executable pages through memory segmentation or paging rules.

  • Emulate trampolines (CONFIG_PAX_EMUTRAMP) if you are on x86_32 architecture (the option is not available for x86_64). This will enable emulation of trampolines (small bits of code in non-executable memory pages) for those applications that you enable this on (which can be triggered through chpax or paxctl).

  • Restrict mprotect() (CONFIG_PAX_MPROTECT) will restrict the use of mprotect() so that applications cannot switch the purpose of pages (executable vs non-executable and such) after creating them.

  • Address Space Layout Randomization (CONFIG_PAX_ASLR) to introduce some randomization in the memory allocation so that attackers will find it much more difficult to guess the address of specific pages correctly.

  • Randomize kernel stack base (CONFIG_PAX_RANDKSTACK) to randomize every task's kernel stack on each system call, making it more difficult to both guess locations as well as use leaked information from previous calls.

  • Randomize user stack base (CONFIG_PAX_RANDUSTACK) to randomize every task's userland stack, providing similar protection as mentioned earlier but for user applications.

  • Randomize mmap() base (CONFIG_PAX_RANDMMAP) to randomize the base address of mmap() requests (unless the requests specify an address themselves). This will cause dynamically loaded libraries to appear at random addresses.

4.4.1.2. Enable file system protection measures

In the grSecurity patches, a set of additional protections are included to thwart information leakage as well as further limit chroot environments. We recommend to enable the following settings:

  • Proc restrictions (CONFIG_GRKERNSEC_PROC) so that the /proc file system will be altered to enhance privacy (prevent information leakage).

  • Restrict /proc to user only (CONFIG_GRKERNSEC_PROC_USER) so that non-root users cannot see processes of other users.

  • Allow special group (CONFIG_GRKERNSEC_PROC_USERGROUP) so that the members of a specific group can see other users' processes and network-related information.

  • Additional restrictions (CONFIG_GRKERNSEC_PROC_ADD) will prevent non-root users to see device information and memory information which can be (ab)used for exploit purposes.

  • Linking restrictions (CONFIG_GRKERNSEC_LINK) will prevent users to follow symlinks that are owned by other users in world-writeable sticky directories such as /tmp (unless that user is the owner of that directory). This prevents a certain kind of race conditions.

  • FIFO restrictions (CONFIG_GRKERNSEC_FIFO) will prevent users to write into FIFOs in world-writeable sticky directories (like /tmp if they do not own these FIFOs themselves.

  • Chroot jail restrictions (CONFIG_GRKERNSEC_CHROOT and all chroot-related options) to make the chroot jails more strict and less easy to break out from.

4.4.1.3. Enable Trusted Path Execution

When using sys-kernel/hardened-sources, enable CONFIG_GRKERNSEC_TPE, which enabled Trusted Path Execution, a safety measure that ensures that, for a set of users, these users can only execute binaries and scripts from root-owned directories.

References

  1. Gentoo Hardened grSecurity TPE Guide. URL: <http://www.gentoo.org/proj/en/hardened/grsec-tpe.xml>.

4.4.2. Kernel Tunables (Sysctl)

The Linux kernel offers an interface, called sysctl, allowing to fine-tune kernel parameters (and even changing its behavior). Many parameters offered through sysctl allow an administrator to further strengthen his systems' security.

To read and change sysctl parameters, you can use the sysctl command or the /etc/sysctl.conf file (which is used by the sysctl service (init script), part of the default boot process.

### Using sysctl command to read and set variables ###
# sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1
# sysctl -w net.ipv4.ip_forward=0
The sysctl values can also be read through the /proc/sys file system.

4.4.2.1. Disable IPv4 Forwarding

The net.ipv4.ip_forward sysctl setting controls if IP forwarding is allowed or not on the system.

Unless the system is used as a router or gateway, IPv4 forwarding should be disabled.

4.4.2.2. Enable Source Route Verification

To offer additional protection against IP spoofing, enable source route verification on all interfaces. This is governed through the net.ipv4.conf.*.rp_filter=1 setting.

With source route verification, the Linux kernel validates that an IP package comes from the right interface. In other words, on a multi-homed system, packets that claim to be from your internal network on your external interface are dropped (and vice versa).

4.4.2.3. Disable IP Source Routing

Disable IP source routing on all interfaces through the net.ipv4.conf.*.accept_source_route=0 setting.

IP source routing would allow a remote user (the sender) to specify the route that the package should take, rather than use the (default) routing tables used by the routers between the sender and the destination. This could be (ab)used to spoof IP addresses and still get the replies (rather than sending the replies to the real owner of the IP address).

4.4.2.4. Disable ICMP Redirects

Set net.ipv4.conf.*.accept_redirects=0 to disable ICMP redirect support on the interfaces.

ICMP redirect messages are used by routers to inform hosts to use a different gateway than the one used. These packages should only be sent by the gateway of the system, but since you control that gateway and know when this gateway is changed, there is no point in allowing ICMP redirect messages on your system. After all, this would allow for "remote" updating of your routing table, which could allow an attacker to get all packets you want to send to the outside first (rather than the packets immediately going to the real gateway).

4.4.2.5. Ignore ICMP Echo Broadcasts

When net.ipv4.icmp_echo_ignore_broadcasts=1 is set, then your system will not reply to broadcast 'ping' requests (a ping is an ICMP Echo request). Similar to hiding a WIFI SSID, this makes your system just a tiny bit more hidden from scanners.

4.4.2.6. Ignore ICMP Bogus Error Responses

When an invalid response is given to broadcast frames (which occurs sometimes in erronous routers), the Linux kernel will by default log this event. To ensure that these (harmless) reports do not clutter your logs, you can disable this through net.ipv4.icmp_ignore_bogus_error_responses by setting it to 1.

4.4.2.7. Enable Logging of Martians

When you receive a packet that seemingly originates from a location where you have no route for, this package is dropped silently. You can enable logging of these packets (which are called martians) so that you at least are aware of them.

Note that martians can only exist if you do not use a "default gateway", since a default gateway always matches (if no other route does) for any IP address.

4.5. Bootloader Configuration

The bootloader (be it GRUB or another tool) is responsible for loading the Linux kernel and handing over system control to the kernel. But boot loaders also allow for a flexible approach on kernel loading, which can be (ab)used to work around security mechanisms.

4.5.1. Password Protect GRUB

It is recommended to password-protect the GRUB configuration so that you cannot modify boot options during a boot without providing the valid password.

You can accomplish this by inserting password abc123 in /boot/grub/grub.conf (which will set the password to "abc123"). But if you do not like having a clear-text password in the configuration file, you can hash it. Just start grub and, in the grub-shell, type md5crypt.

### Getting a hashed password for GRUB ###
# grub

GRUB version 0.92 (640K lower / 3072K upper memory)

[ Minimal BASH-like line editing is supported. ... ]

grub> md5crypt

Password: abc123
Encrypted: $1$18u.M0$J8VbOsGXuoG9Fh3n7ZkqY.

grub> quit

You can then use this hashed password in grub.conf using password --md5 $1$18u.M0$J8VbOsGXuoG9Fh3n7ZkqY..

4.5.2. Password Protect LILO

It is recommended to password-protect the LILO configuration so that you cannot modify boot options during a boot without providing the valid password.

You can accomplish this by inserting password=abc123 followed by restricted in the /etc/lilo.conf file. It is also possible to do this on a per-image level.

### Setting a password for LILO in /etc/lilo.conf ###
password=abc123
restricted
delay=3

image=/boot/bzImage
        read-only
        password=def456
        restricted

The restricted keyword is needed to have LILO only ask for the password if a modification is given. If the defaults are used, then no password needs to be provided.

Rerun lilo after updating the configuration file.

4.6. Authentication and Authorization Settings

An important part in a servers' security is its authentication and authorization support. We have already described how to build in PAM support (through the Portage USE flags), but proper authentication and authorization settings are mode than just compiling in the necessary functionality.

4.6.1. Restrict root System Logon

To restrict where the root user can directly log on, edit /etc/securetty and specify the supported terminals for the root user.

When properly configured, any attempt to log on as the root user from a non-defined terminal will result in logon failure.

A recommended setting is to only allow root user login through the console and the physical terminals (tty0-tty12).

### /etc/securetty ###
console
tty0
tty1
...
tty12

4.6.2. Allow Only Known Users to Login

When PAM is enabled, the /etc/security/access.conf file is used to check which users are allowed to log on and not (through the login application). These limits are based on username, group and host, network or tty that the user is trying to log on from.

By enabling these settings, you reduce the risk that a functional account (say apache) is abused to log on with, or that a new account is created as part of an exploit.

4.6.3. Restrict User Resources

When facing a DoS (Denial-of-Service) attack, reducing the impact of the attack can be done by limited resource consumption. Although the component that is under attack will even more quickly fail, the impact towards the other services on the system (including remote logon to fix things) is more limited.

In Gentoo Linux, the following methods are available to limit resources.

  • /etc/security/limits.conf defines the resource limits for logins that are done through a PAM-aware component (default in our setup)

  • /etc/limits defines the resource limits for logins that are done through login programs that are not PAM-aware.

Generally, you should suffice with setting /etc/security/limits.conf, which is the configuration file used by the pam_limits.so module.

Note that the settings are applicable on a per login session basis.

More information on these files and their syntax can be obtained through their manual pages.

### Reading the limits manual pages ###
# man limits.conf
# man limits

4.6.4. Enforce Password Policy

Usually most organizations have a password policy, telling their users how long their passwords should be and how often the passwords should be changed. Most users see this as an annoying aspect, so it might be best to enforce this policy.

Enforcing password policies is (partially) part of the sys-apps/shadow package (which is installed by default) and can be configured through the /etc/login.defs file. This file is well documented (using comments) and it has a full manual page as well to help you en route.

A second important player when dealing with password policies is the pam_cracklib.so library. You can then use this in the appropriate /etc/pam.d/* files. For instance, for the /etc/pam.d/passwd definition:

### Sample /etc/pam.d/passwd setting with cracklib ###
auth      required pam_unix.so shadow nullok
account   required pam_unix.so
password  required pam_cracklib.so difok=3 retry=3 minlen=8 dcredit=-2 ocredit=-2
password  required pam_unix.so md5 use_authok
session   required pam_unix.so
In the above example, the password is required to be at least 8 characters long, differ more than 3 characters from the previous password, contain 2 digits and 2 non-alphanumeric characters.

4.6.5. Review Password Strength Regularly

Regularly check the strength of your users' passwords. There are tools out there, like app-crypt/johntheripper which, given a /etc/shadow file (or sometimes even LDAP dump) try to find the passwords for the users.

When such a tool can guess a users' password, that users' password should be expired and the user should be notified and asked to change his password.

4.7. Session Settings

Unlike authentication and authorization settings, a session setting is one that is applicable to an authenticated and authorized user when he is logged on to the system.

4.7.1. Disable Access to User Terminals

By default, user terminals are accessible by others to write messages to (using write, wall or talk). It is adviseable to disable this unless explicitly necessary.

Messages can confuse users and trick them into performing malicious actions.

You can disable this by setting mesg n in /etc/profile. A user-friendly method for doing so in Gentoo is to create a file /etc/profile.d/disable_mesg which contains this command.

4.8. File and Directory Privileges and Integrity

Proper privileges on files makes it far more difficult to malicious users to obtain sensitive information or write/update files they should not have access to.

4.8.1. Limit World Writable Files and Locations

Limit (or even remove) the use of world writable files and locations. If a directory is world writable, you probably want to have the sticky bit set on it as well (like with /tmp).

You can use find to locate such files or directories.

### Using find to find world writable files and directories ###
# find / -perm +o=w ! \( -type d -perm +o=t \) ! -type l -print
The above command shows world writable files and locations, unless it is a directory with the sticky bit set, or a symbolic link (whose world writable privilege is not accessible anyhow).

4.8.2. Limit Setuid and Setgid File and Directory Usage

The setuid and setgid flags for files and directories can be used to work around authentication and authorization measures taken on the system. So their use should be carefully guarded.

In case of files, the setuid or setgid bit causes the application (if the file is marked as executable) to run with the privileges of the file owner (setuid) or group owner (setgid). It is necessary for applications that need elevated privileges, like su or sudo.

In case of directories, the setgit bit causes newly created files in that directory to automatically be owned by the same group as the mentioned (parent) directory.

4.8.3. Logs Only Readable By Proper Group

No log file in /var/log should be world readable. Log files should be limited by particular groups (either the group representing the service, like apache or portage, or a specific administrative group like wheel).

4.8.4. Files Only Used By Root Should be Root-Only

Some files, like /etc/shadow, are meant to be read (and perhaps modified) by root only. These files should never have privileges for group- or others.

A nonexhaustive list of such files is:

  • /etc/shadow which contains account password information (including password hashes)

  • /etc/securetty which contains the list of terminals where root is allowed to log on from

4.8.5. Review File Integrity Regularly

Deploy intrusion detection tool(s) to validate the integrity and privileges on important files. app-forensics/aide is an example of such a tool.

5. Data Flows

Clearly map out how data flows in and out of your server (and which data this is). You will need this anyhow when you want to add firewalls, but it also improves integration of the server in a larger infrastructure.

5.1. Backup Your Data

Make sure that your data is backed up. This is not only in case of server loss, but also when you accidentally remove files or have an awkward bug in a service that deleted important information.

5.1.1. Automated Backups

Automate backups on the system. If you need to perform a backup manually, then you are doing it wrong and will start forgetting it.

You can use scheduling software like cron to automatically take backups on regular intervals, or use a central backup solution like bacula.

5.1.2. Full Data Coverage

Many users that do take backups only do this on what they seem as important files. However, it is wise to make full system backups too as recreating an entire system from scratch could otherwise take days or even weeks.

5.1.3. Retention

Ensure that your backups use a long enough retention. It is not wise to take a single backup and overwrite this one over and over again, as you might want to recover a file that was corrupted long before you took your last backup.

There is no perfect retention period however, as the more backups you keep, the more storage you require and the more you need to invest in managing your backups.

In most cases, you will want to introduce a "layered" approach on retention. For instance, you can

  • keep daily backups for a week

  • keep weekly backups (say each monday backup) for a month

  • keep monthly backups (say each first monday) for a year

  • keep yearly backups for 30 years

5.1.4. Off-site Backups

Keep your backups off-site in case of disaster. But consider this location carefully. Investigate how fast you can put the backup there, but also retrieve it in case you need it. Also investigate if this location is juridically sane (are you allowed to put your location there, and do you trust this off-site location).

Also ensure that the backups are stored securely. If necessary, encrypt your backups.

5.1.5. Validate and Test

Validate that your backup system works. Try recovering files (for instance on a second server or different location) or even entire systems (virtualization is a great help here) and do this regularly.

6. Decommissioning Servers

When you want to decommission a server, you should take care that its data is safeguarded from future extraction.

Table of Contents

6.1. Wipe Disks

Clear all data from the disks on the server in a secure manner. Applications like shred (part of sys-apps/coreutils) can be used to security wipe data or even entire partitions or disks.

It is recommended to perform full disk wipes rather than file wipes. If you need to do this on file level, see if you can disable file system journaling during the wipe session as journaling might "buffer" the secure writes and only write the end result to the disk.

References

  1. NIST Publication "Guidelines for Media Sanitization" (PDF). URL: <http://csrc.nist.gov/publications/nistpubs/800-88/NISTSP800-88_rev1.pdf>.