Chapter 4. Workstation Security
Securing a Linux environment begins with the workstation. Whether locking down a personal machine or securing an enterprise system, sound security policy begins with the individual computer. After all, a computer network is only as secure as its weakest node.
4.1. Evaluating Workstation Security
When evaluating the security of a Red Hat Enterprise Linux workstation, consider the following:
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?
4.2. BIOS and Boot Loader Security
Password protection for the BIOS (or BIOS equivalent) and the boot loader can prevent unauthorized users who have physical access to systems from booting using removable media or attaining root privileges through single user mode. But the security measures one should take to protect against such attacks depends both on the sensitivity of the information the workstation holds and the location of the machine.
For instance, if a machine is used in a trade show and contains no sensitive information, than it may not be critical to prevent such attacks. However, if an employee's laptop with private, unencrypted SSH keys for the corporate network is left unattended at that same trade show, it could lead to a major security breach with ramifications for the entire company.
On the other hand, if the workstation is located in a place where only authorized or trusted people have access, then securing the BIOS or the boot loader may not be necessary at all.
The following are the two primary reasons for password protecting the BIOS of a computer[]:
Preventing Changes to BIOS Settings — If an intruder has access to the BIOS, they can set it to boot from a diskette or CD-ROM. This makes it possible for them 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.
Because the methods for setting a BIOS password vary between computer manufacturers, consult the computer's manual for specific instructions.
If you forget the BIOS password, it can either be reset with jumpers on the motherboard or by disconnecting the CMOS battery. For this reason, it is good practice to lock the computer case if possible. However, consult the manual for the computer or motherboard before attempting to disconnect the CMOS battery.
4.2.1.1. Securing Non-x86 Platforms
Other architectures use different programs to perform low-level tasks roughly equivalent to those of the BIOS on x86 systems. For instance, Intel® Itanium™ computers use the Extensible Firmware Interface (EFI) shell.
For instructions on password protecting BIOS-like programs on other architectures, refer to the manufacturer's instructions.
4.2.2. Boot Loader Passwords
The following are the primary reasons for password protecting a Linux boot loader:
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.
Preventing Access to the GRUB Console — If the machine uses GRUB as its boot loader, an attacker can use the use the GRUB editor interface to change its configuration or to gather information using the cat command.
Preventing Access to Non-Secure Operating Systems — If it is a dual-boot system, an attacker can select at boot time an operating system, such as DOS, which ignores access controls and file permissions.
The GRUB boot loader ships with Red Hat Enterprise Linux on the x86 platform. For a detailed look at GRUB, consult the chapter titled The GRUB Boot Loader in the Reference Guide.
4.2.2.1. Password Protecting GRUB
GRUB can be configured to address the first two issues listed in
Section 4.2.2, “Boot Loader Passwords” by adding a password directive to its configuration file. To do this, first decide on a password, then open a shell prompt, log in as root, and type:
/sbin/grub-md5-crypt
When prompted, type the GRUB password and press Enter. This returns an MD5 hash of the password.
Next, edit the GRUB configuration file /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>
Replace <password-hash> with the value returned by /sbin/grub-md5-crypt[].
The next time the system boots, the GRUB menu does not allow access to the editor or command interface without first pressing p followed by the GRUB password.
Unfortunately, this solution does not prevent an attacker from booting into a non-secure operating system in a dual-boot environment. For this, a different part of the /boot/grub/grub.conf file must be edited.
Look for the title line of the non-secure operating system and add a line that says lock directly beneath it.
For a DOS system, the stanza should begin similar to the following:
title DOS
lock
A 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.
To create a different password for a particular kernel or operating system, add a lock line to the stanza, followed by a password line.
Each stanza protected with a unique password should begin with lines similar to the following example:
title DOS
lock
password --md5 <password-hash>
Passwords are the primary method Red Hat Enterprise Linux uses to verify a user's identity. This is why password security is enormously important for protection of the user, the workstation, and the network.
For security purposes, the installation program configures the system to use Message-Digest Algorithm (MD5) and shadow passwords. It is highly recommended that you do not alter these settings.
If MD5 passwords are deselected during installation, the older Data Encryption Standard (DES) format is used. This format limits passwords to eight alphanumeric character passwords (disallowing punctuation and other special characters) and provides a modest 56-bit level of encryption.
If shadow passwords are deselected during installation, all passwords are stored as a one-way hash in the world-readable /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 cracker discovers it.
Shadow passwords eliminate this type of attack by storing the password hashes in the file /etc/shadow, which is readable only by the root user.
This forces a potential attacker to attempt password cracking remotely by logging into a network service on the machine, such as SSH or FTP. This sort of brute-force attack is much slower and leaves an obvious trail as hundreds of failed login attempts are written to system files. Of course, if the cracker starts an attack in the middle of the night on a system with weak passwords, the cracker may have gained access before dawn and edited the log files to cover his tracks.
Beyond matters of format and storage is the issue of content. The single most important thing a user can do to protect his account against a password cracking attack is create a strong password.
4.3.1. Creating Strong Passwords
When creating a secure password, it is a good idea to follow these guidelines:
- Do Not Do the Following:
Do Not Use Only Words or Numbers — Never use only numbers or words in a password.
Some insecure examples include the following:
Do Not Use Recognizable Words — Words such as proper names, dictionary words, or even terms from television shows or novels should be avoided, even if they are bookended with numbers.
Some insecure examples include the following:
Do Not Use Words in Foreign Languages — Password cracking programs often check against word lists that encompass dictionaries of many languages. Relying on foreign languages for secure passwords is not secure.
Some insecure examples include the following:
cheguevara
bienvenido1
1dumbKopf
Do Not Use Hacker Terminology — If you think you are elite because you use hacker terminology — also called l337 (LEET) speak — in your password, think again. Many word lists include LEET speak.
Some insecure examples include the following:
Do Not Use Personal Information — Steer clear of personal information. If the attacker knows your identity, the task of deducing your password becomes easier. The following is a list of the types of information to avoid when creating a password:
Some insecure examples include the following:
Do Not Invert Recognizable Words — Good password checkers always reverse common words, so inverting a bad password does not make it any more secure.
Some insecure examples include the following:
Do Not Write Down Your Password — Never store a password on paper. It is much safer to memorize it.
Do Not Use the Same Password For All Machines — It is important to make separate passwords for each machine. This way if one system is compromised, all of your machines are not immediately at risk.
- Do the Following:
Make the Password At Least Eight Characters Long — The longer the password, the better. If using MD5 passwords, it should be 15 characters or longer. With DES passwords, use the maximum length (eight characters).
Mix Upper and Lower Case Letters — Red Hat Enterprise Linux is case sensitive, so mix cases to enhance the strength of the password.
Mix Letters and Numbers — Adding numbers to passwords, especially when added to the middle (not just at the beginning or the end), can enhance password strength.
Include Non-Alphanumeric Characters — Special characters such as &, $, and > can greatly improve the strength of a password (this is not possible if using DES passwords).
Pick a Password You Can Remember — The best password in the world does little good if you cannot remember it; use acronyms or other mnemonic devices to aid in memorizing passwords.
With all these rules, it may seem difficult to create a password meeting all of the criteria for good passwords while avoiding the traits of a bad one. Fortunately, there are some steps one can take to generate a memorable, secure password.
4.3.1.1. Secure Password Creation Methodology
There are many methods people use to create secure passwords. One of the more popular methods involves acronyms. For example:
Think of a memorable phrase, such as:
"over the river and through the woods, to grandmother's house we go."
Next, turn it into an acronym (including the punctuation).
otrattw,tghwg.
Add complexity by substituting numbers and symbols for letters in the acronym. For example, substitute 7 for t and the at symbol (@) for a:
o7r@77w,7ghwg.
Add more complexity by capitalizing at least one letter, such as H.
o7r@77w,7gHwg.
Finally, do not use the example password above for any systems, ever.
While creating secure passwords is imperative, managing them properly is also important, especially for system administrators within larger organizations. The following section details good practices for creating and managing user passwords within an organization.
4.3.2. Creating User Passwords Within an Organization
If there are a significant number of users within an organization, the system administrators have two basic options available to force the use of good passwords. They can create passwords for the user, or they can let users create their own passwords, while verifying the passwords are of acceptable quality.
Creating the passwords for the users ensures that the passwords are good, but it becomes a daunting task as the organization grows. It also increases the risk of users writing their passwords down.
For these reasons, most system administrators prefer to have the users create their own passwords, but actively verify that the passwords are good and, in some cases, force users to change their passwords periodically through password aging.
4.3.2.1. Forcing Strong Passwords
To protect the network from intrusion it is a good idea for system administrators to verify that the passwords used within an organization are strong ones. When users are asked to create or change passwords, they can use the command line application
passwd, which is
Pluggable Authentication Manager (
PAM) aware and therefore checks to see if the password is easy to crack or too short in length via the
pam_cracklib.so PAM module. Since PAM is customizable, it is possible to add further password integrity checkers, such as
pam_passwdqc (available from
http://www.openwall.com/passwdqc/) or to write a new module. For a list of available PAM modules, refer to
http://www.kernel.org/pub/linux/libs/pam/modules.html. For more information about PAM, refer to the chapter titled
Pluggable Authentication Modules (PAM) in the
Reference Guide.
It should be noted, however, that the check performed on passwords at the time of their creation does not discover bad passwords as effectively as running a password cracking program against the passwords within the organization.
There are many password cracking programs that run under Red Hat Enterprise Linux although none ship with the operating system. Below is a brief list of some of the more popular password cracking programs:
None of these tools are supplied with Red Hat Enterprise Linux and are therefore not supported by Red Hat, Inc in any way.
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. It can be found online at
http://www.crypticide.com/users/alecm/.
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.
Always get authorization in writing before attempting to crack passwords within an organization.
Password aging is another technique used by system administrators to defend against bad passwords within an organization. Password aging means that after a set amount of time (usually 90 days) the user is prompted to create a new password. The theory behind this is that if a user is forced to change his password periodically, a cracked password is only useful to an intruder for a limited amount of time. The downside to password aging, however, is that users are more likely to write their passwords down.
There are two primary programs used to specify password aging under Red Hat Enterprise Linux: the chage command or the graphical User Manager (system-config-users) application.
The -M option of the chage command specifies the maximum number of days the password is valid. So, for instance, to set a user's password to expire in 90 days, type the following command:
chage -M 90 <username>
In the above command, replace <username> with the name of the user. To disable password expiration, it is traditional to use a value of 99999 after the -M option (this equates to a little over 273 years).
The graphical User Manager application may also be used to create password aging policies. To access this application, go to the button (on the Panel) => => or type the command system-config-users at a shell prompt (for example, in an XTerm or a GNOME terminal). Click on the Users tab, select the user from the user list, and click Properties from the button menu (or choose => from the pull-down menu).
For more information about user and group configuration (including instructions on forcing first time passwords), refer to the chapter titled User and Group Configuration in the System Administrators Guide. For an overview of user and resource management, refer to the chapter titled Managing User Accounts and Resource Access in the Red Hat Enterprise Linux Introduction to System Adminitration.
4.4. Administrative Controls
When administering a home machine, the user must perform some tasks as the root user or by acquiring effective root privileges via a setuid program, such as 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 a lower case s in the owner section of a long format listing, as in the following example:
-rwsr-xr-x 1 root root 47324 May 1 08:09 /bin/su
For the system administrators of an organization, however, choices must be made as to how much administrative access users within the organization should have to their machine. Through a PAM module called 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 the chapter titled Pluggable Authentication Modules (PAM) in the Reference Guide for more 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 priveleges. As a result, system administrators must decide how much access the users on their network should receive.
4.4.1. Allowing Root Access
If the users within an organization are a trusted, computer-savvy group, then allowing them root access may not be an issue. Allowing root access by users means that minor activities, like adding devices or configuring network interfaces, can be handled by the individual users, leaving system administrators free to deal with network security and other important issues.
On the other hand, giving root access to individual users can lead to the following issues:
Machine Misconfiguration — Users with root access can misconfigure their machines and require assistance or worse, open up security holes without knowing it.
Running Insecure Services — Users with root access may run insecure servers on their machine, such as FTP or Telnet, potentially putting usernames and passwords at risk as they pass over the network in the clear.
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.
4.4.2. Disallowing Root Access
If an administrator is uncomfortable allowing users to log in as root for these or other reasons, the root password should be kept secret, and access to runlevel one or single user mode should be disallowed through boot loader password protection (refer to
Section 4.2.2, “Boot Loader Passwords” for more information on this topic.)
The following are four different ways that an administrator can further ensure that root logins are disallowed:
-
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 4.1. 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 via 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 via the console or a raw network interface. This is dangerous, because a user can log in to their machine as root via 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 enable securetty 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:
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 4.2. Disabling Root Logins
|
Effects
|
Does Not Affect
|
|---|
|
Prevents access to the root account via the console or the network. The following programs are prevented from accessing the root account:
|
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:
|
-
Disabling root SSH logins
To prevent root logins via 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 4.3. Disabling Root SSH Logins
|
Effects
|
Does Not Affect
|
|---|
|
Prevents root access via the OpenSSH suite of tools. The following programs are prevented from accessing the root account:
|
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 the pam_listfile.so module is required for authentication.
The following is an example of how the module is used for the vsftpd 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, refer to the chapter titled Pluggable Authentication Modules (PAM) in the Reference Guide.
Table 4.4. 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.
|
4.4.3. Limiting Root Access
Rather than completely deny access to the root user, the administrator may want to allow access only via setuid programs, such as su or sudo.
Upon typing the su command, the user is prompted for the root password and, after authentication, is given a root shell prompt.
Once logged in via the su command, the user is the root user and has absolute administrative access to the system. In addition, once a user has become root, it is possible for them to use the su command to change to any other user on the system without being prompted for a password.
Because this program is so powerful, administrators within an organization may wish to limit who has access to the command.
One of the simplest ways to do this is to add users to the special administrative group called wheel. To do this, type the following command as root:
usermod -G wheel <username>
In the previous command, replace <username> with the username you want to add to the wheel group.
To use the User Manager for this purpose, go to the (on the Panel) => => or type the command system-config-users at a shell prompt. Select the Users tab, select the user from the user list, and click Properties from the button menu (or choose => from the pull-down menu).
Next, open the PAM configuration file for su (/etc/pam.d/su) in a text editor and remove the comment # from the following line:
auth required /lib/security/$ISA/pam_wheel.so use_uid
Doing this permits only members of the administrative group wheel to use the program.
The root user is part of the wheel group by default.
4.4.3.2. The sudo Command
The sudo command offers another approach to giving users administrative access. When trusted users precede an administrative command with sudo, they are prompted for their own password. Then, once authenticated and assuming that the command is permitted, the administrative command is executed as if by the root user.
The basic format of the sudo command is as follows:
sudo <command>
In the above example, <command> would be replaced by a command normally reserved for the root user, such as mount.
Users of the sudo command should take extra care to log out before walking away from their machines since sudoers can use the command again without being asked for a password within a five minute period. This setting can be altered via the configuration file, /etc/sudoers.
The
sudo command allows for a high degree of flexibility. For instance, only users listed in the
/etc/sudoers configuration file are allowed to use the
sudo command and the command is executed in
the user's shell, not a root shell. This means the root shell can be completely disabled, as shown in
Section 4.4.1, “Allowing Root Access”.
The sudo command also provides a comprehensive audit trail. Each successful authentication is logged to the file /var/log/messages and the command issued along with the issuer's user name is logged to the file /var/log/secure.
Another advantage of the sudo command is that an administrator can allow different users access to specific commands based on their needs.
Administrators wanting to edit the sudo configuration file, /etc/sudoers, should use the visudo command.
To give someone full administrative privileges, type visudo and add a line similar to the following in the user privilege specification section:
juan ALL=(ALL) ALL
This example states that the user, juan, can use sudo from any host and execute any command.
The example below illustrates the granularity possible when configuring sudo:
%users localhost=/sbin/shutdown -h now
This example states that any user can issue the command /sbin/shutdown -h now as long as it is issued from the console.
The man page for sudoers has a detailed listing of options for this file.
4.5. Available Network Services
While user access to administrative controls is an important issue for system administrators within an organization, keeping tabs on which network services are active is of paramount importance to anyone who administers and operates a Linux system.
Many services under Red Hat Enterprise Linux behave as network servers. If a network service is running on a machine, then a server application called a daemon is listening for connections on one or more network ports. Each of these servers should be treated as potential avenue of attack.
Network services can pose many risks for Linux systems. Below is a list of some of the primary issues:
Denial of Service Attacks (DoS) — By flooding a service with requests, a denial of service attack can bring a system to a screeching halt as it tries to log and answer each request.
Script Vulnerability Attacks — If a server is using scripts to execute server-side actions, as Web servers commonly do, a cracker can mount an attack on 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 which 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, crackers 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.
The threat of buffer overflow vulnerabilities is mitigated in Red Hat Enterprise Linux by ExecShield, an executable memory segmentation and protection technology supported by x86-compatible uni- and multi-processor kernels. ExecShield reduces the risk of buffer overflow by separating virtual memory into executable and non-executable segments. Any program code that tries to execute outside of the executable segment (such as malicious code injected from a buffer overflow exploit) triggers a segmentation fault and terminates.
Execshield also includes support for
No eXecute (
NX) technology on AMD64 platforms and
eXecute Disable (
XD) technology on Itanium and EM64T systems. These technologies work in conjunction with ExecShield to prevent malicious code from running in the executable portion of virtual memory with a granularity of 4kb of executable code, lowering the risk of attack from stealthy buffer overflow exploits.
For more information about ExecShield and NX or XD technologies, refer to the whitepaper entitled New Security Enhancements in Red Hat Enterprise Linux v.3, Update 3, available at the following URL:
To limit exposure to attacks over the network, all services that are unused should be turned off.
4.5.2. Identifying and Configuring Services
To enhance security, most network services installed with Red Hat Enterprise Linux are turned off by default. There are, however, some notable exceptions:
cupsd — The default print server for Red Hat Enterprise Linux.
lpd — An alternate print server.
xinetd — A super server that controls connections to a host of subordinate servers, such as vsftpd and telnet.
sendmail — The Sendmail mail transport agent is enabled by default, but only listens for connections from the localhost.
sshd — The OpenSSH server, which is a secure replacement for Telnet.
When determining whether to leave these services running, it is best to use common sense and err on the side of caution. For example, if a printer is not available, do not leave 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.
Red Hat Enterprise Linux ships with three programs designed to switch services on or off. They are the Services Configuration Tool (system-config-services), ntsysv, and chkconfig. For information on using these tools, refer to the chapter titled Controlling Access to Services in the System Administrators Guide.
But checking which network services are available to start at boot time is not enough. Good system administrators should also check which ports are open and listening. Refer to
Section 5.8, “Verifying Which Ports Are Listening” for more on this subject.
Potentially, any network service is insecure. This is why turning unused services off is so important. Exploits for services are revealed and patched routinely, making it very important to keep packages associated with any network service updated. Refer to
Chapter 3, Security Updates for more information about this issue.
Some network protocols are inherently more insecure than others. These include any services which do the following things:
Pass 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.
Pass Sensitive Data Over a Network Unencrypted — Many protocols pass data over the network unencrypted. These protocols include Telnet, FTP, HTTP, and SMTP. Many network file systems, such as NFS and SMB, also pass information over the network unencrypted. It is the user's responsibility when using these protocols to limit what type of data is transmitted.
Also, remote memory dump services, like netdump, pass the contents of memory over the network unencrypted. Memory dumps can contain passwords or, even worse, database entries and other sensitive information.
Other services like finger and rwhod reveal information about users of the system.
Examples of inherently insecure services includes the following:
FTP is not as inherently dangerous to the security of the system as remote shells, but FTP servers must be carefully configured and monitored to avoid problems. Refer to
Section 5.6, “Securing FTP” for more information on securing FTP servers.
Services that should be carefully implemented and behind a firewall include:
The next section discusses tools available to set up a simple firewall.
Once the necessary network services are configured, it is important to implement a firewall.
Firewalls prevent network packets from accessing the system's network interface. If a request is made to a port that is blocked by a firewall, the request is ignored. If a service is listening on one of these blocked ports, it does not receive the packets and is effectively disabled. For this reason, care should be taken when configuring a firewall to block access to ports not in use, while not blocking access to ports used by configured services.
For most users, the best tool for configuring a simple firewall is the straight-forward, graphical firewall configuration tool which ships with Red Hat Enterprise Linux: the Security Level Configuration Tool (system-config-securitylevel). This tool creates broad iptables rules for a general-purpose firewall using a control panel interface.
For more information about using this application and the options it offers, refer to the chapter titled Basic Firewall Configuration in the System Administrators Guide.
For advanced users and server administrators, manually configuring a firewall with
iptables is likely the best option. Refer to
Chapter 7, Firewalls for more information. For a comprehensive guide to the
iptables command, consult the chapter titled
iptables in the
Reference Guide.
Chapter 5. Server Security
When a system is used as a server on a public network, it becomes a target for attacks. For this reason, hardening the system and locking down services is of paramount importance for the system administrator.
Before delving into specific issues, review the following general tips for enhancing 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.
5.1. Securing Services With TCP Wrappers and xinetd
TCP wrappers provide access control to a variety of services. Most modern network services, such as SSH, Telnet, and FTP, make use of TCP wrappers, which stand guard between an incoming request and the requested service.
The benefits offered by TCP wrappers are enhanced when used in conjunction with xinetd, a super service that provides additional access, logging, binding, redirection, and resource utilization control.
It is a good idea to use IPTables firewall rules in conjunction with TCP wrappers and
xinetd to create redundancy within service access controls. Refer to
Chapter 7, Firewalls for more information about implementing firewalls with IPTables commands.
More information on configuring TCP wrappers and xinetd can be found in the chapter titled TCP Wrappers and xinetd in the Reference Guide.
The following subsections assume a basic knowledge of each topic and focus on specific security options.
5.1.1. Enhancing Security With TCP Wrappers
TCP wrappers are capable of much more than denying access to services. This section illustrates how it can be used to send connection banners, warn of attacks from particular hosts, and enhance logging functionality. For a thorough list of TCP wrapper functionality and control language, refer to the hosts_options man page.
5.1.1.1. TCP Wrappers and Connection Banners
Sending a client an intimidating banner when they connect to a service is a good way to disguise what system the server is running while letting a potential attacker know that system administrator is vigilant. To implement a TCP wrappers banner for a service, use the banner option.
This example implements a banner for vsftpd. To begin, create a banner file. It can be anywhere on the system, but it must bear same name as the daemon. For this example, the file is called /etc/banners/vsftpd.
The contents of the file look like this:
220-Hello, %c 220-All activity on ftp.example.com is logged. 220-Act up and you will be banned.
The %c token supplies a variety of client information, such as the username and hostname, or the username and IP address to make the connection even more intimidating. The Reference Guide has a list of other tokens available for TCP wrappers.
For this banner to be presented to incoming connections, add the following line to the /etc/hosts.allow file:
vsftpd : ALL : banners /etc/banners/
5.1.1.2. TCP Wrappers and Attack Warnings
If a particular host or network has been caught attacking the server, TCP wrappers can be used to warn the administrator of subsequent attacks from that host or network via the spawn directive.
In this example, assume that a cracker from the 206.182.68.0/24 network has been caught attempting to attack the server. By placing the following line in the /etc/hosts.deny file, the connection attempt is denied and logged into a special file:
ALL : 206.182.68.0 : spawn /bin/ 'date' %c %d >> /var/log/intruder_alert
The %d token supplies the name of the service that the attacker was trying to access.
To allow the connection and log it, place the spawn directive in the /etc/hosts.allow file.
Since the spawn directive executes any shell command, 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.
5.1.1.3. TCP Wrappers and Enhanced Logging
If certain types of connections are of more concern than others, the log level can be elevated for that service via the severity option.
For this example, assume anyone attempting to connect to port 23 (the Telnet port) on an FTP server is a cracker. To denote this, place a emerg flag in the log files instead of the default flag, info, and deny the connection.
To do this, place the following line in /etc/hosts.deny:
in.telnetd : ALL : severity emerg
This uses the default authpriv logging facility, but elevates the priority from the default value of info to emerg, which posts log messages directly to the console.
5.1.2. Enhancing Security With xinetd
The xinetd super server is another useful tool for controlling access to its subordinate services. This section focuses on how xinetd can be used to set a trap service and control the amount of resources any given xinetd service can use to thwart denial of service attacks. For a more thorough list of the options available, refer to the man pages for xinetd and xinetd.conf.
One important feature of 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 length of time or until xinetd is restarted. This is accomplished using the SENSOR attribute. This technique is an easy way to block hosts attempting to port scan the server.
The first step in setting up a SENSOR is to choose a service you do not plan on using. For this example, Telnet is used.
Edit the file /etc/xinetd.d/telnet and change the flags line to read:
flags = SENSOR
Add the following line within the braces:
deny_time = 30
This denies the host that attempted to connect to the port for 30 minutes. Other acceptable values for the deny_time attribute are FOREVER, which keeps the ban in effect until xinetd is restarted, and NEVER, which allows the connection and logs it.
Finally, the last line should read:
disable = no
While using SENSOR is a good way to detect and stop connections from nefarious 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.
5.1.2.2. Controlling Server Resources
Another important feature of xinetd is its ability to control the amount of resources which services under its control can utilize.
It does this by way of the following directives:
cps = <number_of_connections> <wait_period> — Dictates the connections allowed to the service per second. This directive accepts only integer values.
instances = <number_of_connections> — Dictates the total number of connections allowed to a service. This directive accepts either an integer value or UNLIMITED.
per_source = <number_of_connections> — Dictates the connections allowed to a service by each host. This directive accepts either an integer value or UNLIMITED.
rlimit_as = <number[K|M]> — Dictates the amount of memory address space the service can occupy in kilobytes or megabytes. This directive accepts either an integer value or UNLIMITED.
rlimit_cpu = <number_of_seconds> — Dictates the amount of time in seconds that a service may occupy the CPU. This directive accepts either an integer value or UNLIMITED.
Using these directives can help prevent any one xinetd service from overwhelming the system, resulting in a denial of service.
The 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.
Securing portmap only affects NFSv2 and NFSv3 implementations, since NFSv4 no longer requires it. If you plan to implement a NFSv2 or NFSv3 server, then portmap is required, and the following section applies.
If running RPC services, follow these basic rules.
5.2.1. Protect portmap With TCP Wrappers
It is important to use TCP wrappers to limit which networks or hosts have access to the portmap service since it has no built-in form of authentication.
Further, use only IP addresses when limiting access to the service. Avoid using hostnames, as they can be forged via DNS poisoning and other methods.
5.2.2. Protect portmap With IPTables
To further restrict access to the portmap service, it is a good idea to add IPTables rules to the server and restrict access to specific networks.
Below are two example IPTables commands that allow TCP connections to the portmap service (listening on port 111) from the 192.168.0/24 network and from the localhost (which 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
To similarly limit UDP traffic, use the following command.
iptables -A INPUT -p udp -s! 192.168.0.0/24 --dport 111 -j DROP
Refer to
Chapter 7, Firewalls for more information about implementing firewalls with IPTables commands.
NIS stands for Network Information Service. It is an RPC service, called ypserv, which is used in conjunction with portmap and other related services to distribute maps of usernames, passwords, and other sensitive information to any computer claiming to be within its domain.
An NIS server is comprised of several applications. They include the following:
/usr/sbin/rpc.yppasswdd — Also called the yppasswdd service, this daemon allows users to change their NIS passwords.
/usr/sbin/rpc.ypxfrd — Also called the ypxfrd 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.
NIS is rather insecure by todays standards. It has no host authentication mechanisms and passes all of its information over the network unencrypted, including password hashes. As a result, extreme care must be taken to set up a network that uses NIS. Further complicating the situation, the default configuration of NIS is inherently insecure.
It is recommended that anyone planning to implement an NIS server first secure the
portmap service as outlined in
Section 5.2, “Securing Portmap”, then address the following issues, such as network planning.
5.3.1. Carefully Plan the Network
Because NIS passes sensitive information unencrypted over the network, it is important the service be run behind a firewall and on a segmented and secure network. Any time NIS information is passed over an insecure network, it risks being intercepted. Careful network design in these regards can help prevent severe security breaches.
5.3.2. Use a Password-like NIS Domain Name and Hostname
Any machine within an NIS domain can use commands to extract information from the server without authentication, as long as the user knows the NIS server's DNS hostname and NIS domain name.
For instance, if someone either connects a laptop computer into the network or breaks into the network from outside (and manages to spoof an internal IP address), the following command reveals the /etc/passwd map:
ypcat -d <NIS_domain> -h <DNS_hostname> passwd
If this attacker is a root user, they can obtain the /etc/shadow file by typing the following command:
ypcat -d <NIS_domain> -h <DNS_hostname> shadow
If Kerberos is used, the /etc/shadow file is not stored within an NIS map.
To make access to NIS maps harder for an attacker, create a random string for the DNS hostname, such as 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.
5.3.3. Edit the /var/yp/securenets File
NIS listens to all networks, if the /var/yp/securenets file is blank or does not exist (as is the case after a default installation). 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 proper network.
Below is a sample entry from a /var/yp/securenets file:
255.255.255.0 192.168.0.0
Never start an NIS server for the first time without creating the /var/yp/securenets file.
This technique does not provide protection from an IP spoofing attack, but it does at least place limits on what networks the NIS server services.
5.3.4. Assign Static Ports and Use IPTables Rules
All of the servers related to NIS can be assigned specific ports except for 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.
To do this, add the following lines to /etc/sysconfig/network:
YPSERV_ARGS="-p 834" YPXFRD_ARGS="-p 835"
The following IPTables rules can be issued to enforce which network the server listens to for these ports:
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
Refer to
Chapter 7, Firewalls for more information about implementing firewalls with IPTables commands.
5.3.5. Use Kerberos Authentication
One of the most glaring flaws inherent when NIS is used for authentication is that whenever a user logs into a machine, a password hash from the /etc/shadow map is sent over the network. If an intruder gains access to an NIS domain and sniffs network traffic, usernames and password hashes can be quietly collected. With enough time, a password cracking program can guess weak passwords, and an attacker can gain access to a valid account on the network.
Since Kerberos uses secret-key cryptography, no password hashes are ever sent over the network, making the system far more secure. For more about Kerberos, refer to the chapter titled Kerberos in the Reference Guide.
The Network File System, or NFS, is service that provides network accessible file systems for client machines. For more information on how NFS works, refer to the chapter titled Network File System (NFS) in the Reference Guide. For more information about configuring NFS, refer to the System Administrators Guide. The following subsections assume a basic knowledge of NFS.
The version of NFS included in Red Hat Enterprise Linux, NFSv4, no longer requires the
portmap service as outlined in
Section 5.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 supports NFSv2 and NFSv3 which utilize it.
5.4.1. Carefully Plan the Network
Now that NFSv4 has the ability to pass all information encrypted using Kerberos over a network, it is important that the service be configured correctly if it is behind a firewall or on a segmented network. NFSv2 and NFSv3 still pass data insecurely, and concerns should be taken into consideration. Careful network design in all of these regards can help prevent security breaches.
5.4.2. Beware of Syntax Errors
The NFS server determines which file systems to export and which hosts to export these directories to via the /etc/exports file. Be careful not to add extraneous spaces when editing this file.
For instance, the following line in the /etc/exports file shares the directory /tmp/nfs/ to the host bob.example.com with read/write permissions.
/tmp/nfs/ bob.example.com(rw)
This line in the /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)
It is good practice to check any configured NFS shares by using the showmount command to verify what is being shared:
showmount -e <hostname>
5.4.3. Do Not Use the no_root_squash Option
By default, NFS shares change the root user to the nfsnobody user, an unprivileged user account. In this way, all root-created files are owned by nfsnobody, which prevents uploading of programs with the setuid bit set.
If no_root_squash is used, remote root users are able to change any file on the shared file system and leave trojaned applications for other users to inadvertently execute.
5.5. Securing the Apache HTTP Server
The Apache HTTP Server is one of the most stable and secure services that ships with Red Hat Enterprise Linux. There are an overwhelming number of options and techniques available to secure the Apache HTTP Server — too numerous to delve into deeply here.
It is important when configuring the Apache HTTP Server to read the documentation available for the application. This includes the chapter titled Apache HTTP Server in the Reference Guide, the chapter titled Apache HTTP Server Configuration in the System Administrators Guide.
Below is a list of configuration options administrators should be careful using.
This directive is enabled by default, 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 /.
5.5.2. The Indexes Directive
This directive is enabled by default, but may not be desirable. To prevent visitors from browsing files on the server, remove this directive.
5.5.3. The UserDir Directive
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 the UserDir disabled line.
5.5.4. Do Not Remove the IncludesNoExec Directive
By default, the server-side includes module cannot execute commands. It is ill advised to change this setting unless absolutely necessary, as it could potentially enable an attacker to execute commands on the system.
5.5.5. Restrict Permissions for Executable Directories
Be certain to only assign write permissions to the root user for any directory containing scripts or CGIs. This can be accomplished by typing the following commands:
chown root <directory_name> chmod 755 <directory_name>
Also, always verify that any scripts running on the system work as intended before putting them into production.
The File Transport Protocol, or FTP, is an older TCP protocol designed to transfer files over a network. Because all transactions with the server, including user authentication, are unencrypted, it is considered an insecure protocol and should be carefully configured.
Red Hat Enterprise Linux provides three FTP servers.
gssftpd — A kerberized xinetd-based FTP daemon which does not pass 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.
The following security guidelines are for setting up the vsftpd FTP service.
5.6.1. FTP Greeting Banner
Before submitting a username and password, all users are presented with a greeting banner. By default, this banner includes version information useful to crackers trying to identify weaknesses in a system.
To change the greeting banner for vsftpd, add the following directive to the /etc/vsftpd/vsftpd.conf file:
ftpd_banner=<insert_greeting_here>
Replace <insert_greeting_here> in the above directive with the text of the greeting message.
For mutli-line banners, it is best to use a banner file. To simplify management of multiple banners, place all banners in a new directory called /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.# ####################################################
To reference this greeting banner file for vsftpd, add the following directive to the /etc/vsftpd/vsftpd.conf file:
banner_file=/etc/banners/ftp.msg
The presence of the /var/ftp/ directory activates the anonymous account.
The easiest way to create this directory is to install the vsftpd package. This package sets a directory tree up for anonymous users and configures the permissions on directories to read-only for anonymous users.
By default the anonymous user cannot write to any directories.
If enabling anonymous access to an FTP server, be aware of where sensitive data is stored.
5.6.2.1. Anonymous Upload
To allow anonymous users to upload, it is recommended that a write-only directory be created within /var/ftp/pub/.
To do this, type:
mkdir /var/ftp/pub/upload
Next change the permissions so that anonymous users cannot see what is within the directory by typing:
chmod 730 /var/ftp/pub/upload
A long format listing of the directory should look like this:
drwx-wx--- 2 root ftp 4096 Feb 13 20:05 upload
Administrators who allow anonymous users to read and write in directories often find that their servers become a repository of stolen software.
Additionally, under vsftpd, add the following line to the /etc/vsftpd/vsftpd.conf file:
anon_upload_enable=YES
Because FTP passes unencrypted usernames and passwords over insecure networks for authentication, it is a good idea to deny system users access to the server from their user accounts.
To disable user accounts in vsftpd, add the following directive to /etc/vsftpd/vsftpd.conf:
local_enable=NO
5.6.3.1. Restricting User Accounts
The easiest way to disable a specific group of accounts, such as the root user and those with
sudo privileges, from accessing an FTP server is to use a PAM list file as described in
Section 4.4.1, “Allowing Root Access”. The PAM configuration file for
vsftpd is
/etc/pam.d/vsftpd.
It is also possible to disable user accounts within each service directly.
To disable specific user accounts in vsftpd, add the username to /etc/vsftpd.ftpusers.
5.6.4. Use TCP Wrappers To Control Access
Sendmail is a Mail Transport Agent (MTA) that uses the Simple Mail Transport Protocol (SMTP) to deliver electronic messages between other MTAs and to email clients or delivery agents. Although many MTAs are capable of encrypting traffic between one another, most do not, so sending email over any public networks is considered an inherently insecure form of communication.
For more information about how email works and an overview of common configuration settings, refer to the chapter titled Email in the Reference Guide. This section assumes a basic knowledge of how to generate a valid /etc/mail/sendmail.cf by editing the /etc/mail/sendmail.mc and running the m4 command as explained in the Reference Guide.
It is recommended that anyone planning to implement a Sendmail server address the following issues.
5.7.1. Limiting a Denial of Service Attack
Because of the nature of email, a determined attacker can flood the server with mail fairly easily and cause a denial of service. By setting limits to the following directives in /etc/mail/sendmail.mc, the effectiveness of such attacks are 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 any one message.
Never put the mail spool directory, /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. With NFSv4 using Kerberos, this is not the case, since the SECRPC_GSS kernel module does not utilize UID-based authentication.
To help prevent local user exploits on the Sendmail server, it is best for mail users to only access the Sendmail server using an email program. Shell accounts on the mail server should not be allowed and all user shells in the /etc/passwd file should be set to /sbin/nologin (with the possible exception of the root user).
5.8. Verifying Which Ports Are Listening
After configuring network services, it is important to pay attention to which ports are actually listening on the system's network interfaces. Any open ports can be evidence of an intrusion.
There are two basic approaches for listing the ports that are listening on the network. The less reliable approach is to query the network stack by typing commands such as netstat -an or lsof -i. This method is less reliable since these programs do not connect to the machine from the network, but rather check to see what is running on the system. For this reason, these applications are frequent targets for replacement by attackers. In this way, crackers attempt to cover their tracks if they open unauthorized network ports.
A more reliable way to check which ports are listening on the network is to use a port scanner such as nmap.
The following command issued from the console determines which ports are listening for TCP connections from the network:
nmap -sT -O localhost
The output of this command looks like the following:
Starting nmap 3.55 ( http://www.insecure.org/nmap/ ) at 2004-09-24 13:49 EDT
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1653 ports scanned but not shown below are in state: closed)
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
111/tcp open rpcbind
113/tcp open auth
631/tcp open ipp
834/tcp open unknown
2601/tcp open zebra
32774/tcp open sometimes-rpc11
Device type: general purpose
Running: Linux 2.4.X|2.5.X|2.6.X
OS details: Linux 2.5.25 - 2.6.3 or Gentoo 1.2 Linux 2.4.19 rc1-rc7)
Uptime 12.857 days (since Sat Sep 11 17:16:20 2004)
Nmap run completed -- 1 IP address (1 host up) scanned in 5.190 seconds
This output shows the system is running portmap due to the presence of the sunrpc service. However, there is also a mystery service on port 834. To check if the port is associated with the official list of known services, type:
cat /etc/services | grep 834
This command returns no output. This indicates that while the port is in the reserved range (meaning 0 through 1023) and requires root access to open, it is not associated with a known service.
Next, check for information about the port using netstat or lsof. To check for port 834 using netstat, use the following command:
netstat -anp | grep 834
The command returns the following output:
tcp 0 0 0.0.0.0:834 0.0.0.0:* LISTEN 653/ypbind
The presence of the open port in netstat is reassuring because a cracker opening a port surreptitiously on a hacked system would likely not allow it to be revealed through this command. Also, the [p] option reveals the process id (PID) of the service which opened the port. In this case, the open port belongs to ypbind (NIS), which is an RPC service handled in conjunction with the portmap service.
The lsof command reveals similar information since it is also capable of linking open ports to services:
lsof -i | grep 834
Below is the relevant portion of the output for this command:
ypbind 653 0 7u IPv4 1319 TCP *:834 (LISTEN)
ypbind 655 0 7u IPv4 1319 TCP *:834 (LISTEN)
ypbind 656 0 7u IPv4 1319 TCP *:834 (LISTEN)
ypbind 657 0 7u IPv4 1319 TCP *:834 (LISTEN)
These tools reveal a great deal about the status of the services running on a machine. These tools are flexible and can provide a wealth of information about network services and configuration. Consulting the man pages for lsof, netstat, nmap, and services is therefore highly recommended.
Chapter 6. Virtual Private Networks
Organizations with several satellite offices often connect to each other with dedicated lines for efficiency and protection of sensitive data in transit. For example, many businesses use frame relay or Asynchronous Transfer Mode (ATM) lines as an end-to-end networking solution to link one office with others. This can be an expensive proposition, especially for small to medium sized businesses (SMBs) that want to expand without paying the high costs associated with enterprise-level, dedicated digital circuits.
To address this need,
Virtual Private Networks (
VPNs) were developed. Following the same functional principles as dedicated circuits, VPNs allow for secured digital communication between two parties (or networks), creating a Wide Area Network (WAN) from existing
Local Area Networks (
LANs). Where it differs from frame relay or ATM is in its transport medium. VPNs transmit over IP using datagrams as the transport layer, making it a secure conduit through the Internet to an intended destination. Most free software VPN implementations incorporate open standard encryption methods to further mask data in transit.
Some organizations employ hardware VPN solutions to augment security, while others use the software or protocol-based implementations. There are several vendors with hardware VPN solutions such as Cisco, Nortel, IBM, and Checkpoint. There is a free software-based VPN solution for Linux called FreeS/Wan that utilizes a standardized IPsec (or Internet Protocol Security) implementation. These VPN solutions, regardless if hardware or software based, act as specialized routers that sit between the IP connection from one office to another.
When a packet is transmitted from a client, it sends it through the router or gateway, which then adds header information for routing and authentication called the
Authentication Header (
AH). The data is encrypted and is enclosed with decryption and handling instruction called the
Encapsulating Security Payload (
ESP). The receiving VPN router strips the header information, decrypts the data, and routes it to its intended destination (either a workstation or node on a network). Using a network-to-network connection, the receiving node on the local network receives the packets decrypted and ready for processing. The encryption/decryption process in a network-to-network VPN connection is transparent to a local node.
With such a heightened level of security, a cracker must not only intercept a packet, but decrypt the packet as well. Intruders who employ a man-in-the-middle attack between a server and client must also have access to at least one of the private keys for authenticating sessions. Because they employ several layers of authentication and encryption, VPNs are a secure and effective means to connect multiple remote nodes to act as a unified Intranet.
6.1. VPNs and Red Hat Enterprise Linux
Red Hat Enterprise Linux users have various options in terms of implementing a software solution to securely connect to their WAN.
Internet Protocol Security, or
IPsec is the supported VPN implementation for Red Hat Enterprise Linux that sufficiently addresses the usability needs of organizations with branch offices or remote users.
Red Hat Enterprise Linux supports IPsec for connecting remote hosts and networks to each other using a secure tunnel on a common carrier network such as the Internet. IPsec can be implemented using a host-to-host (one computer workstation to another) or network-to-network (one LAN/WAN to another). The IPsec implementation in Red Hat Enterprise Linux uses
Internet Key Exchange (
IKE), which is a protocol implemented by the Internet Engineering Task Force (
IETF) to be used for mutual authentication and secure associations between connecting systems.
An IPsec connection is split into two logical phases. In phase 1, an IPsec node initializes the connection with the remote node or network. The remote node/network checks the requesting node's credentials and both parties negotiate the authentication method for the connection. On Red Hat Enterprise Linux systems, an IPsec connection uses the pre-shared key method of IPsec node authentication. In a pre-shared key IPsec connection, both hosts must use the same key in order to move to the second phase of the IPsec connection.
Phase 2 of the IPsec connection is where the
security association (
SA) is created between IPsec nodes. This phase establishes an SA database with configuration information, such as the encryption method, secret session key exchange parameters, and more. This phase manages the actual IPsec connection between remote nodes and networks.
The Red Hat Enterprise Linux implementation of IPsec uses IKE for sharing keys between hosts across the Internet. The racoon keying daemon handles the IKE key distribution and exchange.
Implementing IPsec requires that the ipsec-tools RPM package be installed on all IPsec hosts (if using a host-to-host configuration) or routers (if using a network-to-network configuration). The RPM package contains essential libraries, daemons, and configuration files to aid in setup of the IPsec connection, including:
/sbin/setkey — manipulates the key management and security attributes of IPsec in the kernel. This executable is controlled by the racoon key management daemon. For more information on setkey, refer to the setkey(8) man page.
/sbin/racoon — the IKE key management daemon, used to manage and control security associations and key sharing between IPsec-connected systems. This daemon can be configured by editing the /etc/racoon/racoon.conf file. For more information about racoon, refer to the racoon(8) man page.
/etc/racoon/racoon.conf — the racoon daemon configuration file used to configure various aspects of the IPsec connection, including authentication methods and encryption algorithms used in the connection. For a complete listing of directives available, refer to the racoon.conf(5) man page.
Configuring IPsec on Red Hat Enterprise Linux can be done via the Network Administration Tool or by manually editing networking and IPsec configuration files. For more information about using the Network Administration Tool, refer to the System Administrators Guide.
6.4. IPsec Host-to-Host Configuration
IPsec can be configured to connect one desktop or workstation to another by way of a host-to-host connection. This type of connection uses the network to which each host is connected to create the secure tunnel to each other. The requirements of a host-to-host connection are minimal, as is the configuration of IPsec on each host. The hosts need only a dedicated connection to a carrier network (such as the Internet) and Red Hat Enterprise Linux to create the IPsec connection.
The first step in creating a connection is to gather system and network information from each workstation. For a host-to-host connection, you need the following information:
The IP address for both hosts
A unique name to identify the IPsec connection and distinguish it from other devices or connections (for example, ipsec0)
A fixed encryption key or one automatically generated by racoon
A pre-shared authentication key that is used to initiate the connection and exchange encryption keys during the session
For example, suppose Workstation A and Workstation B want to connect to each other through an IPsec tunnel. They want to connect using a pre-shared key with the value of foobarbaz and the users agree to let racoon automatically generate and share an authentication key between each host. Both host users decide to name their connections ipsec0.
The following is the ifcfg file for Workstation A for a host-to-host IPsec connection with Workstation B (the unique name to identify the connection in this example is ipsec0, so the resulting file is named /etc/sysconfig/network-scripts/ifcfg-ipsec0):
DST=X.X.X.X
TYPE=IPSEC
ONBOOT=yes
IKE_METHOD=PSK
Workstation A would replace X.X.X.X with the IP address of Workstation B, while Workstation B replaces X.X.X.X with the IP address of Workstation A. The connection is set to initiate upon boot-up (ONBOOT=yes) and uses the pre-shared key method of authentication (IKE_METHOD=PSK).
The following is the content of the pre-shared key file (called /etc/sysconfig/network-scripts/keys-ipsec0) that both workstations need to authenticate each other. The contents of this file should be identical on both workstations and only the root user should be able to read or write this file.
IKE_PSK=foobarbaz
To change the keys-ipsec0 file so that only the root user can read or edit the file, perform the following command after creating the file:
chmod 600 /etc/sysconfig/network-scripts/keys-ipsec0
To change the authentication key at any time, edit the keys-ipsec0 file on both workstations. Both keys must be identical for proper connectivity.
The next example shows the specific configuration for the phase 1 connection to the remote host. The file is named X.X.X.X.conf (X.X.X.X is replaced with the IP address of the remote IPsec router). Note that this file is automatically generated once the IPsec tunnel is activated and should not be edited directly.
;
remote X.X.X.X
{
exchange_mode aggressive, main;
my_identifier address;
proposal {
encryption_algorithm 3des;
hash_algorithm sha1;
authentication_method pre_shared_key;
dh_group 2 ;
}
}
The default phase 1 configuration file created when an IPsec connection is initialized contains the following statements used by the Red Hat Enterprise Linux implementation of IPsec:
remote X.X.X.X
Specifies that the subsequent stanzas of this configuration file applies only to the remote node identified by the X.X.X.X IP address.
exchange_mode aggressive
The default configuration for IPsec on Red Hat Enterprise Linux uses an aggressive authentication mode, which lowers the connection overhead while allowing configuration of several IPsec connections with multiple hosts.
my_identifier address
Defines the identification method to be used when authenticating nodes. Red Hat Enterprise Linux uses IP addresses to identify nodes.
encryption_algorithm 3des
Defines the encryption cipher used during authentication. By default,
Triple Data Encryption Standard (
3DES) is used.
hash_algorithm sha1;
Specifies the hash algorithm used during phase 1 negotiation between nodes. By default, Secure Hash Algorithm version 1 is used.
authentication_method pre_shared_key
Defines the authentication method used during node negotiation. Red Hat Enterprise Linux by default uses pre-shared keys for authentication.
dh_group 2
Specifies the Diffie-Hellman group number for establishing dynamically-generated session keys. By default, the 1024-bit group is used.
The /etc/racoon/racoon.conf files should be identical on all IPsec nodes except for the include "/etc/racoon/X.X.X.X.conf" statement. This statement (and the file it references) is generated when the IPsec tunnel is activated. For Workstation A, the X.X.X.X in the include statement is Workstation B's IP address. The opposite is true of Workstation B. The following shows a typical racoon.conf file when IPsec connection is activated.
# Racoon IKE daemon configuration file.
# See 'man racoon.conf' for a description of the format and entries.
path include "/etc/racoon";
path pre_shared_key "/etc/racoon/psk.txt";
path certificate "/etc/racoon/certs";
sainfo anonymous
{
pfs_group 2;
lifetime time 1 hour ;
encryption_algorithm 3des, blowfish 448, rijndael ;
authentication_algorithm hmac_sha1, hmac_md5 ;
compression_algorithm deflate ;
}
include "/etc/racoon/X.X.X.X.conf"
This default racoon.conf file includes defined paths for IPsec configuration, pre-shared key files, and certificates. The fields in sainfo anonymous describe the phase 2 SA between the IPsec nodes — the nature of the IPsec connection (including the supported encryption algorithms used) and the method of exchanging keys. The following list defines the fields of phase 2:
sainfo anonymous
Denotes that SA can anonymously initialize with any peer insofar as the IPsec credentials match.
pfs_group 2
Defines the Diffie-Hellman key exchange protocol, which determines the method in which the IPsec nodes establish a mutual temporary session key for the second phase of IPsec connectivity. By default, the Red Hat Enterprise Linux implementation of IPsec uses group 2 (or modp1024) of the Diffie-Hellman cryptographic key exchange groups. Group 2 uses a 1024-bit modular exponentiation that prevents attackers from decrypting previous IPsec transmissions even if a private key is compromised.
lifetime time 1 hour
This parameter specifies the life cycle of an SA and can be quantified either by time or by bytes of data. The Red Hat Enterprise Linux implementation of IPsec specifies a one hour lifetime.
encryption_algorithm 3des, blowfish 448, rijndael
Specifies the supported encryption ciphers for phase 2. Red Hat Enterprise Linux supports 3DES, 448-bit Blowfish, and Rijndael (the cipher used in the
Advanced Encryption Standard, or
AES).
authentication_algorithm hmac_sha1, hmac_md5
Lists the supported hash algorithms for authentication. Supported modes are sha1 and md5 hashed message authentication codes (HMAC).
compression_algorithm deflate
Defines the Deflate compression algorithm for IP Payload Compression (IPCOMP) support, which allows for potentially faster transmission of IP datagrams over slow connections.
To start the connection, either reboot the workstation or execute the following command as root on each host:
/sbin/ifup ipsec0
To test the IPsec connection, run the tcpdump utility to view the network packets being transfered between the hosts (or networks) and verify that they are encrypted via IPsec. The packet should include an AH header and should be shown as ESP packets. ESP means it is encrypted. For example:
17:13:20.617872 pinky.example.com > ijin.example.com: \
AH(spi=0x0aaa749f,seq=0x335): ESP(spi=0x0ec0441e,seq=0x335) (DF)
6.5. IPsec Network-to-Network configuration
IPsec can also be configured to connect an entire network (such as a LAN or WAN) to a remote network by way of a network-to-network connection. A network-to-network connection requires the setup of IPsec routers on each side of the connecting networks to transparently process and route information from one node on a LAN to a node on a remote LAN.
Figure 6.1, “A Network-to-network IPsec tunneled connection” shows a network-to-network IPsec tunneled connection.
This diagram shows two separate LANs separated by the Internet. These LANs use IPsec routers to authenticate and initiate a connection using a secure tunnel through the Internet. Packets that are intercepted in transit would require brute-force decryption in order to crack the cipher protecting the packets between these LANs. The process of communicating from one node on the 192.168.1.0/24 IP range to another on 192.168.2.0/24 is completely transparent to the nodes as the processing, encryption/decryption, and routing of the IPsec packets are completely handled by the IPsec router.
The information needed for a network-to-network connection include:
The externally-accessible IP addresses of the dedicated IPsec routers
The network address ranges of the LAN/WAN served by the IPsec routers (such as 192.168.0.0/24 or 10.0.1.0/24)
The IP addresses of the gateway devices that route the data from the network nodes to the Internet
A unique name to identify the IPsec connection and distinguish it from other devices or connections (for example, ipsec0)
A fixed encryption key or one automatically generated by racoon
A pre-shared authentication key that initiates the connection and exchange encryption keys during the session
For example, suppose LAN A (lana.example.com) and LAN B (lanb.example.com) want to connect to each other through an IPsec tunnel. The network address for LAN A is in the 192.168.1.0/24 range, while LAN B uses the 192.168.2.0/24 range. The gateway IP address is 192.168.1.254 for LAN A and 192.168.2.254 for LAN B. The IPsec routers are separate from each LAN gateway and uses two network devices: eth0 is assigned to an externally-accessible static IP address which accesses the Internet, while eth1 acts as a routing point to process and transmit LAN packets from one network node to the remote network nodes.
The IPsec connection between each network uses a pre-shared key with the value of r3dh4tl1nux, and the administrators of A and B agree to let racoon automatically generate and share an authentication key between each IPsec router. The administrator of LAN A decides to name the IPsec connection ipsec0, while the administrator of LAN B names the IPsec connection ipsec1..
The following example are the contents the ifcfg file for a network-to-network IPsec connection for LAN A. The unique name to identify the connection in this example is ipsec0, so the resulting file is named /etc/sysconfig/network-scripts/ifcfg-ipsec0.
TYPE=IPSEC
ONBOOT=yes
IKE_METHOD=PSK
SRCGW=192.168.1.254
DSTGW=192.168.2.254
SRCNET=192.168.1.0/24
DSTNET=192.168.2.0/24
DST=X.X.X.X
The connection is set to initiate upon boot-up (ONBOOT=yes) and uses the pre-shared key method of authentication (IKE_METHOD=PSK). The administrator for LAN A enters the destination gateway, which is the gateway for LAN B (DSTGW=192.168.2.254) as well as the source gateway, which is the gateway IP address for LAN A (SRCGW=192.168.1.254). The administrator then enters the destination network, which is the network range for LAN B (DSTNET=192.168.2.0/24) as well as the source network (SRCNET=192.168.1.0/24). Finally, the administrator enters the destination IP address, which is the externally-accessible IP address for LAN B (X.X.X.X).
The following example is the content of the pre-shared key file called /etc/sysconfig/network-scripts/keys-ipsecX (where X is 0 for LAN A and 1 for LAN B) that both networks use to authenticate each other. The contents of this file should be identical and only the root user should be able to read or write this file.
IKE_PSK=r3dh4tl1nux
To change the keys-ipsecX file so that only the root user can read or edit the file, perform the following command after creating the file:
chmod 600 /etc/sysconfig/network-scripts/keys-ipsec1
To change the authentication key at any time, edit the keys-ipsecX file on both IPsec routers. Both keys must be identical for proper connectivity.
The following example is the contents of the /etc/racoon/racoon.conf configuration file for the IPsec connection. Note that the include line at the bottom of the file is automatically generated and only appears if the IPsec tunnel is running.
# Racoon IKE daemon configuration file.
# See 'man racoon.conf' for a description of the format and entries.
path include "/etc/racoon";
path pre_shared_key "/etc/racoon/psk.txt";
path certificate "/etc/racoon/certs";
sainfo anonymous
{
pfs_group 2;
lifetime time 1 hour ;
encryption_algorithm 3des, blowfish 448, rijndael ;
authentication_algorithm hmac_sha1, hmac_md5 ;
compression_algorithm deflate ;
}
include "/etc/racoon/X.X.X.X.conf"
The following is the specific configuration for the connection to the remote network. The file is named X.X.X.X.conf (replace X.X.X.X with the IP address of the remote IPsec router). Note that this file is automatically generated once the IPsec tunnel is activated and should not be edited directly.
;
remote X.X.X.X
{
exchange_mode aggressive, main;
my_identifier address;
proposal {
encryption_algorithm 3des;
hash_algorithm sha1;
authentication_method pre_shared_key;
dh_group 2 ;
}
}
Prior to starting the IPsec connection, IP forwarding should be enabled in the kernel. As root at a shell prompt, enable IP forwarding:
Edit /etc/sysctl.conf and set net.ipv4.ip_forward to 1.
Execute the following command to enable the change:
sysctl -p /etc/sysctl.conf
To start the IPsec connection, either reboot the IPsec routers or execute the following command as root on each router:
/sbin/ifup ipsec0
The connections are activated, and both LAN A and B are able to communicate with each other. The routes are created automatically via the initialization script called by running ifup on the IPsec connection. To show a list of routes for the network, run the following command:
/sbin/ip route list
To test the IPsec connection, run the tcpdump utility on the externally-routable device (eth0 in this example) to view the network packets being transfered between the hosts (or networks) and verify that they are encrypted via IPsec. For example, to check the IPsec connectivity of LAN A, type the following:
tcpdump -n -i eth0 host lana.example.com
The packet should include an AH header and should be shown as ESP packets. ESP means it is encrypted. For example (back slashes denote a continuation of one line):
12:24:26.155529 lanb.example.com > lana.example.com: AH(spi=0x021c9834,seq=0x358): \
lanb.example.com > lana.example.com: ESP(spi=0x00c887ad,seq=0x358) (DF) \
(ipip-proto-4)
Information security is commonly thought of as a process and not a product. However, standard security implementations usually employ some form of dedicated mechanism to control access privileges and restrict network resources to users who are authorized, identifiable, and traceable. Red Hat Enterprise Linux includes several powerful tools to assist administrators and security engineers with network-level access control issues.
Along with VPN solutions, such as IPsec (discussed in
Chapter 6, Virtual Private Networks), firewalls are one of the core components of a network security implementation. Several vendors market firewall solutions catering to all levels of the marketplace: from home users protecting one PC to data center solutions safeguarding vital enterprise information. Firewalls can be standalone hardware solutions, such as firewall appliances by Cisco, Nokia, and Sonicwall. There are also proprietary software firewall solutions developed for home and business markets by vendors such as Checkpoint, McAfee, and Symantec.
Apart from the differences between hardware and software firewalls, there are also differences in the way firewalls function that separate one solution from another.
Table 7.1, “Firewall Types” details three common types of firewalls and how they function:
Table 7.1. 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.
|
| · Can be configured transparently to machines on a LAN | | · Protection of many machines and services behind one or more external IP address(es) 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 within and outside of 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, which is convenient for cutting down on unnecessary 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 |
|
7.1. Netfilter and iptables
The Linux kernel features a powerful networking subsystem called Netfilter. The Netfilter subsystem provides stateful or stateless packet filtering as well as NAT and IP masquerading services. Netfilter also has the ability to mangle IP header information for advanced routing and connection state management. Netfilter is controlled through the iptables utility.
The power and flexibility of Netfilter is implemented through the iptables interface. This command line tool is similar in syntax to its predecessor, ipchains; however, iptables uses the Netfilter subsystem to enhance network connection, inspection, and processing; whereas ipchains used intricate rule sets for filtering source and destination paths, as well as connection ports for both. iptables features advanced logging, pre- and post-routing actions, network address translation, and port forwarding all in one command line interface.
This section provides an overview of iptables. For more detailed information about iptables, refer to the Reference Guide.
The first step in using iptables is to start the iptables service. This can be done with the command:
service iptables start
The ip6tables services should be turned off to use the iptables service with the following commands:
service ip6tables stop
chkconfig ip6tables off
To make iptables start by default whenever the system is booted, you must change runlevel status on the service using chkconfig.
chkconfig --level 345 iptables on
The syntax of iptables is separated into tiers. The main tier is the chain. A chain specifies the state at which a packet is manipulated. The usage is as follows:
iptables -A chain -j target
The -A option appends a rule at the end of an existing ruleset. The chain is the name of the chain for a rule. The three built-in chains of iptables (that is, the chains that affect every packet which traverses a network) are INPUT, OUTPUT, and FORWARD. These chains are permanent and cannot be deleted. The -j target option specifies the location in the iptables ruleset where this particular rule should jump. Some built in targets are ACCEPT, DROP, and REJECT.
New chains (also called user-defined chains) can be created by using the -N option. Creating a new chain is useful for customizing granular or elaborate rules.
7.2.1. Basic Firewall Policies
Establishing basic firewall policies creates a foundation for building more detailed, user-defined rules. iptables uses policies (-P) to create default rules. Security-minded administrators usually elect to drop all packets as a policy and only allow specific packets on a case-by-case basis. The following rules block all incoming and outgoing packets on a network gateway:
iptables -P INPUT DROP
iptables -P OUTPUT DROP
Additionally, it is recommended that any forwarded packets — network traffic that is to be routed from the firewall to its destination node — be denied as well, to restrict internal clients from inadvertent exposure to the Internet. To do this, use the following rule:
iptables -P FORWARD DROP
After setting the policy chains, you can create new rules for your particular network and security requirements. The following sections outline some rules you may implement in the course of building your iptables firewall.
7.2.2. Saving and Restoring iptables Rules
Firewall rules are only valid for the time the computer is on; so, if the system is rebooted, the rules are automatically flushed and reset. To save the rules so that they are loaded later, use the following command:
/sbin/service iptables save
The rules are stored in the file /etc/sysconfig/iptables and are applied whenever the service is started or restarted, including when the machine is rebooted.
7.3. Common iptables Filtering
Keeping remote attackers out of a LAN is an important aspect of network security, if not the most important. The integrity of a LAN should be protected from malicious remote users through the use of stringent firewall rules. However, with a default policy set to block all incoming, outgoing, and forwarded packets, it is impossible for the firewall/gateway and internal LAN users to communicate with each other or with external resources. To allow users to perform network-related functions and use networking applications, administrators must open certain ports for communication.
For example, to allow access to port 80 on the firewall, append the following rule:
iptables -A INPUT -p tcp -m tcp --sport 80 -j ACCEPT iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
This allows regular Web browsing from websites that communicate via port 80. To allow access to secure websites (such as https://www.example.com/), you must open port 443, as well.
iptables -A INPUT -p tcp -m tcp --sport 443 -j ACCEPT iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
When creating an iptables ruleset, it is critical to remember that order is important. For example, if one chain that specifies that any packets from the local 192.168.100.0/24 subnet be dropped, and then another chain is appended (-A) to allow packets from 192.168.100.13 (which is within the dropped restricted subnet), then the appended rule is ignored. You must set a rule to allow 192.168.100.13 first, and then set a drop rule on the subnet.
To arbitrarily insert a rule in an existing chain of rules, use -I, followed by the chain in which to insert the rule, and a rule number (1,2,3,...,n) for where the rule should reside. For example:
iptables -I INPUT 1 -i lo -p all -j ACCEPT
The rule is inserted as the first rule in the INPUT chain to allow local loopback device traffic.
There may be times when you require remote access to the LAN from outside the LAN. Secure services such as SSH, can be used for encrypted remote connection to LAN services. For administrators with PPP-based resources (such as modem banks or bulk ISP accounts), dial-up access can be used to circumvent firewall barriers securely, as modem connections are typically behind a firewall/gateway because they are direct connections. However, for remote users with broadband connections, special cases can be made. You can configure iptables to accept connections from remote SSH clients. For example, to allow remote SSH access, the following rules may be used:
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p udp --sport 22 -j ACCEPT
There are other services for which you may need to define rules. Refer to the Reference Guide for comprehensive information on iptables and its various options.
These rules allow incoming and outbound access for an individual system, such as a single PC directly connected to the Internet or a firewall/gateway. However, they do not allow nodes behind the firewall/gateway to access these services. To allow LAN access to these services, you can use NAT with iptables filtering rules.
7.4. FORWARD and NAT Rules
Most organizations are allotted a limited number of publicly routable IP addresses from their ISP. Due to this limited allowance, administrators must find creative ways to share access to Internet services without giving limited public IP addresses to every node on the LAN. Using private IP address is the common way to allow all nodes on a LAN to properly access internal and external network services. Edge routers (such as firewalls) can receive incoming transmissions from the Internet and route the packets to the intended LAN node. At the same time, firewall/gateways can also route outgoing requests from a LAN node to the remote Internet service. This forwarding of network traffic can become dangerous at times, especially with the availability of modern cracking tools that can spoof internal IP addresses and make the remote attacker's machine act as a node on your LAN. To prevent this, iptables provides routing and forwarding policies that can be implemented to prevent aberrant usage of network resources.
The FORWARD policy 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), the following rules can be set:
iptables -A FORWARD -i eth1 -j ACCEPT
iptables -A FORWARD -o eth1 -j ACCEPT
This rule gives systems behind the firewall/gateway access to the internal network. The gateway routes packets from one LAN node to its intended destination node, passing all packets through its eth1 device.
By default, the IPv4 policy in Red Hat Enterprise Linux kernels disables support for IP forwarding, which prevents boxes running Red Hat Enterprise Linux from functioning as dedicated edge routers. To enable IP forwarding, run the following command:
sysctl -w net.ipv4.ip_forward=1
If this command is run via shell prompt, then the setting is not remembered after a reboot. You can permanently set forwarding by editing the /etc/sysctl.conf file. Find and edit the following line, replacing 0 with 1:
net.ipv4.ip_forward = 0
Execute the following command to enable the change to the sysctl.conf file:
sysctl -p /etc/sysctl.conf
Accepting forwarded packets via the firewall's internal IP device allows LAN nodes to communicate with each other; however they still are not allowed to communicate externally to the Internet. To allow LAN nodes with private IP addresses to communicate with external public networks, configure the firewall for IP masquerading, which masks requests from LAN nodes with the IP address of the firewall's external device (in this case, eth0):
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
The rule uses the NAT packet matching table (-t nat) and specifies the built-in POSTROUTING chain for NAT (-A POSTROUTING) on the firewall's external networking device (-o eth0). POSTROUTING allows packets to be altered as they are leaving the firewall's external device. The -j MASQUERADE target is specified to mask the private IP address of a node with the external IP address of the firewall/gateway.
If you have a server on your internal network that you want make available externally, you can use the -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. For example, if you wanted to forward incoming HTTP requests to your dedicated Apache HTTP Server server system at 172.31.0.23, run the following command:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT \
--to 172.31.0.23:80
This rule specifies that the NAT table use the built-in PREROUTING chain to forward incoming HTTP requests exclusively to the listed destination IP address of 172.31.0.23.
If you have a default policy of DROP in your FORWARD chain, you must append a rule to allow forwarding of incoming HTTP requests so that destination NAT routing can be possible. To do this, run the following command:
iptables -A FORWARD -i eth0 -p tcp --dport 80 -d 172.31.0.23 -j ACCEPT
This rule allows forwarding of incoming HTTP requests from the firewall to its intended destination of the Apache HTTP Server server behind the firewall.
iptables rules can be set to route traffic to certain machines, such as a dedicated HTTP or FTP server, in a
demilitarized zone (
DMZ) — a special local subnetwork dedicated to providing services on a public carrier such as the Internet. For example, to set a rule for routing incoming HTTP requests to a dedicated HTTP server at 10.0.4.2 (outside of the 192.168.1.0/24 range of the LAN), NAT calls a
PREROUTING table to forward the packets to their proper destination:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT \ --to-destination 10.0.4.2:80
With this command, all HTTP connections to port 80 from the outside of the LAN are routed to the HTTP server on a separate network from the rest of the internal network. This form of network segmentation can prove safer than allowing HTTP connections to a machine on the network. If the HTTP server is configured to accept secure connections, then port 443 must be forwarded as well.
7.5. Viruses and Spoofed IP Addresses
More elaborate rules can be created that control access to specific subnets, or even specific nodes, within a LAN. You can also restrict certain dubious services such as trojans, worms, and other client/server viruses from contacting their server. For example, there are some trojans that scan networks for services on ports from 31337 to 31340 (called the elite ports in cracking terminology). Since there are no legitimate services that communicate via these non-standard ports, blocking it can effectively diminish the chances that potentially infected nodes on your network independently communicate with their remote master servers.
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
You can also block outside connections that attempt to spoof private IP address ranges to infiltrate your LAN. For example, if your LAN uses the 192.168.1.0/24 range, a rule can set the Internet facing network device (for example, eth0) to drop any packets to that device with an address in your LAN IP range. Because it is recommended to reject forwarded packets as a default policy, any other spoofed IP address to the external-facing device (eth0) is rejected automatically.
iptables -A FORWARD -s 192.168.1.0/24 -i eth0 -j DROP
There is a distinction between the DROP and REJECT targets when dealing with appended rules. The 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. Administrators can use their own discretion when using these targets. However, to avoid user confusion and attempts to continue connecting, the REJECT target is recommended.
7.6. iptables and Connection Tracking
iptables includes a module that allows administrators to inspect and restrict connections to services available on an internal network using a method called connection tracking. Connection tracking stores connections in a table, which allows administrators to 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, such as passive FTP connections where the connection port is 20, but the transfer port can be any unused port 1024 or higher.
INVALID — A packet that is not part of any connections in the connection tracking table.
You can use the stateful functionality of 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
The introduction of the next-generation Internet Protocol, called IPv6, expands beyond the 32-bit address limit of IPv4 (or IP). IPv6 supports 128-bit addresses and, as such, carrier networks that are IPv6 aware are able to address a larger number of routable addresses than IPv4.
Red Hat Enterprise Linux supports IPv6 firewall rules using the Netfilter 6 subsystem and the ip6tables command. The first step in using ip6tables is to start the ip6tables service. This can be done with the command:
service ip6tables start
The iptables services must be turned off to use the ip6tables service exclusively:
service iptables stop
chkconfig iptables off
To make ip6tables start by default whenever the system is booted, change the runlevel status on the service using chkconfig.
chkconfig --level 345 ip6tables on
The syntax is identical to iptables in every aspect except that ip6tables supports 128-bit addresses. For example, SSH connections on a IPv6-aware network server can be enabled with the following rule:
ip6tables -A INPUT -i eth0 -p tcp -s 3ffe:ffff:100::1/128 --dport 22 -j ACCEPT
For more information about IPv6 networking, refer to the IPv6 Information Page at
http://www.ipv6.org/.
7.8. Additional Resources
There are several aspects to firewalls and the Linux Netfilter subsystem that could not be covered in this chapter. For more information, refer to the following resources.
7.8.1. Installed Documentation
The Reference Guide has a comprehensive chapter on iptables, including definitions for all command options.
The iptables man page contains a brief summary of the various options, as well.
http://www.tldp.org/ — The Linux Documentation Project contains several useful guides relating to firewall creation and administration.
7.8.3. 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 such topics as analyzing firewall logs, developing firewall rules, and customizing your firewall with graphical tools such as lokkit.
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 and iptables. Additional security topics such as remote access issues and intrusion detection systems are also covered.