Red Hat Training
A Red Hat training course is available for Red Hat Enterprise Linux
Security Guide
A Guide to Securing Red Hat Enterprise Linux
Robert Krátký
Martin Prpič
Tomáš Čapek
Stephen Wadeley
Yoana Ruseva
Miroslav Svoboda
Abstract
Chapter 1. Security Overview
Note
/lib
directory. When using 64-bit systems, some of the files mentioned may instead be located in /lib64
.
1.1. Introduction to Security
1.1.1. What is Computer Security?
1.1.1.1. How did Computer Security come about?
1.1.1.2. Security Today
1.1.1.3. Standardizing Security
- Confidentiality — Sensitive information must be available only to a set of pre-defined individuals. Unauthorized transmission and usage of information should be restricted. For example, confidentiality of information ensures that a customer's personal or financial information is not obtained by an unauthorized individual for malicious purposes such as identity theft or credit fraud.
- Integrity — Information should not be altered in ways that render it incomplete or incorrect. Unauthorized users should be restricted from the ability to modify or destroy sensitive information.
- Availability — Information should be accessible to authorized users any time that it is needed. Availability is a warranty that information can be obtained with an agreed-upon frequency and timeliness. This is often measured in terms of percentages and agreed to formally in Service Level Agreements (SLAs) used by network service providers and their enterprise clients.
1.1.2. SELinux
1.1.3. Security Controls
- Physical
- Technical
- Administrative
1.1.3.1. Physical Controls
- Closed-circuit surveillance cameras
- Motion or thermal alarm systems
- Security guards
- Picture IDs
- Locked and dead-bolted steel doors
- Biometrics (includes fingerprint, voice, face, iris, handwriting, and other automated methods used to recognize individuals)
1.1.3.2. Technical Controls
- Encryption
- Smart cards
- Network authentication
- Access control lists (ACLs)
- File integrity auditing software
1.1.3.3. Administrative Controls
- Training and awareness
- Disaster preparedness and recovery plans
- Personnel recruitment and separation strategies
- Personnel registration and accounting
1.1.4. Conclusion
1.2. Vulnerability Assessment
- The expertise of the staff responsible for configuring, monitoring, and maintaining the technologies.
- The ability to patch and update services and kernels quickly and efficiently.
- The ability of those responsible to keep constant vigilance over the network.
1.2.1. Thinking Like the Enemy
1.2.2. Defining Assessment and Testing
Warning
- Creates proactive focus on information security.
- Finds potential exploits before attackers find them.
- Results in systems being kept up to date and patched.
- Promotes growth and aids in developing staff expertise.
- Abates financial loss and negative publicity.
1.2.2.1. Establishing a Methodology
- http://www.owasp.org/ The Open Web Application Security Project
1.2.3. Evaluating the Tools
1.2.3.1. Scanning Hosts with Nmap
yum install nmap
command as the root user.
1.2.3.1.1. Using Nmap
nmap
command followed by the host name or IP address of the machine to scan:
nmap
<host name>
foo.example.com
, type the following at a shell prompt:
~]$ nmap foo.example.com
Interesting ports on foo.example.com: Not shown: 1710 filtered ports PORT STATE SERVICE 22/tcp open ssh 53/tcp open domain 80/tcp open http 113/tcp closed auth
1.2.3.2. Nessus
Note
1.2.3.3. Nikto
1.2.3.4. Anticipating Your Future Needs
1.3. Security Threats
1.3.1. Threats to Network Security
1.3.1.1. Insecure Architectures
1.3.1.1.1. Broadcast Networks
1.3.1.1.2. Centralized Servers
1.3.2. Threats to Server Security
1.3.2.1. Unused Services and Open Ports
1.3.2.2. Inattentive Administration
1.3.2.3. Inherently Insecure Services
1.3.3. Threats to Workstation and Home PC Security
1.3.3.1. Bad Passwords
1.3.3.2. Vulnerable Client Applications
1.4. Common Exploits and Attacks
Table 1.1. Common Exploits
Exploit | Description | Notes |
---|---|---|
Null or Default Passwords | Leaving administrative passwords blank or using a default password set by the product vendor. This is most common in hardware such as routers and firewalls, but some services that run on Linux can contain default administrator passwords as well (though Red Hat Enterprise Linux does not ship with them). |
Commonly associated with networking hardware such as routers, firewalls, VPNs, and network attached storage (NAS) appliances.
Common in many legacy operating systems, especially those that bundle services (such as UNIX and Windows.)
Administrators sometimes create privileged user accounts in a rush and leave the password null, creating a perfect entry point for malicious users who discover the account.
|
Default Shared Keys | Secure services sometimes package default security keys for development or evaluation testing purposes. If these keys are left unchanged and are placed in a production environment on the Internet, all users with the same default keys have access to that shared-key resource, and any sensitive information that it contains. | Most common in wireless access points and preconfigured secure server appliances. |
IP Spoofing | A remote machine acts as a node on your local network, finds vulnerabilities with your servers, and installs a backdoor program or Trojan horse to gain control over your network resources. |
Spoofing is quite difficult as it involves the attacker predicting TCP/IP sequence numbers to coordinate a connection to target systems, but several tools are available to assist attackers in performing such a vulnerability.
Depends on target system running services (such as
rsh , telnet , FTP and others) that use source-based authentication techniques, which are not recommended when compared to PKI or other forms of encrypted authentication used in ssh or SSL/TLS.
|
Eavesdropping | Collecting data that passes between two active nodes on a network by eavesdropping on the connection between the two nodes. |
This type of attack works mostly with plain text transmission protocols such as Telnet, FTP, and HTTP transfers.
Remote attacker must have access to a compromised system on a LAN in order to perform such an attack; usually the attacker has used an active attack (such as IP spoofing or man-in-the-middle) to compromise a system on the LAN.
Preventative measures include services with cryptographic key exchange, one-time passwords, or encrypted authentication to prevent password snooping; strong encryption during transmission is also advised.
|
Service Vulnerabilities | An attacker finds a flaw or loophole in a service run over the Internet; through this vulnerability, the attacker compromises the entire system and any data that it may hold, and could possibly compromise other systems on the network. |
HTTP-based services such as CGI are vulnerable to remote command execution and even interactive shell access. Even if the HTTP service runs as a non-privileged user such as "nobody", information such as configuration files and network maps can be read, or the attacker can start a denial of service attack which drains system resources or renders it unavailable to other users.
Services sometimes can have vulnerabilities that go unnoticed during development and testing; these vulnerabilities (such as buffer overflows, where attackers crash a service using arbitrary values that fill the memory buffer of an application, giving the attacker an interactive command prompt from which they may execute arbitrary commands) can give complete administrative control to an attacker.
Administrators should make sure that services do not run as the root user, and should stay vigilant of patches and errata updates for applications from vendors or security organizations such as CERT and CVE.
|
Application Vulnerabilities | Attackers find faults in desktop and workstation applications (such as e-mail clients) and execute arbitrary code, implant Trojan horses for future compromise, or crash systems. Further exploitation can occur if the compromised workstation has administrative privileges on the rest of the network. |
Workstations and desktops are more prone to exploitation as workers do not have the expertise or experience to prevent or detect a compromise; it is imperative to inform individuals of the risks they are taking when they install unauthorized software or open unsolicited email attachments.
Safeguards can be implemented such that email client software does not automatically open or execute attachments. Additionally, the automatic update of workstation software using Red Hat Network or other system management services can alleviate the burdens of multi-seat security deployments.
|
Denial of Service (DoS) Attacks | Attacker or group of attackers coordinate against an organization's network or server resources by sending unauthorized packets to the target host (either server, router, or workstation). This forces the resource to become unavailable to legitimate users. |
Source packets are usually forged (as well as rebroadcast), making investigation as to the true source of the attack difficult.
Advances in ingress filtering (IETF rfc2267) using
iptables and Network Intrusion Detection Systems such as snort assist administrators in tracking down and preventing distributed DoS attacks.
|
1.5. Security Updates
1.5.1. Updating Packages
Note
1.5.2. Verifying Signed Packages
/mnt/cdrom
, use the following command as the root user to import it into the keyring (a database of trusted keys on the system):
~]# rpm --import /mnt/cdrom/RPM-GPG-KEY
/etc/pki/rpm-gpg/
directory.
~]# rpm -qa gpg-pubkey*
gpg-pubkey-db42a60e-37ea5438
rpm -qi
command followed by the output from the previous command, as in this example:
~]# rpm -qi gpg-pubkey-db42a60e-37ea5438
Name : gpg-pubkey Relocations: (not relocatable)
Version : 2fa658e0 Vendor: (none)
Release : 45700c69 Build Date: Fri 07 Oct 2011 02:04:51 PM CEST
Install Date: Fri 07 Oct 2011 02:04:51 PM CEST Build Host: localhost
Group : Public Keys Source RPM: (none)
[output truncated]
~]# rpm -K /root/updates/*.rpm
alsa-lib-1.0.22-3.el6.x86_64.rpm: rsa sha1 (md5) pgp md5 OK
alsa-utils-1.0.21-3.el6.x86_64.rpm: rsa sha1 (md5) pgp md5 OK
aspell-0.60.6-12.el6.x86_64.rpm: rsa sha1 (md5) pgp md5 OK
gpg OK
. If it does not, make sure you are using the correct Red Hat public key, as well as verifying the source of the content. Packages that do not pass GPG verification should not be installed, as they may have been altered by a third party.
[main]
section of your /etc/yum.conf
file:
gpgcheck=1
1.5.3. Installing Signed Packages
rpm
-Uvh
<package>…
updates/
, under the /tmp
directory, run:
~]# rpm -Uvh /tmp/updates/*.rpm
Preparing... ########################################### [100%]
1:alsa-lib ########################################### [ 33%]
2:alsa-utils ########################################### [ 67%]
3:aspell ########################################### [100%]
rpm
-ivh
<kernel-package>
~]# rpm -ivh /tmp/updates/kernel-2.6.32-220.el6.x86_64.rpm
Preparing... ########################################### [100%]
1:kernel ########################################### [100%]
rpm
-e
<old-kernel-package>
~]# rpm -e kernel-2.6.32-206.el6.x86_64
~]# yum install kernel-2.6.32-220.el6.x86_64.rpm
~]# yum localinstall /root/updates/emacs-23.1-21.el6_2.3.x86_64.rpm
Note
Important
1.5.4. Applying the Changes
Note
- Applications
- User-space applications are any programs that can be initiated by a system user. Typically, such applications are used only when a user, script, or automated task utility launches them and they do not persist for long periods of time.Once such a user-space application is updated, halt any instances of the application on the system and launch the program again to use the updated version.
- Kernel
- The kernel is the core software component for the Red Hat Enterprise Linux operating system. It manages access to memory, the processor, and peripherals as well as schedules all tasks.Because of its central role, the kernel cannot be restarted without also stopping the computer. Therefore, an updated version of the kernel cannot be used until the system is rebooted.
- Shared Libraries
- Shared libraries are units of code, such as
glibc
, which are used by a number of applications and services. Applications utilizing a shared library typically load the shared code when the application is initialized, so any applications using the updated library must be halted and relaunched.To determine which running applications link against a particular library, use thelsof
command:lsof
<path>For example, to determine which running applications link against thelibwrap.so
library, type:~]#
lsof /lib64/libwrap.so*
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 13600 root mem REG 253,0 43256 400501 /lib64/libwrap.so.0.7.6 sshd 13603 juan mem REG 253,0 43256 400501 /lib64/libwrap.so.0.7.6 gnome-set 14898 juan mem REG 253,0 43256 400501 /lib64/libwrap.so.0.7.6 metacity 14925 juan mem REG 253,0 43256 400501 /lib64/libwrap.so.0.7.6 [output truncated]This command returns a list of all the running programs which use TCP wrappers for host access control. Therefore, any program listed must be halted and relaunched if thetcp_wrappers
package is updated. - SysV Services
- SysV services are persistent server programs launched during the boot process. Examples of SysV services include
sshd
,vsftpd
, andxinetd
.Because these programs usually persist in memory as long as the machine is booted, each updated SysV service must be halted and relaunched after the package is upgraded. This can be done using the Services Configuration Tool or by logging into a root shell prompt and issuing the/sbin/service
command:/sbin/service
<service-name>restart
Replace <service-name> with the name of the service, such assshd
. xinetd
Services- Services controlled by the
xinetd
super service only run when a there is an active connection. Examples of services controlled byxinetd
include Telnet, IMAP, and POP3.Because new instances of these services are launched byxinetd
each time a new request is received, connections that occur after an upgrade are handled by the updated software. However, if there are active connections at the time thexinetd
controlled service is upgraded, they are serviced by the older version of the software.To kill off older instances of a particularxinetd
controlled service, upgrade the package for the service then halt all processes currently running. To determine if the process is running, use theps
orpgrep
command and then use thekill
orkillall
command to halt current instances of the service.For example, if security errataimap
packages are released, upgrade the packages, then type the following command as root into a shell prompt:~]#
pgrep -l imap
1439 imapd 1788 imapd 1793 imapdThis command returns all active IMAP sessions. Individual sessions can then be terminated by issuing the following command as root:kill
<PID>If this fails to terminate the session, use the following command instead:kill
-9
<PID>In the previous examples, replace <PID> with the process identification number (found in the second column of thepgrep -l
command) for an IMAP session.To kill all active IMAP sessions, issue the following command:~]#
killall imapd
Chapter 2. Securing Your Network
2.1. Workstation Security
2.1.1. Evaluating Workstation Security
- BIOS and Boot Loader Security — Can an unauthorized user physically access the machine and boot into single user or rescue mode without a password?
- Password Security — How secure are the user account passwords on the machine?
- Administrative Controls — Who has an account on the system and how much administrative control do they have?
- Available Network Services — What services are listening for requests from the network and should they be running at all?
- Personal Firewalls — What type of firewall, if any, is necessary?
- Security Enhanced Communication Tools — Which tools should be used to communicate between workstations and which should be avoided?
2.1.2. BIOS and Boot Loader Security
2.1.2.1. BIOS Passwords
- Preventing Changes to BIOS Settings — If an intruder has access to the BIOS, they can set it to boot from a CD-ROM or a flash drive. This makes it possible for an intruder to enter rescue mode or single user mode, which in turn allows them to start arbitrary processes on the system or copy sensitive data.
- Preventing System Booting — Some BIOSes allow password protection of the boot process. When activated, an attacker is forced to enter a password before the BIOS launches the boot loader.
2.1.2.1.1. Securing Non-x86 Platforms
2.1.2.2. Boot Loader Passwords
- Preventing Access to Single User Mode — If attackers can boot the system into single user mode, they are logged in automatically as root without being prompted for the root password.
Warning
Protecting access to single user mode with a password by editing theSINGLE
parameter in the/etc/sysconfig/init
file is not recommended. An attacker can bypass the password by specifying a custom initial command (using theinit=
parameter) on the kernel command line in GRUB. It is recommended to password-protect the GRUB boot loader as specified in Section 2.1.2.2.1, “Password Protecting GRUB”. - Preventing Access to the GRUB Console — If the machine uses GRUB as its boot loader, an attacker can use the GRUB editor interface to change its configuration or to gather information using the
cat
command. - Preventing Access to Insecure Operating Systems — If it is a dual-boot system, an attacker can select an operating system at boot time (for example, DOS), which ignores access controls and file permissions.
2.1.2.2.1. Password Protecting GRUB
/sbin/grub-md5-crypt
/boot/grub/grub.conf
. Open the file and below the timeout
line in the main section of the document, add the following line:
password --md5 <password-hash>
/sbin/grub-md5-crypt
[4].
/boot/grub/grub.conf
file must be edited.
title
line of the operating system that you want to secure, and add a line with the lock
directive immediately beneath it.
title DOS lock
Warning
password
line must be present in the main section of the /boot/grub/grub.conf
file for this method to work properly. Otherwise, an attacker can access the GRUB editor interface and remove the lock line.
lock
line to the stanza, followed by a password line.
title DOS lock password --md5 <password-hash>
2.1.2.2.2. Disabling Interactive Startup
PROMPT
parameter in the /etc/sysconfig/init
file:
PROMPT=no
2.1.3. Password Security
/etc/passwd
file, which makes the system vulnerable to offline password cracking attacks. If an intruder can gain access to the machine as a regular user, he can copy the /etc/passwd
file to his own machine and run any number of password cracking programs against it. If there is an insecure password in the file, it is only a matter of time before the password attacker discovers it.
/etc/shadow
, which is readable only by the root user.
2.1.3.1. Creating Strong Passwords
randomword1 randomword2 randomword3 randomword4
1!
". Note that such a modification does not increase the security of the passphrase significantly.
- Using a single dictionary word, a word in a foreign language, an inverted word, or only numbers.
- Using less than 10 characters for a password or passphrase.
- Using a sequence of keys from the keyboard layout.
- Writing down your passwords.
- Using personal information in a password, such as birth dates, anniversaries, family member names, or pet names.
- Using the same passphrase or password on multiple machines.
2.1.4. Creating User Passwords Within an Organization
2.1.4.1. Forcing Strong Passwords
passwd
, which is Pluggable Authentication Modules (PAM) aware and therefore checks to see if the password is too short or otherwise easy to crack. This check is performed using the pam_cracklib.so
PAM module. In Red Hat Enterprise Linux, the pam_cracklib
PAM module can be used to check a password's strength against a set of rules. It can be stacked alongside other PAM modules in the password
component of the/etc/pam.d/passwd
file to configure a custom set of rules for user login. The pam_cracklib
's routine consists of two parts: it checks whether the password provided is found in a dictionary, and, if that is not the case, it continues with a number of additional checks. For a complete list of these checks, see the pam_cracklib(8)
manual page.
Example 2.1. Configuring password strength-checking with pam_cracklib
password
section of the /etc/pam.d/passwd
file:
password required pam_cracklib.so retry=3 minlen=8 minclass=4
password
section of the /etc/pam.d/passwd
file:
password required pam_cracklib.so retry=3 maxsequence=3 maxrepeat=3
Note
pam_passwdqc
(available from http://www.openwall.com/passwdqc/) or to write a new module. For a list of available PAM modules, see http://uw714doc.sco.com/en/SEC_pam/pam-6.html. For more information about PAM, see the Managing Single Sign-On and Smart Cards guide.
- John The Ripper — A fast and flexible password cracking program. It allows the use of multiple word lists and is capable of brute-force password cracking. It is available online at http://www.openwall.com/john/.
- Crack — Perhaps the most well known password cracking software, Crack is also very fast, though not as easy to use as John The Ripper.
- Slurpie — Slurpie is similar to John The Ripper and Crack, but it is designed to run on multiple computers simultaneously, creating a distributed password cracking attack. It can be found along with a number of other distributed attack security evaluation tools online at http://www.ussrback.com/distributed.htm.
Warning
2.1.4.2. Passphrases
2.1.4.3. Password Aging
chage
command or the graphical User Manager (system-config-users
) application.
Important
chage
command. For more information, see the Red Hat Enterprise Linux 6 Deployment Guide.
-M
option of the chage
command specifies the maximum number of days the password is valid. For example, to set a user's password to expire in 90 days, use the following command:
chage
-M 90
<username>
99999
after the -M
option (this equates to a little over 273 years).
chage
command, see the table below.
Table 2.1. chage command line options
Option | Description |
---|---|
-d days | Specifies the number of days since January 1, 1970 the password was changed. |
-E date | Specifies the date on which the account is locked, in the format YYYY-MM-DD. Instead of the date, the number of days since January 1, 1970 can also be used. |
-I days | Specifies the number of inactive days after the password expiration before locking the account. If the value is 0 , the account is not locked after the password expires. |
-l | Lists current account aging settings. |
-m days | Specify the minimum number of days after which the user must change passwords. If the value is 0 , the password does not expire. |
-M days | Specify the maximum number of days for which the password is valid. When the number of days specified by this option plus the number of days specified with the -d option is less than the current day, the user must change passwords before using the account. |
-W days | Specifies the number of days before the password expiration date to warn the user. |
chage
command in interactive mode to modify multiple password aging and account details. Use the following command to enter interactive mode:
chage
<username>
~]#chage juan
Changing the aging information for juan Enter the new value, or press ENTER for the default Minimum Password Age [0]:10
Maximum Password Age [99999]:90
Last Password Change (YYYY-MM-DD) [2006-08-18]: Password Expiration Warning [7]: Password Inactive [-1]: Account Expiration Date (YYYY-MM-DD) [1969-12-31]:
- Set up an initial password. There are two common approaches to this step: you can either assign a default password, or you can use a null password.To assign a default password, type the following at a shell prompt as
root
:passwd
usernameTo assign a null password instead, use the following command:passwd
-d
usernameWarning
Using a null password, while convenient, is a highly insecure practice, as any third party can log in first and access the system using the insecure user name. Always make sure that the user is ready to log in before unlocking an account with a null password. - Force immediate password expiration by running the following command as
root
:chage
-d
0
usernameThis command sets the value for the date the password was last changed to the epoch (January 1, 1970). This value forces immediate password expiration no matter what password aging policy, if any, is in place.
- Click the System menu on the Panel, point to Administration and then click Users and Groups to display the User Manager. Alternatively, type the command
system-config-users
at a shell prompt. - Click the Users tab, and select the required user in the list of users.
- Click Properties on the toolbar to display the User Properties dialog box (or choose Properties on the File menu).
- Click the Password Info tab, and select the check box for Enable password expiration.
- Enter the required value in the Days before change required field, and click OK.

Figure 2.1. Specifying password aging options
screenshot needs to be updated
2.1.5. Locking Inactive Accounts
pam_lastlog
PAM module is used to lock out users who have not logged in recently enough, or to display information about the last login attempt of a user. The module does not perform a check on the root account, so it is never locked out.
lastlog
command displays the last login of the user, аs opposed to the last
command, which displays all current and previous login sessions. The commands read respectively from the /var/log/lastlog
and /var/log/wtmp
files where the data is stored in binary format.
- To display the number of failed login attempts prior to the last successful login of a user, add, as root, the following line to the
session
section in the/etc/pam.d/login
file:session optional pam_lastlog.so silent noupdate showfailed
- To lock out an account after 10 days of inactivity, add, as root, the following line to the
auth
section of the/etc/pam.d/login
file:auth required pam_lastlog.so inactive=10
- To lock out an account for the GNOME desktop environment, add, as root, the following line to the
auth
section of the/etc/pam.d/gdm
file:auth required pam_lastlog.so inactive=10
Note
2.1.6. Customizing Access Control
pam_access
PAM module allows an administrator to customize access control based on login names, host or domain names, or IP addresses. By default, the module reads the access rules from the /etc/security/access.conf
file if no other is specified. For a complete description of the format of these rules, see the access.conf(5)
manual page. By default, in Red Hat Enterprise Linux, pam_access
is included in the /etc/pam.d/crond
and /etc/pam.d/atd
files.
- Include the following line in the
account
section of both/etc/pam.d/login
and/etc/pam.d/gdm-*
files:account required pam_access.so
- Specify the following rule in the
/etc/security/access.conf
file:- : john : ALL
This rule prohibits all logins from user john from any location.
- Include the following line in the
account
section of/etc/pam.d/sshd
:account required pam_access.so
- Specify the following rule in the /etc/security/access.conf file:
+ : ALL EXCEPT john : 1.2.3.4
pam_access
module should be required in the respective file in the /etc/pam.d
directory.
pam_access
module for all services that call the system wide PAM configuration files (*-auth
files in the /etc/pam.d
directory) using the following command:
authconfig --enablepamaccess --update
pam_access
module using the Authentication Configuration utility. To start this utility, select System → Administration → Authentication from the top menu. From the Advanced Options tab, check the "enable local access control option". This will add the pam_access
module to the systemwide PAM configuration.
2.1.7. Time-based Restriction of Access
pam_time
PAM module is used to restrict access during a certain time of the day. It can also be configured to control access based on specific days of a week, user name, usage of a system service, and more. By default, the module reads the access rules from the /etc/security/time.conf
file. For a complete description of the format of these rules, see the time.conf(5)
manual page.
- Include the following line in the account section of the
/etc/pam.d/login
file:account required pam_time.so
- Specify the following rule in the
/etc/security/time.conf
file:login ; tty* ; ALL ; !root ; !Wk1730-0800
- Add the following line to the
/etc/pam.d/sshd file:
account required pam_time.so
- Specify the following rule in the
/etc/security/time.conf
file:sshd ; tty* ; john ; Wk0800-1730
Note
pam_time
module should be included in the corresponding files in the /etc/pam.d
directory.
2.1.8. Applying Account Limits
pam_limits
PAM module is used to:
- apply limits to user login sessions, such as maximum simultaneous login sessions per user,
- specify limits to be set by the ulimit utility,
- and specify priority to be set by the nice utility.
/etc/security/limits.conf
file. For a complete description of the format of these rules, see the limits.conf(5)
manual page. Additionally, you can create individual configuration files in the /etc/security/limits.d
directory specifically for certain applications or services. By default, the pam_limits
module is included in a number of files in the/etc/pam.d/
directory. A default limit of user processes is defined in the /etc/security/limits.d/90-nproc.conf
file to prevent malicious denial of service attacks, such as fork bombs. To change the default limit of user processes to 50, change the value in the /etc/security/limits.d/90-nproc.conf
, following the format in the file:
* soft nproc 50
Example 2.2. Specifying a maximum number of logins per user
- To set a maximum number of simultaneous logins for each user in a group called
office
, specify the following rule in the/etc/security/limits.conf
file:@office - maxlogins 4
- The following line should be present by default in
/etc/pam.d/system-auth
. If not, add it manually.session required pam_limits.so
2.1.9. Administrative Controls
sudo
or su
. A setuid program is one that operates with the user ID (UID) of the program's owner rather than the user operating the program. Such programs are denoted by an s
in the owner section of a long format listing, as in the following example:
~]$ ls -l /bin/su
-rwsr-xr-x. 1 root root 34904 Mar 10 2011 /bin/su
Note
s
may be upper case or lower case. If it appears as upper case, it means that the underlying permission bit has not been set.
pam_console.so
, some activities normally reserved only for the root user, such as rebooting and mounting removable media are allowed for the first user that logs in at the physical console (see Managing Single Sign-On and Smart Cards for more information about the pam_console.so
module.) However, other important system administration tasks, such as altering network settings, configuring a new mouse, or mounting network devices, are not possible without administrative privileges. As a result, system administrators must decide how much access the users on their network should receive.
2.1.9.1. Allowing Root Access
- Machine Misconfiguration — Users with root access can misconfigure their machines and require assistance to resolve issues. Even worse, they might open up security holes without knowing it.
- Running Insecure Services — Users with root access might run insecure servers on their machine, such as FTP or Telnet, potentially putting user names and passwords at risk. These services transmit this information over the network in plain text.
- Running Email Attachments As Root — Although rare, email viruses that affect Linux do exist. The only time they are a threat, however, is when they are run by the root user.
- Keeping the audit trail intact — Because the root account is often shared by multiple users, so that multiple system administrators can maintain the system, it is impossible to figure out which of those users was root at a given time. When using separate logins, the account a user logs in with, as well as a unique number for session tracking purposes, is put into the task structure, which is inherited by every process that the user starts. When using concurrent logins, the unique number can be used to trace actions to specific logins. When an action generates an audit event, it is recorded with the login account and the session associated with that unique number. Use the
aulast
command to view these logins and sessions. The--proof
option of theaulast
command can be used suggest a specificausearch
query to isolate auditable events generated by a particular session.
2.1.9.2. Disallowing Root Access
- Changing the root shell
- To prevent users from logging in directly as root, the system administrator can set the root account's shell to
/sbin/nologin
in the/etc/passwd
file.Table 2.2. Disabling the Root Shell
Effects Does Not Affect Prevents access to the root shell and logs any such attempts. The following programs are prevented from accessing the root account:login
gdm
kdm
xdm
su
ssh
scp
sftp
Programs that do not require a shell, such as FTP clients, mail clients, and many setuid programs. The following programs are not prevented from accessing the root account:sudo
- FTP clients
- Email clients
- Disabling root access through any console device (tty)
- To further limit access to the root account, administrators can disable root logins at the console by editing the
/etc/securetty
file. This file lists all devices the root user is allowed to log into. If the file does not exist at all, the root user can log in through any communication device on the system, whether through the console or a raw network interface. This is dangerous, because a user can log in to their machine as root through Telnet, which transmits the password in plain text over the network.By default, Red Hat Enterprise Linux's/etc/securetty
file only allows the root user to log in at the console physically attached to the machine. To prevent the root user from logging in, remove the contents of this file by typing the following command at a shell prompt as root:echo > /etc/securetty
To enablesecuretty
support in the KDM, GDM, and XDM login managers, add the following line:auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
to the files listed below:/etc/pam.d/gdm
/etc/pam.d/gdm-autologin
/etc/pam.d/gdm-fingerprint
/etc/pam.d/gdm-password
/etc/pam.d/gdm-smartcard
/etc/pam.d/kdm
/etc/pam.d/kdm-np
/etc/pam.d/xdm
Warning
A blank/etc/securetty
file does not prevent the root user from logging in remotely using the OpenSSH suite of tools because the console is not opened until after authentication.Table 2.3. Disabling Root Logins
Effects Does Not Affect Prevents access to the root account using the console or the network. The following programs are prevented from accessing the root account:login
gdm
kdm
xdm
- Other network services that open a tty
Programs that do not log in as root, but perform administrative tasks through setuid or other mechanisms. The following programs are not prevented from accessing the root account:su
sudo
ssh
scp
sftp
- Disabling root SSH logins
- To prevent root logins using the SSH protocol, edit the SSH daemon's configuration file,
/etc/ssh/sshd_config
, and change the line that reads:#PermitRootLogin yes
to read as follows:PermitRootLogin no
Table 2.4. Disabling Root SSH Logins
Effects Does Not Affect Prevents root access using the OpenSSH suite of tools. The following programs are prevented from accessing the root account:ssh
scp
sftp
Programs that are not part of the OpenSSH suite of tools. - Using PAM to limit root access to services
- PAM, through the
/lib/security/pam_listfile.so
module, allows great flexibility in denying specific accounts. The administrator can use this module to reference a list of users who are not allowed to log in. To limit root access to a system service, edit the file for the target service in the/etc/pam.d/
directory and make sure thepam_listfile.so
module is required for authentication.The following is an example of how the module is used for thevsftpd
FTP server in the/etc/pam.d/vsftpd
PAM configuration file (the\
character at the end of the first line is not necessary if the directive is on a single line):auth required /lib/security/pam_listfile.so item=user \ sense=deny file=/etc/vsftpd.ftpusers onerr=succeed
This instructs PAM to consult the/etc/vsftpd.ftpusers
file and deny access to the service for any listed user. The administrator can change the name of this file, and can keep separate lists for each service or use one central list to deny access to multiple services.If the administrator wants to deny access to multiple services, a similar line can be added to the PAM configuration files, such as/etc/pam.d/pop
and/etc/pam.d/imap
for mail clients, or/etc/pam.d/ssh
for SSH clients.For more information about PAM, see the chapter titled Using Pluggable Authentication Modules (PAM) in the Red Hat Enterprise Linux Managing Single Sign-On and Smart Cards guide.Table 2.5. Disabling Root Using PAM
Effects Does Not Affect Prevents root access to network services that are PAM aware. The following services are prevented from accessing the root account:login
gdm
kdm
xdm
ssh
scp
sftp
- FTP clients
- Email clients
- Any PAM aware services
Programs and services that are not PAM aware.
2.1.9.3. Enabling Automatic Logouts
root
, an unattended login session may pose a significant security risk. To reduce this risk, you can configure the system to automatically log out idle users after a fixed period of time:
- Make sure the screen package is installed. You can do so by running the following command as
root
:~]#
yum
install
screen
For more information on how to install packages in Red Hat Enterprise Linux, see the Installing Packages section in the Red Hat Enterprise Linux 6 Deployment Guide. - As
root
, add the following line at the beginning of the/etc/profile
file to make sure the processing of this file cannot be interrupted:trap "" 1 2 3 15
- Add the following lines at the end of the
/etc/profile
file to start ascreen
session each time a user logs in to a virtual console or remotely:SCREENEXEC="screen" if [ -w $(tty) ]; then trap "exec $SCREENEXEC" 1 2 3 15 echo -n 'Starting session in 10 seconds' sleep 10 exec $SCREENEXEC fi
Note that each time a new session starts, a message will be displayed and the user will have to wait ten seconds. To adjust the time to wait before starting a session, change the value after thesleep
command. - Add the following lines to the
/etc/screenrc
configuration file to close thescreen
session after a given period of inactivity:idle 120 quit autodetach off
This will set the time limit to 120 seconds. To adjust this limit, change the value after theidle
directive.Alternatively, you can configure the system to only lock the session by using the following lines instead:idle 120 lockscreen autodetach off
This way, a password will be required to unlock the session.
2.1.9.4. Limiting Root Access
su
or sudo
. For more information on su
and sudo
, see the Red Hat Enterprise Linux 6 Deployment Guide and the su(1)
and sudo(8)
man pages.
2.1.9.5. Account Locking
pam_faillock
PAM module allows system administrators to lock out user accounts after a specified number of failed attempts. Limiting user login attempts serves mainly as a security measure that aims to prevent possible brute force attacks targeted to obtain a user's account password.
pam_faillock
module, failed login attempts are stored in a separate file for each user in the /var/run/faillock
directory.
Note
even_deny_root
option is used.
- To lock out any non-root user after three unsuccessful attempts and unlock that user after 10 minutes, add the following lines to the
auth
section of the/etc/pam.d/system-auth
and/etc/pam.d/password-auth
files:auth required pam_faillock.so preauth silent audit deny=3 unlock_time=600 auth sufficient pam_unix.so nullok try_first_pass auth [default=die] pam_faillock.so authfail audit deny=3 unlock_time=600
- Add the following line to the
account
section of both files specified in the previous step:account required pam_faillock.so
- To apply account locking for the root user as well, add the
even_deny_root
option to thepam_faillock
entries in the/etc/pam.d/system-auth
and/etc/pam.d/password-auth
files:auth required pam_faillock.so preauth silent audit deny=3 even_deny_root unlock_time=600 auth sufficient pam_unix.so nullok try_first_pass auth [default=die] pam_faillock.so authfail audit deny=3 even_deny_root unlock_time=600 account required pam_faillock.so
john
attempts to log in for the fourth time after failing to log in three times previously, his account is locked upon the fourth attempt:
[user@localhost ~]$ su - john Account locked due to 3 failed logins su: incorrect password
pam_faillock
is called for the first time in both /etc/pam.d/system-auth
and /etc/pam.d/password-auth
. Also replace user1
, user2
, user3
with the actual user names.
auth [success=1 default=ignore] pam_succeed_if.so user in user1:user2:user3
[root@localhost ~]# faillock
john:
When Type Source Valid
2013-03-05 11:44:14 TTY pts/0 V
faillock
--user <username> --reset
system-auth
and password-auth
files are overwritten with the settings from the authconfig utility. This can be avoided by creating symbolic links in place of the configuration files, which authconfig recognizes and does not overwrite. In order to use custom settings in the configuration files and authconfig simultaneously, configure account locking using the following steps:
- Rename the configuration files:
~]#
mv /etc/pam.d/system-auth /etc/pam.d/system-auth-local
~]#mv /etc/pam.d/password-auth /etc/pam.d/password-auth-local
- Create the following symbolic links:
~]#
ln -s /etc/pam.d/system-auth-local /etc/pam.d/system-auth
~]#ln -s /etc/pam.d/password-auth-local /etc/pam.d/password-auth
- The
/etc/pam.d/system-auth-local
file should contain the following lines:auth required pam_faillock.so preauth silent audit deny=3 unlock_time=600 auth include system-auth-ac auth [default=die] pam_faillock.so authfail silent audit deny=3 unlock_time=600 account required pam_faillock.so account include system-auth-ac password include system-auth-ac session include system-auth-ac
- The
/etc/pam.d/password-auth-local
file should contain the following lines:auth required pam_faillock.so preauth silent audit deny=3 unlock_time=600 auth include password-auth-ac auth [default=die] pam_faillock.so authfail silent audit deny=3 unlock_time=600 account required pam_faillock.so account include password-auth-ac password include system-auth-ac session include system-auth-ac
pam_faillock
configuration options, see the pam_faillock(8)
man page.
2.1.10. Session Locking
Note
2.1.10.1. Locking GNOME Using gnome-screensaver-command
- Press the key combination specified in System → Preferences → Keyboard Shortcuts → Desktop → Lock screen. The default combination is Ctrl+Alt+L.
- Select System → Lock screen on the panel.
- Execute the following command from a command line interface:
gnome-screensaver-command
-l
gnome-screensaver
process to be running. You can check whether this is the case by using any command which provides information about processes. For example, execute the following command from the terminal:
pidof gnome-screensaver
gnome-screensaver
process is currently running, a number denoting its identification number (PID) will be displayed on the screen after executing the command. If the process is not currently running, the command will provide no output at all.
gnome-screensaver-command(1)
man page for additional information.
Important
2.1.10.1.1. Automatic Lock on Screen Saver Activation
gnome-screensaver-command
suggests, the locking functionality is tied to GNOME's screen saver. It is possible to tie the lock to the screen saver's activation, locking the workstation every time it is left unattended for a set period of time. This function is activated by default with a five minute timeout.

Figure 2.2. Changing the screen saver preferences
Note
2.1.10.1.2. Remote Session Locking
ssh
as long as the target workstation accepts connections over this protocol. To remotely lock the screen on a machine you have access to, execute the following command:
ssh -X <username>@<server> "export DISPLAY=:0; gnome-screensaver-command -l"
ssh
.
2.1.10.2. Locking Virtual Consoles Using vlock
vlock
. To install this utility, execute the following command as root:
~]# yum install vlock
vlock
command without any additional parameters. This locks the currently active virtual console session while still allowing access to the others. To prevent access to all virtual consoles on the workstation, execute the following:
vlock
-a
vlock
locks the currently active console and the -a
option prevents switching to other virtual consoles.
vlock(1)
man page for additional information.
Important
vlock
currently available for Red Hat Enterprise Linux 6:
- The program does not currently allow unlocking consoles using the root password. Additional information can be found in BZ#895066.
- Locking a console does not clear the screen and scrollback buffer, allowing anyone with physical access to the workstation to view previously issued commands and any output displayed in the console. Refer to BZ#807369 for more information.
2.1.11. Available Network Services
2.1.11.1. Risks To Services
- Denial of Service Attacks (DoS) — By flooding a service with requests, a denial of service attack can render a system unusable as it tries to log and answer each request.
- Distributed Denial of Service Attack (DDoS) — A type of DoS attack which uses multiple compromised machines (often numbering in the thousands or more) to direct a coordinated attack on a service, flooding it with requests and making it unusable.
- Script Vulnerability Attacks — If a server is using scripts to execute server-side actions, as Web servers commonly do, an attacker can attack improperly written scripts. These script vulnerability attacks can lead to a buffer overflow condition or allow the attacker to alter files on the system.
- Buffer Overflow Attacks — Services that connect to ports numbered 0 through 1023 must run as an administrative user. If the application has an exploitable buffer overflow, an attacker could gain access to the system as the user running the daemon. Because exploitable buffer overflows exist, attackers use automated tools to identify systems with vulnerabilities, and once they have gained access, they use automated rootkits to maintain their access to the system.
Note
Important
2.1.11.2. Identifying and Configuring Services
cupsd
— The default print server for Red Hat Enterprise Linux.lpd
— An alternative print server.xinetd
— A super server that controls connections to a range of subordinate servers, such asgssftp
andtelnet
.sendmail
— The Sendmail Mail Transport Agent (MTA) is enabled by default, but only listens for connections from the localhost.sshd
— The OpenSSH server, which is a secure replacement for Telnet.
cupsd
running. The same is true for portmap
. If you do not mount NFSv3 volumes or use NIS (the ypbind
service), then portmap
should be disabled.

Figure 2.3. Services Configuration Tool
2.1.11.3. Insecure Services
- Transmit Usernames and Passwords Over a Network Unencrypted — Many older protocols, such as Telnet and FTP, do not encrypt the authentication session and should be avoided whenever possible.
- Transmit Sensitive Data Over a Network Unencrypted — Many protocols transmit data over the network unencrypted. These protocols include Telnet, FTP, HTTP, and SMTP. Many network file systems, such as NFS and SMB, also transmit information over the network unencrypted. It is the user's responsibility when using these protocols to limit what type of data is transmitted.Remote memory dump services, like
netdump
, transmit the contents of memory over the network unencrypted. Memory dumps can contain passwords or, even worse, database entries and other sensitive information.Other services likefinger
andrwhod
reveal information about users of the system.
rlogin
, rsh
, telnet
, and vsftpd
.
rlogin
, rsh
, and telnet
) should be avoided in favor of SSH. Refer to Section 2.1.13, “Security Enhanced Communication Tools” for more information about sshd
.
finger
authd
(this was calledidentd
in previous Red Hat Enterprise Linux releases.)netdump
netdump-server
nfs
rwhod
sendmail
smb
(Samba)yppasswdd
ypserv
ypxfrd
2.1.12. Personal Firewalls
Important
system-config-firewall
). This tool creates broad iptables
rules for a general-purpose firewall using a control panel interface.
iptables
is preferable. Refer to Section 2.8, “Firewalls” for more information. Refer to Section 2.8.9, “IPTables” for a comprehensive guide to the iptables
command.
2.1.13. Security Enhanced Communication Tools
- OpenSSH — A free implementation of the SSH protocol for encrypting network communication.
- Gnu Privacy Guard (GPG) — A free implementation of the PGP (Pretty Good Privacy) encryption application for encrypting data.
telnet
and rsh
. OpenSSH includes a network service called sshd
and three command line client applications:
ssh
— A secure remote console access client.scp
— A secure remote copy command.sftp
— A secure pseudo-ftp client that allows interactive file transfer sessions.
Important
sshd
service is inherently secure, the service must be kept up-to-date to prevent security threats. Refer to Section 1.5, “Security Updates” for more information.
2.1.14. Enforcing Read-Only Mounting of Removable Media
udev
rule to detect removable media and configure them to be mounted read-only using the blockdev utility. Starting with Red Hat Enterprise Linux 6.7, a special parameter can be also passed to the udisks
disk manager to force read-only mounting of file systems.
udev
rule that triggers the blockdev utility is sufficient for enforcing read-only mounting of physical media, the udisks
parameter can be used to enforce read-only mounting of filesystems on read-write mounted media.
Using blockdev to Force Read-Only Mounting of Removable Media
udev
configuration file named, for example, 80-readonly-removables.rules
in the /etc/udev/rules.d/
directory with the following content:
SUBSYSTEM=="block",ATTRS{removable}=="1",RUN{program}="/sbin/blockdev --setro %N"
udev
rule ensures that any newly connected removable block (storage) device is automatically configured as read-only using the blockdev
utility.
Using udisks to Force Read-Only Mounting of Filesystems
udisks
parameter needs to be set through udev
. Create a new udev
configuration file named, for example, 80-udisks.rules
in the /etc/udev/rules.d/
directory with the following content (or add the following lines to this file if it already exists):
ENV{UDISKS_MOUNT_OPTIONS}="ro,noexec" ENV{UDISKS_MOUNT_OPTIONS_ALLOW}="noexec,nodev,nosuid,atime,noatime,nodiratime,ro,sync,dirsync"
80-udisks.rules
file is installed with the udisks package in the /lib/udev/rules.d/
directory. This file contains the above rules, but they are commented out.
udev
rules instruct the udisks
disk manager to only allow read-only mounting of file systems. Also, the noexec
parameter forbids direct execution of any binaries on the mounted file systems. This policy is enforced regardless of the way the actual physical device is mounted. That is, file systems are mounted read-only even on read-write mounted devices.
Applying New udev and udisks Settings
udev
rules need to be applied. The udev
service automatically detects changes to its configuration files, but new settings are not applied to already existing devices. Only newly connected devices are affected by the new settings. Therefore, you need to unmount and unplug all connected removable media to ensure that the new settings are applied to them when they are next plugged in.
udev
to re-apply all rules to already existing devices, enter the following command as root
:
~#
udevadm trigger
udev
to re-apply all rules using the above command does not affect any storage devices that are already mounted.
udev
to reload all rules (in case the new rules are not automatically detected for some reason), use the following command:
~#
udevadm control --reload
2.2. Server Security
- Keep all services current, to protect against the latest threats.
- Use secure protocols whenever possible.
- Serve only one type of network service per machine whenever possible.
- Monitor all servers carefully for suspicious activity.
2.2.1. Securing Services With TCP Wrappers and xinetd
xinetd
, a super server that provides additional access, logging, binding, redirection, and resource utilization control.
Note
xinetd
to create redundancy within service access controls. Refer to Section 2.8, “Firewalls” for more information about implementing firewalls with iptables commands.
2.2.1.1. Enhancing Security With TCP Wrappers
hosts_options
man page for information about the TCP Wrapper functionality and control language. Refer to the xinetd.conf
man page available online at http://linux.die.net/man/5/xinetd.conf for available flags, which act as options you can apply to a service.
2.2.1.1.1. TCP Wrappers and Connection Banners
banner
option.
vsftpd
. To begin, create a banner file. It can be anywhere on the system, but it must have same name as the daemon. For this example, the file is called /etc/banners/vsftpd
and contains the following lines:
220-Hello, %c 220-All activity on ftp.example.com is logged. 220-Inappropriate use will result in your access privileges being removed.
%c
token supplies a variety of client information, such as the user name and hostname, or the user name and IP address to make the connection even more intimidating.
/etc/hosts.allow
file:
vsftpd : ALL : banners /etc/banners/
2.2.1.1.2. TCP Wrappers and Attack Warnings
spawn
directive.
/etc/hosts.deny
file to deny any connection attempts from that network, and to log the attempts to a special file:
ALL : 206.182.68.0 : spawn /bin/echo `date` %c %d >> /var/log/intruder_alert
%d
token supplies the name of the service that the attacker was trying to access.
spawn
directive in the /etc/hosts.allow
file.
Note
spawn
directive executes any shell command, it is a good idea to create a special script to notify the administrator or execute a chain of commands in the event that a particular client attempts to connect to the server.
2.2.1.1.3. TCP Wrappers and Enhanced Logging
severity
option.
emerg
flag in the log files instead of the default flag, info
, and deny the connection.
/etc/hosts.deny
:
in.telnetd : ALL : severity emerg
authpriv
logging facility, but elevates the priority from the default value of info
to emerg
, which posts log messages directly to the console.
2.2.1.2. Enhancing Security With xinetd
xinetd
to set a trap service and using it to control resource levels available to any given xinetd
service. Setting resource limits for services can help thwart Denial of Service (DoS) attacks. Refer to the man pages for xinetd
and xinetd.conf
for a list of available options.
2.2.1.2.1. Setting a Trap
xinetd
is its ability to add hosts to a global no_access
list. Hosts on this list are denied subsequent connections to services managed by xinetd
for a specified period or until xinetd
is restarted. You can do this using the SENSOR
attribute. This is an easy way to block hosts attempting to scan the ports on the server.
SENSOR
is to choose a service you do not plan on using. For this example, Telnet is used.
/etc/xinetd.d/telnet
and change the flags
line to read:
flags = SENSOR
deny_time = 30
deny_time
attribute are FOREVER, which keeps the ban in effect until xinetd
is restarted, and NEVER, which allows the connection and logs it.
disable = no
SENSOR
is a good way to detect and stop connections from undesirable hosts, it has two drawbacks:
- It does not work against stealth scans.
- An attacker who knows that a
SENSOR
is running can mount a Denial of Service attack against particular hosts by forging their IP addresses and connecting to the forbidden port.
2.2.1.2.2. Controlling Server Resources
xinetd
is its ability to set resource limits for services under its control.
cps = <number_of_connections> <wait_period>
— Limits the rate of incoming connections. This directive takes two arguments:<number_of_connections>
— The number of connections per second to handle. If the rate of incoming connections is higher than this, the service is temporarily disabled. The default value is fifty (50).<wait_period>
— The number of seconds to wait before re-enabling the service after it has been disabled. The default interval is ten (10) seconds.
instances = <number_of_connections>
— Specifies the total number of connections allowed to a service. This directive accepts either an integer value orUNLIMITED
.per_source = <number_of_connections>
— Specifies the number of connections allowed to a service by each host. This directive accepts either an integer value orUNLIMITED
.rlimit_as = <number[K|M]>
— Specifies the amount of memory address space the service can occupy in kilobytes or megabytes. This directive accepts either an integer value orUNLIMITED
.rlimit_cpu = <number_of_seconds>
— Specifies the amount of time in seconds that a service may occupy the CPU. This directive accepts either an integer value orUNLIMITED
.
xinetd
service from overwhelming the system, resulting in a denial of service.
2.2.2. Securing Portmap
portmap
service is a dynamic port assignment daemon for RPC services such as NIS and NFS. It has weak authentication mechanisms and has the ability to assign a wide range of ports for the services it controls. For these reasons, it is difficult to secure.
Note
portmap
only affects NFSv2 and NFSv3 implementations, since NFSv4 no longer requires it. If you plan to implement an NFSv2 or NFSv3 server, then portmap
is required, and the following section applies.
2.2.2.1. Protect portmap With TCP Wrappers
portmap
service since it has no built-in form of authentication.
2.2.2.2. Protect portmap With iptables
portmap
service, it is a good idea to add iptables rules to the server and restrict access to specific networks.
portmap
service) from the 192.168.0.0/24 network. The second allows TCP connections to the same port from the localhost. This is necessary for the sgi_fam
service used by Nautilus. All other packets are dropped.
~]#iptables -A INPUT -p tcp -s ! 192.168.0.0/24 --dport 111 -j DROP
~]#iptables -A INPUT -p tcp -s 127.0.0.1 --dport 111 -j ACCEPT
~]# iptables -A INPUT -p udp -s ! 192.168.0.0/24 --dport 111 -j DROP
Note
2.2.3. Securing NIS
ypserv
, which is used in conjunction with portmap
and other related services to distribute maps of user names, passwords, and other sensitive information to any computer claiming to be within its domain.
/usr/sbin/rpc.yppasswdd
— Also called theyppasswdd
service, this daemon allows users to change their NIS passwords./usr/sbin/rpc.ypxfrd
— Also called theypxfrd
service, this daemon is responsible for NIS map transfers over the network./usr/sbin/yppush
— This application propagates changed NIS databases to multiple NIS servers./usr/sbin/ypserv
— This is the NIS server daemon.
portmap
service as outlined in Section 2.2.2, “Securing Portmap”, then address the following issues, such as network planning.
2.2.3.1. Carefully Plan the Network
2.2.3.2. Use a Password-like NIS Domain Name and Hostname
/etc/passwd
map:
ypcat
-d
<NIS_domain>-h
<DNS_hostname>passwd
/etc/shadow
file by typing the following command:
ypcat
-d
<NIS_domain>-h
<DNS_hostname>shadow
Note
/etc/shadow
file is not stored within a NIS map.
o7hfawtgmhwg.domain.com
. Similarly, create a different randomized NIS domain name. This makes it much more difficult for an attacker to access the NIS server.
2.2.3.3. Edit the /var/yp/securenets
File
/var/yp/securenets
file is blank or does not exist (as is the case after a default installation), NIS listens to all networks. One of the first things to do is to put netmask/network pairs in the file so that ypserv
only responds to requests from the appropriate network.
/var/yp/securenets
file:
255.255.255.0 192.168.0.0
Warning
/var/yp/securenets
file.
2.2.3.4. Assign Static Ports and Use iptables Rules
rpc.yppasswdd
— the daemon that allows users to change their login passwords. Assigning ports to the other two NIS server daemons, rpc.ypxfrd
and ypserv
, allows for the creation of firewall rules to further protect the NIS server daemons from intruders.
/etc/sysconfig/network
:
YPSERV_ARGS="-p 834" YPXFRD_ARGS="-p 835"
~]#iptables -A INPUT -p ALL -s ! 192.168.0.0/24 --dport 834 -j DROP
~]#iptables -A INPUT -p ALL -s ! 192.168.0.0/24 --dport 835 -j DROP
Note
2.2.3.5. Use Kerberos Authentication
/etc/shadow
map is sent over the network. If an intruder gains access to a NIS domain and sniffs network traffic, they can collect user names and password hashes. With enough time, a password cracking program can guess weak passwords, and an attacker can gain access to a valid account on the network.
2.2.4. Securing NFS
Important
portmap
service as outlined in Section 2.2.2, “Securing Portmap”. NFS traffic now utilizes TCP in all versions, rather than UDP, and requires it when using NFSv4. NFSv4 now includes Kerberos user and group authentication, as part of the RPCSEC_GSS
kernel module. Information on portmap
is still included, since Red Hat Enterprise Linux 6 supports NFSv2 and NFSv3, both of which utilize portmap
.
2.2.4.1. Carefully Plan the Network
2.2.4.2. Securing NFS Mount Options
mount
command in the /etc/fstab
file is explained in the Storage Administration Guide. From a security administration point of view it is worthwhile to note that the NFS mount options can also be specified in /etc/nfsmount.conf
, which can be used to set custom default options.
2.2.4.2.1. Review the NFS Server
Warning
exports(5)
man page.
ro
option to export the file system as read-only whenever possible to reduce the number of users able to write to the mounted file system. Only use the rw
option when specifically required. Refer to the man exports(5)
page for more information. Allowing write access increases the risk from symlink attacks for example. This includes temporary directories such as /tmp
and /usr/tmp
.
rw
option avoid making them world-writable whenever possible to reduce risk. Exporting home directories is also viewed as a risk as some applications store passwords in clear text or weakly encrypted. This risk is being reduced as application code is reviewed and improved. Some users do not set passwords on their SSH keys so this too means home directories present a risk. Enforcing the use of passwords or using Kerberos would mitigate that risk.
showmount -e
command on an NFS server to review what the server is exporting. Do not export anything that is not specifically required.
no_root_squash
option and review existing installations to make sure it is not used. Refer to Section 2.2.4.4, “Do Not Use the no_root_squash
Option” for more information.
secure
option is the server-side export option used to restrict exports to “reserved” ports. By default, the server allows client communication only from “reserved” ports (ports numbered less than 1024), because traditionally clients have only allowed “trusted” code (such as in-kernel NFS clients) to use those ports. However, on many networks it is not difficult for anyone to become root on some client, so it is rarely safe for the server to assume that communication from a reserved port is privileged. Therefore the restriction to reserved ports is of limited value; it is better to rely on Kerberos, firewalls, and restriction of exports to particular clients.
2.2.4.2.2. Review the NFS Client
nosuid
option to disallow the use of a setuid program. The nosuid
option disables the set-user-identifier
or set-group-identifier
bits. This prevents remote users from gaining higher privileges by running a setuid program. Use this option on the client and the server side.
noexec
option disables all executable files on the client. Use this to prevent users from inadvertently executing files placed in the file system being shared. The nosuid
and noexec
options are standard options for most, if not all, file systems.
nodev
option to prevent “device-files” from being processed as a hardware device by the client.
resvport
option is a client-side mount option and secure
is the corresponding server-side export option (see explanation above). It restricts communication to a "reserved port". The reserved or "well known" ports are reserved for privileged users and processes such as the root user. Setting this option causes the client to use a reserved source port to communicate with the server.
sec=krb5
.
krb5i
for integrity and krb5p
for privacy protection. These are used when mounting with sec=krb5
, but need to be configured on the NFS server. Refer to the man page on exports (man 5 exports
) for more information.
man 5 nfs
) has a “SECURITY CONSIDERATIONS” section which explains the security enhancements in NFSv4 and contains all the NFS specific mount options.
2.2.4.3. Beware of Syntax Errors
/etc/exports
file. Be careful not to add extraneous spaces when editing this file.
/etc/exports
file shares the directory /tmp/nfs/
to the host bob.example.com
with read/write permissions.
/tmp/nfs/ bob.example.com(rw)
/etc/exports
file, on the other hand, shares the same directory to the host bob.example.com
with read-only permissions and shares it to the world with read/write permissions due to a single space character after the hostname.
/tmp/nfs/ bob.example.com (rw)
showmount
command to verify what is being shared:
showmount
-e
<hostname>
2.2.4.4. Do Not Use the no_root_squash
Option
nfsnobody
user, an unprivileged user account. This changes the owner of all root-created files to nfsnobody
, which prevents uploading of programs with the setuid bit set.
no_root_squash
is used, remote root users are able to change any file on the shared file system and leave applications infected by Trojans for other users to inadvertently execute.
2.2.4.5. NFS Firewall Configuration
MOUNTD_PORT
— TCP and UDP port for mountd (rpc.mountd)STATD_PORT
— TCP and UDP port for status (rpc.statd)LOCKD_TCPPORT
— TCP port for nlockmgr (rpc.lockd)LOCKD_UDPPORT
— UDP port nlockmgr (rpc.lockd)
rpcinfo -p
command on the NFS server to see which ports and RPC programs are being used.
2.2.5. Securing the Apache HTTP Server
chown
root
<directory_name>
chmod
755
<directory_name>
/etc/httpd/conf/httpd.conf
):
FollowSymLinks
- This directive is enabled by default, so be sure to use caution when creating symbolic links to the document root of the Web server. For instance, it is a bad idea to provide a symbolic link to
/
. Indexes
- This directive is enabled by default, but may not be desirable. To prevent visitors from browsing files on the server, remove this directive.
UserDir
- The
UserDir
directive is disabled by default because it can confirm the presence of a user account on the system. To enable user directory browsing on the server, use the following directives:UserDir enabled UserDir disabled root
These directives activate user directory browsing for all user directories other than/root/
. To add users to the list of disabled accounts, add a space-delimited list of users on theUserDir disabled
line. ServerTokens
- The
ServerTokens
directive controls the server response header field which is sent back to clients. It includes various information which can be customized using the following parameters:ServerTokens Full
(default option) — provides all available information (OS type and used modules), for example:Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2
ServerTokens Prod
orServerTokens ProductOnly
— provides the following information:Apache
ServerTokens Major
— provides the following information:Apache/2
ServerTokens Minor
— provides the following information:Apache/2.0
ServerTokens Min
orServerTokens Minimal
— provides the following information:Apache/2.0.41
ServerTokens OS
— provides the following information:Apache/2.0.41 (Unix)
It is recommended to use theServerTokens Prod
option so that a possible attacker does not gain any valuable information about your system.
Important
IncludesNoExec
directive. By default, the Server-Side Includes (SSI) module cannot execute commands. It is recommended that you do not change this setting unless absolutely necessary, as it could, potentially, enable an attacker to execute commands on the system.
Removing httpd Modules
httpd
modules to limit the functionality of the HTTP Server. To do so, simply comment out the entire line which loads the module you want to remove in the /etc/httpd/conf/httpd.conf
file. For example, to remove the proxy module, comment out the following line by prepending it with a hash sign:
#LoadModule proxy_module modules/mod_proxy.so
/etc/httpd/conf.d/
directory contains configuration files which are used to load modules as well.
httpd and SELinux
2.2.6. Securing FTP
gssftpd
— A Kerberos-awarexinetd
-based FTP daemon that does not transmit authentication information over the network.- Red Hat Content Accelerator (
tux
) — A kernel-space Web server with FTP capabilities. vsftpd
— A standalone, security oriented implementation of the FTP service.
vsftpd
FTP service.
2.2.6.1. FTP Greeting Banner
vsftpd
, add the following directive to the /etc/vsftpd/vsftpd.conf
file:
ftpd_banner=<insert_greeting_here>
/etc/banners/
. The banner file for FTP connections in this example is /etc/banners/ftp.msg
. Below is an example of what such a file may look like:
######### Hello, all activity on ftp.example.com is logged. #########
Note
220
as specified in Section 2.2.1.1.1, “TCP Wrappers and Connection Banners”.
vsftpd
, add the following directive to the /etc/vsftpd/vsftpd.conf
file:
banner_file=/etc/banners/ftp.msg
2.2.6.2. Anonymous Access
/var/ftp/
directory activates the anonymous account.
vsftpd
package. This package establishes a directory tree for anonymous users and configures the permissions on directories to read-only for anonymous users.
Warning
Procedure 2.1. Anonymous Upload
- To allow anonymous users to upload files, it is recommended to create a write-only directory within the
/var/ftp/pub/
directory. Run the following command as root to create such directory named/upload/
:~]#
mkdir /var/ftp/pub/upload
- Next, change the permissions so that anonymous users cannot view the contents of the directory:
~]#
chmod 730 /var/ftp/pub/upload
A long format listing of the directory should look like this:~]#
ls -ld /var/ftp/pub/upload
drwx-wx---. 2 root ftp 4096 Nov 14 22:57 /var/ftp/pub/uploadNote
Administrators who allow anonymous users to read and write in directories often find that their servers become a repository of stolen software. - Under
vsftpd
, add the following line to the/etc/vsftpd/vsftpd.conf
file:anon_upload_enable=YES
- In Red Hat Enterprise Linux, the SELinux is running in Enforcing mode by default. Therefore, the
allow_ftpd_anon_write
Boolean must be enabled in order to allowvsftpd
to upload files:~]#
setsebool -P allow_ftpd_anon_write=1
- Label the
/upload/
directory and its files with thepublic_content_rw_t
SELinux context:~]#
semanage fcontext -a -t public_content_rw_t '/var/ftp/pub/upload(/.*)'
Note
Thesemanage
utility is provided by the policycoreutils-python package, which is not installed by default. To install it, use the following command as root:~]#
yum install policycoreutils-python
- Use the
restorecon
utility to change the type of/upload/
and its files:~]#
restorecon -R -v /var/ftp/pub/upload
The directory is now properly labeled withpublic_content_rw_t
so that SELinux in Enforcing mode allows anonymous users to upload files to it:~]$
ls -dZ /var/ftp/pub/upload
drwx-wx---. root root unconfined_u:object_r:public_content_t:s0 /var/ftp/pub/upload/For further information about using SELinux, see the Security-Enhanced Linux User Guide and Managing Confined Services guides.
2.2.6.3. User Accounts
vsftpd
, add the following directive to /etc/vsftpd/vsftpd.conf
:
local_enable=NO
2.2.6.3.1. Restricting User Accounts
sudo
privileges, the easiest way is to use a PAM list file as described in Section 2.1.9.2, “Disallowing Root Access”. The PAM configuration file for vsftpd
is /etc/pam.d/vsftpd
.
vsftpd
, add the user name to /etc/vsftpd/ftpusers
2.2.6.4. Use TCP Wrappers To Control Access
2.2.7. Securing Postfix
2.2.7.1. Limiting a Denial of Service Attack
/etc/postfix/main.cf
file. You can change the value of the directives which are already there or you can add the directives you need with the value you want in the following format:
<directive> = <value>
smtpd_client_connection_rate_limit
— The maximum number of connection attempts any client is allowed to make to this service per time unit (described below). The default value is 0, which means a client can make as many connections per time unit as Postfix can accept. By default, clients in trusted networks are excluded.anvil_rate_time_unit
— This time unit is used for rate limit calculations. The default value is 60 seconds.smtpd_client_event_limit_exceptions
— Clients that are excluded from the connection and rate limit commands. By default, clients in trusted networks are excluded.smtpd_client_message_rate_limit
— The maximum number of message deliveries a client is allowed to request per time unit (regardless of whether or not Postfix actually accepts those messages).default_process_limit
— The default maximum number of Postfix child processes that provide a given service. This limit can be overruled for specific services in themaster.cf
file. By default the value is 100.queue_minfree
— The minimum amount of free space in bytes in the queue file system that is needed to receive mail. This is currently used by the Postfix SMTP server to decide if it will accept any mail at all. By default, the Postfix SMTP server rejectsMAIL FROM
commands when the amount of free space is less than 1.5 times the message_size_limit. To specify a higher minimum free space limit, specify a queue_minfree value that is at least 1.5 times the message_size_limit. By default the queue_minfree value is 0.header_size_limit
— The maximum amount of memory in bytes for storing a message header. If a header is larger, the excess is discarded. By default the value is 102400.message_size_limit
— The maximum size in bytes of a message, including envelope information. By default the value is 10240000.
2.2.7.2. NFS and Postfix
/var/spool/postfix/
, on an NFS shared volume.
Note
SECRPC_GSS
kernel module does not utilize UID-based authentication. However, it is still considered good practice not to put the mail spool directory on NFS shared volumes.
2.2.7.3. Mail-only Users
/etc/passwd
file should be set to /sbin/nologin
(with the possible exception of the root user).
2.2.7.4. Disable Postfix Network Listening
/etc/postfix/main.cf
.
/etc/postfix/main.cf
to ensure that only the following inet_interfaces
line appears:
inet_interfaces = localhost
inet_interfaces = all
setting can be used.
2.2.7.5. Configuring Postfix to Use SASL
SASL
implementations for SMTP Authentication (or SMTP AUTH). SMTP Authentication is an extension of the Simple Mail Transfer Protocol
. When enabled, SMTP
clients are required to authenticate to the SMTP
server using an authentication method supported and accepted by both the server and the client. This section describes how to configure Postfix to make use of the Dovecot SASL
implementation.
POP
/IMAP
server, and thus make the Dovecot SASL
implementation available on your system, issue the following command as the root
user:
~]# yum install dovecot
SMTP
server can communicate with the Dovecot SASL
implementation using either a UNIX-domain socket or a TCP socket. The latter method is only needed in case the Postfix and Dovecot applications are running on separate machines. This guide gives preference to the UNIX-domain socket method, which affords better privacy.
SASL
implementation, a number of configuration changes need to be performed for both applications. Follow the procedures below to effect these changes.
Setting Up Dovecot
- Modify the main Dovecot configuration file,
/etc/dovecot/conf.d/10-master.conf
, to include the following lines (the default configuration file already includes most of the relevant section, and the lines just need to be uncommented):service auth { unix_listener /var/spool/postfix/private/auth { mode = 0660 user = postfix group = postfix } }
The above example assumes the use of UNIX-domain sockets for communication between Postfix and Dovecot. It also assumes default settings of the PostfixSMTP
server, which include the mail queue located in the/var/spool/postfix/
directory, and the application running under thepostfix
user and group. In this way, read and write permissions are limited to thepostfix
user and group.Alternatively, you can use the following configuration to set up Dovecot to listen for Postfix authentication requests viaTCP
:service auth { inet_listener { port = 12345 } }
In the above example, replace12345
with the number of the port you want to use. - Edit the
/etc/dovecot/conf.d/10-auth.conf
configuration file to instruct Dovecot to provide the PostfixSMTP
server with theplain
andlogin
authentication mechanisms:auth_mechanisms = plain login
Setting Up Postfix
/etc/postfix/main.cf
, needs to be modified. Add or edit the following configuration directives:
- Enable SMTP Authentication in the Postfix
SMTP
server:smtpd_sasl_auth_enable = yes
- Instruct Postfix to use the Dovecot
SASL
implementation for SMTP Authentication:smtpd_sasl_type = dovecot
- Provide the authentication path relative to the Postfix queue directory (note that the use of a relative path ensures that the configuration works regardless of whether the Postfix server runs in a chroot or not):
smtpd_sasl_path = private/auth
This step assumes that you want to use UNIX-domain sockets for communication between Postfix and Dovecot. To configure Postfix to look for Dovecot on a different machine in case you useTCP
sockets for communication, use configuration values similar to the following:smtpd_sasl_path = inet:127.0.0.1:12345
In the above example,127.0.0.1
needs to be substituted by theIP
address of the Dovecot machine and12345
by the port specified in Dovecot's/etc/dovecot/conf.d/10-master.conf
configuration file. - Specify
SASL
mechanisms that the PostfixSMTP
server makes available to clients. Note that different mechanisms can be specified for encrypted and unencrypted sessions.smtpd_sasl_security_options = noanonymous, noplaintext smtpd_sasl_tls_security_options = noanonymous
The above example specifies that during unencrypted sessions, no anonymous authentication is allowed and no mechanisms that transmit unencrypted usernames or passwords are allowed. For encrypted sessions (usingTLS
), only non-anonymous authentication mechanisms are allowed.See http://www.postfix.org/SASL_README.html#smtpd_sasl_security_options for a list of all supported policies for limiting allowedSASL
mechanisms.
Additional Resources
SASL
.
- http://wiki2.dovecot.org/HowTo/PostfixAndDovecotSASL — Contains information on how to set up Postfix to use the Dovecot
SASL
implementation for SMTP Authentication. - http://www.postfix.org/SASL_README.html#server_sasl — Contains information on how to set up Postfix to use either the Dovecot or Cyrus
SASL
implementations for SMTP Authentication.
2.2.8. Securing Sendmail
2.2.8.1. Limiting a Denial of Service Attack
/etc/mail/sendmail.mc
, the effectiveness of such attacks is limited.
confCONNECTION_RATE_THROTTLE
— The number of connections the server can receive per second. By default, Sendmail does not limit the number of connections. If a limit is set and reached, further connections are delayed.confMAX_DAEMON_CHILDREN
— The maximum number of child processes that can be spawned by the server. By default, Sendmail does not assign a limit to the number of child processes. If a limit is set and reached, further connections are delayed.confMIN_FREE_BLOCKS
— The minimum number of free blocks which must be available for the server to accept mail. The default is 100 blocks.confMAX_HEADERS_LENGTH
— The maximum acceptable size (in bytes) for a message header.confMAX_MESSAGE_SIZE
— The maximum acceptable size (in bytes) for a single message.
2.2.8.2. NFS and Sendmail
/var/spool/mail/
, on an NFS shared volume. Because NFSv2 and NFSv3 do not maintain control over user and group IDs, two or more users can have the same UID, and receive and read each other's mail.
Note
SECRPC_GSS
kernel module does not utilize UID-based authentication. However, it is still considered good practice not to put the mail spool directory on NFS shared volumes.
2.2.8.3. Mail-only Users
/etc/passwd
file should be set to /sbin/nologin
(with the possible exception of the root user).
2.2.8.4. Disable Sendmail Network Listening
/etc/mail/sendmail.mc
to ensure that the following line appears:
DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl
.mc
file, running /etc/mail/make
and finally restarting sendmail. The .cf
configuration file will be regenerated. Note that the system clock must be correct and working and that there must not be any system clock time shifts between these actions in order for the configuration file to be automatically regenerated.
2.2.9. Verifying Which Ports Are Listening
~]# netstat -tanp | grep LISTEN
tcp 0 0 0.0.0.0:45876 0.0.0.0:* LISTEN 1193/rpc.statd
tcp 0 0 192.168.122.1:53 0.0.0.0:* LISTEN 1241/dnsmasq
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 1783/cupsd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 7696/sendmail
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 1167/rpcbind
tcp 0 0 127.0.0.1:30003 0.0.0.0:* LISTEN 1118/tcsd
tcp 0 0 :::631 :::* LISTEN 1/init
tcp 0 0 :::35018 :::* LISTEN 1193/rpc.statd
tcp 0 0 :::111 :::* LISTEN 1167/rpcbind
-6
option for scanning an IPv6 address. See man nmap(1)
for more information.
~]# nmap -sT -O 192.168.122.1
2.2.10. Disable Source Routing
accept_source_route
option causes network interfaces to accept packets with the Strict Source Route (SSR) or Loose Source Routing (LSR) option set. The acceptance of source routed packets is controlled by sysctl settings. Issue the following command as root to drop packets with the SSR or LSR option set:
~]# /sbin/sysctl -w net.ipv4.conf.all.accept_source_route=0
~]# /sbin/sysctl -w net.ipv4.conf.all.forwarding=0
~]# /sbin/sysctl -w net.ipv6.conf.all.forwarding=0
~]# /sbin/sysctl -w net.ipv4.conf.all.mc_forwarding=0
~]# /sbin/sysctl -w net.ipv6.conf.all.mc_forwarding=0
~]# /sbin/sysctl -w net.ipv4.conf.all.accept_redirects=0
~]# /sbin/sysctl -w net.ipv6.conf.all.accept_redirects=0
~]# /sbin/sysctl -w net.ipv4.conf.all.secure_redirects=0
~]# /sbin/sysctl -w net.ipv4.conf.all.send_redirects=0
Important
0
value for every interface. To automatically disable sending of ICMP requests whenever you add a new interface, enter the following command:
~]# /sbin/sysctl -w net.ipv4.conf.default.send_redirects=0
/etc/sysctl.conf
.
Warning
2.2.11. Reverse Path Forwarding
IP
addresses from local subnets and reduces the opportunity for DDoS attacks.
Note
IPv4
in Red Hat Enterprise Linux 6.
Warning
-
rp_filter
- Reverse Path Forwarding is enabled by means of the
rp_filter
directive. Therp_filter
option is used to direct the kernel to select from one of three modes.It takes the following form when setting the default behavior:~]# /sbin/sysctl -w net.ipv4.conf.default.rp_filter=INTEGER
where INTEGER is one of the following:0
— No source validation.1
— Strict mode as defined in RFC 3704.2
— Loose mode as defined in RFC 3704.
The setting can be overridden per network interface usingnet.ipv4.interface.rp_filter
. To make these settings persistent across reboot, modify the/etc/sysctl.conf
file.
2.2.11.1. Additional Resources
- Installed Documentation
usr/share/doc/kernel-doc-version/Documentation/networking/ip-sysctl.txt
— This file contains a complete list of files and options available in the/proc/sys/net/ipv4/
directory. - Useful Websiteshttps://access.redhat.com/knowledge/solutions/53031 — The Red Hat Knowledgebase article about
rp_filter
.See RFC 3704 for an explanation of Ingress Filtering for Multihomed Networks.
2.3. Single Sign-on (SSO)
2.4. Pluggable Authentication Modules (PAM)
2.5. Kerberos
2.6. TCP Wrappers and xinetd
iptables
-based firewall filters out unwelcome network packets within the kernel's network stack. For network services that utilize it, TCP Wrappers add an additional layer of protection by defining which hosts are or are not allowed to connect to "wrapped" network services. One such wrapped network service is the xinetd
super server. This service is called a super server because it controls connections to a subset of network services and further refines access control.

Figure 2.4. Access Control to Network Services
iptables
, see Section 2.8.9, “IPTables”.
2.6.1. TCP Wrappers
/lib/libwrap.so
or /lib64/libwrap.so
library. In general terms, a TCP-wrapped service is one that has been compiled against the libwrap.so
library.
/etc/hosts.allow
and /etc/hosts.deny
) to determine whether or not the client is allowed to connect. In most cases, it then uses the syslog daemon (syslogd
) to write the name of the requesting client and the requested service to /var/log/secure
or /var/log/messages
.
libwrap.so
library. Such applications include /usr/sbin/sshd
, /usr/sbin/sendmail
, and /usr/sbin/xinetd
.
Note
libwrap.so
, type the following command as the root user:
ldd
<binary-name> |grep
libwrap
libwrap.so
.
/usr/sbin/sshd
is linked to libwrap.so
:
~]# ldd /usr/sbin/sshd | grep libwrap
libwrap.so.0 => /lib/libwrap.so.0 (0x00655000)
2.6.1.1. Advantages of TCP Wrappers
- Transparency to both the client and the wrapped network service — Both the connecting client and the wrapped network service are unaware that TCP Wrappers are in use. Legitimate users are logged and connected to the requested service while connections from banned clients fail.
- Centralized management of multiple protocols — TCP Wrappers operate separately from the network services they protect, allowing many server applications to share a common set of access control configuration files, making for simpler management.
2.6.2. TCP Wrappers Configuration Files
/etc/hosts.allow
/etc/hosts.deny
- It references
/etc/hosts.allow
— The TCP-wrapped service sequentially parses the/etc/hosts.allow
file and applies the first rule specified for that service. If it finds a matching rule, it allows the connection. If not, it moves on to the next step. - It references
/etc/hosts.deny
— The TCP-wrapped service sequentially parses the/etc/hosts.deny
file. If it finds a matching rule, it denies the connection. If not, it grants access to the service.
- Because access rules in
hosts.allow
are applied first, they take precedence over rules specified inhosts.deny
. Therefore, if access to a service is allowed inhosts.allow
, a rule denying access to that same service inhosts.deny
is ignored. - The rules in each file are read from the top down and the first matching rule for a given service is the only one applied. The order of the rules is extremely important.
- If no rules for the service are found in either file, or if neither file exists, access to the service is granted.
- TCP-wrapped services do not cache the rules from the hosts access files, so any changes to
hosts.allow
orhosts.deny
take effect immediately, without restarting network services.
Warning
/var/log/messages
or /var/log/secure
. This is also the case for a rule that spans multiple lines without using the backslash character. The following example illustrates the relevant portion of a log message for a rule failure due to either of these circumstances:
warning: /etc/hosts.allow, line 20: missing newline or line too long
2.6.2.1. Formatting Access Rules
/etc/hosts.allow
and /etc/hosts.deny
is identical. Each rule must be on its own line. Blank lines or lines that start with a hash (#) are ignored.
<daemon list> : <client list> [: <option> : <option> : …]
- <daemon list> — A comma-separated list of process names (not service names) or the
ALL
wildcard. The daemon list also accepts operators (refer to Section 2.6.2.1.4, “Operators”) to allow greater flexibility. - <client list> — A comma-separated list of hostnames, host IP addresses, special patterns, or wildcards which identify the hosts affected by the rule. The client list also accepts operators listed in Section 2.6.2.1.4, “Operators” to allow greater flexibility.
- <option> — An optional action or colon-separated list of actions performed when the rule is triggered. Option fields support expansions, launch shell commands, allow or deny access, and alter logging behavior.
Note
vsftpd : .example.com
vsftpd
) from any host in the example.com
domain. If this rule appears in hosts.allow
, the connection is accepted. If this rule appears in hosts.deny
, the connection is rejected.
sshd : .example.com \ : spawn /bin/echo `/bin/date` access denied>>/var/log/sshd.log \ : deny
sshd
) is attempted from a host in the example.com
domain, execute the echo
command to append the attempt to a special log file, and deny the connection. Because the optional deny
directive is used, this line denies access even if it appears in the hosts.allow
file. Refer to Section 2.6.2.2, “Option Fields” for a more detailed look at available options.
2.6.2.1.1. Wildcards
ALL
— Matches everything. It can be used for both the daemon list and the client list.LOCAL
— Matches any host that does not contain a period (.), such as localhost.KNOWN
— Matches any host where the hostname and host address are known or where the user is known.UNKNOWN
— Matches any host where the hostname or host address are unknown or where the user is unknown.PARANOID
— A reverse DNS lookup is done on the source IP address to obtain the host name. Then a DNS lookup is performed to resolve the IP address. If the two IP addresses do not match the connection is dropped and the logs are updated
Important
KNOWN
, UNKNOWN
, and PARANOID
wildcards should be used with care, because they rely on a functioning DNS server for correct operation. Any disruption to name resolution may prevent legitimate users from gaining access to a service.
2.6.2.1.2. Patterns
- Hostname beginning with a period (.) — Placing a period at the beginning of a hostname matches all hosts sharing the listed components of the name. The following example applies to any host within the
example.com
domain:ALL : .example.com
- IP address ending with a period (.) — Placing a period at the end of an IP address matches all hosts sharing the initial numeric groups of an IP address. The following example applies to any host within the
192.168.x.x
network:ALL : 192.168.
- IP address/netmask pair — Netmask expressions can also be used as a pattern to control access to a particular group of IP addresses. The following example applies to any host with an address range of
192.168.0.0
through192.168.1.255
:ALL : 192.168.0.0/255.255.254.0
Important
When working in the IPv4 address space, the address/prefix length (prefixlen) pair declarations (CIDR notation) are not supported. Only IPv6 rules can use this format. - [IPv6 address]/prefixlen pair — [net]/prefixlen pairs can also be used as a pattern to control access to a particular group of IPv6 addresses. The following example would apply to any host with an address range of
3ffe:505:2:1::
through3ffe:505:2:1:ffff:ffff:ffff:ffff
:ALL : [3ffe:505:2:1::]/64
- The asterisk (*) — Asterisks can be used to match entire groups of hostnames or IP addresses, as long as they are not mixed in a client list containing other types of patterns. The following example would apply to any host within the
example.com
domain:ALL : *.example.com
- The slash (/) — If a client list begins with a slash, it is treated as a file name. This is useful if rules specifying large numbers of hosts are necessary. The following example refers TCP Wrappers to the
/etc/telnet.hosts
file for all Telnet connections:in.telnetd : /etc/telnet.hosts
hosts_access
man 5 page for more information.
Warning
2.6.2.1.3. Portmap and TCP Wrappers
Portmap
's implementation of TCP Wrappers does not support host look-ups, which means portmap
can not use hostnames to identify hosts. Consequently, access control rules for portmap in hosts.allow
or hosts.deny
must use IP addresses, or the keyword ALL
, for specifying hosts.
portmap
access control rules may not take effect immediately. You may need to restart the portmap
service.
portmap
to operate, so be aware of these limitations.
2.6.2.1.4. Operators
EXCEPT
. It can be used in both the daemon list and the client list of a rule.
EXCEPT
operator allows specific exceptions to broader matches within the same rule.
hosts.allow
file, all example.com
hosts are allowed to connect to all services except attacker.example.com
:
ALL : .example.com EXCEPT attacker.example.com
hosts.allow
file, clients from the 192.168.0.x
network can use all services except for FTP:
ALL EXCEPT vsftpd : 192.168.0.
Note
EXCEPT
operators. This allows other administrators to quickly scan the appropriate files to see what hosts are allowed or denied access to services, without having to sort through EXCEPT
operators.
2.6.2.2. Option Fields
2.6.2.2.1. Logging
severity
directive.
example.com
domain are logged to the default authpriv
syslog
facility (because no facility value is specified) with a priority of emerg
:
sshd : .example.com : severity emerg
severity
option. The following example logs any SSH connection attempts by hosts from the example.com
domain to the local0
facility with a priority of alert
:
sshd : .example.com : severity local0.alert
Note
syslogd
) is configured to log to the local0
facility. Refer to the syslog.conf
man page for information about configuring custom log facilities.
2.6.2.2.2. Access Control
allow
or deny
directive as the final option.
client-1.example.com
, but deny connections from client-2.example.com
:
sshd : client-1.example.com : allow sshd : client-2.example.com : deny
hosts.allow
or hosts.deny
. Some administrators consider this an easier way of organizing access rules.
2.6.2.2.3. Shell Commands
spawn
— Launches a shell command as a child process. This directive can perform tasks like using/usr/sbin/safe_finger
to get more information about the requesting client or create special log files using theecho
command.In the following example, clients attempting to access Telnet services from theexample.com
domain are quietly logged to a special file:in.telnetd : .example.com \ : spawn /bin/echo `/bin/date` from %h>>/var/log/telnet.log \ : allow
twist
— Replaces the requested service with the specified command. This directive is often used to set up traps for intruders (also called "honey pots"). It can also be used to send messages to connecting clients. Thetwist
directive must occur at the end of the rule line.In the following example, clients attempting to access FTP services from theexample.com
domain are sent a message using theecho
command:vsftpd : .example.com \ : twist /bin/echo "421 This domain has been black-listed. Access denied!"
hosts_options
man page.
2.6.2.2.4. Expansions
spawn
and twist
directives, provide information about the client, server, and processes involved.
%a
— Returns the client's IP address.%A
— Returns the server's IP address.%c
— Returns a variety of client information, such as the user name and hostname, or the user name and IP address.%d
— Returns the daemon process name.%h
— Returns the client's hostname (or IP address, if the hostname is unavailable).%H
— Returns the server's hostname (or IP address, if the hostname is unavailable).%n
— Returns the client's hostname. If unavailable,unknown
is printed. If the client's hostname and host address do not match,paranoid
is printed.%N
— Returns the server's hostname. If unavailable,unknown
is printed. If the server's hostname and host address do not match,paranoid
is printed.%p
— Returns the daemon's process ID.%s
—Returns various types of server information, such as the daemon process and the host or IP address of the server.%u
— Returns the client's user name. If unavailable,unknown
is printed.
spawn
command to identify the client host in a customized log file.
sshd
) are attempted from a host in the example.com
domain, execute the echo
command to log the attempt, including the client hostname (by using the %h
expansion), to a special file:
sshd : .example.com \ : spawn /bin/echo `/bin/date` access denied to %h>>/var/log/sshd.log \ : deny
example.com
domain are informed that they have been banned from the server:
vsftpd : .example.com \ : twist /bin/echo "421 %h has been banned from this server!"
hosts_access
(man 5 hosts_access
) and the man page for hosts_options
.
2.6.3. xinetd
xinetd
daemon is a TCP-wrapped super service which controls access to a subset of popular network services, including FTP, IMAP, and Telnet. It also provides service-specific configuration options for access control, enhanced logging, binding, redirection, and resource utilization control.
xinetd
, the super service receives the request and checks for any TCP Wrappers access control rules.
xinetd
verifies that the connection is allowed under its own access rules for that service. It also checks that the service is able to have more resources assigned to it and that it is not in breach of any defined rules.
xinetd
then starts an instance of the requested service and passes control of the connection to it. After the connection has been established, xinetd
takes no further part in the communication between the client and the server.
2.6.4. xinetd Configuration Files
xinetd
are as follows:
/etc/xinetd.conf
— The globalxinetd
configuration file./etc/xinetd.d/
— The directory containing all service-specific files.
2.6.4.1. The /etc/xinetd.conf File
/etc/xinetd.conf
file contains general configuration settings which affect every service under xinetd
's control. It is read when the xinetd
service is first started, so for configuration changes to take effect, you need to restart the xinetd
service. The following is a sample /etc/xinetd.conf
file:
defaults { instances = 60 log_type = SYSLOG authpriv log_on_success = HOST PID log_on_failure = HOST cps = 25 30 } includedir /etc/xinetd.d
xinetd
:
instances
— Specifies the maximum number of simultaneous requests thatxinetd
can process.log_type
— Configuresxinetd
to use theauthpriv
log facility, which writes log entries to the/var/log/secure
file. Adding a directive such asFILE /var/log/xinetdlog
would create a custom log file calledxinetdlog
in the/var/log/
directory.log_on_success
— Configuresxinetd
to log successful connection attempts. By default, the remote host's IP address and the process ID of the server processing the request are recorded.log_on_failure
— Configuresxinetd
to log failed connection attempts or if the connection was denied.cps
— Configuresxinetd
to allow no more than 25 connections per second to any given service. If this limit is exceeded, the service is retired for 30 seconds.includedir
/etc/xinetd.d/
— Includes options declared in the service-specific configuration files located in the/etc/xinetd.d/
directory. Refer to Section 2.6.4.2, “The /etc/xinetd.d/ Directory” for more information.
Note
log_on_success
and log_on_failure
settings in /etc/xinetd.conf
are further modified in the service-specific configuration files. More information may therefore appear in a given service's log file than the /etc/xinetd.conf
file may indicate. Refer to Section 2.6.4.3.1, “Logging Options” for further information.
2.6.4.2. The /etc/xinetd.d/ Directory
/etc/xinetd.d/
directory contains the configuration files for each service managed by xinetd
and the names of the files are correlated to the service. As with xinetd.conf
, this directory is read only when the xinetd
service is started. For any changes to take effect, the administrator must restart the xinetd
service.
/etc/xinetd.d/
directory use the same conventions as /etc/xinetd.conf
. The primary reason the configuration for each service is stored in a separate file is to make customization easier and less likely to affect other services.
/etc/xinetd.d/krb5-telnet
file:
service telnet { flags = REUSE socket_type = stream wait = no user = root server = /usr/kerberos/sbin/telnetd log_on_failure += USERID disable = yes }
telnet
service:
service
— Specifies the service name, usually one of those listed in the/etc/services
file.flags
— Sets any of a number of attributes for the connection.REUSE
instructsxinetd
to reuse the socket for a Telnet connection.Note
TheREUSE
flag is deprecated. All services now implicitly use theREUSE
flag.socket_type
— Sets the network socket type tostream
.wait
— Specifies whether the service is single-threaded (yes
) or multi-threaded (no
).user
— Specifies which user ID the process runs under.server
— Specifies which binary executable to launch.log_on_failure
— Specifies logging parameters forlog_on_failure
in addition to those already defined inxinetd.conf
.disable
— Specifies whether the service is disabled (yes
) or enabled (no
).
xinetd.conf
man page for more information about these options and their usage.
2.6.4.3. Altering xinetd Configuration Files
xinetd
. This section highlights some of the more commonly used options.
2.6.4.3.1. Logging Options
/etc/xinetd.conf
and the service-specific configuration files within the /etc/xinetd.d/
directory.
ATTEMPT
— Logs the fact that a failed attempt was made (log_on_failure
).DURATION
— Logs the length of time the service is used by a remote system (log_on_success
).EXIT
— Logs the exit status or termination signal of the service (log_on_success
).HOST
— Logs the remote host's IP address (log_on_failure
andlog_on_success
).PID
— Logs the process ID of the server receiving the request (log_on_success
).USERID
— Logs the remote user using the method defined in RFC 1413 for all multi-threaded stream services (log_on_failure
andlog_on_success
).
xinetd.conf
man page.
2.6.4.3.2. Access Control Options
xinetd
services can choose to use the TCP Wrappers hosts access rules, provide access control via the xinetd
configuration files, or a mixture of both. Refer to Section 2.6.2, “TCP Wrappers Configuration Files” for more information about TCP Wrappers hosts access control files.
xinetd
to control access to services.
Note
xinetd
administrator restarts the xinetd
service.
xinetd
only affects services controlled by xinetd
.
xinetd
hosts access control differs from the method used by TCP Wrappers. While TCP Wrappers places all of the access configuration within two files, /etc/hosts.allow
and /etc/hosts.deny
, xinetd
's access control is found in each service's configuration file in the /etc/xinetd.d/
directory.
xinetd
:
only_from
— Allows only the specified hosts to use the service.no_access
— Blocks listed hosts from using the service.access_times
— Specifies the time range when a particular service may be used. The time range must be stated in 24-hour format notation, HH:MM-HH:MM.
only_from
and no_access
options can use a list of IP addresses or host names, or can specify an entire network. Like TCP Wrappers, combining xinetd
access control with the enhanced logging configuration can increase security by blocking requests from banned hosts while verbosely recording each connection attempt.
/etc/xinetd.d/telnet
file can be used to block Telnet access from a particular network group and restrict the overall time range that even allowed users can log in:
service telnet { disable = no flags = REUSE socket_type = stream wait = no user = root server = /usr/kerberos/sbin/telnetd log_on_failure += USERID no_access = 172.16.45.0/24 log_on_success += PID HOST EXIT access_times = 09:45-16:15 }
172.16.45.0/24
network, such as 172.16.45.2
, tries to access the Telnet service, it receives the following message:
Connection closed by foreign host.
/var/log/messages
as follows:
Sep 7 14:58:33 localhost xinetd[5285]: FAIL: telnet address from=172.16.45.107 Sep 7 14:58:33 localhost xinetd[5283]: START: telnet pid=5285 from=172.16.45.107 Sep 7 14:58:33 localhost xinetd[5283]: EXIT: telnet status=0 pid=5285 duration=0(sec)
xinetd
access controls, it is important to understand the relationship between the two access control mechanisms.
xinetd
when a client requests a connection:
- The
xinetd
daemon accesses the TCP Wrappers hosts access rules using alibwrap.so
library call. If a deny rule matches the client, the connection is dropped. If an allow rule matches the client, the connection is passed toxinetd
. - The
xinetd
daemon checks its own access control rules both for thexinetd
service and the requested service. If a deny rule matches the client, the connection is dropped. Otherwise,xinetd
starts an instance of the requested service and passes control of the connection to that service.
Important
xinetd
access controls. Misconfiguration can cause undesirable effects.
2.6.4.3.3. Binding and Redirection Options
xinetd
support binding the service to an IP address and redirecting incoming requests for that service to another IP address, hostname, or port.
bind
option in the service-specific configuration files and links the service to one IP address on the system. When this is configured, the bind
option only allows requests to the correct IP address to access the service. You can use this method to bind different services to different network interfaces based on requirements.
redirect
option accepts an IP address or hostname followed by a port number. It configures the service to redirect any requests for this service to the specified host and port number. This feature can be used to point to another port number on the same system, redirect the request to a different IP address on the same machine, shift the request to a totally different system and port number, or any combination of these options. A user connecting to a certain service on a system may therefore be rerouted to another system without disruption.
xinetd
daemon is able to accomplish this redirection by spawning a process that stays alive for the duration of the connection between the requesting client machine and the host actually providing the service, transferring data between the two systems.
bind
and redirect
options are most clearly evident when they are used together. By binding a service to a particular IP address on a system and then redirecting requests for this service to a second machine that only the first machine can see, an internal system can be used to provide services for a totally different network. Alternatively, these options can be used to limit the exposure of a particular service on a multi-homed machine to a known IP address, as well as redirect any requests for that service to another machine especially configured for that purpose.
service telnet { socket_type = stream wait = no server = /usr/kerberos/sbin/telnetd log_on_success += DURATION USERID log_on_failure += USERID bind = 123.123.123.123 redirect = 10.0.1.13 23 }
bind
and redirect
options in this file ensure that the Telnet service on the machine is bound to the external IP address (123.123.123.123
), the one facing the Internet. In addition, any requests for Telnet service sent to 123.123.123.123
are redirected via a second network adapter to an internal IP address (10.0.1.13
) that only the firewall and internal systems can access. The firewall then sends the communication between the two systems, and the connecting system thinks it is connected to 123.123.123.123
when it is actually connected to a different machine.
xinetd
are configured with the bind
and redirect
options, the gateway machine can act as a proxy between outside systems and a particular internal machine configured to provide the service. In addition, the various xinetd
access control and logging options are also available for additional protection.
2.6.4.3.4. Resource Management Options
xinetd
daemon can add a basic level of protection from Denial of Service (DoS) attacks. The following is a list of directives which can aid in limiting the effectiveness of such attacks:
per_source
— Defines the maximum number of instances for a service per source IP address. It accepts only integers as an argument and can be used in bothxinetd.conf
and in the service-specific configuration files in thexinetd.d/
directory.cps
— Defines the maximum number of connections per second. This directive takes two integer arguments separated by white space. The first argument is the maximum number of connections allowed to the service per second. The second argument is the number of seconds thatxinetd
must wait before re-enabling the service. It accepts only integers as arguments and can be used in either thexinetd.conf
file or the service-specific configuration files in thexinetd.d/
directory.max_load
— Defines the CPU usage or load average threshold for a service. It accepts a floating point number argument.The load average is a rough measure of how many processes are active at a given time. See theuptime
,who
, andprocinfo
commands for more information about load average.
xinetd
. Refer to the xinetd.conf
man page for more information.
2.6.5. Additional Resources
xinetd
is available from system documentation and on the Internet.
2.6.5.1. Installed TCP Wrappers Documentation
xinetd
, and access control.
/usr/share/doc/tcp_wrappers-<version>/
— This directory contains aREADME
file that discusses how TCP Wrappers work and the various hostname and host address spoofing risks that exist./usr/share/doc/xinetd-<version>/
— This directory contains aREADME
file that discusses aspects of access control and asample.conf
file with various ideas for modifying service-specific configuration files in the/etc/xinetd.d/
directory.- TCP Wrappers and
xinetd
-related man pages — A number of man pages exist for the various applications and configuration files involved with TCP Wrappers andxinetd
. The following are some of the more important man pages:- Server Applications
man xinetd
— The man page forxinetd
.
- Configuration Files
man 5 hosts_access
— The man page for the TCP Wrappers hosts access control files.man hosts_options
— The man page for the TCP Wrappers options fields.man xinetd.conf
— The man page listingxinetd
configuration options.
2.6.5.2. Related Books
- Hacking Linux Exposed by Brian Hatch, James Lee, and George Kurtz; Osbourne/McGraw-Hill — An excellent security resource with information about TCP Wrappers and
xinetd
.
2.7. Securing Virtual Private Networks (VPNs)
IPsec
tunneling protocol which is supported by the Libreswan application. Libreswan is a fork of the Openswan application and examples in documentation should be interchangeable. The NetworkManager IPsec
plug-in is called NetworkManager-openswan.
Note
IPsec
implementation available in Red Hat Enterprise Linux 6. It uses the Internet key exchange (IKE) protocol. IKE
version 1 and 2 are implemented as a user-level daemon. Manual key establishment is also possible via ip xfrm
commands, however this is not recommended. Libreswan interfaces with the Linux kernel using netlink to transfer the encryption keys. Packet encryption and decryption happen in the Linux kernel.
2.7.1. IPsec VPN Using Libreswan
root
. Note that the libreswan package is available from the Extras repository, which needs to be enabled for the installation to succeed. See How to enable/disable a repository using Red Hat Subscription Manager? (The ID of the Extras repository is rhel-6-server-extras-rpms
.)
~]# yum install libreswan
~]$ yum info libreswan
~]# rm /etc/ipsec.d/*db
root
:
~]# ipsec initnss
Initializing NSS database
See 'man pluto' if you want to protect the NSS database with a password
ipsec
daemon provided by Libreswan, issue the following command as root
:
~]# service ipsec start
~]$ service ipsec status
pluto (pid 3496) is running...
root
:
~]# chkconfig ipsec on
ipsec
service. See Section 2.8, “Firewalls” for information on firewalls and allowing specific services to pass through. Libreswan requires the firewall to allow the following packets:
UDP
port 500 for theInternet Key Exchange
(IKE) protocolUDP
port 4500 forIKE NAT-Traversal
- Protocol 50 for
Encapsulated Security Payload
(ESP)IPsec
packets - Protocol 51 for
Authenticated Header
(AH)IPsec
packets (uncommon)
IPsec
VPN. The first example is for connecting two hosts together so that they may communicate securely. The second example is connecting two sites together to form one network. The third example is supporting roaming users, known as road warriors in this context.
2.7.2. VPN Configurations Using Libreswan
- Raw RSA keys are commonly used for static host-to-host or subnet-to-subnet
IPsec
configurations. The hosts are manually configured with each other's public RSA key. This method does not scale well when dozens or more hosts all need to setupIPsec
tunnels to each other. - X.509 certificates are commonly used for large scale deployments where there are many hosts that need to connect to a common
IPsec
gateway. A central certificate authority (CA) is used to sign RSA certificates for hosts or users. This central CA is responsible for relaying trust, including the revocations of individual hosts or users. - Pre-Shared Keys (PSK) is the simplest authentication method. PSK's should consist of random characters and have a length of at least 20 characters. Due to the dangers of non-random and short PSKs, this is the least secure form of authentication and it is recommended to use either raw RSA keys or certificate based authentication instead.
2.7.3. Host-To-Host VPN Using Libreswan
IPsec
VPN, between two hosts referred to as “left” and “right”, and enter the following commands as root
on both of the hosts (“left” and “right”) to create new raw RSA key pairs:
~]#ipsec newhostkey --configdir /etc/ipsec.d \
--output /etc/ipsec.d/myvpn.secrets
Generated RSA key pair using the NSS database
root
on either of the hosts. For example, to view the public key on the “left” host, run:
~]# ipsec showhostkey --left
ipsec showhostkey loading secrets from "/etc/ipsec.secrets"
ipsec showhostkey loading secrets from "/etc/ipsec.d/myvpn.secrets"
ipsec showhostkey loaded private key for keyid: PPK_RSA:AQOjAKLlL
# rsakey AQOjAKLlL
leftrsasigkey=0sAQOjAKLlL4a7YBv [...]
/etc/ipsec.d/*.db
files, also called the “NSS database”.
leftrsasigkey=
and rightrsasigkey=
from above, are added to a custom configuration file placed in the /etc/ipsec.d/
directory.
root
, create a file with a corresponding name in the following format:
/etc/ipsec.d/myvpn.conf
conn myvpn leftid=@west.example.com left=192.1.2.23 leftrsasigkey=0sAQOrlo+hOafUZDlCQmXFrje/oZm [...] W2n417C/4urYHQkCvuIQ== rightid=@east.example.com right=192.1.2.45 rightrsasigkey=0sAQO3fwC6nSSGgt64DWiYZzuHbc4 [...] D/v8t5YTQ== authby=rsasig # load and initiate automatically auto=start
IP
address is not known in advance, then on the mobile host use %defaultroute
as its IP
address. This picks up the dynamic IP
address automatically. On the static host that accepts connections from incoming mobile hosts, specify the mobile host using %any
for its IP
address.
leftrsasigkey
value is obtained from the “left” host and the rightrsasigkey
value is obtained from the “right” host.
ipsec
to ensure it reads the new configuration:
~]# service ipsec --full-restart
root
:
~]# ipsec whack --trafficstatus
006 #2: "myvpn", type=ESP, add_time=1234567890, inBytes=336, outBytes=336, id='@east'
auto=start
option in the /etc/ipsec.d/*.conf
file or if a tunnel is not succesfully established, use the following command as root
to load the IPsec
tunnel:
~]# ipsec auto --add myvpn
root
, on the left or the right side:
~]# ipsec auto --up myvpn
2.7.3.1. Verify Host-To-Host VPN Using Libreswan
IKE
negotiation takes place on UDP
port 500. IPsec
packets show up as Encapsulated Security Payload
(ESP) packets. When the VPN connection needs to pass through a NAT router, the ESP
packets are encapsulated in UDP
packets on port 4500.
root
in the following format:
~]# tcpdump -n -i interface esp or udp port 500 or udp port 4500
00:32:32.632165 IP 192.1.2.45 > 192.1.2.23: ESP(spi=0x63ad7e17,seq=0x1a), length 132
00:32:32.632592 IP 192.1.2.23 > 192.1.2.45: ESP(spi=0x4841b647,seq=0x1a), length 132
00:32:32.632592 IP 192.0.2.254 > 192.0.1.254: ICMP echo reply, id 2489, seq 7, length 64
00:32:33.632221 IP 192.1.2.45 > 192.1.2.23: ESP(spi=0x63ad7e17,seq=0x1b), length 132
00:32:33.632731 IP 192.1.2.23 > 192.1.2.45: ESP(spi=0x4841b647,seq=0x1b), length 132
00:32:33.632731 IP 192.0.2.254 > 192.0.1.254: ICMP echo reply, id 2489, seq 8, length 64
00:32:34.632183 IP 192.1.2.45 > 192.1.2.23: ESP(spi=0x63ad7e17,seq=0x1c), length 132
00:32:34.632607 IP 192.1.2.23 > 192.1.2.45: ESP(spi=0x4841b647,seq=0x1c), length 132
00:32:34.632607 IP 192.0.2.254 > 192.0.1.254: ICMP echo reply, id 2489, seq 9, length 64
00:32:35.632233 IP 192.1.2.45 > 192.1.2.23: ESP(spi=0x63ad7e17,seq=0x1d), length 132
00:32:35.632685 IP 192.1.2.23 > 192.1.2.45: ESP(spi=0x4841b647,seq=0x1d), length 132
00:32:35.632685 IP 192.0.2.254 > 192.0.1.254: ICMP echo reply, id 2489, seq 10, length 64
Note
IPsec
. It only sees the outgoing encrypted packet, not the outgoing plaintext packet. It does see the encrypted incoming packet, as well as the decrypted incoming packet. If possible, run tcpdump on a router between the two machines and not on one of the endpoints itself.
2.7.4. Site-to-Site VPN Using Libreswan
IPsec
VPN, joining together two networks, an IPsec
tunnel is created between two hosts, endpoints, which are configured to permit traffic from one or more subnets to pass through. They can therefore be thought of as gateways to the remote portion of the network. The configuration of the site-to-site VPN only differs from the host-to-host VPN in that one or more networks or subnets must be specified in the configuration file.
IPsec
VPN, first configure a host-to-host IPsec
VPN as described in Section 2.7.3, “Host-To-Host VPN Using Libreswan” and then copy or move the file to a file with a suitable name, such as /etc/ipsec.d/my_site-to-site.conf
. Using an editor running as root
, edit the custom configuration file /etc/ipsec.d/my_site-to-site.conf
as follows:
conn mysubnet also=mytunnel leftsubnet=192.0.1.0/24 rightsubnet=192.0.2.0/24 conn mysubnet6 also=mytunnel connaddrfamily=ipv6 leftsubnet=2001:db8:0:1::/64 rightsubnet=2001:db8:0:2::/64 conn mytunnel leftid=@west.example.com left=192.1.2.23 leftrsasigkey=0sAQOrlo+hOafUZDlCQmXFrje/oZm [...] W2n417C/4urYHQkCvuIQ== rightid=@east.example.com right=192.1.2.45 rightrsasigkey=0sAQO3fwC6nSSGgt64DWiYZzuHbc4 [...] D/v8t5YTQ== authby=rsasig
root
:
~]# ipsec auto --add mysubnet
~]# ipsec auto --add mysubnet6
~]# ipsec auto --add mytunnel
~]# ipsec auto --up mysubnet
104 "mysubnet" #1: STATE_MAIN_I1: initiate
003 "mysubnet" #1: received Vendor ID payload [Dead Peer Detection]
003 "mytunnel" #1: received Vendor ID payload [FRAGMENTATION]
106 "mysubnet" #1: STATE_MAIN_I2: sent MI2, expecting MR2
108 "mysubnet" #1: STATE_MAIN_I3: sent MI3, expecting MR3
003 "mysubnet" #1: received Vendor ID payload [CAN-IKEv2]
004 "mysubnet" #1: STATE_MAIN_I4: ISAKMP SA established {auth=OAKLEY_RSA_SIG cipher=aes_128 prf=oakley_sha group=modp2048}
117 "mysubnet" #2: STATE_QUICK_I1: initiate
004 "mysubnet" #2: STATE_QUICK_I2: sent QI2, IPsec SA established tunnel mode {ESP=>0x9414a615 <0x1a8eb4ef xfrm=AES_128-HMAC_SHA1 NATOA=none NATD=none DPD=none}
~]# ipsec auto --up mysubnet6
003 "mytunnel" #1: received Vendor ID payload [FRAGMENTATION]
117 "mysubnet" #2: STATE_QUICK_I1: initiate
004 "mysubnet" #2: STATE_QUICK_I2: sent QI2, IPsec SA established tunnel mode {ESP=>0x06fe2099 <0x75eaa862 xfrm=AES_128-HMAC_SHA1 NATOA=none NATD=none DPD=none}
~]# ipsec auto --up mytunnel
104 "mytunnel" #1: STATE_MAIN_I1: initiate
003 "mytunnel" #1: received Vendor ID payload [Dead Peer Detection]
003 "mytunnel" #1: received Vendor ID payload [FRAGMENTATION]
106 "mytunnel" #1: STATE_MAIN_I2: sent MI2, expecting MR2
108 "mytunnel" #1: STATE_MAIN_I3: sent MI3, expecting MR3
003 "mytunnel" #1: received Vendor ID payload [CAN-IKEv2]
004 "mytunnel" #1: STATE_MAIN_I4: ISAKMP SA established {auth=OAKLEY_RSA_SIG cipher=aes_128 prf=oakley_sha group=modp2048}
117 "mytunnel" #2: STATE_QUICK_I1: initiate
004 "mytunnel" #2: STATE_QUICK_I2: sent QI2, IPsec SA established tunnel mode {ESP=>0x16bca4f7 >0x9c2ae273 xfrm=AES_128-HMAC_SHA1 NATOA=none NATD=none DPD=none}
2.7.4.1. Verify Site-to-Site VPN Using Libreswan
2.7.5. Site-to-Site Single Tunnel VPN Using Libreswan
IP
addresses instead of their public IP
addresses. This can be accomplished using a single tunnel. If the left host, with host name west
, has internal IP
address 192.0.1.254
and the right host, with host name east
, has internal IP
address 192.0.2.254
, store the following configuration using a single tunnel to the /etc/ipsec.d/myvpn.conf
file on both servers:
conn myvpn leftid=@west.example.com leftrsasigkey=0sAQOrlo+hOafUZDlCQmXFrje/oZm [...] W2n417C/4urYHQkCvuIQ== left=192.1.2.23 leftsourceip=192.0.1.254 leftsubnet=192.0.1.0/24 rightid=@east.example.com rightrsasigkey=0sAQO3fwC6nSSGgt64DWiYZzuHbc4 [...] D/v8t5YTQ== right=192.1.2.45 rightsourceip=192.0.2.254 rightsubnet=192.0.2.0/24 auto=start authby=rsasig
2.7.6. Subnet Extrusion Using Libreswan
IPsec
is often deployed in a hub-and-spoke architecture. Each leaf node has an IP
range that is part of a larger range. Leaves communicate with each other via the hub. This is called subnet extrusion. In the example below, we configure the head office with 10.0.0.0/8
and two branches that use a smaller /24
subnet.
conn branch1 left=1.2.3.4 leftid=@headoffice leftsubnet=0.0.0.0/0 leftrsasigkey=0sA[...] # right=5.6.7.8 rightid=@branch1 rightsubnet=10.0.1.0/24 rightrsasigkey=0sAXXXX[...] # auto=start authby=rsasig conn branch2 left=1.2.3.4 leftid=@headoffice leftsubnet=0.0.0.0/0 leftrsasigkey=0sA[...] # right=10.11.12.13 rightid=@branch2 rightsubnet=10.0.2.0/24 rightrsasigkey=0sAYYYY[...] # auto=start authby=rsasig
conn branch1 left=1.2.3.4 leftid=@headoffice leftsubnet=0.0.0.0/0 leftrsasigkey=0sA[...] # right=10.11.12.13 rightid=@branch2 rightsubnet=10.0.1.0/24 rightrsasigkey=0sAYYYY[...] # auto=start authby=rsasig conn passthrough left=1.2.3.4 right=0.0.0.0 leftsubnet=10.0.1.0/24 rightsubnet=10.0.1.0/24 authby=never type=passthrough auto=route
2.7.7. Road Warrior Access VPN Using Libreswan
IP
address, such as laptops. These are authenticated using certificates.
conn roadwarriors left=1.2.3.4 # if access to the LAN is given, enable this #leftsubnet=10.10.0.0/16 leftcert=vpn-server.example.com leftid=%fromcert right=%any # trust our own Certificate Agency rightca=%same # allow clients to be behind a NAT router rightsubnet=vhost:%priv,%no authby=rsasig # load connection, don't initiate auto=add # kill vanished roadwarriors dpddelay=30 dpdtimeout=120 dpdaction=%clear
left=1.2.3.4
- The 1.2.3.4 value specifies the actual IP address or host name of your server.
leftcert=vpn-server.example.com
- This option specifies a certificate referring to its friendly name or nickname that has been used to import the certificate. Usually, the name is generated as a part of a PKCS #12 certificate bundle in the form of a
.p12
file. See thepkcs12(1)
andpk12util(1)
man pages for more information.
conn roadwarriors # pick up our dynamic IP left=%defaultroute leftcert=myname.example.com leftid=%fromcert # right can also be a DNS hostname right=1.2.3.4 # if access to the remote LAN is required, enable this #rightsubnet=10.10.0.0/16 # trust our own Certificate Agency rightca=%same authby=rsasig # Initiate connection auto=start
auto=start
- This option enables the user to connect to the VPN whenever the
ipsec
system service is started. Replace it with theauto=add
if you want to establish the connection later.
2.7.8. Road Warrior Access VPN Using Libreswan and XAUTH with X.509
IP
address and DNS information to roaming VPN clients as the connection is established by using the XAUTH IPsec
extension. Extended authentication (XAUTH) can be deployed using PSK or X.509 certificates. Deploying using X.509 is more secure. Client certificates can be revoked by a certificate revocation list or by Online Certificate Status Protocol (OCSP). With X.509 certificates, individual clients cannot impersonate the server. With a PSK, also called Group Password, this is theoretically possible.
xauthby=pam
- This uses the configuration in
/etc/pam.d/pluto
to authenticate the user. Pluggable Authentication Modules (PAM) can be configured to use various backends by itself. It can use the system account user-password scheme, an LDAP directory, a RADIUS server or a custom password authentication module. See the Using Pluggable Authentication Modules (PAM) chapter for more information. xauthby=file
- This uses the configuration file
/etc/ipsec.d/passwd
(not to be confused with/etc/ipsec.d/nsspassword
). The format of this file is similar to the Apache.htpasswd
file and the Apachehtpasswd
command can be used to create entries in this file. However, after the user name and password, a third column is required with the connection name of theIPsec
connection used, for example when using aconn remoteusers
to offer VPN to remote users, a password file entry should look as follows:user1:$apr1$MIwQ3DHb$1I69LzTnZhnCT2DPQmAOK.:remoteusers
NOTE: when using thehtpasswd
command, the connection name has to be manually added after the user:password part on each line. xauthby=alwaysok
- The server will always pretend the XAUTH user and password combination was correct. The client still has to specify a user name and a password, although the server ignores these. This should only be used when users are already identified by X.509 certificates, or when testing the VPN without needing an XAUTH backend.
conn xauth-rsa auto=add authby=rsasig pfs=no rekey=no left=ServerIP leftcert=vpn.example.com #leftid=%fromcert leftid=vpn.example.com leftsendcert=always leftsubnet=0.0.0.0/0 rightaddresspool=10.234.123.2-10.234.123.254 right=%any rightrsasigkey=%cert modecfgdns1=1.2.3.4 modecfgdns2=8.8.8.8 modecfgdomain=example.com modecfgbanner="Authorized access is allowed" leftxauthserver=yes rightxauthclient=yes leftmodecfgserver=yes rightmodecfgclient=yes modecfgpull=yes xauthby=pam dpddelay=30 dpdtimeout=120 dpdaction=clear ike_frag=yes # for walled-garden on xauth failure # xauthfail=soft #leftupdown=/custom/_updown
xauthfail
is set to soft, instead of hard, authentication failures are ignored, and the VPN is setup as if the user authenticated properly. A custom updown script can be used to check for the environment variable XAUTH_FAILED
. Such users can then be redirected, for example, using iptables DNAT, to a “walled garden” where they can contact the administrator or renew a paid subscription to the service.
modecfgdomain
value and the DNS entries to redirect queries for the specified domain to these specified nameservers. This allows roaming users to access internal-only resources using the internal DNS names.
modecfgdns
options contain a comma-separated list of internal DNS servers for the client to use for DNS resolution. Optionally, to send a banner text to VPN cliens, use the modecfgbanner
option.
leftsubnet
is not 0.0.0.0/0
, split tunneling configuration requests are sent automatically to the client. For example, when using leftsubnet=10.0.0.0/8
, the VPN client would only send traffic for 10.0.0.0/8
through the VPN.
xauthby=file
- The administrator generated the password and stored it in the
/etc/ipsec.d/passwd
file. xauthby=pam
- The password is obtained at the location specified in the PAM configuration in the
/etc/pam.d/pluto
file. xauthby=alwaysok
- The password is not checked and always accepted. Use this option for testing purposes or if you want to ensure compatibility for xauth-only clients.
2.7.9. Additional Resources
ipsec
daemon.
2.7.9.1. Installed Documentation
ipsec(8)
man page — Describes command options foripsec
.ipsec.conf(5)
man page — Contains information on configuringipsec
.ipsec.secrets(5)
man page — Describes the format of theipsec.secrets
file.ipsec_auto(8)
man page — Describes the use of the auto command line client for manipulating LibreswanIPsec
connections established using automatic exchanges of keys.ipsec_rsasigkey(8)
man page — Describes the tool used to generate RSA signature keys./usr/share/doc/libreswan-version/README.nss
— Describes the commands for using raw RSA keys and certificates with the NSS crypto library used with the Libreswanpluto
daemon.
2.7.9.2. Online Documentation
- https://libreswan.org
- The website of the upstream project.
- http://www.mozilla.org/projects/security/pki/nss/
- Network Security Services (NSS) project.
2.8. Firewalls
Table 2.6. Firewall Types
Method | Description | Advantages | Disadvantages |
---|---|---|---|
NAT | Network Address Translation (NAT) places private IP subnetworks behind one or a small pool of public IP addresses, masquerading all requests to one source rather than several. The Linux kernel has built-in NAT functionality through the Netfilter kernel subsystem. |
Can be configured transparently to machines on a LAN.
Protection of many machines and services behind one or more external IP addresses simplifies administration duties.
Restriction of user access to and from the LAN can be configured by opening and closing ports on the NAT firewall/gateway.
|
Cannot prevent malicious activity once users connect to a service outside of the firewall.
|
Packet Filter | A packet filtering firewall reads each data packet that passes through a LAN. It can read and process packets by header information and filters the packet based on sets of programmable rules implemented by the firewall administrator. The Linux kernel has built-in packet filtering functionality through the Netfilter kernel subsystem. |
Customizable through the
iptables front-end utility.
Does not require any customization on the client side, as all network activity is filtered at the router level rather than the application level.
Since packets are not transmitted through a proxy, network performance is faster due to direct connection from client to remote host.
|
Cannot filter packets for content like proxy firewalls.
Processes packets at the protocol layer, but cannot filter packets at an application layer.
Complex network architectures can make establishing packet filtering rules difficult, especially if coupled with IP masquerading or local subnets and DMZ networks.
|
Proxy | Proxy firewalls filter all requests of a certain protocol or type from LAN clients to a proxy machine, which then makes those requests to the Internet on behalf of the local client. A proxy machine acts as a buffer between malicious remote users and the internal network client machines. |
Gives administrators control over what applications and protocols function outside of the LAN.
Some proxy servers can cache frequently-accessed data locally rather than having to use the Internet connection to request it. This helps to reduce bandwidth consumption.
Proxy services can be logged and monitored closely, allowing tighter control over resource utilization on the network.
|
Proxies are often application-specific (HTTP, Telnet, etc.), or protocol-restricted (most proxies work with TCP-connected services only).
Application services cannot run behind a proxy, so your application servers must use a separate form of network security.
Proxies can become a network bottleneck, as all requests and transmissions are passed through one source rather than directly from a client to a remote service.
|
2.8.1. Netfilter and IPTables
iptables
tool.
2.8.1.1. IPTables Overview
iptables
administration tool, a command line tool similar in syntax to its predecessor, ipchains
, which Netfilter/iptables replaced in the Linux kernel 2.4 and above.
iptables
uses the Netfilter subsystem to enhance network connection, inspection, and processing. iptables
features advanced logging, pre- and post-routing actions, network address translation, and port forwarding, all in one command line interface.
iptables
. For more detailed information, see Section 2.8.9, “IPTables”.
2.8.2. Basic Firewall Configuration
2.8.2.1. Firewall Configuration Tool
system-config-firewall
at a shell prompt.

Figure 2.5. Firewall Configuration Tool
Note
iptables
rules.
iptables
and ip6tables
services now provide the ability to assign a fallback firewall configuration if the default configuration cannot be applied. If application of the firewall rules from /etc/sysconfig/iptables
fails, the fallback file is applied if it exists. The fallback file is named /etc/sysconfig/iptables.fallback
and uses the same file format as /etc/sysconfig/iptables
. If application of the fallback file also fails, there is no further fallback. To create a fallback file, use the standard firewall configuration tool and rename or copy the file to the fallback file.
ip6tables
service, replace all occurrences of iptables
with ip6tables
in the above examples.
Warning
iptables
utility (as described in Section 2.8.9, “IPTables”), running the system-config-firewall
utility will erase these custom rules immediately.
2.8.2.2. Enabling and Disabling the Firewall
- Disabled — Disabling the firewall provides complete access to your system and does no security checking. This should only be selected if you are running on a trusted network (not the Internet) or need to configure a custom firewall using the
iptables
command line tool.Warning
Firewall configurations and any customized firewall rules are stored in the/etc/sysconfig/iptables
file. If you choose Disabled and click OK, these configurations and firewall rules will be lost. - Enabled — This option configures the system to reject incoming connections that are not in response to outbound requests, such as DNS replies or DHCP requests. If access to services running on this machine is needed, you can choose to allow specific services through the firewall.If you are connecting your system to the Internet, but do not plan to run a server, this is the safest choice.
2.8.2.3. Trusted Services
- WWW (HTTP)
- The HTTP protocol is used by Apache (and by other Web servers) to serve web pages. If you plan on making your Web server publicly available, select this check box. This option is not required for viewing pages locally or for developing web pages. This service requires that the
httpd
package be installed.Enabling WWW (HTTP) will not open a port for HTTPS, the SSL version of HTTP. If this service is required, select the Secure WWW (HTTPS) check box. - FTP
- The FTP protocol is used to transfer files between machines on a network. If you plan on making your FTP server publicly available, select this check box. This service requires that the
vsftpd
package be installed. - SSH
- Secure Shell (SSH) is a suite of tools for logging into and executing commands on a remote machine. To allow remote access to the machine via SSH, select this check box. This service requires that the
openssh-server
package be installed. - Telnet
- Telnet is a protocol for logging into remote machines. Telnet communications are unencrypted and provide no security from network snooping. Allowing incoming Telnet access is not recommended. To allow remote access to the machine via telnet, select this check box. This service requires that the
telnet-server
package be installed. - Mail (SMTP)
- SMTP is a protocol that allows remote hosts to connect directly to your machine to deliver mail. You do not need to enable this service if you collect your mail from your ISP's server using POP3 or IMAP, or if you use a tool such as
fetchmail
. To allow delivery of mail to your machine, select this check box. Note that an improperly configured SMTP server can allow remote machines to use your server to send spam. - NFS4
- The Network File System (NFS) is a file sharing protocol commonly used on *NIX systems. Version 4 of this protocol is more secure than its predecessors. If you want to share files or directories on your system with other network users, select this check box.
- Samba
- Samba is an implementation of Microsoft's proprietary SMB networking protocol. If you need to share files, directories, or locally-connected printers with Microsoft Windows machines, select this check box.
2.8.2.4. Other Ports
iptables
. For example, to allow IRC and Internet printing protocol (IPP) to pass through the firewall, add the following to the Other ports section:
194:tcp,631:tcp
2.8.2.5. Saving the Settings
iptables
commands and written to the /etc/sysconfig/iptables
file. The iptables
service is also started so that the firewall is activated immediately after saving the selected options. If Disable firewall was selected, the /etc/sysconfig/iptables
file is removed and the iptables
service is stopped immediately.
/etc/sysconfig/system-config-firewall
file so that the settings can be restored the next time the application is started. Do not edit this file manually.
iptables
service is not configured to start automatically at boot time. Refer to Section 2.8.2.6, “Activating the IPTables Service” for more information.
2.8.2.6. Activating the IPTables Service
iptables
service is running. To manually start the service, use the following command as the root user:
~]# service iptables restart
iptables: Applying firewall rules: [ OK ]
iptables
starts when the system is booted, use the following command:
~]# chkconfig --level 345 iptables on
2.8.3. Using IPTables
iptables
is to start the iptables
service. Use the following command as the root user to start the iptables
service:
~]# service iptables restart
iptables: Applying firewall rules: [ OK ]
Note
ip6tables
service can be turned off if you intend to use the iptables
service only. If you deactivate the ip6tables
service, remember to deactivate the IPv6 network also. Never leave a network device active without the matching firewall.
iptables
to start by default when the system is booted, use the following command as the root user:
~]# chkconfig --level 345 iptables on
iptables
to start whenever the system is booted into runlevel 3, 4, or 5.
2.8.3.1. IPTables Command Syntax
iptables
command illustrates the basic command syntax:
iptables
-A
<chain>-j
<target>
-A
option specifies that the rule be appended to <chain>. Each chain is comprised of one or more rules, and is therefore also known as a ruleset.
-j <target>
option specifies the target of the rule; i.e., what to do if the packet matches the rule. Examples of built-in targets are ACCEPT, DROP, and REJECT.
iptables
man page for more information on the available chains, options, and targets.
2.8.3.2. Basic Firewall Policies
iptables
chain is comprised of a default policy, and zero or more rules which work in concert with the default policy to define the overall ruleset for the firewall.
~]#iptables -P INPUT DROP
~]#iptables -P OUTPUT DROP
~]# iptables -P FORWARD DROP
iptables
rules and outline some of the rules you might implement in the course of building your iptables
firewall.
2.8.3.3. Saving and Restoring IPTables Rules
iptables
are transitory; if the system is rebooted or if the iptables
service is restarted, the rules are automatically flushed and reset. To save the rules so that they are loaded when the iptables
service is started, use the following command as the root user:
~]# service iptables save
iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ]
/etc/sysconfig/iptables
and are applied whenever the service is started or the machine is rebooted.
2.8.4. Common IPTables Filtering
~]# iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
~]# iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
Important
iptables
ruleset, order is important.
-I
option. For example:
~]# iptables -I INPUT 1 -i lo -p all -j ACCEPT
iptables
to accept connections from remote SSH clients. For example, the following rules allow remote SSH access:
~]#iptables -A INPUT -p tcp --dport 22 -j ACCEPT
~]#iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT
iptables
filtering rules.
2.8.5. FORWARD
and NAT Rules
iptables
provides routing and forwarding policies that can be implemented to prevent abnormal usage of network resources.
FORWARD
chain allows an administrator to control where packets can be routed within a LAN. For example, to allow forwarding for the entire LAN (assuming the firewall/gateway is assigned an internal IP address on eth1), use the following rules:
~]#iptables -A FORWARD -i eth1 -j ACCEPT
~]#iptables -A FORWARD -o eth1 -j ACCEPT
eth1
device.
Note
~]# sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
/etc/sysctl.conf
file as follows:
net.ipv4.ip_forward = 0
net.ipv4.ip_forward = 1
sysctl.conf
file:
~]# sysctl -p /etc/sysctl.conf
net.ipv4.ip_forward = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
[output truncated]
2.8.5.1. Postrouting and IP Masquerading
~]# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
-t nat
) and specifies the built-in POSTROUTING chain for NAT (-A POSTROUTING
) on the firewall's external networking device (-o eth0
).
-j MASQUERADE
target is specified to mask the private IP address of a node with the external IP address of the firewall/gateway.
2.8.5.2. Prerouting
-j DNAT
target of the PREROUTING chain in NAT to specify a destination IP address and port where incoming packets requesting a connection to your internal service can be forwarded.
~]# iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to 172.31.0.23:80
Note
~]# iptables -A FORWARD -i eth0 -p tcp --dport 80 -d 172.31.0.23 -j ACCEPT
2.8.5.3. DMZs and IPTables
iptables
rules to route traffic to certain machines, such as a dedicated HTTP or FTP server, in a demilitarized zone (DMZ). A DMZ is a special local subnetwork dedicated to providing services on a public carrier, such as the Internet.
PREROUTING
table to forward the packets to the appropriate destination:
~]#iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT \
--to-destination 10.0.4.2:80
2.8.6. Malicious Software and Spoofed IP Addresses
~]#iptables -A OUTPUT -o eth0 -p tcp --dport 31337 --sport 31337 -j DROP
~]#iptables -A FORWARD -o eth0 -p tcp --dport 31337 --sport 31337 -j DROP
~]# iptables -A FORWARD -s 192.168.1.0/24 -i eth0 -j DROP
Note
DROP
and REJECT
targets when dealing with appended rules.
REJECT
target denies access and returns a connection refused
error to users who attempt to connect to the service. The DROP
target, as the name implies, drops the packet without any warning.
2.8.7. IPTables and Connection Tracking
iptables
uses a method called connection tracking to store information about incoming connections. You can allow or deny access based on the following connection states:
NEW
— A packet requesting a new connection, such as an HTTP request.ESTABLISHED
— A packet that is part of an existing connection.RELATED
— A packet that is requesting a new connection but is part of an existing connection. For example, FTP uses port 21 to establish a connection, but data is transferred on a different port (typically port 20).INVALID
— A packet that is not part of any connections in the connection tracking table.
iptables
connection tracking with any network protocol, even if the protocol itself is stateless (such as UDP). The following example shows a rule that uses connection tracking to forward only the packets that are associated with an established connection:
~]# iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
2.8.8. IPv6
ip6tables
command. In Red Hat Enterprise Linux 6, both IPv4 and IPv6 services are enabled by default.
ip6tables
command syntax is identical to iptables
in every aspect except that it supports 128-bit addresses. For example, use the following command to enable SSH connections on an IPv6-aware network server:
~]# ip6tables -A INPUT -i eth0 -p tcp -s 3ffe:ffff:100::1/128 --dport 22 -j ACCEPT
2.8.9. IPTables
ipchains
for packet filtering and used lists of rules applied to packets at each step of the filtering process. The 2.4 kernel introduced iptables
(also called netfilter), which is similar to ipchains
but greatly expands the scope and control available for filtering network packets.
iptables
commands, and explains how filtering rules can be preserved between system reboots.
Important
iptables
, but iptables
cannot be used if ipchains
is already running. If ipchains
is present at boot time, the kernel issues an error and fails to start iptables
.
ipchains
is not affected by these errors.
2.8.9.1. Packet Filtering
filter
— The default table for handling network packets.nat
— Used to alter packets that create a new connection and used for Network Address Translation (NAT).mangle
— Used for specific types of packet alteration.raw
— Used mainly for configuring exemptions from connection tracking in combination with the NOTRACK target.security
— Used for Mandatory Access Control (MAC) networking rules, such as those enabled by the SECMARK and CONNSECMARK targets.
netfilter
.
filter
table are as follows:
- INPUT — Applies to network packets that are targeted for the host.
- OUTPUT — Applies to locally-generated network packets.
- FORWARD — Applies to network packets routed through the host.
nat
table are as follows:
- PREROUTING — Applies to network packets when they arrive.
- OUTPUT — Applies to locally-generated network packets before they are sent out.
- POSTROUTING — Applies to network packets before they are sent out.
mangle
table are as follows:
- INPUT — Applies to network packets targeted for the host.
- OUTPUT — Applies to locally-generated network packets before they are sent out.
- FORWARD — Applies to network packets routed through the host.
- PREROUTING — Applies to incoming network packets before they are routed.
- POSTROUTING — Applies to network packets before they are sent out.
raw
table are as follows:
- OUTPUT — Applies to locally-generated network packets before they are sent out.
- PREROUTING — Applies to incoming network packets before they are routed.
security
table are as follows:
- INPUT — Applies to network packets targeted for the host.
- OUTPUT — Applies to locally-generated network packets before they are sent out.
- FORWARD — Applies to network packets routed through the host.
iptables
subsystem:

Figure 2.6. Packet filtering in IPTables
Important
/etc/sysconfig/iptables
or /etc/sysconfig/ip6tables
files.
iptables
service starts before any DNS-related services when a Linux system is booted. This means that firewall rules can only reference numeric IP addresses (for example, 192.168.0.1). Domain names (for example, host.example.com) in such rules produce errors.
ACCEPT
target for a matching packet, the packet skips the rest of the rule checks and is allowed to continue to its destination. If a rule specifies a DROP
target, that packet is refused access to the system and nothing is sent back to the host that sent the packet. If a rule specifies a QUEUE
target, the packet is passed to user-space. If a rule specifies the optional REJECT
target, the packet is dropped, but an error packet is sent to the packet's originator.
ACCEPT
, DROP
, REJECT
, or QUEUE
. If none of the rules in the chain apply to the packet, then the packet is dealt with in accordance with the default policy.
iptables
command configures these tables, as well as sets up new tables if necessary.
Note
/proc/
directory as it only shows what is being used or has been loaded already. This means that there is no way to see what features of netfilter are available before you attempt to use it.
2.8.9.2. Command Options for IPTables
iptables
command. The following aspects of the packet are most often used as criteria:
- Packet Type — Specifies the type of packets the command filters.
- Packet Source/Destination — Specifies which packets the command filters based on the source or destination of the packet.
- Target — Specifies what action is taken on packets matching the above criteria.
iptables
rules must be grouped logically, based on the purpose and conditions of the overall rule, for the rule to be valid. The remainder of this section explains commonly-used options for the iptables
command.
2.8.9.2.1. Structure of IPTables Command Options
iptables
commands have the following structure:
iptables
[-t
<table-name>] <command> <chain-name> \ <parameter-1> <option-1> \ <parameter-n> <option-n>
filter
table is used.
iptables
command can change significantly, based on its purpose.
iptables
-D
<chain-name> <line-number>
iptables
commands, it is important to remember that some parameters and options require further parameters and options to construct a valid rule. This can produce a cascading effect, with the further parameters requiring yet more parameters. Until every parameter and option that requires another set of options is satisfied, the rule is not valid.
iptables -h
to view a comprehensive list of iptables
command structures.
2.8.9.2.2. Command Options
iptables
to perform a specific action. Only one command option is allowed per iptables
command. With the exception of the help command, all commands are written in upper-case characters.
iptables
command options are as follows:
-A
— Appends the rule to the end of the specified chain. Unlike the-I
option described below, it does not take an integer argument. It always appends the rule to the end of the specified chain.-D <integer> | <rule>
— Deletes a rule in a particular chain by number (such as5
for the fifth rule in a chain), or by rule specification. The rule specification must exactly match an existing rule.-E
— Renames a user-defined chain. A user-defined chain is any chain other than the default, pre-existing chains. (Refer to the-N
option, below, for information on creating user-defined chains.) This is a cosmetic change and does not affect the structure of the table.Note
If you attempt to rename one of the default chains, the system reports aMatch not found
error. You cannot rename the default chains.-F
— Flushes the selected chain, which effectively deletes every rule in the chain. If no chain is specified, this command flushes every rule from every chain.-h
— Provides a list of command structures, as well as a quick summary of command parameters and options.-I [<integer>]
— Inserts the rule in the specified chain at a point specified by a user-defined integer argument. If no argument is specified, the rule is inserted at the top of the chain.Important
As noted above, the order of rules in a chain determines which rules apply to which packets. This is important to remember when adding rules using either the-A
or-I
option.This is especially important when adding rules using the-I
with an integer argument. If you specify an existing number when adding a rule to a chain,iptables
adds the new rule before (or above) the existing rule.-L
— Lists all of the rules in the chain specified after the command. To list all rules in all chains in the defaultfilter
table, do not specify a chain or table. Otherwise, the following syntax should be used to list the rules in a specific chain in a particular table:iptables
-L
<chain-name>-t
<table-name>Additional options for the-L
command option, which provide rule numbers and allow more verbose rule descriptions, are described in Section 2.8.9.2.6, “Listing Options”.-N
— Creates a new chain with a user-specified name. The chain name must be unique, otherwise an error message is displayed.-P
— Sets the default policy for the specified chain, so that when packets traverse an entire chain without matching a rule, they are sent to the specified target, such as ACCEPT or DROP.-R
— Replaces a rule in the specified chain. The rule's number must be specified after the chain's name. The first rule in a chain corresponds to rule number one.-X
— Deletes a user-specified chain. You cannot delete a built-in chain.-Z
— Sets the byte and packet counters in all chains for a table to zero.
2.8.9.2.3. IPTables Parameter Options
iptables
commands, including those used to add, append, delete, insert, or replace rules within a particular chain, require various parameters to construct a packet filtering rule.
-c
— Resets the counters for a particular rule. This parameter accepts thePKTS
andBYTES
options to specify which counter to reset.-d
— Sets the destination hostname, IP address, or network of a packet that matches the rule. When matching a network, the following IP address/netmask formats are supported:N.N.N.N/M.M.M.M
— Where N.N.N.N is the IP address range and M.M.M.M is the netmask.N.N.N.N/M
— Where N.N.N.N is the IP address range and M is the bitmask.
-f
— Applies this rule only to fragmented packets.You can use the exclamation point character (!
) option before this parameter to specify that only unfragmented packets are matched.Note
Distinguishing between fragmented and unfragmented packets is desirable, despite fragmented packets being a standard part of the IP protocol.Originally designed to allow IP packets to travel over networks with differing frame sizes, these days fragmentation is more commonly used to generate DoS attacks using malformed packets. It's also worth noting that IPv6 disallows fragmentation entirely.-i
— Sets the incoming network interface, such aseth0
orppp0
. Withiptables
, this optional parameter may only be used with the INPUT and FORWARD chains when used with thefilter
table and the PREROUTING chain with thenat
andmangle
tables.This parameter also supports the following special options:- Exclamation point character (
!
) — Reverses the directive, meaning any specified interfaces are excluded from this rule. - Plus character (
+
) — A wildcard character used to match all interfaces that match the specified string. For example, the parameter-i eth+
would apply this rule to any Ethernet interfaces but exclude any other interfaces, such asppp0
.
If the-i
parameter is used but no interface is specified, then every interface is affected by the rule.-j
— Jumps to the specified target when a packet matches a particular rule.The standard targets areACCEPT
,DROP
,QUEUE
, andRETURN
.Extended options are also available through modules loaded by default with the Red Hat Enterprise Linuxiptables
RPM package. Valid targets in these modules includeLOG
,MARK
, andREJECT
, among others. Refer to theiptables
man page for more information about these and other targets.This option can also be used to direct a packet matching a particular rule to a user-defined chain outside of the current chain so that other rules can be applied to the packet.If no target is specified, the packet moves past the rule with no action taken. The counter for this rule, however, increases by one.-o
— Sets the outgoing network interface for a rule. This option is only valid for the OUTPUT and FORWARD chains in thefilter
table, and the POSTROUTING chain in thenat
andmangle
tables. This parameter accepts the same options as the incoming network interface parameter (-i
).-p <protocol>
— Sets the IP protocol affected by the rule. This can be eithericmp
,tcp
,udp
, orall
, or it can be a numeric value, representing one of these or a different protocol. You can also use any protocols listed in the/etc/protocols
file.The "all
" protocol means the rule applies to every supported protocol. If no protocol is listed with this rule, it defaults to "all
".-s
— Sets the source for a particular packet using the same syntax as the destination (-d
) parameter.
2.8.9.2.4. IPTables Match Options
iptables
command. For example, -p <protocol-name>
enables options for the specified protocol. Note that you can also use the protocol ID, instead of the protocol name. Refer to the following examples, each of which have the same effect:
~]#iptables -A INPUT -p icmp --icmp-type any -j ACCEPT
~]#iptables -A INPUT -p 5813 --icmp-type any -j ACCEPT
/etc/services
file. For readability, it is recommended that you use the service names rather than the port numbers.
Warning
/etc/services
file to prevent unauthorized editing. If this file is editable, attackers can use it to enable ports on your machine you have otherwise closed. To secure this file, run the following commands as root:
~]#chown root.root /etc/services
~]#chmod 0644 /etc/services
~]#chattr +i /etc/services
2.8.9.2.4.1. TCP Protocol
-p tcp
):
--dport
— Sets the destination port for the packet.To configure this option, use a network service name (such as www or smtp); a port number; or a range of port numbers.To specify a range of port numbers, separate the two numbers with a colon (:
). For example:-p tcp --dport 3000:3200
. The largest acceptable valid range is0:65535
.Use an exclamation point character (!
) after the--dport
option to match all packets that do not use that network service or port.To browse the names and aliases of network services and the port numbers they use, view the/etc/services
file.The--destination-port
match option is synonymous with--dport
.--sport
— Sets the source port of the packet using the same options as--dport
. The--source-port
match option is synonymous with--sport
.--syn
— Applies to all TCP packets designed to initiate communication, commonly called SYN packets. Any packets that carry a data payload are not touched.Use an exclamation point character (!
) before the--syn
option to match all non-SYN packets.--tcp-flags <tested flag list> <set flag list>
— Allows TCP packets that have specific bits (flags) set, to match a rule.The--tcp-flags
match option accepts two parameters. The first parameter is the mask; a comma-separated list of flags to be examined in the packet. The second parameter is a comma-separated list of flags that must be set for the rule to match.The possible flags are:ACK
FIN
PSH
RST
SYN
URG
ALL
NONE
For example, aniptables
rule that contains the following specification only matches TCP packets that have the SYN flag set and the ACK and FIN flags not set:--tcp-flags ACK,FIN,SYN SYN
Use the exclamation point character (!
) after the--tcp-flags
to reverse the effect of the match option.--tcp-option
— Attempts to match with TCP-specific options that can be set within a particular packet. This match option can also be reversed by using the exclamation point character (!
) after the option.
2.8.9.2.4.2. UDP Protocol
-p udp
):
--dport
— Specifies the destination port of the UDP packet, using the service name, port number, or range of port numbers. The--destination-port
match option is synonymous with--dport
.--sport
— Specifies the source port of the UDP packet, using the service name, port number, or range of port numbers. The--source-port
match option is synonymous with--sport
.
--dport
and --sport
options, to specify a range of port numbers, separate the two numbers with a colon (:). For example: -p tcp --dport 3000:3200
. The largest acceptable valid range is 0:65535
.
2.8.9.2.4.3. ICMP Protocol
-p icmp
):
--icmp-type
— Sets the name or number of the ICMP type to match with the rule. A list of valid ICMP names can be retrieved by typing theiptables -p icmp -h
command.
2.8.9.2.4.4. Additional Match Option Modules
iptables
command.
-m <module-name>
, where <module-name> is the name of the module.
limit
module — Places limits on how many packets are matched to a particular rule.When used in conjunction with theLOG
target, thelimit
module can prevent a flood of matching packets from filling up the system log with repetitive messages or using up system resources.Refer to Section 2.8.9.2.5, “Target Options” for more information about theLOG
target.Thelimit
module enables the following options:--limit
— Sets the maximum number of matches for a particular time period, specified as a<value>/<period>
pair. For example, using--limit 5/hour
allows five rule matches per hour.Periods can be specified in seconds, minutes, hours, or days.If a number and time modifier are not used, the default value of3/hour
is assumed.--limit-burst
— Sets a limit on the number of packets able to match a rule at one time.This option is specified as an integer and should be used in conjunction with the--limit
option.If no value is specified, the default value of five (5) is assumed.
state
module — Enables state matching.Thestate
module enables the following options:--state
— match a packet with the following connection states:ESTABLISHED
— The matching packet is associated with other packets in an established connection. You need to accept this state if you want to maintain a connection between a client and a server.INVALID
— The matching packet cannot be tied to a known connection.NEW
— The matching packet is either creating a new connection or is part of a two-way connection not previously seen. You need to accept this state if you want to allow new connections to a service.RELATED
— The matching packet is starting a new connection related in some way to an existing connection. An example of this is FTP, which uses one connection for control traffic (port 21), and a separate connection for data transfer (port 20).
These connection states can be used in combination with one another by separating them with commas, such as-m state --state INVALID,NEW
.
mac
module — Enables hardware MAC address matching.Themac
module enables the following option:--mac-source
— Matches a MAC address of the network interface card that sent the packet. To exclude a MAC address from a rule, place an exclamation point character (!
) after the--mac-source
match option.
iptables
man page for more match options available through modules.
2.8.9.2.5. Target Options
<user-defined-chain>
— A user-defined chain within the table. User-defined chain names must be unique. This target passes the packet to the specified chain.ACCEPT
— Allows the packet through to its destination or to another chain.DROP
— Drops the packet without responding to the requester. The system that sent the packet is not notified of the failure.QUEUE
— The packet is queued for handling by a user-space application.RETURN
— Stops checking the packet against rules in the current chain. If the packet with aRETURN
target matches a rule in a chain called from another chain, the packet is returned to the first chain to resume rule checking where it left off. If theRETURN
rule is used on a built-in chain and the packet cannot move up to its previous chain, the default target for the current chain is used.
LOG
— Logs all packets that match this rule. Because the packets are logged by the kernel, the/etc/syslog.conf
file determines where these log entries are written. By default, they are placed in the/var/log/messages
file.Additional options can be used after theLOG
target to specify the way in which logging occurs:--log-level
— Sets the priority level of a logging event. Refer to thesyslog.conf
man page for a list of priority levels.--log-ip-options
— Logs any options set in the header of an IP packet.--log-prefix
— Places a string of up to 29 characters before the log line when it is written. This is useful for writing syslog filters for use in conjunction with packet logging.Note
Due to an issue with this option, you should add a trailing space to the log-prefix value.--log-tcp-options
— Logs any options set in the header of a TCP packet.--log-tcp-sequence
— Writes the TCP sequence number for the packet in the log.
REJECT
— Sends an error packet back to the remote system and drops the packet.TheREJECT
target accepts--reject-with <type>
(where <type> is the rejection type) allowing more detailed information to be returned with the error packet. The messageport-unreachable
is the default error type given if no other option is used. Refer to theiptables
man page for a full list of<type>
options.
nat
table, or with packet alteration using the mangle
table, can be found in the iptables
man page.
2.8.9.2.6. Listing Options
iptables -L [<chain-name>]
, provides a very basic overview of the default filter table's current chains. Additional options provide more information:
-v
— Displays verbose output, such as the number of packets and bytes each chain has processed, the number of packets and bytes each rule has matched, and which interfaces apply to a particular rule.-x
— Expands numbers into their exact values. On a busy system, the number of packets and bytes processed by a particular chain or rule may be abbreviated toKilobytes
,Megabytes
, orGigabytes
. This option forces the full number to be displayed.-n
— Displays IP addresses and port numbers in numeric format, rather than the default hostname and network service format.--line-numbers
— Lists rules in each chain next to their numeric order in the chain. This option is useful when attempting to delete the specific rule in a chain or to locate where to insert a rule within a chain.-t <table-name>
— Specifies a table name. If omitted, defaults to the filter table.
2.8.9.3. Saving IPTables Rules
iptables
command are stored in memory. If the system is restarted before saving the iptables
rule set, all rules are lost. For netfilter rules to persist through a system reboot, they need to be saved. To save netfilter rules, type the following command as root:
~]# /sbin/service iptables save
iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ]
iptables
init script, which runs the /sbin/iptables-save
program and writes the current iptables
configuration to /etc/sysconfig/iptables
. The existing /etc/sysconfig/iptables
file is saved as /etc/sysconfig/iptables.save
.
iptables
init script reapplies the rules saved in /etc/sysconfig/iptables
by using the /sbin/iptables-restore
command.
iptables
rule before committing it to the /etc/sysconfig/iptables
file, it is possible to copy iptables
rules into this file from another system's version of this file. This provides a quick way to distribute sets of iptables
rules to multiple machines.
iptables
rules to a separate file for distribution, backup, or other purposes. To do so, run the following command as root:
iptables-save
> <filename>
Important
/etc/sysconfig/iptables
file to other machines, type /sbin/service iptables reload
or /sbin/service iptables restart
for the new rules to take effect. It is better to use the reload
command because there is no period of time without a firewall in place. See the description of the reload
command in Section 2.8.9.4, “IPTables Control Scripts”. For IPv6
, substitute ip6tables
for iptables
in the /sbin/service
commands listed in this section. For more information about IPv6
and netfilter, see Section 2.8.9.6, “IPTables and IPv6”.
Note
iptables
command (/sbin/iptables
), which is used to manipulate the tables and chains that constitute the iptables
functionality, and the iptables
service (/sbin/service iptables
), which is used to enable and disable the iptables
service itself.
2.8.9.4. IPTables Control Scripts
iptables
in Red Hat Enterprise Linux:
- Firewall Configuration Tool (
system-config-firewall
) — A graphical interface for creating, activating, and saving basic firewall rules. Refer to Section 2.8.2, “Basic Firewall Configuration” for more information. /sbin/service iptables <option>
— Used to manipulate various functions ofiptables
using its initscript. The following options are available:start
— If a firewall is configured (that is,/etc/sysconfig/iptables
exists), all runningiptables
are stopped completely and then started using the/sbin/iptables-restore
command. This option only works if theipchains
kernel module is not loaded. To check if this module is loaded, type the following command as root:~]#
lsmod | grep ipchains
If this command returns no output, it means the module is not loaded. If necessary, use the/sbin/rmmod
command to remove the module.stop
— If a firewall is running, the firewall rules in memory are flushed, and alliptables
modules and helpers are unloaded.If theIPTABLES_SAVE_ON_STOP
directive in the/etc/sysconfig/iptables-config
configuration file is changed from its default value toyes
, current rules are saved to/etc/sysconfig/iptables
and any existing rules are moved to the file/etc/sysconfig/iptables.save
.Refer to Section 2.8.9.4.1, “IPTables Control Scripts Configuration File” for more information about theiptables-config
file.reload
— If a firewall is running, the firewall rules are reloaded from the configuration file. Thereload
command does not unload helpers that have been in use before, but will add new helpers that have been added to IPTABLES_MODULES (forIPv4
) and IP6TABLES_MODULES (forIPv6
). The advantage of not flushing the current firewall rules is that if the new rules cannot be applied, because of an error in the rules, the old rules are still in place.restart
— If a firewall is running, the firewall rules in memory are flushed, and the firewall is started again if it is configured in/etc/sysconfig/iptables
. This option only works if theipchains
kernel module is not loaded.If theIPTABLES_SAVE_ON_RESTART
directive in the/etc/sysconfig/iptables-config
configuration file is changed from its default value toyes
, current rules are saved to/etc/sysconfig/iptables
and any existing rules are moved to the file/etc/sysconfig/iptables.save
.Refer to Section 2.8.9.4.1, “IPTables Control Scripts Configuration File” for more information about theiptables-config
file.status
— Displays the status of the firewall and lists all active rules.The default configuration for this option displays IP addresses in each rule. To display domain and hostname information, edit the/etc/sysconfig/iptables-config
file and change the value ofIPTABLES_STATUS_NUMERIC
tono
. Refer to Section 2.8.9.4.1, “IPTables Control Scripts Configuration File” for more information about theiptables-config
file.panic
— Flushes all firewall rules. The policy of all configured tables is set toDROP
.This option could be useful if a server is known to be compromised. Rather than physically disconnecting from the network or shutting down the system, you can use this option to stop all further network traffic but leave the machine in a state ready for analysis or other forensics.save
— Saves firewall rules to/etc/sysconfig/iptables
usingiptables-save
. Refer to Section 2.8.9.3, “Saving IPTables Rules” for more information.
Note
ip6tables
for iptables
in the /sbin/service
commands listed in this section. For more information about IPv6 and netfilter, see Section 2.8.9.6, “IPTables and IPv6”.
2.8.9.4.1. IPTables Control Scripts Configuration File
iptables
initscripts is controlled by the /etc/sysconfig/iptables-config
configuration file. The following is a list of directives contained in this file:
IPTABLES_MODULES
— Specifies a space-separated list of additionaliptables
modules to load when a firewall is activated. These can include connection tracking and NAT helpers.IPTABLES_MODULES_UNLOAD
— Unloads modules on restart and stop. This directive accepts the following values:yes
— The default value. This option must be set to achieve a correct state for a firewall restart or stop.no
— This option should only be set if there are problems unloading the netfilter modules.
IPTABLES_SAVE_ON_STOP
— Saves current firewall rules to/etc/sysconfig/iptables
when the firewall is stopped. This directive accepts the following values:yes
— Saves existing rules to/etc/sysconfig/iptables
when the firewall is stopped, moving the previous version to the/etc/sysconfig/iptables.save
file.no
— The default value. Does not save existing rules when the firewall is stopped.
IPTABLES_SAVE_ON_RESTART
— Saves current firewall rules when the firewall is restarted. This directive accepts the following values:yes
— Saves existing rules to/etc/sysconfig/iptables
when the firewall is restarted, moving the previous version to the/etc/sysconfig/iptables.save
file.no
— The default value. Does not save existing rules when the firewall is restarted.
IPTABLES_SAVE_COUNTER
— Saves and restores all packet and byte counters in all chains and rules. This directive accepts the following values:yes
— Saves the counter values.no
— The default value. Does not save the counter values.
IPTABLES_STATUS_NUMERIC
— Outputs IP addresses in numeric form instead of domain or hostnames. This directive accepts the following values:yes
— The default value. Returns only IP addresses within a status output.no
— Returns domain or hostnames within a status output.
2.8.9.5. IPTables and IP Sets
~]#The set is created as follows:iptables -A INPUT -s 10.0.0.0/8 -j DROP
~]#iptables -A INPUT -s 172.16.0.0/12 -j DROP
~]#iptables -A INPUT -s 192.168.0.0/16 -j DROP
~]#The set is then referenced in an iptables command as follows:ipset create my-block-set hash:net
~]#ipset add my-block-set 10.0.0.0/8
~]#ipset add my-block-set 172.16.0.0/12
~]#ipset add my-block-set 192.168.0.0/16
~]# iptables -A INPUT -m set --set my-block-set src -j DROP
If the set is used more than once a saving in configuration time is made. If the set contains many entries a saving in processing time is made.
2.8.9.5.1. Installing ipset
root
:
~]# yum install ipset
To see the usage message:
~]$ ipset -h
ipset v6.11
Usage: ipset [options] COMMAND
2.8.9.5.2. ipset Commands
ipset [options] command [command-options]Where command is one of:
create | add | del | test | destroy | list | save | restore | flush | rename | swap | help | version | -Allowed options are:
-exist | -output [ plain | save | xml ] | -quiet | -resolve | -sorted | -name | -terse
create
command is used to create a new data structure to store a set of IP data. The add
command adds new data to the set, the data added is referred to as an element of the set.
-exist
option suppresses error message if the element already exists, and it has a special role in updating a time out value. To change a time out, use the ipset add
command and specify all the data for the element again, changing only the time out value as required, and using the -exist
option.
test
option is for testing if the element already exists within a set.
create
command is as follows: ipset create set-name type-name [create-options]
The set-name is a suitable name chosen by the user, the type-name is the name of the data structure used to store the data comprising the set. The format of the type-name is as follows: method:datatype[,datatype[,datatype]]
The allowed methods for storing data are: bitmap | hash | listThe allowed data types are:
ip | net | mac | port | ifaceWhen adding, deleting, or testing entries in a set, the same comma separated data syntax must be used for the data that makes up one entry, or element, in the set. For example:
ipset add set-name ipaddr,portnum,ipaddr
Note
IPv4
and IPv6
addresses at the same time. When a set is created it is bound to a family, inet
for IPv4
or inet6
for IPv6
, and the default is inet
.
Example 2.3. Create an IP Set
~]# ipset create my-set hash:ip,port,ip
Once the set is created, entries can be added as follows:
~]#ipset add my-set 192.168.1.2,80,192.168.2.2
~]#ipset add my-set 192.168.1.2,443,192.168.2.2
timeout
— The value given with thecreate
command will be the default value for the set created. If a value is given with theadd
command, it will be the initial non-default value for the element.
Example 2.4. List an IP Set
my-set
, issue a command as follows:
~]# ipset list my-set
Name: my-set
Type: hash:ip,port,ip
Header: family inet hashsize 1024 maxelem 65536
Size in memory: 8360
References: 0
Members:
192.168.1.2,tcp:80,192.168.2.2
192.168.1.2,tcp:443,192.168.2.2
Example 2.5. Test the Elements of an IP Set
~]# ipset test my-set 192.168.1.2,80,192.168.2.2
192.168.1.2,tcp:80,192.168.2.2 is in set my-set.
2.8.9.5.3. IP Set Types
- bitmap:ip
- Stores an IPv4 host address, a network range, or an IPv4 network addresses with the prefix-length in CIDR notation if the
netmask
option is used when the set is created. It can optionally store a timeout value, a counter value, and a comment. It can store up to65536
entries. The command to create thebitmap:ip
set has the following format:ipset create set-name range start_ipaddr-end_ipaddr |ipaddr/prefix-length [netmask prefix-length] [timeout value] [counters] [comment]
Example 2.6. Create an IP Set for a Range of Addresses Using a Prefix Length
bitmap:ip
set type as follows:
~]# ipset create my-range bitmap:ip range 192.168.33.0/28
~]# ipset add my-range 192.168.33.1
~]# ipset list my-range
Name: my-range
Type: bitmap:ip
Header: range 192.168.33.0-192.168.33.15
Size in memory: 84
References: 0
Members:
192.168.33.1
~]# ipset add my-range 192.168.33.2-192.168.33.4
~]# ipset list my-range
Name: my-range
Type: bitmap:ip
Header: range 192.168.33.0-192.168.33.15
Size in memory: 84
References: 0
Members:
192.168.33.1
192.168.33.2
192.168.33.3
192.168.33.4
Example 2.7. Create an IP Set for a Range of Addresses Using a Netmask
bitmap:ip
set type as follows:
~]# ipset create my-big-range bitmap:ip range 192.168.124.0-192.168.126.0 netmask 24
Once the set is created, entries can be added as follows:
~]# ipset add my-big-range 192.168.124.0
~]#ipset add my-big-range 192.168.125.150
~]#ipset list my-big-range
Name: my-big-range Type: bitmap:ip Header: range 192.168.124.0-192.168.126.255 netmask 24 Size in memory: 84 References: 0 Members: 192.168.124.0 192.168.125.0
- bitmap:ip,mac
- Stores an IPv4 address and a MAC address as a pair. It can store up to
65536
entries.ipset create my-range bitmap:ip,mac range start_ipaddr-end_ipaddr | ipaddr/prefix-length [timeout value ] [counters] [comment]
Example 2.8. Create an IP Set for a Range of IPv4 MAC Address Pairs
bitmap:ip,mac
set type as follows:
~]# ipset create my-range bitmap:ip,mac range 192.168.1.0/24
It is not necessary to specify a MAC address when creating the set.
~]# ipset add my-range 192.168.1.1,12:34:56:78:9A:BC
- bitmap:port
- Stores a range of ports. It can store up to
65536
entries.ipset create my-port-range bitmap:port range start_port-end_port [timeout value ] [counters] [comment]
The set match and SET target netfilter kernel modules interpret the stored numbers as TCP or UDP port numbers. The protocol can optionally be specified together with the port. Theproto
only needs to be specified if a service name is used, and that name does not exist as a TCP service.
Example 2.9. Create an IP Set for a Range of Ports
bitmap:port
set type as follows:
~]# ipset create my-permitted-port-range bitmap:port range 1024-49151
Once the set is created, entries can be added as follows:
~]# ipset add my-permitted-port-range 5060-5061
- hash:ip
- Stores a host or network address in the form of a hash. By default, an address specified without a network prefix length is a host address. The all-zero IP address cannot be stored.
ipset create my-addresses hash:ip [family[ inet | inet6 ]] [hashsize value] [maxelem value ] [netmask prefix-length] [timeout value ]
Theinet
family is the default, iffamily
is omitted addresses will be interpreted as IPv4 addresses. Thehashsize
value is the initial hash size to use and defaults to1024
. Themaxelem
value is the maximum number of elements which can be stored in the set, it defaults to65536
.The netfilter tool searches for a network prefix which is the most specific, it tries to find the smallest block of addresses that match.
Example 2.10. Create an IP Set for IP Addresses
hash:ip
set type as follows:
~]# ipset create my-addresses hash:ip
Once the set is created, entries can be added as follows:
~]# ipset add my-addresses 10.10.10.0
~]# ipset create my-busy-addresses hash:ip maxelem 24 netmask 28 timeout 100
The maxelem option restricts to total number of elements in the set, thus conserving memory space.
~]# ipset add my-busy-addresses timeout 100
The following output shows the time counting down:
[root@rhel6 ~]# ipset add my-busy-addresses 192.168.60.0 timeout 100 [root@rhel6 ~]# ipset list my-busy-addresses Name: my-busy-addresses Type: hash:ip Header: family inet hashsize 1024 maxelem 24 netmask 28 timeout 100 Size in memory: 8300 References: 0 Members: 192.168.60.0 timeout 90 [root@rhel6 ~]# ipset list my-busy-addresses Name: my-busy-addresses Type: hash:ip Header: family inet hashsize 1024 maxelem 24 netmask 28 timeout 100 Size in memory: 8300 References: 0 Members: 192.168.60.0 timeout 83The element will be removed from the set when the timeout period ends.
ipset(8)
manual page for more examples.
2.8.9.6. IPTables and IPv6
iptables-ipv6
package is installed, netfilter in Red Hat Enterprise Linux can filter the next-generation IPv6 Internet protocol. The command used to manipulate the IPv6 netfilter is ip6tables
.
iptables
, except the nat
table is not yet supported. This means that it is not yet possible to perform IPv6 network address translation tasks, such as masquerading and port forwarding.
ip6tables
are saved in the /etc/sysconfig/ip6tables
file. Previous rules saved by the ip6tables
initscripts are saved in the /etc/sysconfig/ip6tables.save
file.
ip6tables
init script are stored in /etc/sysconfig/ip6tables-config
, and the names for each directive vary slightly from their iptables
counterparts.
iptables-config
directive IPTABLES_MODULES
the equivalent in the ip6tables-config
file is IP6TABLES_MODULES
.
2.8.9.7. Additional Resources
2.8.9.7.1. Useful Firewall Websites
- http://www.netfilter.org/ — The home of the netfilter/iptables project. Contains assorted information about
iptables
, including a FAQ addressing specific problems and various helpful guides by Rusty Russell, the Linux IP firewall maintainer. The HOWTO documents on the site cover subjects such as basic networking concepts, kernel packet filtering, and NAT configurations. - http://www.tldp.org/ — The Linux Documentation Project contains several useful guides relating to firewall creation and administration.
- http://www.iana.org/assignments/port-numbers — The official list of registered and common service ports as assigned by the Internet Assigned Numbers Authority.
2.8.9.7.2. Related Documentation
- Red Hat Linux Firewalls, by Bill McCarty; Red Hat Press — a comprehensive reference to building network and server firewalls using open source packet filtering technology such as Netfilter and
iptables
. It includes topics that cover analyzing firewall logs, developing firewall rules, and customizing your firewall using various graphical tools. - Linux Firewalls, by Robert Ziegler; New Riders Press — contains a wealth of information on building firewalls using both 2.2 kernel
ipchains
as well as Netfilter andiptables
. Additional security topics such as remote access issues and intrusion detection systems are also covered.
2.8.9.7.3. Installed IP Tables Documentation
man iptables
— Contains a description ofiptables
as well as a comprehensive list of targets, options, and match extensions.
Chapter 3. Encryption
3.1. Data at Rest
3.1.1. Full Disk Encryption
3.1.2. File-Based Encryption
3.1.3. LUKS Disk Encryption
Overview of LUKS
- What LUKS does
- LUKS encrypts entire block devices and is therefore well-suited for protecting the contents of mobile devices such as removable storage media or laptop disk drives.
- The underlying contents of the encrypted block device are arbitrary. This makes it useful for encrypting
swap
devices. This can also be useful with certain databases that use specially formatted block devices for data storage. - LUKS uses the existing device mapper kernel subsystem.
- LUKS provides passphrase strengthening which protects against dictionary attacks.
- LUKS devices contain multiple key slots, allowing users to add backup keys/passphrases.
- What LUKS does not do:
- LUKS is not well-suited for applications requiring many (more than eight) users to have distinct access keys to the same device.
- LUKS is not well-suited for applications requiring file-level encryption.
3.1.3.1. LUKS Implementation in Red Hat Enterprise Linux
cryptsetup --help
) is aes-cbc-essiv:sha256. Note that the installation program, Anaconda, uses by default the AES cipher in XTS mode, aes-xts-plain64. The default key size for LUKS is 256 bits. The default key size for LUKS with Anaconda (XTS mode) is 512 bits.
Warning
--cipher
and --key-size
options. The syntax of the command is the following:
cryptsetup --verify-passphrase
--cipher
<cipher>-<mode>-<iv> --key-size
<key-size> luksFormat <device>
- AES — Advanced Encryption Standard, a 128-bit symmetric block cipher using encryption keys with lengths of 128, 192, and 256 bits; for more information, see the FIPS PUB 197.
- Twofish — A 128-bit block cipher operating with encryption keys of the range from 128 bits to 256 bits.
- Serpent — A 128-bit block cipher operating with 128-bit, 192-bit and 256-bit encryption keys.
- cast5 — A 64-bit Feistel cipher supporting encryption keys of the range from 40 to 128 bits; for more information, see the RFC 2144.
- cast6 — A 128-bit Feistel cipher using 128-bit, 160-bit, 192-bit, 224-bit, or 256-bit encryption keys; for more information, see the RFC 2612.
- CBC — Cipher Block Chaining; for more information, see the NIST SP 800-38A.
- XTS — XEX Tweakable Block Cipher with Ciphertext Stealing; for more information, see the IEEE 1619, or NIST SP 800-38E.
- CTR — Counter; for more information, see the NIST SP 800-38A.
- ECB — Electronic Codebook; for more information, see the NIST SP 800-38A.
- CFB — Cipher Feedback; for more information, see the NIST SP 800-38A.
- OFB — Output Feedback; for more information, see the NIST SP 800-38A.
- ESSIV — Encrypted Salt-Sector Initialization Vector - This IV should be used for ciphers in CBC mode. You should use the default hash: sha256.
- plain64 (or plain) — IV sector offset - This IV should be used for ciphers in XTS mode.
3.1.3.2. Manually Encrypting Directories
Warning
- Enter runlevel 1 by typing the following at a shell prompt as root:
telinit 1
- Unmount your existing
/home
:umount /home
- If the command in the previous step fails, use
fuser
to find processes hogging/home
and kill them:fuser -mvk /home
- Verify
/home
is no longer mounted:grep home /proc/mounts
- Fill your partition with random data:
shred -v --iterations=1 /dev/VG00/LV_home
This command proceeds at the sequential write speed of your device and may take some time to complete. It is an important step to ensure no unencrypted data is left on a used device, and to obfuscate the parts of the device that contain encrypted data as opposed to just random data. - Initialize your partition:
cryptsetup --verbose --verify-passphrase luksFormat /dev/VG00/LV_home
- Open the newly encrypted device:
cryptsetup luksOpen /dev/VG00/LV_home home
- Make sure the device is present:
ls -l /dev/mapper | grep home
- Create a file system:
mkfs.ext3 /dev/mapper/home
- Mount the file system:
mount /dev/mapper/home /home
- Make sure the file system is visible:
df -h | grep home
- Add the following to the
/etc/crypttab
file:home /dev/VG00/LV_home none
- Edit the
/etc/fstab
file, removing the old entry for/home
and adding the following line:/dev/mapper/home /home ext3 defaults 1 2
- Restore default SELinux security contexts:
/sbin/restorecon -v -R /home
- Reboot the machine:
shutdown -r now
- The entry in the
/etc/crypttab
makes your computer ask yourluks
passphrase on boot. - Log in as root and restore your backup.
3.1.3.3. Adding a New Passphrase to an Existing Device
cryptsetup luksAddKey <device>
3.1.3.4. Removing a Passphrase from an Existing Device
cryptsetup luksRemoveKey <device>
3.1.3.5. Creating Encrypted Block Devices in Anaconda
Note
Note
kickstart
file to set a separate passphrase for each new encrypted block device. Also, kickstart allows you to specify a different type of encryption if the Anaconda default cipher, aes-xts-plain64, does not suit you. In dependencies on a device you want to encrypt, you can specify the --cipher=<cipher-string>
along with the autopart
, part
, partition
, logvol
, and raid
directives. This option has to be used together with the --encrypted
option, otherwise it has no effect. For more information about the <cipher-string> format and possible cipher combinations, see Section 3.1.3.1, “LUKS Implementation in Red Hat Enterprise Linux”. For more information about kickstart configuration, see the Red Hat Enterprise Linux 6 Installation Guide.
3.1.3.6. Additional Resources
3.2. Data in Motion
3.2.1. Virtual Private Networks
3.2.2. Secure Shell
SSH
are encrypted and protected from interception. Cryptographic login can also be utilized to provide a better authentication method over traditional user names and passwords. See Section 3.2.2.1, “Cryptographic Login”.
SSH
is very easy to activate. By starting the sshd
daemon, the system begins to accept connections and will allow access to the system when a correct user name and password is provided during the connection process. The standard TCP
port for the SSH
service is 22
. However, this can be changed by modifying the /etc/ssh/sshd_config
configuration file and restarting the service. This file also contains other configuration options for SSH
.
sshd
service starts automatically at boot time. Run the following command as root
to query the status of the daemon:
~]# service sshd status
sshd
service, issue the following command as root
:
~]# service sshd restart
SSH
tunnel and traffic will be encrypted as it passes through that tunnel, but using port forwarding is not as fluid as a VPN (Section 3.2.1, “Virtual Private Networks”).
3.2.2.1. Cryptographic Login
SSH
supports the use of cryptographic keys for logging in to computers. This is much more secure than using only a password. If you combine this method with other authentication methods, it can be considered a multi-factor authentication. See Section 3.2.2.2, “Multiple Authentication Methods” for more information about using multiple authentication methods.
PubkeyAuthentication
configuration directive in the /etc/ssh/sshd_config
file needs to be set to yes
. Note that this is the default setting. Set the PasswordAuthentication
directive to no
to disable the possibility of using passwords for logging in.
SSH
keys can be generated using the ssh-keygen
command. If invoked without additional arguments, it creates a 2048-bit RSA key set. The keys are stored, by default, in the ~/.ssh
directory. You can utilize the -b
switch to modify the bit-strength of the key. Using 2048-bit keys is normally sufficient. See the Generating Key Pairs chapter of the Red Hat Enterprise Linux 6 Deployment Guide for more detailed information about generating SSH
keys.
~/.ssh
directory. If you accepted the defaults when running the ssh-keygen
command, then the generated files are named id_rsa
and id_rsa.pub
and contain the private and public key respectively. You should always protect the private key from exposure by making it unreadable by anyone else but the file's owner. The public key, however, needs to be transferred to the system you are going to log in to. You can use the ssh-copy-id
command to transfer the key to the server:
~]$ ssh-copy-id -i [user@]server
~/.ssh/authorized_key
file on the server. The sshd
daemon will check this file when you attempt to log in to the server.
SSH
keys regularly. When you do, make sure you remove any unused keys from the authorized_key
file.
3.2.2.2. Multiple Authentication Methods
AuthenticationMethods
configuration directive in the /etc/ssh/sshd_config
file to specify which authentication methods are to be utilized. Note that it is possible to define more than one list of required authentication methods using this directive. If that is the case, the user must complete every method in at least one of the lists. The lists need to be separated by blank spaces, and the individual authentication-method names within the lists must be comma-separated. For example:
AuthenticationMethods publickey,gssapi-with-mic publickey,keyboard-interactive
sshd
daemon configured using the above AuthenticationMethods
directive only grants access if the user attempting to log in successfully completes either publickey
authentication followed by gssapi-with-mic
or by keyboard-interactive
authentication. Note that each of the requested authentication methods needs to be explicitly enabled using a corresponding configuration directive (such as PubkeyAuthentication
) in the /etc/ssh/sshd_config
file. Refer to the AUTHENTICATION section of ssh(1)
for a general list of available authentication methods.
3.2.2.3. Other Ways of Securing SSH
Protocol Version
SSH
protocol supplied with Red Hat Enterprise Linux supports both the SSH-1 and SSH-2 versions of the protocol, only the latter should be used whenever possible. The SSH-2 version contains a number of improvements over the older SSH-1, and the majority of advanced configuration options is only available when using SSH-2.
SSH
protocol protects the authentication and communication for which it is used. The version or versions of the protocol supported by the sshd
daemon can be specified using the Protocol
configuration directive in the /etc/ssh/sshd_config
file. The default setting is 2
.
Key Types
ssh-keygen
command generates a pair of SSH-2 RSA keys by default, using the -t
option, it can be instructed to generate DSA or ECDSA keys as well. The ECDSA (Elliptic Curve Digital Signature Algorithm) offers better performance at the same symmetric key length. It also generates shorter keys.
Non-Default Port
sshd
daemon listens on the 22
network port. Changing the port reduces the exposure of the system to attacks based on automated network scanning, thus increasing security through obscurity. The port can be specified using the Port
directive in the /etc/ssh/sshd_config
configuration file. Note also that the default SELinux policy must be changed to allow for the use of a non-default port. You can do this by modifying the ssh_port_t
SELinux type by typing the following command as root
:
~]# semanage -a -t ssh_port_t -p tcp port_number
Port
directive.
No Root Login
root
user, you should consider setting the PermitRootLogin
configuration directive to no
in the /etc/ssh/sshd_config
file. By disabling the possibility of logging in as the root
user, the administrator can audit which user runs what privileged command after they log in as regular users and then gain root
rights.
Important
SSH
setup. By no means should this list of suggested measures be considered exhaustive or definitive. Refer to sshd_config(5)
for a description of all configuration directives available for modifying the behavior of the sshd
daemon and to ssh(1)
for an explanation of basic SSH
concepts.
3.3. OpenSSL Intel AES-NI Engine
Note
- Ensure that the processor has the AES instruction set:
~]#
grep -m1 -o aes /proc/cpuinfo
aes - As root, run the following commands and compare their outputs. Significantly better performance of the latter command indicates that AES-NI is enabled. Note that the outputs below are shortened for brevity:
~]#
openssl speed aes-128-cbc
The 'numbers' are in 1000s of bytes per second processed. type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes aes-128 cbc 99696.17k 107792.98k 109961.22k 110559.91k 110742.19k~]#
openssl speed -evp aes-128-cbc
The 'numbers' are in 1000s of bytes per second processed. type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes aes-128-cbc 800450.23k 873269.82k 896864.85k 903446.19k 902752.94k
~]# dd if=/dev/zero count=100 bs=1M | ssh -c aes128-cbc localhost "cat >/dev/null"
root@localhost's password:
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 4.81868 s, 21.8 MB/s
3.4. Using the Random Number Generator
rngd
daemon, which is a part of the rng-tools package, is capable of using both environmental noise and hardware random number generators for extracting entropy. The daemon checks whether the data supplied by the source of randomness is sufficiently random and then stores it in the kernel's random-number entropy pool. The random numbers it generates are made available through the /dev/random
and /dev/urandom
character devices.
/dev/random
and /dev/urandom
is that the former is a blocking device, which means it stops supplying numbers when it determines that the amount of entropy is insufficient for generating a properly random output. Conversely, /dev/urandom
is a non-blocking source, which reuses the kernel's entropy pool and is thus able to provide an unlimited supply of pseudo-random numbers, albeit with less entropy. As such, /dev/urandom
should not be used for creating long-term cryptographic keys.
root
user:
~]# yum install rng-tools
rngd
daemon, execute the following command as root
:
~]# service rngd start
~]# service rngd status
rngd
daemon with optional parameters, execute it directly. For example, to specify an alternative source of random-number input (other than /dev/hwrandom
), use the following command:
~]# rngd --rng-device=/dev/hwrng
rngd
daemon with /dev/hwrng
as the device from which random numbers are read. Similarly, you can use the -o
(or --random-device
) option to choose the kernel device for random-number output (other than the default /dev/random
). See the rngd(8) manual page for a list of all available options.
/dev/random
, use the rngtest tool as follows:
~]$ cat /dev/random | rngtest -c 1000
rngtest 2
Copyright (c) 2004 by Henrique de Moraes Holschuh
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
rngtest: starting FIPS tests...
rngtest: bits received from input: 20000032
rngtest: FIPS 140-2 successes: 1000
rngtest: FIPS 140-2 failures: 0
rngtest: FIPS 140-2(2001-10-10) Monobit: 0
rngtest: FIPS 140-2(2001-10-10) Poker: 0
rngtest: FIPS 140-2(2001-10-10) Runs: 0
rngtest: FIPS 140-2(2001-10-10) Long run: 1
rngtest: FIPS 140-2(2001-10-10) Continuous run: 0
rngtest: input channel speed: (min=308.697; avg=623.670; max=730.823)Kibits/s
rngtest: FIPS tests speed: (min=51.971; avg=137.737; max=167.311)Mibits/s
rngtest: Program run time: 31461595 microseconds
3.5. GNU Privacy Guard (GPG)
3.5.1. Creating GPG Keys in GNOME
- Install the Seahorse utility, which makes GPG key management easier:
~]#
yum install seahorse
- To create a key, from the Applications → Accessories menu select Passwords and Encryption Keys, which starts the application Seahorse.
- From the File menu select New and then PGP Key. Then click Continue.
- Type your full name, email address, and an optional comment describing who you are (for example: John C. Smith, jsmith@example.com, Software Engineer). Click Create. A dialog is displayed asking for a passphrase for the key. Choose a strong passphrase but also easy to remember. Click OK and the key is created.
Warning
0x
to the key ID, as in 0x6789ABCD
. You should make a backup of your private key and store it somewhere secure.
3.5.2. Creating GPG Keys in KDE
- Start the KGpg program from the main menu by selecting Applications → Utilities → Encryption Tool. If you have never used KGpg before, the program walks you through the process of creating your own GPG keypair.
- A dialog box appears prompting you to create a new key pair. Enter your name, email address, and an optional comment. You can also choose an expiration time for your key, as well as the key strength (number of bits) and algorithms.
- Enter your passphrase in the next dialog box. At this point, your key appears in the main
KGpg
window.
Warning
0x
to the key ID, as in 0x6789ABCD
. You should make a backup of your private key and store it somewhere secure.
3.5.3. Creating GPG Keys Using the Command Line
- Use the following shell command:
~]$
gpg2 --gen-key
This command generates a key pair that consists of a public and a private key. Other people use your public key to authenticate and/or decrypt your communications. Distribute your public key as widely as possible, especially to people who you know will want to receive authentic communications from you, such as a mailing list. - A series of prompts directs you through the process. Press the Enter key to assign a default value if desired. The first prompt asks you to select what kind of key you prefer:
Please select what kind of key you want: (1) RSA and RSA (default) (2) DSA and Elgamal (3) DSA (sign only) (4) RSA (sign only) Your selection?
In almost all cases, the default is the correct choice. An RSA/RSA key allows you not only to sign communications, but also to encrypt files. - Choose the key size:
RSA keys may be between 1024 and 4096 bits long. What keysize do you want? (2048)
Again, the default, 2048, is sufficient for almost all users and represents an extremely strong level of security. - Choose when the key will expire. It is a good idea to choose an expiration date instead of using the default, which is
none
. If, for example, the email address on the key becomes invalid, an expiration date will remind others to stop using that public key.Please specify how long the key should be valid. 0 = key does not expire d = key expires in n days w = key expires in n weeks m = key expires in n months y = key expires in n years key is valid for? (0)
Entering a value of 1y, for example, makes the key valid for one year. (You may change this expiration date after the key is generated, if you change your mind.) - Before the gpg2 application asks for signature information, the following prompt appears:
Is this correct (y/N)?
Entery
to finish the process. - Enter your name and email address for your GPG key. Remember this process is about authenticating you as a real individual. For this reason, include your real name. If you choose a bogus email address, it will be more difficult for others to find your public key. This makes authenticating your communications difficult. If you are using this GPG key for self-introduction on a mailing list, for example, enter the email address you use on that list.Use the comment field to include aliases or other information. (Some people use different keys for different purposes and identify each key with a comment, such as "Office" or "Open Source Projects.")
- At the confirmation prompt, enter the letter
O
to continue if all entries are correct, or use the other options to fix any problems. Finally, enter a passphrase for your secret key. The gpg2 program asks you to enter your passphrase twice to ensure you made no typing errors. - Finally,
gpg2
generates random data to make your key as unique as possible. Move your mouse, type random keys, or perform other tasks on the system during this step to speed up the process. Once this step is finished, your keys are complete and ready to use:pub 1024D/1B2AFA1C 2005-03-31 John Q. Doe <jqdoe@example.com> Key fingerprint = 117C FE83 22EA B843 3E86 6486 4320 545E 1B2A FA1C sub 1024g/CEA4B22E 2005-03-31 [expires: 2006-03-31]
- The key fingerprint is a shorthand "signature" for your key. It allows you to confirm to others that they have received your actual public key without any tampering. You do not need to write this fingerprint down. To display the fingerprint at any time, use this command, substituting your email address:
~]$
gpg2 --fingerprint jqdoe@example.com
Your "GPG key ID" consists of 8 hex digits identifying the public key. In the example above, the GPG key ID is1B2AFA1C
. In most cases, if you are asked for the key ID, prepend0x
to the key ID, as in0x6789ABCD
.
Warning
3.5.4. About Public Key Encryption
3.6. Using stunnel
3.6.1. Installing stunnel
root
:
~]# yum install stunnel
3.6.2. Configuring stunnel as a TLS Wrapper
- You need a valid certificate for stunnel regardless of what service you use it with. If you do not have a suitable certificate, you can apply to a Certificate Authority to obtain one, or you can create a self-signed cerfiticate.
Warning
Always use certificates signed by a Certificate Authority for servers running in a production environment. Self-signed certificates are only appropriate for testing purposes or private networks.To create a self-signed certificate for stunnel, enter the/etc/pki/tls/certs/
directory and type the following command asroot
:certs]#
make stunnel.pem
Answer all of the questions to complete the process. - When you have a certificate, create a configuration file for stunnel. It is a text file in which every line specifies an option or the beginning of a service definition. You can also keep comments and empty lines in the file to improve its legibility, where comments start with a semicolon.The stunnel RPM package contains the
/etc/stunnel/
directory, in which you can store the configuration file. Although stunnel does not require any special format of the file name or its extension, use/etc/stunnel/stunnel.conf
. The following content configures stunnel as a TLS wrapper:cert = /etc/pki/tls/certs/stunnel.pem ; Allow only TLS, thus avoiding SSL sslVersion = TLSv1 chroot = /var/run/stunnel setuid = nobody setgid = nobody pid = /stunnel.pid socket = l:TCP_NODELAY=1 socket = r:TCP_NODELAY=1 [service_name] accept = port connect = port TIMEOUTclose = 0
Alternatively, you can avoid SSL by replacing the line containingsslVersion = TLSv1
with the following lines:options = NO_SSLv2 options = NO_SSLv3
The purpose of the options is as follows:cert
— the path to your certificatesslVersion
— the version of SSL; note that you can useTLS
here even though SSL and TLS are two independent cryptographic protocolschroot
— the changed root directory in which the stunnel process runs, for greater securitysetuid
,setgid
— the user and group that the stunnel process runs as;nobody
is a restricted system accountpid
— the file in which stunnel saves its process ID, relative tochroot
socket
— local and remote socket options; in this case, disable Nagle's algorithm to improve network latency[service_name]
— the beginning of the service definition; the options used below this line apply to the given service only, whereas the options above affect stunnel globallyaccept
— the port to listen onconnect
— the port to connect to; this must be the port that the service you are securing usesTIMEOUTclose
— how many seconds to wait for the close_notify alert from the client;0
instructs stunnel not to wait at alloptions
— OpenSSL library options
Example 3.1. Securing OpenLDAP
To configure stunnel as a TLS wrapper for OpenLDAP older than 2.4.39, use the following values:[openldap] accept = 636 connect = 389
636
is the standard port for secure LDAP.389
is the port that the OpenLDAP daemon listens on.Example 3.2. Securing CUPS
Similarly, to configure stunnel as a TLS wrapper for CUPS, use the following values:[cups] accept = 632 connect = 631
Instead of632
, you can use any free port that you prefer.631
is the port that CUPS normally uses. - Create the
chroot
directory and give the user specified by thesetuid
option write access to it. To do so, run the following commands asroot
:~]#
mkdir /var/run/stunnel
~]#chown nobody:nobody /var/run/stunnel
This allows stunnel to create the PID file. - If your system is using firewall settings that disallow access to the new port, change them accordingly. See Section 2.8.2.4, “Other Ports” in Section 2.8, “Firewalls” for details.
- When you have created the configuration file and the
chroot
directory, and when you are sure that the specified port is accessible, you are ready to start using stunnel.
3.6.3. Starting, Stopping and Restarting stunnel
root
:
~]#stunnel
/etc/stunnel/stunnel.conf
/var/log/secure
to log its output.
root
:
~]# kill `cat /var/run/stunnel/stunnel.pid`
3.7. Hardening TLS Configuration
TLS
(Transport Layer Security
) is a cryptographic protocol used to secure network communications. When hardening system security settings by configuring preferred key-exchange protocols, authentication methods, and encryption algorithms, it is necessary to bear in mind that the broader the range of supported clients, the lower the resulting security. Conversely, strict security settings lead to a limited compatibility with clients, which can result in some users being locked out of the system. Be sure to target the strictest available configuration and only relax it when it is required for compatibility reasons.
TLS
implementations use secure algorithms where possible while not preventing connections from or to legacy clients or servers. Apply the hardened settings described in this section in environments with strict security requirements where legacy clients or servers that do not support secure algorithms or protocols are not expected or allowed to connect.
3.7.1. Choosing Algorithms to Enable
Protocol Versions
TLS
provides the best security mechanism. Unless you have a compelling reason to include support for older versions of TLS
(or even SSL
), allow your systems to negotiate connections using only the latest version of TLS
.
SSL
version 2 or 3. Both of those versions have serious security vulnerabilities. Only allow negotiation using TLS
version 1.0 or higher. The current version of TLS
, 1.2, should always be preferred.
Note
TLS
depends on the use of TLS
extensions, specific ciphers (see below), and other workarounds. All TLS
connection peers need to implement secure renegotiation indication (RFC 5746), must not support compression, and must implement mitigating measures for timing attacks against CBC
-mode ciphers (the Lucky Thirteen attack). TLS v1.0
clients need to additionally implement record splitting (a workaround against the BEAST attack). TLS v1.2
supports Authenticated Encryption with Associated Data (AEAD) mode ciphers like AES-GCM
, AES-CCM
, or Camellia-GCM
, which have no known issues. All the mentioned mitigations are implemented in cryptographic libraries included in Red Hat Enterprise Linux.
Table 3.1. Protocol Versions
Protocol Version | Usage Recommendation |
---|---|
SSL v2 |
Do not use. Has serious security vulnerabilities.
|
SSL v3 |
Do not use. Has serious security vulnerabilities.
|
TLS v1.0 |
Use for interoperability purposes where needed. Has known issues that cannot be mitigated in a way that guarantees interoperability, and thus mitigations are not enabled by default. Does not support modern cipher suites.
|
TLS v1.1 |
Use for interoperability purposes where needed. Has no known issues but relies on protocol fixes that are included in all the
TLS implementations in Red Hat Enterprise Linux. Does not support modern cipher suites.
|
TLS v1.2 |
Recommended version. Supports the modern
AEAD cipher suites.
|
TLS v1.0
even though they provide support for TLS v1.1
or even v1.2
. This is motivated by an attempt to achieve the highest level of interoperability with external services that may not support the latest versions of TLS
. Depending on your interoperability requirements, enable the highest available version of TLS
.
Important
SSL v3
is not recommended for use. However, if, despite the fact that it is considered insecure and unsuitable for general use, you absolutely must leave SSL v3
enabled, see Section 3.6, “Using stunnel” for instructions on how to use stunnel to securely encrypt communications even when using services that do not support encryption or are only capable of using obsolete and insecure modes of encryption.
3DES
ciphers advertise the use of 168 bits, they actually offer 112 bits of security.
RSA
key exchange, but allows for the use of ECDHE
and DHE
. Of the two, ECDHE
is the faster and therefore the preferred choice.
ECDHE
key exchange with ECDSA
certificates, the transaction is even faster than pure RSA
key exchange. To provide support for legacy clients, you can install two pairs of certificates and keys on a server: one with ECDSA
keys (for new clients) and one with RSA
keys (for legacy ones).
Public Key Length
RSA
keys, always prefer key lengths of at least 3072 bits signed by at least SHA-256, which is sufficiently large for true 128 bits of security.
Warning
3.7.2. Using Implementations of TLS
TLS
. In this section, the configuration of OpenSSL and GnuTLS is described. See Section 3.7.3, “Configuring Specific Applications” for instructions on how to configure TLS
support in individual applications.
TLS
implementations offer support for various cipher suites that define all the elements that come together when establishing and using TLS
-secured communications.
Important
3.7.2.1. Working with Cipher Suites in OpenSSL
SSL
and TLS
protocols. On Red Hat Enterprise Linux, a configuration file is provided at /etc/pki/tls/openssl.cnf
. The format of this configuration file is described in config(1).
openssl
command with the ciphers
subcommand as follows:
~]$ openssl ciphers -v 'ALL:COMPLEMENTOFALL'
ciphers
subcommand to narrow the output. Special keywords can be used to only list suites that satisfy a certain condition. For example, to only list suites that are defined as belonging to the HIGH
group, use the following command:
~]$ openssl ciphers -v 'HIGH'
~]$ openssl ciphers -v 'kEECDH+aECDSA+AES:kEECDH+AES+aRSA:kEDH+aRSA+AES' | column -t
ECDHE-ECDSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(256) Mac=AEAD
ECDHE-ECDSA-AES256-SHA384 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA384
ECDHE-ECDSA-AES256-SHA SSLv3 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA1
ECDHE-ECDSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(128) Mac=AEAD
ECDHE-ECDSA-AES128-SHA256 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA256
ECDHE-ECDSA-AES128-SHA SSLv3 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA1
ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD
ECDHE-RSA-AES256-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA384
ECDHE-RSA-AES256-SHA SSLv3 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA1
ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD
ECDHE-RSA-AES128-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA256
ECDHE-RSA-AES128-SHA SSLv3 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA1
DHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(256) Mac=AEAD
DHE-RSA-AES256-SHA256 TLSv1.2 Kx=DH Au=RSA Enc=AES(256) Mac=SHA256
DHE-RSA-AES256-SHA SSLv3 Kx=DH Au=RSA Enc=AES(256) Mac=SHA1
DHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(128) Mac=AEAD
DHE-RSA-AES128-SHA256 TLSv1.2 Kx=DH Au=RSA Enc=AES(128) Mac=SHA256
DHE-RSA-AES128-SHA SSLv3 Kx=DH Au=RSA Enc=AES(128) Mac=SHA1
ephemeral elliptic curve Diffie-Hellman
key exchange and ECDSA
ciphers, and omits RSA
key exchange (thus ensuring perfect forward secrecy).
3.7.2.2. Working with Cipher Suites in GnuTLS
SSL
and TLS
protocols and related technologies.
Note
gnutls-cli
command with the -l
(or --list
) option to list all supported cipher suites:
~]$ gnutls-cli -l
-l
option, pass one or more parameters (referred to as priority strings and keywords in GnuTLS documentation) to the --priority
option. See the GnuTLS documentation at http://www.gnutls.org/manual/gnutls.html#Priority-Strings for a list of all available priority strings. For example, issue the following command to get a list of cipher suites that offer at least 128 bits of security:
~]$ gnutls-cli --priority SECURE128 -l
~]$ gnutls-cli --priority SECURE256:+SECURE128:-VERS-TLS-ALL:+VERS-TLS1.2:-RSA:-DHE-DSS:-CAMELLIA-128-CBC:-CAMELLIA-256-CBC -l
Cipher suites for SECURE256:+SECURE128:-VERS-TLS-ALL:+VERS-TLS1.2:-RSA:-DHE-DSS:-CAMELLIA-128-CBC:-CAMELLIA-256-CBC
TLS_ECDHE_ECDSA_AES_256_GCM_SHA384 0xc0, 0x2c TLS1.2
TLS_ECDHE_ECDSA_AES_256_CBC_SHA384 0xc0, 0x24 TLS1.2
TLS_ECDHE_ECDSA_AES_256_CBC_SHA1 0xc0, 0x0a SSL3.0
TLS_ECDHE_ECDSA_AES_128_GCM_SHA256 0xc0, 0x2b TLS1.2
TLS_ECDHE_ECDSA_AES_128_CBC_SHA256 0xc0, 0x23 TLS1.2
TLS_ECDHE_ECDSA_AES_128_CBC_SHA1 0xc0, 0x09 SSL3.0
TLS_ECDHE_RSA_AES_256_GCM_SHA384 0xc0, 0x30 TLS1.2
TLS_ECDHE_RSA_AES_256_CBC_SHA1 0xc0, 0x14 SSL3.0
TLS_ECDHE_RSA_AES_128_GCM_SHA256 0xc0, 0x2f TLS1.2
TLS_ECDHE_RSA_AES_128_CBC_SHA256 0xc0, 0x27 TLS1.2
TLS_ECDHE_RSA_AES_128_CBC_SHA1 0xc0, 0x13 SSL3.0
TLS_DHE_RSA_AES_256_CBC_SHA256 0x00, 0x6b TLS1.2
TLS_DHE_RSA_AES_256_CBC_SHA1 0x00, 0x39 SSL3.0
TLS_DHE_RSA_AES_128_GCM_SHA256 0x00, 0x9e TLS1.2
TLS_DHE_RSA_AES_128_CBC_SHA256 0x00, 0x67 TLS1.2
TLS_DHE_RSA_AES_128_CBC_SHA1 0x00, 0x33 SSL3.0
Certificate types: CTYPE-X.509
Protocols: VERS-TLS1.2
Compression: COMP-NULL
Elliptic curves: CURVE-SECP384R1, CURVE-SECP521R1, CURVE-SECP256R1
PK-signatures: SIGN-RSA-SHA384, SIGN-ECDSA-SHA384, SIGN-RSA-SHA512, SIGN-ECDSA-SHA512, SIGN-RSA-SHA256, SIGN-DSA-SHA256, SIGN-ECDSA-SHA256
RSA
key exchange and DSS
authentication.
3.7.3. Configuring Specific Applications
TLS
. This section describes the TLS
-related configuration files employed by the most commonly used server applications and offers examples of typical configurations.
3.7.3.1. Configuring the Apache HTTP Server
TLS
needs. Depending on your choice of the TLS
library, you need to install either the mod_ssl or the mod_nss module (provided by eponymous packages). For example, to install the package that provides the OpenSSL mod_ssl module, issue the following command as root:
~]# yum install mod_ssl
/etc/httpd/conf.d/ssl.conf
configuration file, which can be used to modify the TLS
-related settings of the Apache HTTP Server. Similarly, the mod_nss package installs the /etc/httpd/conf.d/nss.conf
configuration file.
TLS
configuration. The directives available in the /etc/httpd/conf.d/ssl.conf
configuration file are described in detail in /usr/share/httpd/manual/mod/mod_ssl.html
. Examples of various settings are in /usr/share/httpd/manual/ssl/ssl_howto.html
.
/etc/httpd/conf.d/ssl.conf
configuration file, be sure to consider the following three directives at the minimum:
-
SSLProtocol
- Use this directive to specify the version of
TLS
(orSSL
) you want to allow. -
SSLCipherSuite
- Use this directive to specify your preferred cipher suite or disable the ones you want to disallow.
-
SSLHonorCipherOrder
- Uncomment and set this directive to
on
to ensure that the connecting clients adhere to the order of ciphers you specified.
SSLProtocol all -SSLv2 -SSLv3 SSLCipherSuite HIGH:!aNULL:!MD5 SSLHonorCipherOrder on
/etc/httpd/conf.d/nss.conf
configuration file. The mod_nss module is derived from mod_ssl, and as such it shares many features with it, not least the structure of the configuration file, and the directives that are available. Note that the mod_nss directives have a prefix of NSS
instead of SSL
. See https://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html for an overview of information about mod_nss, including a list of mod_ssl configuration directives that are not applicable to mod_nss.
3.7.4. Additional Information
Installed Documentation
- config(1) — Describes the format of the
/etc/ssl/openssl.conf
configuration file. - ciphers(1) — Includes a list of available OpenSSL keywords and cipher strings.
/usr/share/httpd/manual/mod/mod_ssl.html
— Contains detailed descriptions of the directives available in the/etc/httpd/conf.d/ssl.conf
configuration file used by the mod_ssl module for the Apache HTTP Server./usr/share/httpd/manual/ssl/ssl_howto.html
— Contains practical examples of real-world settings in the/etc/httpd/conf.d/ssl.conf
configuration file used by the mod_ssl module for the Apache HTTP Server.
Online Documentation
- Red Hat Enterprise Linux 6 Security-Enhanced Linux — The Security-Enhanced Linux guide for Red Hat Enterprise Linux 6 describes the basic principles of SELinux.
- http://tools.ietf.org/html/draft-ietf-uta-tls-bcp-00 — Recommendations for secure use of
TLS
andDTLS
.
Chapter 4. General Principles of Information Security
- Encrypt all data transmitted over networks to help prevent man-in-the-middle attacks and eavesdropping. It is important to encrypt authentication information, such as passwords.
- Minimize the amount of software installed and running services.
- Use security-enhancing software and tools, for example, Security-Enhanced Linux (SELinux) for Mandatory Access Control (MAC), Netfilter iptables for packet filtering (firewall), and the GNU Privacy Guard (GPG) for encrypting files.
- If possible, run each network service on a separate system to minimize the risk of one compromised service being used to compromise other services.
- Maintain user accounts: create and enforce a strong password policy; delete unused user accounts.
- Routinely review system and application logs. By default, security-relevant system logs are written to
/var/log/secure
and/var/log/audit/audit.log
. Note: sending logs to a dedicated log server helps prevent attackers from easily modifying local logs to avoid detection. - Never log in as the root user unless absolutely necessary. It is recommended that administrators use
sudo
to execute commands as root when required. Users capable of runningsudo
are specified in/etc/sudoers
. Use thevisudo
utility to edit/etc/sudoers
.
Chapter 5. Secure Installation
5.1. Disk Partitions
/boot
, /
, /home
, /tmp/
, and /var/tmp/
. If the root partition (/
) becomes corrupt, your data could be lost forever. By using separate partitions, the data is slightly more protected. You can also target these partition for frequent backups. The purpose for each partition is different and we will address each partition.
/boot
- This partition is the first partition that is read by the system during the boot. The boot loader and kernel images that are used to boot your system into Red Hat Enterprise Linux are stored in this partition. This partition should not be encrypted. If this partition is included in /
and that partition is encrypted or otherwise becomes unavailable, your system will not be able to boot.
/home
- When user data (/home
) is stored in /
instead of a separate partition, the partition can fill up causing the operating system to become unstable. Also, when upgrading your system to the next version of Red Hat Enterprise Linux, it is a lot easier if you can keep your data in the /home
partition as it will not be overwritten during installation.
/tmp
and /var/tmp/
- Both the /tmp
and the /var/tmp/
directories are used to store data that does not need to be stored for a long period of time. However, if a lot of data floods one of these directories, it can consume all of your storage space. If this happens and these directories are stored within /
, your system could become unstable and crash. For this reason, moving these directories into their own partitions is a good idea.
5.2. Utilize LUKS Partition Encryption
Chapter 6. Software Maintenance
6.1. Install Minimal Software
--nobase
option. For more information, see the "Package Selection" section of the Red Hat Enterprise Linux 6 Installation Guide.
6.2. Plan and Configure Security Updates
6.3. Adjusting Automatic Updates
6.4. Install Signed Packages from Well Known Repositories
Chapter 7. System Auditing
- Date and time, type, and outcome of an event.
- Sensitivity labels of subjects and objects.
- Association of an event with the identity of the user who triggered the event.
- All modifications to Audit configuration and attempts to access Audit log files.
- All uses of authentication mechanisms, such as SSH, Kerberos, and others.
- Changes to any trusted database, such as
/etc/passwd
. - Attempts to import or export information into or from the system.
- Include or exclude events based on user identity, subject and object labels, and other attributes.
- Controlled Access Protection Profile (CAPP)
- Labeled Security Protection Profile (LSPP)
- Rule Set Base Access Control (RSBAC)
- National Industrial Security Program Operating Manual (NISPOM)
- Federal Information Security Management Act (FISMA)
- Payment Card Industry — Data Security Standard (PCI-DSS)
- Security Technical Implementation Guides (STIG)
- Evaluated by National Information Assurance Partnership (NIAP) and Best Security Industries (BSI).
- Certified to LSPP/CAPP/RSBAC/EAL4+ on Red Hat Enterprise Linux 5.
- Certified to Operating System Protection Profile / Evaluation Assurance Level 4+ (OSPP/EAL4+) on Red Hat Enterprise Linux 6.
Use Cases
- Watching file access
- Audit can track whether a file or a directory has been accessed, modified, executed, or the file's attributes have been changed. This is useful, for example, to detect access to important files and have an Audit trail available in case one of these files is corrupted.
- Monitoring system calls
- Audit can be configured to generate a log entry every time a particular system call is used. This can be used, for example, to track changes to the system time by monitoring the
settimeofday
,clock_adjtime
, and other time-related system calls. - Recording commands run by a user
- Because Audit can track whether a file has been executed, a number of rules can be defined to record every execution of a particular command. For example, a rule can be defined for every executable in the
/bin
directory. The resulting log entries can then be searched by user ID to generate an audit trail of executed commands per user. - Recording security events
- The
pam_faillock
authentication module is capable of recording failed login attempts. Audit can be set up to record failed login attempts as well, and provides additional information about the user who attempted to log in. - Searching for events
- Audit provides the ausearch utility, which can be used to filter the log entries and provide a complete audit trail based on a number of conditions.
- Running summary reports
- The aureport utility can be used to generate, among other things, daily reports of recorded events. A system administrator can then analyze these reports and investigate suspicious activity furthermore.
- Monitoring network access
- The iptables and ebtables utilities can be configured to trigger Audit events, allowing system administrators to monitor network access.
Note
7.1. Audit System Architecture

Figure 7.1. Audit system architecture
- audisp — the Audit dispatcher daemon interacts with the Audit daemon and sends events to other applications for further processing. The purpose of this daemon is to provide a plug-in mechanism so that real-time analytical programs can interact with Audit events.
- auditctl — the Audit control utility interacts with the kernel Audit component to control a number of settings and parameters of the event generation process.
- The remaining Audit utilities take the contents of the Audit log files as input and generate output based on user's requirements. For example, the aureport utility generates a report of all recorded events.
7.2. Installing the audit Packages
~]# yum install audit
7.3. Configuring the audit
Service
/etc/audit/auditd.conf
configuration file. This file consists of configuration parameters that modify the behavior of the Audit daemon. Any empty lines or any text following a hash sign (#
) is ignored. See the auditd.conf(5) man page for a complete listing of all configuration parameters and their explanation.
7.3.1. Configuring auditd
for a CAPP Environment
auditd
configuration should be suitable for most environments. However, if your environment has to meet the criteria set by the Controlled Access Protection Profile (CAPP), which is a part of the Common Criteria certification, the Audit daemon must be configured with the following settings:
- The directory that holds the Audit log files (usually
/var/log/audit/
) should reside on a separate partition. This prevents other processes from consuming space in this directory, and provides accurate detection of the remaining space for the Audit daemon. - The
max_log_file
parameter, which specifies the maximum size of a single Audit log file, must be set to make full use of the available space on the partition that holds the Audit log files. - The
max_log_file_action
parameter, which decides what action is taken once the limit set inmax_log_file
is reached, should be set tokeep_logs
to prevent Audit log files from being overwritten. - The
space_left
parameter, which specifies the amount of free space left on the disk for which an action that is set in thespace_left_action
parameter is triggered, must be set to a number that gives the administrator enough time to respond and free up disk space. Thespace_left
value depends on the rate at which the Audit log files are generated. - It is recommended to set the
space_left_action
parameter toemail
orexec
with an appropriate notification method. - The
admin_space_left
parameter, which specifies the absolute minimum amount of free space for which an action that is set in theadmin_space_left_action
parameter is triggered, must be set to a value that leaves enough space to log actions performed by the administrator. - The
admin_space_left_action
parameter must be set tosingle
to put the system into single-user mode and allow the administrator to free up some disk space. - The
disk_full_action
parameter, which specifies an action that is triggered when no free space is available on the partition that holds the Audit log files, must be set tohalt
orsingle
. This ensures that the system is either shut down or operating in single-user mode when Audit can no longer log events. - The
disk_error_action
, which specifies an action that is triggered in case an error is detected on the partition that holds the Audit log files, must be set tosyslog
,single
, orhalt
, depending on your local security policies regarding the handling of hardware malfunctions. - The
flush
configuration parameter must be set tosync
ordata
. These parameters assure that all Audit event data is fully synchronized with the log files on the disk.
7.4. Starting the audit
Service
auditd
is properly configured, start the service to collect Audit information and store it in the log files. Execute the following command as the root user to start auditd
:
~]# service auditd start
auditd
to start at boot time using the following command as the root user:
~]# chkconfig auditd on
auditd
using the service auditd action
command, where action can be one of the following:
stop
— stopsauditd
.restart
— restartsauditd
.reload
orforce-reload
— reloads the configuration of auditd from the/etc/audit/auditd.conf
file.rotate
— rotates the log files in the/var/log/audit/
directory.resume
— resumes logging of Audit events after it has been previously suspended, for example, when there is not enough free space on the disk partition that holds the Audit log files.condrestart
ortry-restart
— restarts auditd only if it is already running.status
— displays the running status of auditd.
7.5. Defining Audit Rules
- Control rules — allow the Audit system's behavior and some of its configuration to be modified.
- File system rules — also known as file watches, allow the auditing of access to a particular file or a directory.
- System call rules — allow logging of system calls that any specified program makes.
/etc/audit/audit.rules
file. The following two sections summarize both approaches to defining Audit rules.
7.5.1. Defining Audit Rules with the auditctl Utility
Note
auditctl
command allows you to control the basic functionality of the Audit system and to define rules that decide which Audit events are logged.
Defining Control Rules
-b
- sets the maximum amount of existing Audit buffers in the kernel, for example:
~]#
auditctl -b 8192
-f
- sets the action that is performed when a critical error is detected, for example:
~]#
auditctl -f 2
The above configuration triggers a kernel panic in case of a critical error. -e
- enables and disables the Audit system or locks its configuration, for example:
~]#
auditctl -e 2
The above command locks the Audit configuration. -r
- sets the rate of generated messages per second, for example:
~]#
auditctl -r 0
The above configuration sets no rate limit on generated messages. -s
- reports the status of the Audit system, for example:
~]#
auditctl -s
AUDIT_STATUS: enabled=1 flag=2 pid=0 rate_limit=0 backlog_limit=8192 lost=259 backlog=0 -l
- lists all currently loaded Audit rules, for example:
~]#
auditctl -l
LIST_RULES: exit,always watch=/etc/localtime perm=wa key=time-change LIST_RULES: exit,always watch=/etc/group perm=wa key=identity LIST_RULES: exit,always watch=/etc/passwd perm=wa key=identity LIST_RULES: exit,always watch=/etc/gshadow perm=wa key=identity ⋮ -D
- deletes all currently loaded Audit rules, for example:
~]#
auditctl -D
No rules
Defining File System Rules
auditctl -w path_to_file -p permissions -k key_name
- path_to_file is the file or directory that is audited.
- permissions are the permissions that are logged:
r
— read access to a file or a directory.w
— write access to a file or a directory.x
— execute access to a file or a directory.a
— change in the file's or directory's attribute.
- key_name is an optional string that helps you identify which rule or a set of rules generated a particular log entry.
Example 7.1. File System Rules
/etc/passwd
file, execute the following command:
~]# auditctl -w /etc/passwd -p wa -k passwd_changes
-k
option is arbitrary.
/etc/selinux/
directory, execute the following command:
~]# auditctl -w /etc/selinux/ -p wa -k selinux_changes
/sbin/insmod
command, which inserts a module into the Linux kernel, execute the following command:
~]# auditctl -w /sbin/insmod -p x -k module_insertion
Defining System Call Rules
auditctl -a action,filter -S system_call -F field=value -k key_name
- action and filter specify when a certain event is logged. action can be either
always
ornever
. filter specifies which kernel rule-matching filter is applied to the event. The rule-matching filter can be one of the following:task
,exit
,user
, andexclude
. For more information about these filters, see the beginning of Section 7.1, “Audit System Architecture”. - system_call specifies the system call by its name. A list of all system calls can be found in the
/usr/include/asm/unistd_64.h
file. Several system calls can be grouped into one rule, each specified after the-S
option. - field=value specifies additional options that furthermore modify the rule to match events based on a specified architecture, group ID, process ID, and others. For a full listing of all available field types and their values, see the auditctl(8) man page.
- key_name is an optional string that helps you identify which rule or a set of rules generated a particular log entry.
Example 7.2. System Call Rules
adjtimex
or settimeofday
system calls are used by a program, and the system uses the 64-bit architecture, execute the following command:
~]# auditctl -a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time_change
-F auid!=4294967295
option is used to exclude users whose login UID is not set), execute the following command:
~]# auditctl -a always,exit -S unlink -S unlinkat -S rename -S renameat -F auid>=500 -F auid!=4294967295 -k delete
-w /etc/shadow -p wa
file system rule:
~]# auditctl -a always,exit -F path=/etc/shadow -F perm=wa
7.5.2. Defining Persistent Audit Rules and Controls in the /etc/audit/audit.rules
File
/etc/audit/audit.rules
file. This file uses the same auditctl
command line syntax to specify the rules. Any empty lines or any text following a hash sign (#
) is ignored.
auditctl
command can also be used to read rules from a specified file with the -R
option, for example:
~]# auditctl -R /usr/share/doc/audit-version/stig.rules
Defining Control Rules
-b
, -D
, -e
, -f
, and -r
. For more information on these options, see the section called “Defining Control Rules”.
Example 7.3. Control rules in audit.rules
# Delete all previous rules -D # Set buffer size -b 8192 # Make the configuration immutable -- reboot is required to change audit rules -e 2 # Panic when a failure occurs -f 2 # Generate at most 100 audit messages per second -r 100
Defining File System and System Call Rules
auditctl
syntax. The examples in Section 7.5.1, “Defining Audit Rules with the auditctl Utility” can be represented with the following rules file:
Example 7.4. File system and system call rules in audit.rules
-w /etc/passwd -p wa -k passwd_changes -w /etc/selinux/ -p wa -k selinux_changes -w /sbin/insmod -p x -k module_insertion -a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time_change -a always,exit -S unlink -S unlinkat -S rename -S renameat -F auid>=500 -F auid!=4294967295 -k delete
Preconfigured Rules Files
/usr/share/doc/audit-version/
directory, the audit package provides a set of pre-configured rules files according to various certification standards:
nispom.rules
— Audit rule configuration that meets the requirements specified in Chapter 8 of the National Industrial Security Program Operating Manual.capp.rules
— Audit rule configuration that meets the requirements set by Controlled Access Protection Profile (CAPP), which is a part of the Common Criteria certification.lspp.rules
— Audit rule configuration that meets the requirements set by Labeled Security Protection Profile (LSPP), which is a part of the Common Criteria certification.stig.rules
— Audit rule configuration that meets the requirements set by Security Technical Implementation Guides (STIG).
/etc/audit/audit.rules
file and copy the configuration file of your choice over the /etc/audit/audit.rules
file:
~]#cp /etc/audit/audit.rules /etc/audit/audit.rules_backup
~]#cp /usr/share/doc/audit-version/stig.rules /etc/audit/audit.rules
7.6. Understanding Audit Log Files
/var/log/audit/audit.log
file; if log rotation is enabled, rotated audit.log
files are stored in the same directory.
/etc/ssh/sshd_config
file:
-w /etc/ssh/sshd_config -p warx -k sshd_config
auditd
daemon is running, running the following command creates a new event in the Audit log file:
~]# cat /etc/ssh/sshd_config
audit.log
file looks as follows:
type=SYSCALL msg=audit(1364481363.243:24287): arch=c000003e syscall=2 success=no exit=-13 a0=7fffd19c5592 a1=0 a2=7fffd19c4b50 a3=a items=1 ppid=2686 pid=3538 auid=500 uid=500 gid=500 euid=500 suid=500 fsuid=500 egid=500 sgid=500 fsgid=500 tty=pts0 ses=1 comm="cat" exe="/bin/cat" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key="sshd_config" type=CWD msg=audit(1364481363.243:24287): cwd="/home/shadowman" type=PATH msg=audit(1364481363.243:24287): item=0 name="/etc/ssh/sshd_config" inode=409248 dev=fd:00 mode=0100600 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:etc_t:s0
type=
keyword), which share the same time stamp and serial number. Each record consists of several name=value
pairs separated by a white space or a comma. A detailed analysis of the above event follows:
First Record
type=SYSCALL
- The
type
field contains the type of the record. In this example, theSYSCALL
value specifies that this record was triggered by a system call to the kernel.For a list of all possible type values and their explanations, see Section B.2, “Audit Record Types”. msg=audit(1364481363.243:24287):
- The
msg
field records:- a time stamp and a unique ID of the record in the form
audit(time_stamp:ID)
. Multiple records can share the same time stamp and ID if they were generated as part of the same Audit event. - various event-specific
name=value
pairs provided by the kernel or user space applications.
arch=c000003e
- The
arch
field contains information about the CPU architecture of the system. The value,c000003e
, is encoded in hexadecimal notation. When searching Audit records with theausearch
command, use the-i
or--interpret
option to automatically convert hexadecimal values into their human-readable equivalents. Thec000003e
value is interpreted asx86_64
. syscall=2
- The
syscall
field records the type of the system call that was sent to the kernel. The value,2
, can be matched with its human-readable equivalent in the/usr/include/asm/unistd_64.h
file. In this case,2
is theopen
system call. Note that the ausyscall utility allows you to convert system call numbers to their human-readable equivalents. Use theausyscall --dump
command to display a listing of all system calls along with their numbers. For more information, see the ausyscall(8) man page. success=no
- The
success
field records whether the system call recorded in that particular event succeeded or failed. In this case, the call did not succeed. exit=-13
- The
exit
field contains a value that specifies the exit code returned by the system call. This value varies for different system call. You can interpret the value to its human-readable equivalent with the following command:ausearch --interpret --exit -13
(assuming your Audit log contains an event that failed with exit code-13
). a0=7fffd19c5592
,a1=0
,a2=7fffd19c5592
,a3=a
- The
a0
toa3
fields record the first four arguments, encoded in hexadecimal notation, of the system call in this event. These arguments depend on the system call that is used; they can be interpreted by the ausearch utility. items=1
- The
items
field contains the number of path records in the event. ppid=2686
- The
ppid
field records the Parent Process ID (PPID). In this case,2686
was the PPID of thebash
process. pid=3538
- The
pid
field records the Process ID (PID). In this case,3538
was the PID of thecat
process. auid=500
- The
auid
field records the Audit user ID, that is the loginuid. This ID is assigned to a user upon login and is inherited by every process even when the user's identity changes (for example, by switching user accounts with thesu - john
command). uid=500
- The
uid
field records the user ID of the user who started the analyzed process. The user ID can be interpreted into user names with the following command:ausearch -i --uid UID
. In this case,500
is the user ID of usershadowman
. gid=500
- The
gid
field records the group ID of the user who started the analyzed process. euid=500
- The
euid
field records the effective user ID of the user who started the analyzed process. suid=500
- The
suid
field records the set user ID of the user who started the analyzed process. fsuid=500
- The
fsuid
field records the file system user ID of the user who started the analyzed process. egid=500
- The
egid
field records the effective group ID of the user who started the analyzed process. sgid=500
- The
sgid
field records the set group ID of the user who started the analyzed process. fsgid=500
- The
fsgid
field records the file system group ID of the user who started the analyzed process. tty=pts0
- The
tty
field records the terminal from which the analyzed process was invoked. ses=1
- The
ses
field records the session ID of the session from which the analyzed process was invoked. comm="cat"
- The
comm
field records the command-line name of the command that was used to invoke the analyzed process. In this case, thecat
command was used to trigger this Audit event. exe="/bin/cat"
- The
exe
field records the path to the executable that was used to invoke the analyzed process. subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
- The
subj
field records the SELinux context with which the analyzed process was labeled at the time of execution. key="sshd_config"
- The
key
field records the administrator-defined string associated with the rule that generated this event in the Audit log.
Second Record
type=CWD
- In the second record, the
type
field value isCWD
— current working directory. This type is used to record the working directory from which the process that invoked the system call specified in the first record was executed.The purpose of this record is to record the current process's location in case a relative path is captured in the associated PATH record. This way the absolute path can be reconstructed. msg=audit(1364481363.243:24287)
- The
msg
field holds the same time stamp and ID value as the value in the first record. cwd="/home/shadowman"
- The
cwd
field contains the path to the directory in which the system call was invoked.
Third Record
type=PATH
- In the third record, the
type
field value isPATH
. An Audit event contains aPATH
-type record for every path that is passed to the system call as an argument. In this Audit event, only one path (/etc/ssh/sshd_config
) was used as an argument. msg=audit(1364481363.243:24287):
- The
msg
field holds the same time stamp and ID value as the value in the first and second record. item=0
- The
item
field indicates which item, of the total number of items referenced in theSYSCALL
type record, the current record is. This number is zero-based; a value of0
means it is the first item. name="/etc/ssh/sshd_config"
- The
name
field records the path of the file or directory that was passed to the system call as an argument. In this case, it was the/etc/ssh/sshd_config
file. inode=409248
- The
inode
field contains the inode number associated with the file or directory recorded in this event. The following command displays the file or directory that is associated with the409248
inode number:~]#
find / -inum 409248 -print
/etc/ssh/sshd_config dev=fd:00
- The
dev
field specifies the minor and major ID of the device that contains the file or directory recorded in this event. In this case, the value represents the/dev/fd/0
device. mode=0100600
- The
mode
field records the file or directory permissions, encoded in numerical notation. In this case,0100600
can be interpreted as-rw-------
, meaning that only the root user has read and write permissions to the/etc/ssh/sshd_config
file. ouid=0
- The
ouid
field records the object owner's user ID. ogid=0
- The
ogid
field records the object owner's group ID. rdev=00:00
- The
rdev
field contains a recorded device identifier for special files only. In this case, it is not used as the recorded file is a regular file. obj=system_u:object_r:etc_t:s0
- The
obj
field records the SELinux context with which the recorded file or directory was labeled at the time of execution.
Example 7.5. Additional audit.log
events
auditd
daemon. The ver
field shows the version of the Audit daemon that was started.
type=DAEMON_START msg=audit(1363713609.192:5426): auditd start, ver=2.2 format=raw kernel=2.6.32-358.2.1.el6.x86_64 auid=500 pid=4979 subj=unconfined_u:system_r:auditd_t:s0 res=success
type=USER_AUTH msg=audit(1364475353.159:24270): user pid=3280 uid=500 auid=500 ses=1 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:authentication acct="root" exe="/bin/su" hostname=? addr=? terminal=pts/0 res=failed'
7.7. Searching the Audit Log Files
/var/log/audit/audit.log
file. You can specify a different file using the ausearch options -if file_name
command. Supplying multiple options in one ausearch
command is equivalent to using the AND operator.
Example 7.6. Using ausearch
to search Audit log files
/var/log/audit/audit.log
file for failed login attempts, use the following command:
~]# ausearch --message USER_LOGIN --success no --interpret
~]# ausearch -m ADD_USER -m DEL_USER -m ADD_GROUP -m USER_CHAUTHTOK -m DEL_GROUP -m CHGRP_ID -m ROLE_ASSIGN -m ROLE_REMOVE -i
auid
), use the following command:
~]# ausearch -ua 500 -i
~]# ausearch --start yesterday --end now -m SYSCALL -sv no -i
ausearch
options, see the ausearch(8) man page.
7.8. Creating Audit Reports
audit.log
files in the /var/log/audit/
directory are queried to create the report. You can specify a different file to run the report against using the aureport options -if file_name
command.
Example 7.7. Using aureport
to generate Audit reports
~]# aureport --start 04/08/2013 00:00:00 --end 04/11/2013 00:00:00
~]# aureport -x
~]# aureport -x --summary
~]# aureport -u --failed --summary -i
~]# aureport --login --summary -i
ausearch
query that searches all file access events for user 500
, use the following command:
~]# ausearch --start today --loginuid 500 --raw | aureport -f --summary
~]# aureport -t
aureport
options, see the aureport(8) man page.
7.9. Configuring PAM for Auditing
7.9.1. Configuring pam_tty_audit
pam_tty_audit
PAM module to enable or disable auditing of TTY input for specified users. When the audited user logs in, pam_tty_audit
records the exact keystrokes the user makes into the /var/log/audit/audit.log
file. The module works with the auditd
daemon, so make sure it is enabled before configuring pam_tty_audit
. See Section 7.4, “Starting the audit
Service” for more information.
/etc/pam.d/system-auth
and /etc/pam.d/password-auth
files using the disable
and enable
options in the following format:
session required pam_tty_audit.so disable=username,username2 enable=username
disable
or enable
option overrides the previous opposite option which matches the same user name. When TTY auditing is enabled, it is inherited by all processes started by that user. In particular, daemons restarted by a user will still have TTY auditing enabled, and will audit TTY input even by other users, unless auditing for these users is explicitly disabled. Therefore, it is recommended to use disable=*
as the first option for most daemons using PAM.
Important
pam_tty_audit
does NOT log keystrokes when the TTY is in password entry mode. Logging can be re-enabled by adding the log_passwd
option along with the other options in the following way: session required pam_tty_audit.so disable=username,username2 enable=username log_passwd
/var/log/audit/audit.log
file, written by the auditd
daemon. Note that the input is not logged immediately, because TTY auditing first stores the keystrokes in a buffer and writes the record periodically, or once the audited user logs out. The audit.log
file contains all keystrokes entered by the specified user, including backspaces, delete and return keys, the control key and others. Although the contents of audit.log
are human-readable it might be easier to use the aureport utility, which provides a TTY report in a format which is easy to read. You can use the following command as root:
~]# aureport --tty
pam_tty_audit
to track the actions of the root
user across all terminals and then review the input.
Example 7.8. Configuring pam_tty_audit to log root actions
session
section of the /etc/pam.d/system-auth
and /etc/pam.d/password-auth
files:
session required pam_tty_audit.so disable=* enable=root
aureport --tty
command to view the log. If the root
user has logged in a TTY console at around 11:00 o'clock and tried to issue the pwd
command, but then deleted it and issued ls
instead, the report will look like this:
~]# aureport --tty -ts today | tail
40. 08/28/2014 11:00:27 901 0 ? 76 bash "pwd",<backspace>,<backspace><backspace>,"ls",<ret>
41. 08/28/2014 11:00:29 903 0 ? 76 bash <^D>
pam_tty_audit(8)
manual page.
7.10. Additional Resources
Online Sources
- The Linux Audit system project page: http://people.redhat.com/sgrubb/audit/.
- Article Investigating kernel Return Codes with the Linux Audit System in the Hack In the Box magazine: http://magazine.hackinthebox.org/issues/HITB-Ezine-Issue-005.pdf.
Installed Documentation
/usr/share/doc/audit-version/
directory.
Manual Pages
- audispd.conf(5)
- auditd.conf(5)
- ausearch-expression(5)
- audit.rules(7)
- audispd(8)
- auditctl(8)
- auditd(8)
- aulast(8)
- aulastlog(8)
- aureport(8)
- ausearch(8)
- ausyscall(8)
- autrace(8)
- auvirt(8)
Chapter 8. Compliance and Vulnerability Scanning with OpenSCAP
8.1. Security Compliance in Red Hat Enterprise Linux
Security Compliance Tools Supported on Red Hat Enterprise Linux 6
- OpenSCAP — The oscap command-line utility is designed to perform configuration and vulnerability scans on a local system, to validate security compliance content, and to generate reports and guides based on these scans and evaluations.
- Script Check Engine (SCE) — SCE is an extension to SCAP protocol that allows content authors to write their security content using a scripting language, such as Bash, Python or Ruby. The SCE extension is provided with the openscap-engine-sce package.
- SCAP Security Guide (SSG) — The scap-security-guide package provides the latest collection of security polices for Linux systems.
Note
8.2. Defining Compliance Policy
SCAP Components
- Languages — This group consists of SCAP languages that define standard vocabularies and conventions for expressing compliance policy.
- The eXtensible Configuration Checklist Description Format (XCCDF) — A language designed to express, organize, and manage security guidance.
- Open Vulnerability and Assessment Language (OVAL) — A language developed to perform logical assertion about the state of the scanned system.
- Open Checklist Interactive Language (OCIL) — A language designed to provide a standard way to query users and interpret user responses to the given questions.
- Asset Identification (AI) — A language developed to provide a data model, methods, and guidance for identifying security assets.
- Asset Reporting Format (ARF) — A language designed to express the transport format of information about collected security assets and the relationship between assets and security reports.
- Enumerations — This group includes SCAP standards that define naming format and an official list or dictionary of items from certain security-related areas of interest.
- Common Configuration Enumeration (CCE) — An enumeration of security-relevant configuration elements for applications and operating systems.
- Common Platform Enumeration (CPE) — A structured naming scheme used to identify information technology (IT) systems, platforms, and software packages.
- Common Vulnerabilities and Exposures (CVE) — A reference method to a collection of publicly known software vulnerabilities and exposures.
- Metrics — This group comprises of frameworks to identify and evaluate security risks.
- Common Configuration Scoring System (CCSS) — A metric system to evaluate security-relevant configuration elements and assign them scores in order to help users to prioritize appropriate response steps.
- Common Vulnerability Scoring System (CVSS) — A metric system to evaluate software vulnerabilities and assign them scores in order to help users prioritize their security risks.
- Integrity — An SCAP specification to maintain integrity of SCAP content and scan results.
- Trust Model for Security Automation Data (TMSAD) — A set of recommendations explaining usage of existing specification to represent signatures, hashes, key information, and identity information in context of an XML file within a security automation domain.
8.2.1. The XCCDF File Format
Main XML Elements of the XCCDF Document
<xccdf:Benchmark>
— This is a root element that encloses the whole XCCDF document. It may also contain checklist metadata, such as a title, description, list of authors, date of the latest modification, and status of the checklist acceptance.<xccdf:Rule>
— This is a key element that represents a checklist requirement and holds its description. It may contain child elements that define actions verifying or enforcing compliance with the given rule or modify the rule itself.<xccdf:Value>
— This key element is used for expressing properties of other XCCDF elements within the benchmark.<xccdf:Group>
— This element is used to organize an XCCDF document to structures with the same context or requirement domains by gathering the<xccdf:Rule>
,<xccdf:Value>
, and<xccdf:Group>
elements.<xccdf:Profile>
— This element serves for a named tailoring of the XCCDF benchmark. It allows the benchmark to hold several different tailorings.<xccdf:Profile>
utilizes several selector elements, such as<xccdf:select>
or<xccdf:refine-rule>
, to determine which elements are going to be modified and processed while it is in effect.<xccdf:Tailoring>
— This element allows defining the benchmark profiles outside the benchmark, which is sometimes desirable for manual tailoring of the compliance policy.<xccdf:TestResult>
— This element serves for keeping the scan results for the given benchmark on the target system. Each<xccdf:TestResult>
should refer to the profile that was used to define the compliance policy for the particular scan and it should also contain important information about the target system that is relevant for the scan.<xccdf:rule-result>
— This is a child element of<xccdf:TestResult>
that is used to hold the result of applying a specific rule from the benchmark to the target system.<xccdf:fix>
— This is a child element of<xccdf:Rule>
that serves for remediation of the target system that is not compliant with the given rule. It can contain a command or script that is run on the target system in order to bring the system into compliance the rule.<xccdf:check>
— This is a child element of<xccdf:Rule>
that refers to an external source which defines how to evaluate the given rule.<xccdf:select>
— This is a selector element that is used for including or excluding the chosen rules or groups of rules from the policy.<xccdf:set-value>
— This is a selector element that is used for overwriting the current value of the specified<xccdf:Value>
element without modifying any of its other properties.<xccdf:refine-value>
— This is a selector element that is used for specifying constraints of the particular<xccdf:Value>
element during policy tailoring.<xccdf:refine-rule>
— This selector element allows overwriting properties of the selected rules.
Example 8.1. An Example of an XCCDF Document
<?xml version="1.0" encoding="UTF-8"?> <Benchmark xmlns="http://checklists.nist.gov/xccdf/1.2" id="xccdf_com.example.www_benchmark_test"> <status>incomplete</status> <version>0.1</version> <Profile id="xccdf_com.example.www_profile_1"> <title>Profile title is compulsory</title> <select idref="xccdf_com.example.www_group_1" selected="true"/> <select idref="xccdf_com.example.www_rule_1" selected="true"/> <refine-value idref="xccdf_com.example.www_value_1" selector="telnet service"/> </Profile> <Group id="xccdf_com.example.www_group_1"> <Value id="xccdf_com.example.www_value_1"> <value selector="telnet_service">telnet-server</value> <value selector="dhcp_servide">dhcpd</value> <value selector="ftp_service">tftpd</value> </Value> <Rule id="xccdf_com.example.www_rule_1"> <title>The telnet-server Package Shall Not Be Installed </title> <rationale> Removing the telnet-server package decreases the risk of the telnet service’s accidental (or intentional) activation </rationale> <fix platform="cpe:/o:redhat:enterprise_linux:6" reboot="false" disruption="low" system="urn:xccdf:fix:script:sh"> yum -y remove <sub idref="xccdf_com.example.www_value_1"/> </fix> <check system="http://oval.mitre.org/XMLSchema/oval-definitions-5"> <check-export value-id="xccdf_com.example.www_value_1" export-name="oval:com.example.www:var:1"/> <check-content-ref href="examplary.oval.xml" name="oval:com.example.www:def:1"/> </check> <check system="http://open-scap.org/page/SCE"> <check-import import-name="stdout"/> <check-content-ref href="telnet_server.sh"/> </check> </Rule> </Group> </Benchmark>
8.2.2. The OVAL File Format
- Representation of the target system configuration.
- Analysis of the target system for the presence of a particular machine state.
- Reporting the results of the comparison between the specified machine state and the observed machine state.
The OVAL Document Formats
- The OVAL Definitions format is the most common OVAL file format that is used directly for system scans. The OVAL Definitions document describes the desired state of the target system.
- The OVAL Variables format defines variables used to amend the OVAL Definitions document. The OVAL Variables document is typically used in conjunction with the OVAL Definitions document to tailor the security content for the target system at runtime.
- The OVAL System Characteristics format holds information about the assessed system. The OVAL System Characteristics document is typically used to compare the actual state of the system against the expected state defined by an OVAL Definitions document.
- The OVAL Results is the most comprehensive OVAL format that is used to report results of the system evaluation. The OVAL Results document typically contains copy of the evaluated OVAL definitions, bound OVAL variables, OVAL system characteristics, and results of tests that are computed based on comparison of the system characteristics and the definitions.
- The OVAL Directives format is used to tailor verbosity of an OVAL Result document by either including or excluding certain details.
- The OVAL Common Model format contains definitions of constructs and enumerations used in several other OVAL schemes. It is used to reuse OVAL definitions in order to avoid duplications across multiple documents.
oval:namespace:type:ID
Example 8.2. An Example of an OVAL Definitions Document
<?xml version="1.0" encoding="utf-8"?> <oval_definitions xmlns:lin-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#linux" xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <generator> <oval:product_name>vim</oval:product_name> <oval:schema_version>5.10.1</oval:schema_version> <oval:timestamp>2012-11-22T15:00:00+01:00</oval:timestamp> </generator> <definitions> <definition class="inventory" id="oval:org.open-scap.cpe.rhel:def:6" version="1"> <metadata> <title>Red Hat Enterprise Linux 6</title> <affected family="unix"> <platform>Red Hat Enterprise Linux 6</platform> </affected> <reference ref_id="cpe:/o:redhat:enterprise_linux:6" source="CPE"/> <description> The operating system installed on the system is Red Hat Enterprise Linux 6 </description> </metadata> <criteria> <criterion comment="Red Hat Enterprise Linux 6 is installed" test_ref="oval:org.open-scap.cpe.rhel:tst:6"/> </criteria> </definition> </definitions> <tests> <lin-def:rpminfo_test check_existence="at_least_one_exists" id="oval:org.open-scap.cpe.rhel:tst:6" version="1" check="at least one" comment="redhat-release is version 6"> <lin-def:object object_ref="oval:org.open-scap.cpe.redhat-release:obj:1"/> <lin-def:state state_ref="oval:org.open-scap.cpe.rhel:ste:6"/> </lin-def:rpminfo_test> </tests> <objects> <lin-def:rpmverifyfile_object id="oval:org.open-scap.cpe.redhat-release:obj:1" version="1"> <!-- This object represents rpm package which owns /etc/redhat-release file --> <lin-def:behaviors nolinkto='true' nomd5='true' nosize='true' nouser='true' nogroup='true' nomtime='true' nomode='true' nordev='true' noconfigfiles='true' noghostfiles='true' /> <lin-def:name operation="pattern match"/> <lin-def:epoch operation="pattern match"/> <lin-def:version operation="pattern match"/> <lin-def:release operation="pattern match"/> <lin-def:arch operation="pattern match"/> <lin-def:filepath>/etc/redhat-release</lin-def:filepath> </lin-def:rpmverifyfile_object> </objects> <states> <lin-def:rpminfo_state id="oval:org.open-scap.cpe.rhel:ste:6" version="1"> <lin-def:name operation="pattern match">^redhat-release</lin-def:name> <lin-def:version operation="pattern match">^6[^\d]</lin-def:version> </lin-def:rpminfo_state> </states> </oval_definitions>
8.2.3. The Data Stream Format
<ds:component>
elements. Each of these elements encompasses an SCAP component such as XCCDF, OVAL, CPE, and other. The data stream file may contain multiple components of the same type, and thus covering all security policies needed by your organization.
Example 8.3. An Example of a Data Stream Header
<ds:data-stream-collection xmlns:ds="http://scap.nist.gov/schema/scap/source/1.2" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:cat="urn:oasis:names:tc:entity:xmlns:xml:catalog" id="scap_org.open-scap_collection_from_xccdf_ssg-rhel6-xccdf-1.2.xml" schematron-version="1.0"> <ds:data-stream id="scap_org.open-scap_datastream_from_xccdf_ssg-rhel6-xccdf-1.2.xml" scap-version="1.2" use-case="OTHER"> <ds:dictionaries> <ds:component-ref id="scap_org.open-scap_cref_output--ssg-rhel6-cpe-dictionary.xml" xlink:href="#scap_org.open-scap_comp_output--ssg-rhel6-cpe-dictionary.xml"> <cat:catalog> <cat:uri name="ssg-rhel6-cpe-oval.xml" uri="#scap_org.open-scap_cref_output--ssg-rhel6-cpe-oval.xml"/> </cat:catalog> </ds:component-ref> </ds:dictionaries> <ds:checklists> <ds:component-ref id="scap_org.open-scap_cref_ssg-rhel6-xccdf-1.2.xml" xlink:href="#scap_org.open-scap_comp_ssg-rhel6-xccdf-1.2.xml"> <cat:catalog> <cat:uri name="ssg-rhel6-oval.xml" uri="#scap_org.open-scap_cref_ssg-rhel6-oval.xml"/> </cat:catalog> </ds:component-ref> </ds:checklists> <ds:checks> <ds:component-ref id="scap_org.open-scap_cref_ssg-rhel6-oval.xml" xlink:href="#scap_org.open-scap_comp_ssg-rhel6-oval.xml"/> <ds:component-ref id="scap_org.open-scap_cref_output--ssg-rhel6-cpe-oval.xml" xlink:href="#scap_org.open-scap_comp_output--ssg-rhel6-cpe-oval.xml"/> <ds:component-ref id="scap_org.open-scap_cref_output--ssg-rhel6-oval.xml" xlink:href="#scap_org.open-scap_comp_output--ssg-rhel6-oval.xml"/> </ds:checks> </ds:data-stream> <ds:component id="scap_org.open-scap_comp_ssg-rhel6-oval.xml" timestamp="2014-03-14T16:21:59"> <oval_definitions xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns:ind="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent" xmlns:unix="http://oval.mitre.org/XMLSchema/oval-definitions-5#unix" xmlns:linux="http://oval.mitre.org/XMLSchema/oval-definitions-5#linux" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://oval.mitre.org/XMLSchema/oval-common-5 oval-common-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5 oval-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5#independent independent-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5#unix unix-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5#linux linux-definitions-schema.xsd">
8.3. Using SCAP Workbench
8.3.1. Installing SCAP Workbench
root
:
~]# yum install scap-workbench
~]#
yum install scap-security-guide
/usr/share/xml/scap/ssg/content/
directory, and you can proceed with other security compliance operations.
8.3.2. Running SCAP Workbench
scap-workbench
, and then press Enter. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar key.

Figure 8.1. Open SCAP Security Guide Window
- File
- This menu list offers several options to load or save a SCAP-related content. To show the initial Open SCAP Security Guide window, click the menu item with the same name. Alternatively, load another customization file in the XCCDF format by clicking Open Other Content. To save your customization as an XCCDF XML file, use the Save Customization Only item. The Save All allows you to save SCAP files either to the selected directory or as an RPM package.
- Customization
- This combo box informs you about the customization used for the given security policy. You can select custom rules that will be applied for the system evaluation by clicking this combo box. The default value is (no customization), which means that there will be no changes to the used security policy. If you made any changes to the selected security profile, you can save those changes as an XML file by clicking the Save Customization Only item in the File menu.
- Profile
- This combo box contains the name of the selected security profile. You can select the security profile from a given XCCDF or data-stream file by clicking this combo box. To create a new profile that inherits properties of the selected security profile, click the Customize button.
- Target
- The two radio buttons enable you to select whether the system to be evaluated is a local or remote machine.
- Selected Rules
- This field displays a list of security rules that are subject of the security policy. Expanding a particular security rule provides detailed information about that rule.
- Status bar
- This is a graphical bar that indicates status of an operation that is being performed.
- Fetch remote resources
- This check box allows to instruct the scanner to download a remote OVAL content defined in an XML file.
- Remediate
- This check box enables the remediation feature during the system evaluation. If you check this box, SCAP Workbench will attempt to correct system settings that would fail to match the state defined by the policy.
- Scan
- This button allows you to start the evaluation of the specified system.

Figure 8.2. SCAP Workbench Window
8.3.3. Scanning the System
- Select a security policy by using either the Open SCAP Security Guide window, or
Open Other Content
in the File menu and search the respective XCCDF, SCAP RPM or data stream file.Warning
Selecting a security policy results in the loss of any previous customization changes that were not saved. To re-apply the lost options, you have to choose the available profile and customization content again. Note that your previous customizations may not be applicable with the new security policy. - To use a pre-arranged a file with customized security content specific to your use case, you can load this file by clicking on the Customization combo box. You can also create a custom tailoring file by altering an available security profile. For more information, see Section 8.3.4, “Customizing Security Profiles”.
- Select the
(no customization)
option if you do not want to use any customization for the current system evaluation. This is the default option if no previous customization was selected. - Select the
(open customization file...)
option to search for the particular tailoring file to be used for the current system evaluation. - If you have previously used some customization file, SCAP Workbench remembers this file and adds it to the list. This simplifies repetitive application of the same scan.
- Select a suitable security profile by clicking the Profile combo box.
- To modify the selected profile, click the Customize button. For more information about profile customization, see Section 8.3.4, “Customizing Security Profiles”.
- Select either of two Target radio buttons to scan either a local or a remote machine.
- If you have selected a remote system, specify it by entering the user name, host name, and the port information as shown in the following example. If you have previously used the remote scan, you can also select a remote system from a list of recently scanned machines.
Figure 8.3. Specifying a Remote System
- You can allow automatic correction of the system configuration by selecting the Remediate check box. With this option enabled, SCAP Workbench attempts to change the system configuration in accordance with the security rules applied by the policy, should the related checks fail during the system scan.
Warning
If not used carefully, running the system evaluation with the remediation option enabled could render the system non-functional. - Click the Scan button to initiate the system scan.
8.3.4. Customizing Security Profiles

Figure 8.4. Customizing the Selected Security Profile
Modify value
field.

Figure 8.5. Setting a value for the selected item in the Customization window
8.3.5. Saving SCAP Content
Save into a directory
or Save as RPM
options.
Save into a directory
option, SCAP Workbench saves both the XCCDF or data-stream file and the customization file to the specified location. This can be useful as a backup solution.
Save as RPM
option, you can instruct SCAP Workbench to create an RPM package containing the XCCDF or data stream file and customization file. This is useful for distributing the desired security content to systems that cannot be scanned remotely, or just for delivering the content for further processing.

Figure 8.6. Saving the Current SCAP Content as an RPM Package
8.3.6. Viewing Scan Results and Generating Scan Reports
Warning
HTML Report
option to generate the scan report in human-readable form. The XCCDF and ARF (data stream) formats are suitable for further automatic processing. You can repeatedly choose all three options.
8.4. Using oscap
--help
option with an oscap command:
oscap [options] module module_operation [module_operation_options_and_arguments] --help
Example 8.4. Getting Help on the Specific oscap Operation
~]$ oscap ds sds-split --help
oscap -> ds -> sds-split
Split given SourceDataStream into separate files
Usage: oscap [options] ds sds-split [options] SDS TARGET_DIRECTORY
SDS - Source data stream that will be split into multiple files.
TARGET_DIRECTORY - Directory of the resulting files.
Options:
--datastream-id <id> - ID of the datastream in the collection to use.
--xccdf-id <id> - ID of XCCDF in the datastream that should be evaluated.
oscap(8)
manual page.
8.4.1. Installing oscap
root
:
~]# yum install openscap-scanner
rhel-6-variant-optional-rpms
repository as described in the Yum chapter of Red Hat Enterprise Linux 6 Deployment Guide, where variant is your Red Hat Enterprise Linux variant, such as server, or workstation. If your system is registered with RHN Classic, subscribe the system to the rhel-architecture-variant-6-optional
channel as documented here: https://access.redhat.com/site/solutions/9907.
~]$ oscap -V
OpenSCAP command line tool (oscap) 1.0.8
Copyright 2009--2014 Red Hat Inc., Durham, North Carolina.
==== Supported specifications ====
XCCDF Version: 1.2
OVAL Version: 5.10.1
CPE Version: 2.3
CVSS Version: 2.0
CVE Version: 2.0
Asset Identification Version: 1.1
Asset Reporting Format Version: 1.1
==== Capabilities added by auto-loaded plugins ====
SCE Version: 1.0 (from libopenscap_sce.so.8)
==== Paths ====
Schema files: /usr/share/openscap/schemas
Schematron files: /usr/share/openscap/xsl
Default CPE files: /usr/share/openscap/cpe
Probes: /usr/libexec/openscap
==== Inbuilt CPE names ====
Red Hat Enterprise Linux - cpe:/o:redhat:enterprise_linux
Red Hat Enterprise Linux 5 - cpe:/o:redhat:enterprise_linux:5
Red Hat Enterprise Linux 6 - cpe:/o:redhat:enterprise_linux:6
Red Hat Enterprise Linux 7 - cpe:/o:redhat:enterprise_linux:7
Fedora 16 - cpe:/o:fedoraproject:fedora:16
Fedora 17 - cpe:/o:fedoraproject:fedora:17
Fedora 18 - cpe:/o:fedoraproject:fedora:18
Fedora 19 - cpe:/o:fedoraproject:fedora:19
Fedora 20 - cpe:/o:fedoraproject:fedora:20
Fedora 21 - cpe:/o:fedoraproject:fedora:21
Red Hat Enterprise Linux Optional Productivity Applications - cpe:/a:redhat:rhel_productivity
Red Hat Enterprise Linux Optional Productivity Applications 5 - cpe:/a:redhat:rhel_productivity:5
==== Supported OVAL objects and associated OpenSCAP probes ====
system_info probe_system_info
family probe_family
filehash probe_filehash
environmentvariable probe_environmentvariable
textfilecontent54 probe_textfilecontent54
textfilecontent probe_textfilecontent
variable probe_variable
xmlfilecontent probe_xmlfilecontent
environmentvariable58 probe_environmentvariable58
filehash58 probe_filehash58
inetlisteningservers probe_inetlisteningservers
rpminfo probe_rpminfo
partition probe_partition
iflisteners probe_iflisteners
rpmverify probe_rpmverify
rpmverifyfile probe_rpmverifyfile
rpmverifypackage probe_rpmverifypackage
selinuxboolean probe_selinuxboolean
selinuxsecuritycontext probe_selinuxsecuritycontext
file probe_file
interface probe_interface
password probe_password
process probe_process
runlevel probe_runlevel
shadow probe_shadow
uname probe_uname
xinetd probe_xinetd
sysctl probe_sysctl
process58 probe_process58
fileextendedattribute probe_fileextendedattribute
routingtable probe_routingtable
~]# yum install scap-security-guide
/usr/share/xml/scap/ssg/content/
directory, and you can proceed with other security compliance operations.
8.4.2. Displaying SCAP Content
info
module of oscap which parses the file and extracts relevant information in human-readable format.
oscap info
file
oscap info
command:
Example 8.5. Displaying Information About SCAP Content
~]$ oscap info /usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
Document type: Source Data Stream
Imported: 2014-08-28T15:41:34
Stream: scap_org.open-scap_datastream_from_xccdf_ssg-rhel6-xccdf-1.2.xml
Generated: (null)
Version: 1.2
Checklists:
Ref-Id: scap_org.open-scap_cref_ssg-rhel6-xccdf-1.2.xml
Profiles:
xccdf_org.ssgproject.content_profile_test
xccdf_org.ssgproject.content_profile_CS2
xccdf_org.ssgproject.content_profile_common
xccdf_org.ssgproject.content_profile_server
xccdf_org.ssgproject.content_profile_stig-rhel6-server-upstream
xccdf_org.ssgproject.content_profile_usgcb-rhel6-server
xccdf_org.ssgproject.content_profile_rht-ccp
xccdf_org.ssgproject.content_profile_CSCF-RHEL6-MLS
xccdf_org.ssgproject.content_profile_C2S
Referenced check files:
ssg-rhel6-oval.xml
system: http://oval.mitre.org/XMLSchema/oval-definitions-5
Checks:
Ref-Id: scap_org.open-scap_cref_ssg-rhel6-oval.xml
Ref-Id: scap_org.open-scap_cref_output--ssg-rhel6-cpe-oval.xml
Ref-Id: scap_org.open-scap_cref_output--ssg-rhel6-oval.xml
Dictionaries:
Ref-Id: scap_org.open-scap_cref_output--ssg-rhel6-cpe-dictionary.xml
8.4.3. Scanning the System
oscap [options] module eval [module_operation_options_and_arguments]
XCCDF
(The eXtensible Configuration Checklist Description Format) benchmark and OVAL
(Open Vulnerability and Assessment Language) definitions. The security policy can have a form of a single OVAL or XCCDF file or multiple separate XML files where each file represents a different component (XCCDF, OVAL, CPE, CVE, and others). The result of a scan can be printed to both, standard output and an XML file. The result file can be then further processed by oscap in order to generate a report in a human-readable format. The following examples illustrate the most common usage of the command.
Example 8.6. Scanning the System Using the SSG OVAL definitions
~]$ oscap oval eval --results
scan-oval-results.xml
/usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
scan-oval-results.xml
file in the current directory.
Example 8.7. Scanning the System Using the SSG OVAL definitions
~]$ oscap oval eval --id
oval:ssg:def:100 --results
scan-oval-results.xml
/usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
scan-oval-results.xml
file in the current directory.
Example 8.8. Scanning the System Using the SSG XCCDF benchmark
xccdf_org.ssgproject.content_profile_rht-ccp
profile on your system, run the following command:
~]$ oscap xccdf eval --profile
xccdf_org.ssgproject.content_profile_rht-ccp --results
scan-xccdf-results.xml
/usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
scan-xccdf-results.xml
file in the current directory.
Note
--profile
command-line argument selects the security profile from the given XCCDF or data stream file. The list of available profiles can be obtained by running the oscap info
command. If the --profile
command-line argument is omitted the default XCCDF profile is used as required by SCAP standard. Note that the default XCCDF profile may or may not be an appropriate security policy.
8.4.4. Generating Reports and Guides
oscap module generate sub-module [specific_module/sub-module_options_and_arguments] file
xccdf
or oval
, sub-module is a type of the generated document, and file represents an XCCDF or OVAL file.
Example 8.9. Generating a Guide with a Checklist
xccdf_org.ssgproject.content_profile_rht-ccp
profile, run the following command:
~]$ oscap xccdf generate guide --profile
xccdf_org.ssgproject.content_profile_rht-ccp
/usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
> ssg-guide-checklist.html
ssg-guide-checklist.html
file in the current directory.
Example 8.10. Transforming an SSG OVAL Scan Result into a Report
~]$oscap oval generate report
scan-oval-results.xml
>
ssg-scan-oval-report.html
ssg-scan-oval-report.html
file in the current directory. This example assumes that you run the command from the same location where the scan-oval-results.xml
file is stored. Otherwise you need to specify the fully-qualified path of the file that contains the scan results.
Example 8.11. Transforming an SSG XCCDF Scan Result into a Report
~]$oscap xccdf generate report
scan-xccdf-results.xml
>
scan-xccdf-report.html
ssg-scan-xccdf-report.html
file in the current directory. Alternatively, you can generate this report in the time of the scan using the --report
command-line argument:
~]$ oscap xccdf eval --profile
xccdf_org.ssgproject.content_profile_rht-ccp --results
scan-xccdf-results.xml
--report
scan-xccdf-report.html
/usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
8.4.5. Validating SCAP Content
oscap module validate
[module_options_and_arguments] file
ds
), which uses the sds-validate
operation instead of validate
. Note that all SCAP components within the given data stream are validated automatically, and none of the components is specified separately, as can be seen in the following example:
~]$ oscap ds
sds-validate
/usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
~]$ oscap oval validate --schematron
/usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
8.4.6. Using OpenSCAP to Remediate the System
- OpenSCAP performs a regular XCCDF evaluation.
- An assessment of the results is performed by evaluating the OVAL definitions. Each rule that has failed is marked as a candidate for remediation.
- OpenSCAP searches for an appropriate fix element, resolves it, prepares the environment, and executes the fix script.
- Any output of the fix script is captured by OpenSCAP and stored within the
rule-result
element. The return value of the fix script is stored as well. - Whenever OpenSCAP executes a fix script, it immediatelly evaluates the OVAL definition again (to verify that the fix script has been applied correctly). During this second run, if the OVAL evaluation returns success, the result of the rule is
fixed
, otherwise it is anerror
. - Detailed results of the remediation are stored in an output XCCDF file. It contains two
TestResult
elements. The firstTestResult
element represents the scan prior to the remediation. The secondTestResult
is derived from the first one and contains remediation results.
8.4.6.1. OpenSCAP Online Remediation
--remediate
command-line option. For example, to execute online remediation using the scap-security-guide package, run:
~]$
oscap xccdf eval --remediate --profile xccdf_org.ssgproject.content_profile_rht-ccp --results scan-xccdf-results.xml /usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
fixed
and error
results. The fixed
result indicates that the scan performed after the remediation passed. The error
result indicates that even after applying the remediation, the evaluation still does not pass.
8.4.6.2. OpenSCAP Offline Remediation
TestResult
element in an XCCDF file.
oscap
executes the fix scripts and verifies the result. It is safe to store the results into the input file, no data will be lost. During offline remediation, OpenSCAP creates a new TestResult
element that is based on the input one and inherits all the data. The newly created TestResult
differs only in the rule-result
elements that have failed. For those, remediation is executed.
~]$
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_rht-ccp --results scan-xccdf-results.xml /usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
~]$
oscap xccdf remediate --results scan-xccdf-results.xml scan-xccdf-results.xml
8.4.6.3. OpenSCAP Remediation Review
~]$
oscap xccdf generate fix --template urn:xccdf:fix:script:sh --profile xccdf_org.ssgproject.content_profile_rht-ccp --output my-remediation-script.sh /usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
8.5. Using OpenSCAP with Red Hat Satellite
OpenSCAP Satellite Web Interface
or run commands and scripts from the Satellite API
. For more information about this solution to security compliance, its requirements and capabilities, see the Red Hat Satellite documentation.
8.6. Installing USGCB-Compliant System with Kickstart
/usr/share/scap-security-guide/kickstart/ssg-rhel6-usgcb-server-with-gui-ks.cfg
8.7. Practical Examples
8.7.1. Auditing Security Vulnerabilities of Red Hat Products
~]$ wget http://www.redhat.com/security/data/oval/com.redhat.rhsa-all.xml
~]$ wget http://www.redhat.com/security/data/metrics/com.redhat.rhsa-all.xccdf.xml
~]$ oscap oval eval --results rhsa-results-oval.xml --report oval-report.html com.redhat.rhsa-all.xml
Note
8.7.2. Auditing System Settings with SCAP Security Guide
oscap info
module:
~]$ oscap info /usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
~]$ oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_rht-ccp --results ssg-rhel6-xccdf-result.xml --report ssg-rhel6-report.html /usr/share/xml/scap/ssg/content/ssg-rhel6-ds.xml
8.8. Additional Resources
Installed Documentation
oscap
(8) — The manual page for the oscap command-line utility provides a complete list of available options and their usage explanation.- Guide to the Secure Configuration of Red Hat Enterprise Linux 6 — An HTML document located in the
/usr/share/doc/scap-security-guide-0.1.18/
directory that provides a detailed guide for security settings of your system in form of an XCCDF checklist.
Online Documentation
- The OpenSCAP project page — The home page to the OpenSCAP project provides detailed information about the oscap utility and other components and projects related to SCAP.
- The SCAP Workbench project page — The home page to the SCAP Workbench project provides detailed information about the scap-workbench application.
- The SCAP Security Guide (SSG) project page — The home page to the SSG project that provides the latest security content for Red Hat Enterprise Linux.
- National Institute of Standards and Technology (NIST) SCAP page — This page represents a vast collection of SCAP related materials, including SCAP publications, specifications, and the SCAP Validation Program.
- National Vulnerability Database (NVD) — This page represents the largest repository of SCAP content and other SCAP standards based vulnerability management data.
- Red Hat OVAL content repository — This is a repository containing OVAL definitions for Red Hat Enterprise Linux systems.
- MITRE CVE — This is a database of publicly known security vulnerabilities provided by the MITRE corporation.
- MITRE OVAL — This page represents an OVAL related project provided by the MITRE corporation. Amongst other OVAL related information, these pages contain the latest version of the OVAL language and a huge repository of OVAL content, counting over 22 thousands OVAL definitions.
- Red Hat Satellite documentation — This set of guides describes, amongst other topics, how to maintain system security on multiple systems by using OpenSCAP.
Chapter 9. Checking Integrity with AIDE
9.1. Introduction
9.2. Installing AIDE
root
:
~]# yum install aide
root
:
~]# aide --init
AIDE, version 0.14
### AIDE database at /var/lib/aide/aide.db.new.gz initialized.
Note
aide --init
command checks just a set of directories and files defined in the /etc/aide.conf
file. To include additional directories or files in the AIDE database, and to change their watched parameters, edit /etc/aide.conf
accordingly.
.new
substring from the initial database file name:
~]# mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
/etc/aide.conf
file and modify the DBDIR
value. For additional security, store the database, configuration, and the /usr/sbin/aide
binary file in a secure location such as a read-only media.
Important
9.3. Performing Integrity Checks
root
:
~]# aide --check
AIDE found differences between database and filesystem!!
Start timestamp: 2017-04-07 17:11:33
Summary:
Total number of files: 104892
Added files: 7
Removed files: 0
Changed files: 52
...
cron
(see the Automating System Tasks chapter in the System Administrator's Guide), add the following line to /etc/crontab
:
05 4 * * * root /usr/sbin/aide --check
9.4. Updating an AIDE Database
~]# aide --update
aide --update
command creates the /var/lib/aide/aide.db.new.gz
database file. To start using it for integrity checks, remove the .new
substring from the file name.
9.5. Additional Resources
aide(1)
man pageaide.conf(5)
man page
Chapter 10. Federal Standards and Regulations
10.1. Introduction
10.2. Federal Information Processing Standard (FIPS)
- Level 1 – Security Level 1 provides the lowest level of security. Basic security requirements are specified for a cryptographic module (e.g., at least one Approved algorithm or Approved security function shall be used). No specific physical security mechanisms are required in a Security Level 1 cryptographic module beyond the basic requirement for production-grade components. An example of a Security Level 1 cryptographic module is a personal computer (PC) encryption board.
- Level 2 – Security Level 2 enhances the physical security mechanisms of a Security Level 1 cryptographic module by adding the requirement for tamper-evidence, which includes the use of tamper-evident coatings or seals or for pick-resistant locks on removable covers or doors of the module. Tamper-evident coatings or seals are placed on a cryptographic module so that the coating or seal must be broken to attain physical access to the plain text cryptographic keys and critical security parameters (CSPs) within the module. Tamper-evident seals or pick-resistant locks are placed on covers or doors to protect against unauthorized physical access.
- Level 3 – In addition to the tamper-evident physical security mechanisms required at Security Level 2, Security Level 3 attempts to prevent the intruder from gaining access to CSPs held within the cryptographic module. Physical security mechanisms required at Security Level 3 are intended to have a high probability of detecting and responding to attempts at physical access, use or modification of the cryptographic module. The physical security mechanisms may include the use of strong enclosures and tamper detection/response circuitry that zeroes all plain text CSPs when the removable covers/doors of the cryptographic module are opened.
- Level 4 – Security Level 4 provides the highest level of security defined in this standard. At this security level, the physical security mechanisms provide a complete envelope of protection around the cryptographic module with the intent of detecting and responding to all unauthorized attempts at physical access. Penetration of the cryptographic module enclosure from any direction has a very high probability of being detected, resulting in the immediate zeroization of all plain text CSPs. Security Level 4 cryptographic modules are useful for operation in physically unprotected environments.
10.2.1. Enabling FIPS Mode
- For proper operation of the in-module integrity verification, the prelink has to be disabled. This can be done by setting
PRELINKING=no
in the/etc/sysconfig/prelink
configuration file. Existing prelinking, if any, should be undone on all system files using theprelink -u -a
command. - Next, install the dracut-fips package:
~]#
yum install dracut-fips
Note
FIPS integrity verification is performed when the dracut-fips package is present on the system, regardless of whether the system operates in FIPS mode or not. However, the integrity verification results are ignored (or only logged) if the system or a shared library is not in FIPS mode, even when dracut-fips is present. - Recreate the
initramfs
file (this operation will overwrite the existinginitramfs
file):~]#
dracut -f
- Modify the kernel command line of the current kernel in the
/boot/grub/grub.conf
file by adding the following option:fips=1
If the/boot
or/boot/efi/
directories are located on a separate partition, theboot=partition
kernel parameter must be added to the kernel command line. Replace partition with the partition that contains the/boot
or/boot/efi/
directory. Partitions can be identified using thedf
command. For example:~]$
df /boot
Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 495844 53780 416464 12% /bootIn the example above, the/boot
directory is located on/dev/sda1
. Therefore, the following string needs to be appended to the kernel command line:boot=/dev/sda1
- Reboot your system.
/etc/ssh/sshd_config
file in FIPS mode. If your /etc/ssh/sshd_config
contains any other ciphers and MACs, modify it to only use algorithms supported in FIPS mode. To do that, use the following configuration or a subset thereof:
Protocol 2 Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc Macs hmac-sha1,hmac-sha2-256,hmac-sha2-512
fips=1
kernel option needs to be added to the kernel command line during system installation so that key generation is done with FIPS approved algorithms and continuous monitoring tests in place. Users should also ensure that the system has plenty of entropy during the installation process by moving the mouse around, or if no mouse is available, ensuring that many keystrokes are typed. The recommended amount of keystrokes is 256 and more. Less than 256 keystrokes may generate a non-unique key.
10.2.2. Enabling FIPS Mode for Applications Using NSS
~]# modutil -fips
true -dbdir
dir
/etc/pki/nssdb
file, the path to the user NSS database is ~/.pki/nssdb
.
10.3. National Industrial Security Program Operating Manual (NISPOM)
10.4. Payment Card Industry Data Security Standard (PCI DSS)
10.5. Security Technical Implementation Guide
Chapter 11. References
Books
- SELinux by Example
- Mayer, MacMillan, and CaplanPrentice Hall, 2007
Tutorials and Help
- Tutorials and talks from Russell Coker
- Generic Writing SELinux policy HOWTO
- Red Hat Knowledgebase
General Information
- NSA SELinux main website
- SELinux NSA's Open Source Security Enhanced Linux
Technology
- Integrating Flexible Support for Security Policies into the Linux Operating System (a history of Flask implementation in Linux)
- A Security Policy Configuration for the Security-Enhanced Linux
Community
- SELinux community page
- IRC
- irc.freenode.net, #selinux, #fedora-selinux, #security
History
- Quick history of Flask
- Full background on Fluke