home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Previous Section Next Section

12.3 Primary Unix Network Services

This section describes selected network services that are usually provided as part of the standard Unix network package, focusing on the major security implications of each of these services.

Every network service carries both known and unknown security risks. Some services have relatively small known risks, while others have substantial ones. And with every network service there is the possibility that a security flaw in the protocol or the server will be discovered at some point in the future. Thus, a conservative security policy would remove every service for which there is no demonstrated need.

Security of Configuration Files and Home Directories

It is very important for the configuration files that control your network services to be properly protected. If they are not, a user of your system could modify the files. Depending on which network service file is modified, this could result in denial of service, loss of privacy, or complete compromise of the system.

For example, if your site runs sendmail (discussed later in this chapter) and has a world-writable aliases file, a user could modify the file so that a copy of every email message that you receive is sent to another address. Alternatively, an attacker could set up an alias to run a program; when email is sent to that alias address, the program will be run as a privileged user. Likewise, if an attacker can change the contents of a user's .forward file, the attacker can redirect a user's mail.

It is not sufficient to assure the security of the individual configuration files: you need to assure the security of the directory containing the configuration files, and all of the directories that contain that directory, all the way back to the system's root directory. In general, none of these directories should be world- or group-writable, and they should all be owned by the superuser. (The notable exception to this rule is the home directories of users who have per-user configuration files; these home directories must be owned by the user, not by root.)

If you think that the risk of a service outweighs its benefit, then you can disable the service simply by placing a hash mark (#) at the beginning of the lines in the /etc/rc* file(s) or /etc/inetd.conf file that cause the server program to be executed. This will comment out those lines. Of course, if you turn off a needed service, people who wish to use it are likely to complain! Remember, too, that disabling a service does not prevent people on your computer from initiating outbound network connections to other computers running that same service.[14]

[14] However, blocking packets for a service using a host-based firewall can be used to block access to a service running on either a local machine or a remote machine, with the caveat that the service won't be blocked if it is running on a port other than the one that you specify. One particularly common siutation in which blocking outbound access can be useful is when an ISP wants all outgoing mail from its clients to be relayed by the ISP's SMTP server (to make it easier for the ISP to detect spammers). By installing a firewall on its network that blocks packets destined to port 25 on any host other than the ISP's SMTP server, the ISP can prevent its clients from running their own SMTP servers and relaying Internet mail.

Most versions of the inetd program do not take notice of any changes to their configurations until they are restarted or sent a HUP (-1) signal. Changes in the startup files do not take effect until you change the run level or restart your system. Thus, if you disable a service, the change may not cause a currently running invocation of the server to terminate—you may need to take some other action before you can verify that you have properly disabled the service.

We recommend that you save a copy of any configuration files before you begin to edit them. That way, if you make a mistake or if something doesn't work as expected, you can roll back to an earlier version of the files to determine what happened. You might consider using the RCS or CVS revision-control systems to manage these files. These systems allow you to put date stamps and comments on each set of changes for future reference. Such markings may also be useful for comparison purposes if you believe that the files have been changed by an intruder, although this isn't a particularly strong form of protection.

For those services that you are determined to enable, take advantage of any logging facilities they offer. See Chapter 21 for more information about logging.

12.3.1 echo and chargen (TCP and UDP Ports 7 and 19)

echo and chargen are two services that were designed for development and testing of IP networks and implementations. The echo service accepts connections on TCP port 7 or individual datagrams on UDP port 7 and echoes back everything that it receives to the sender. The chargen (character generator) service accepts TCP connections and UDP datagrams on port 19 and sends back a character pattern.

For example:

r2# telnet localhost 19 | more
Connection refused
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
 !"#$%&'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg
!"#$%&'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefgh
"#$%&'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi
#$%&'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghij
$%&'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijk
%&'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijkl
&'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklm
'(  )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmn

Although these services are useful for some kinds of testing, they should not be enabled on any computer that is connected to the public Internet. That's because it is possible to use these services, especially the UDP variants, to launch stunningly effective denial-of-service attacks. The attacks can be targeted against the computers that are running the services or against third-party computers.

12.3.2 systat (TCP Port 11)

The systat service is designed to provide status information about your computer to other computers on the network.

Many sites used to configure their /etc/inetd.conf file so that connections to TCP port 11 were answered with the output of the who or w command. You can determine whether your system is still configured in this manner with the telnet command:

unix% telnet media.mit.edu 11
Trying 18.85.0.2... Connected to media.mit.edu.
Escape character is '^]'.
lieber   ttyp0   Aug 12 19:01   (liebernardo.medi)
cahn     ttyp1   Aug 13 14:47   (remedios:0.0)
foner    ttyp2   Aug 11 16:25   (18.85.3.35:0.2)
jrs      ttyp3   Aug 13 17:12   (pu.media.mit.edu)
ereidell ttyp4   Aug 14 08:47   (ISAAC.MIT.EDU)
felice   ttyp5   Aug 14 09:40   (gaudy.media.mit.)
das      ttyp6   Aug 10 19:00   (18.85.4.207:0.0)
...

Although providing this information is certainly a friendly thing to do, usernames, login times, and origination hosts can be used to target specific attacks against your system. We therefore recommend against running this service.

To disable the service, simply comment or remove the line beginning with the word "systat" from your /etc/inetd.conf file. You can also verify that the service has been disabled by using the telnet command:

unix% telnet media.mit.edu 11
Trying 18.85.0.2... Connection refused.
unix%

12.3.3 FTP: File Transfer Protocol (TCP Ports 20 and 21)

The File Transfer Protocol (FTP) allows you to transfer complete files between systems. Its Unix implementation consists of two programs: ftp is the most common client program; ftpd (sometimes named in.ftpd) is the server. TCP port 21 is used for sending commands; port 20 is occasionally used for the data stream, although it is more common for the client and server to mutually negotiate a set of port numbers greater than 1024.

There are several security issues with FTP:

  • When you use FTP to contact a remote machine, the remote computer requires that you log in by providing your username and password; FTP logins are usually recorded on the remote machine in the /usr/adm/wtmp file. Because the passwords typed to FTP are transmitted unencrypted over the network, they can be intercepted (as with the telnet and rexec commands) by an attacker with a packet sniffer.

  • Because of its use of arbitrary ports, active FTP doesn't mix well with packet-filtering firewalls on the FTP server.

  • FTP is a powerful protocol with more than 50 commands. FTP allows the remote user to change working directories, list directories, and even send site-specific commands to the remote system. Because of this richness, there are many opportunities for implementation flaws that could produce security vulnerabilities.

  • Even without implementation flaws, many sites do not wish to give FTP users the ability to switch directories and explore the FTP server's filesystem. To minimize this problem, some FTP servers have provisions for restricting the user's access using the chroot( ) system call.

Because of the security and management problems with FTP, many sites no longer use it. Instead, they use HTTP for downloading files anonymously and either authenticated HTTPS (HTTP over SSL) or sftp or scp (parts of the Secure Shell system) for transferring files where user authentication is first required.[15]

[15] For sites that need to provide FTP connectivity, there are a few products that provide wrappers that can be installed on client and server hosts to transparently encrypt the password or the entire connection. SafeTP (http://safetp.cs.berkeley.edu) is one example.

12.3.3.1 Anonymous FTP

The default mode for FTP is to access an individual account to transfer files. In this mode, a user accesses a particular account and then enters its password. The FTP service then allows the user to specify files to transfer to and from the remote machine. Those files must be accessible to the user on both ends of the connection.

FTP can be set up for anonymous access, which allows people on the network who do not have an account on your machine to deposit or retrieve files from a special directory. Many institutions use anonymous FTP as a low-cost method to distribute software and databases to the public.

To use anonymous FTP, simply specify ftp[16] as your username and your real identity—your email address—as the password:

[16] Some older servers require that you specify "anonymous" for anonymous FTP; most servers accept either username.

% ftp athena-dist.mit.edu
Connected to AENEAS.MIT.EDU.
220 aeneas FTP server (Version 4.136 Mon Oct 31 23:18:38 EST 1988) ready.
Name (athena-dist.mit.edu:fred): ftp
331 Guest login ok, send ident as password.
password: Rachel@ora.com

230 Guest login ok, access restrictions apply.
ftp>

Many Internet FTP sites require that you specify an email address as your "password." Some of these systems verify that the email address looks like a valid email address, but none of them verify that the email address you type is actually your email address.

12.3.3.2 FTP active mode

The FTP protocol supports two modes of operations, active (often called normal) and passive. These modes determine whether the FTP server or the client initiates the TCP connections that are used to send information from the server to the host.

Active mode is the default. In active mode, a client requesting a file provides the server with an IP address and a port number of where that file should be sent. Normally, the IP address and port correspond to a socket on which the client is listening, but this need not be the case. The server then opens a TCP connection to the requested host and port and sends the file, as illustrated in Figure 12-1.

Figure 12-1. Active-mode FTP connection
figs/puis3_1201.gif

Active mode is unfortunate for many reasons:

  • Active mode complicates the construction of firewalls because the firewall must anticipate the connection from the FTP server back to the FTP client program and permit that connection through the firewall.[17]

    [17] Firewalls that employ stateful inspection can usually do this by allowing data connections to individual ports based on its understanding of the state—that the connection is related to an existing FTP control connection.

  • If the firewall employs Network Address Translation (NAT), the firewall must monitor the contents of the FTP control channel and rewrite it so that the IP address sent to the remote IP server is the external IP address, and not the internal, translated IP address.

  • Active mode can be used to attack a site and make it look as if the attack is coming from the FTP server, rather than from the attacker. This is called an FTP bounce attack, and it was documented in CERT Advisory CA-1997-27 (http://www.cert.org/advisories/CA-1997-27.html). A bounce attack can also be used to direct an FTP server to attack computers on a network that is not accessible to the attacker but is accessible to the FTP server.

    To prevent an FTP bounce attack, your FTP server must be configured so that it will open only TCP connections to the host from which the FTP control channel originates. This "fix" violates the FTP RFC, but it is not clear that the ability to initiate third-party FTP transfers should have been put in the RFC in the first place.

Because of the problems that FTP active mode has with firewalls, many FTP implementations now default to passive mode, which is discussed in the next section.

12.3.3.3 FTP passive mode

Under normal circumstances, the FTP server initiates the data connection back to the FTP client. Many FTP servers and clients support an alternative mode of operation called passive mode. In passive mode, the FTP client initiates the connection that the server uses to send data back to the client. (Passive mode is shown in Figure 12-2.) Passive mode is desirable, because it simplifies the task of building a firewall: the firewall simply allows internal connections to pass through to the outside world, but it does not need to allow outside connections to come back in. Not all FTP clients support passive mode, but many do, including the FTP clients that are built in to most popular web browsers. If your software does not yet include it, you should upgrade to software that does.

Figure 12-2. Passive-mode FTP connection
figs/puis3_1202.gif
12.3.3.4 Setting up an FTP server

If you wish to provide FTP service, you have two primary choices regarding your FTP server:

  • You can use the standard Unix ftpd that comes with your system. Depending on your Unix vendor, this version may or may not be secure. Over the years, many security problems have been found with versions of ftpd. Some vendors have been quick to implement the necessary bug fixes; others have not.

  • You can use an alternative FTP server. There are many to choose from these days, including:

    bftpd

    A fast and small FTP server written by Max-Wilhelm Bruker.

    Muddleftpd

    An FTP daemon that is billed as being "simple to set up, fast, secure, and reasonably lightweight."

    NcFTPD

    A commercial FTP server optimized for anonymous FTP access that does not start additional child processes for incoming connections.

    oftpd

    An FTP server described as being "as secure as an anonymous FTP server can possibly be!" because it runs (mostly) as non-root and runs within its own chroot( ) environment.

    ProFTPD

    A highly configurable, GPL-licensed FTP server.

    PureFTPd

    Designed to be a simple and secure FTP server.

    twoftpd

    Another FTP server that "strives to be simple, secure, and efficient." The two in "twoftpd" comes from the fact that there are two parts to the server—a frontend that does authentication and does no file transfer, and a backend that does file transfer but does no authentication. The back end runs in a chroot( ) environment.

    wu-ftpd

    An FTP server originally written at Washington University in Saint Louis. The wuftpd server has many useful options that allow you to create different categories of FTP users, set limits on the number of simultaneous file transfers, and save network bandwidth (by automatically compressing and archiving files as they are transferred).

Some of these FTP daemons are started by the inetd daemon while others are started up at system boot time. Others have their own daemon that is designed to be started at boot time. In general, if you use a third-party FTP daemon, you will need to consult its documentation to determine how it should be started up.

Most FTP servers can either run directly or through a wrapper such as TCP Wrappers. Our discussion of FTP services in the following sections applies to the original Berkeley Unix ftpd server. Many of the FTP servers mentioned in the list implement some or all of the security mechanisms; several of the other servers have additional security options worth studying in their documentation.

12.3.3.5 Restricting FTP with the standard Berkeley FTP server

There are many Unix accounts that do not need to be able to transfer files using FTP. Typically, this category includes all accounts that do not belong to actual human beings (such as root) and possibly others.

The confusingly named /etc/ftpusers file contains a list of the accounts that are not allowed to use FTP to transfer files. For example:

# cat /etc/ftpusers
root
uucp
news
bin
ingres
nobody
daemon

In this example, we specifically block access to the root, uucp, news, bin, and other accounts so that attackers on the Internet will not be able to attempt to log in to these accounts using the FTP program. Blocking system accounts in this manner also prevents the system administrator from transferring files to these accounts using FTP, which is a risk because the passwords can be intercepted with a packet sniffer.

As a further security measure, most versions of FTP will not allow a user to transfer files if the account's shell, as given in the /etc/passwd file of the system, is not also listed in the /etc/shells file.[18] This is to prevent users who have had accounts disabled or who are using restricted shells from using FTP. Before relying on this feature, you should test it with your own server to ensure that it works correctly.

[18] Note that /etc/shells is also used by chsh as a list of allowable shells to change to.

12.3.3.6 Setting up anonymous FTP with the standard Unix FTP server

Setting up anonymous FTP on a server is relatively easy, but you must do it correctly because you are potentially giving access to your system to everybody on the network.

To set up anonymous FTP, you must create a special account with the name ftp. For example:

ftp:*:400:400:Anonymous FTP:/var/spool/ftp:/bin/false

Files that are available by anonymous FTP will be placed in the ftp home directory. You should therefore make the home directory be in a special place, such as /var/spool/ftp.

When it is used for anonymous FTP, ftpd uses the chroot( ) function call to change the root of the perceived filesystem to the home directory of the ftp account. For this reason, you must set up that account's home directory as a mini-filesystem. Three directories go into this mini-filesystem:

bin

This directory holds a copy of the /bin/ls program, which ftpd uses to list files. If your system uses dynamic linking and shared libraries, you must either install programs that are statically linked or install the dynamic libraries in the appropriate directory (e.g., /var/spool/ftp/lib).

etc

This directory holds a version of the /etc/passwd and (optionally) /etc/group files, which are put there so the /bin/ls command will print usernames and groupnames when it lists files. Replace the encrypted passwords in these files with asterisks. Some security-conscious sites may wish to delete some or all account names from the passwd file. The only account name that needs to be present is ftp. (Actually, if neither file exists, most FTP servers will still work normally.)[19]

[19] Some FTP administrators have been known to create bogus password and group files, with random character strings in the password field. We have heard stories of miscreants who thought they found a badly-configured FTP service, downloaded these files, and then burned weeks of CPU time trying to crack the "passwords." At least a few sites have actual accounts and passwords in these files; however, these are passwords to "jails" that are carefully crafted to look like real accounts, but that are used to gather information about potential intruders. We don't recommend this approach for the average user, but we do find it amusing to note.

pub

This directory, short for "public," holds the files that are actually made available for anonymous FTP transfer. You can have as many subdirectories as you wish in the pub directory.

Be sure to place copies of the actual files (or hard links to them) in the mini-filesystem, rather than using symbolic links pointing to other places on your system. Because the ftpd program uses the chroot ( ) system call, symbolic links may not behave properly with anonymous FTP. In general, symbolic links to inside your chroot area will work, and they are commonly used on anonymous FTP sites. However, any symbolic link that points outside the chroot area or is an absolute symbolic link will not work.

You can do all of the operations we've discussed above by executing the following commands as the superuser. We assume that you've already created ~ftp.

# mkdir ~ftp/bin ~ftp/etc ~ftp/pub           Create needed directories.

Set up ~ftp/bin:

# cp /bin/ls ~ftp/bin                        Make a copy of the ls program.
# chown root ~ftp/bin/ls                     Make sure root owns the program.
# chmod 111 ~ftp/bin/ls                      Make sure ls can't be changed.
# chmod 111 ~ftp/bin                         Make directory execute-only.
# chown root ~ftp/bin                        Make sure root owns the directory.

Set up ~ftp/etc:

# cat-passwd awk -F: '{printf "%s:*:%s:%s::\n",$1,$2,$3}' > ~ftp/etc/passwd     
                                            Make a copy of /etc/passwd with 
                                             all passwords changed to asterisks.
# awk -F: '{printf "%s::%s:%s\n",$1,$3,$4}' /etc/group > ~ftp/etc/group 
                                            Make a copy of /etc/group.
# chmod 444 ~ftp/etc/*                       Make sure files in etc are not writable.
# chmod 111 ~ftp/etc                         Make directory execute-only.
# chown root ~ftp/etc                        Make sure root owns the directory.

Set up ~ftp/pub:[20]

[20] You may wish to use a permission of 1777 instead, if you wish to allow anonymous drop-off into the ~ftp/pub directory. But see the sidebar entitled "Don't Be Warezed!" first.

# chown root.wheel ~ftp/pub                  Make sure root owns the directory.
# chmod 555 ~ftp/pub                         Make directory writable by nobody (see warning).

And finally, secure the ~ftp directory:

# chmod 555 ~ftp
# chown root ~ftp

Many ftp servers work fine if the only entries in the passwd file are for root and ftp, and the only entry in the group file is for group ftp. The only side effect is that files left in the ftp directories will show numeric owners and groups when clients do a directory listing. The advantage to having a trimmed file is that even if outsiders do obtain a copy of the file, they will not be able to gain any clues as to your system's user population. The disadvantage is that the dir command will not show symbolic usernames.

Some systems require you to install dynamic libraries and even device files to make the FTP server's file list command work. This is somewhat problematic, as the more complicated it is to set up an anonymous FTP server, the greater the chances are that you will make a mistake. For this reason, many second-generation FTP servers have built-in implementations for the FTP dir command and, as a result, it is considerably simpler to set up these servers for anonymous and chroot( )ed access.

In general, the fewer files accessed in the anonymous FTP area, the harder the system will be to compromise.

Some manpages from some vendors state that the ~ftp directory should be owned by user ftp. This practice is dangerous! If user ftp owns the home directory, anonymous users can change the FTP environment, delete or create new files at will, and run any program that they choose. They can also create .rhosts files to gain direct access to your system!

You should also set up a mail alias for the ftp user so that mail sent to ftp is delivered to one of your system administrators.

Don't Be Warezed!

Years ago, organizations that ran FTP servers would routinely create an "open" directory on their servers so that users on the network could leave files for users of the system. Unfortunately, software and music pirates and purveyors of pornography soon started using those directories as repositories for illegally copied programs, files of stolen passwords, and nasty pictures. Collectively, such contraband is known as warez. Today, if you have a directory on an anonymous FTP server that is writable by the FTP user, the odds are quite high that it eventually will be discovered and used in this manner. If this happens, you may be contributing to large-scale software or media theft; you will also find that your Internet connection's bandwidth is quickly filled up, making it unusable for practically anything else.

Of course, some sites still wish to create "depository" directories on their FTP servers so that users on the network can leave files for users of their system. The correct way to do so is to create a depository that is carefully controlled and automatically emptied:

  1. Create a directory that is writable, but not readable, by the ftp user. The easiest way to do so is to make the directory owned by root and give it a mode of 1733. In this manner, files can be left for users, but other users who connect to your system using anonymous FTP will not be able to list the contents of the directory.[21]

  2. Put a file quota on the ftp user to limit the total number of bytes that can be received. (Alternatively, locate the anonymous FTP directory on an isolated partition.)

  3. Create a shell script that automatically moves any files left in the depository that are more than 15 minutes old into another directory that is not accessible by the anonymous FTP user. You may also wish to have your program send you email when files are received.

  4. Place an entry in your /usr/lib/crontab file so this script runs automatically every 15 minutes.

Alternatively, you can set up an email account that can accept large attachments, or create a small web application that allows users to upload files of a given size.

Be sure to test your handiwork, and good luck!

[21] If you are using the wu archive server, you can configure it in such a way that uploaded files are uploaded in mode 004, so they cannot be downloaded by another client. This provides better protection than simply making the directory unreadable, as it prevents people from uploading files and then telling their friends the exact filename to download (before your script can move the file). If you are writing your own server, this is a good idea to include in your code.

12.3.3.7 Allowing only FTP access

Sometimes, you may wish to give people permission to FTP files to and from your computer, but you may not want to give them permission to actually log in. One simple way to accomplish this goal is to set up the person's account with a special shell, such as /bin/ftponly. Follow these directions:[22]

[22] If you are using wuftpd, note that there is a feature which allows a similar configuration.

  1. Create a shell script /bin/ftponly, which prints a polite error message if the user attempts to log into his account. Here is an example:

    #!/bin/sh
    /bin/cat << XX
    
    You may use FTP to put files on this computer, but you may
    not use this account to login.
    -The Management
    
    XX
    /usr/bin/sleep 10
  2. Create your user account with /bin/ftponly as its shell:

    kelly:Mqu3lQJ41kf/E:502:20:Jim Kelly:/Users/kelly:/bin/ftponly
  3. Finally, add the file /bin/ftponly to the file /etc/shells:[23]

    [23] On AIX, shells must be added to the /etc/security/login.cfg file.

    # List of acceptable shells for chsh/passwd -s
    # Ftpd will not allow users to connect who do not have one of 
    # these shells
    #
    /bin/sh
    /bin/csh
    /bin/ftponly

12.3.4 SSH: The Secure Shell (TCP Port 22)

Originally developed by Tatu Ylonen, SSH (the Secure Shell) is a cryptographically enabled protocol for remote login, file copying, and TCP connection tunneling (perhaps better known as port forwarding by SSH users). Although originally implemented solely by Tatu Ylonen's ssh command-line Unix utility, today the SSH protocol is implemented by dozens of programs on many platforms. The two most popular Unix implementations are Ylonen's original SSH, and OpenSSH, developed by the OpenBSD Project. Commercial clients and servers are also available.

Isolated Services Offer Additional Security

Two of the oldest principles of security are minimization and separation of function. You can use these two principles to have a more secure FTP server (and a more secure web server, too). You do this by configuring a separate, standalone machine as your server. Don't put any user accounts on it. Remove all the commands and libraries that aren't needed. If you have the source to build the kernel, build it with only the options needed to support your server. Then load the server with additional security software alarms and logging.

If the server has no other services running, then those services can't be points of attack. If there are no user accounts on your machine, there is no way to break into them. And if the software and kernel have been minimized, that reduces the chances of a future bug being discovered that gives away the system. As a side effect, you might find that you can get a lot out of an older machine—without all those other services and users, you don't use as much disk of CPU, and the unused resources can thus remain available for use by your server!

You can buy a perfectly serviceable, somewhat older computer for a few hundred dollars in the U.S. You may even have one sitting in storage because it wasn't fast enough to run the latest bloated software release that management wanted installed. The cost will be minimal, but the protection gained will be well worth it.

There are two versions of the SSH protocol. Although both protocols allow the symmetric cipher to be negotiated, SSH Version 1 relies on the RSA public key encryption algorithm for authentication and initial key exchange. SSH Version 2 has extended the protocol by allowing for both the RSA and the DSA public key encryption algorithms and has corrected several flaws in the SSH1 protocol. Version 2 is therefore recommended.

Behavior of the SSH server is determined by the sshd_config file, which can be in the /etc/, /etc/ssh, /usr/local/etc, or /usr/local/etc/ssh directories. The behavior of the SSH client is likewise controlled by the file ssh_config. Systems that have been running SSH for extended periods of time tend to have multiple SSH configuration files in multiple locations, as different releases of the software have changed the location where the configuration file resides. If you have SSH installed on your system, you should be sure that there is only one sshd_config file and one ssh_config file. If there are multiple files, there is a chance that you will make important security-related modifications to the wrong file. Because this is a very important file from a security perspective, you will probably want to track changes to it using an appropriate source code control system, such as RCS or CVS.

12.3.4.1 Host authentication with SSH

Every host that runs an SSH server is supposed to have its own unique RSA public and private key pair, called the SSH HostKey. Version 2 servers have a second public key pair called the HostDSAKey that uses the DSA encryption algorithm. Most SSH startup scripts will automatically create this key the first time that the server is run if the key does not already exist. The size of the RSA key is determined by the ServerKeyBits variable in the sshd_config file.

When an SSH client connects to the server, the server provides its public key. This key serves two purposes. First, the client uses this key to encrypt information that is sent back to the server during the authentication phase. Second, the public key is used by the server to establish its identity. Each time a client connects to the server, the server provides the same public key to the client; the client is thus able to determine, each time it connects to the server, that it is communicating with the same server as it was on previous occasions.

For example, the first time you connect to a new server with SSH, you might see a message that looks like this:

% ssh k1.net
The authenticity of host 'k1.net (204.17.195.90)' can't be established.
RSA1 key fingerprint is 01:1d:e0:19:72:20:9e:6c:81:36:20:87:02:1c:7a:aa.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'k1.net' (RSA1) to the list of known hosts.
simsong@k1.net's password: no54password

Last login: Fri Jul 26 17:05:04 2002 from sdsl-64-7-15-235
Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994
        The Regents of the University of California.  
        All rights reserved.
FreeBSD 4.4-STABLE (KING1) #3: Sun Dec 30 22:47:59 EST 2001

UNAUTHORIZED USE OF THIS SYSTEM IS PROHIBITED AND MAY BE PROSECUTED
TO THE FULL EXTENT OF THE LAW. IF YOU ARE NOT AN AUTHORIZED USER, LOG
OFF NOW!

BY USING THIS COMPUTER, YOU IMPLICITLY GIVE CONSENT TO BE MONITORED BY
K1.NET AND LAW ENFORCEMENT AGENCIES.

[simsong@king1 ~] 301 %

(We couldn't resist showing you a good login banner while we were at it; see the discussion of banners in Chapter 10.)

When the user types yes, the host and its HostKey are added to the user's ~/.ssh/known_hosts file. This file is used both for authenticating remote hosts when they are servers and verifying the identity of users on those remote hosts attempting to SSH into the current host.

Here is the file, by the way:

% cat .ssh/known_hosts 
nitroba.com 1024 35 
1221279801154411047137592780814914240404071816269386780586932489285347521546124117334
7072000249547792523281132073298893235325626460107271167220564024129338624392067682243
1031349991570643961150703034229390489100811195468563413901808940705090204157836601269
074879528767596794520295502327033979623422605015530523
k1.net 1024 35 
1717108657502938468089901929560853045921804378401153006150018098780333649932986316689
5489594546067426463746514797728944186038454047514021440966626196421332883322967452080
2945453703996092707501281813463111467013984910036252588169600476313982544037218325442
275801292413736097002222827453938912602640839717646689
%

The first key was already present; the second key is the key for k1.net, which was added by the SSH example.

On successive connections to the server, no mention is made of the host key:

% ssh k1.net
simsong@k1.net's password: no54password

Last login: Fri Jul 26 17:05:04 2002 from sdsl-64-7-15-235
Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994
        The Regents of the University of California.  
        All rights reserved.
FreeBSD 4.4-STABLE (KING1) #3: Sun Dec 30 22:47:59 EST 2001

...

But if the host key changes, you might see a message like this:

% ssh k1.net
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA1 host key has just been changed.
The fingerprint for the RSA1 key sent by the remote host is
01:1d:e0:19:72:20:9e:6c:81:36:20:87:02:1c:7a:aa.
Please contact your system administrator.
Add correct host key in /usr/home/simsong/.ssh/known_hosts to get rid of this 
message.
Offending key in /usr/home/simsong/.ssh/known_hosts:2
RSA1 host key for k1.net has changed and you have requested strict checking.
[simsong@king1 ~] 199 %

The host key protects against two kinds of attacks:

  • It assures that you are connecting to the correct host. If the host you intend to connect to has changed its IP address or has a new DNS name (or if somebody has attacked your DNS system and it is handing out the wrong IP addresses), the SSH client will note that the new host has a different HostKey from the older address and you will, presumably, not provide your password.

  • It assures that you will have an encrypted connection directly to the remote server, and that no intermediate machine is engaging in a man-in-the-middle attack. For a successful man-in-the-middle attack to take place, an attacker would need to provide his own public key—a public key to which he presumably had the matching private key. (An attacker mounting a man-in-the-middle attack would not provide the HostKey of the server under attack because if he did, he would be unable to decrypt the resulting communications.)

The HostKey is a good idea. Unfortunately, HostKeys seem to change on a fairly regular basis—sometimes whenever a new operating system is installed, or when a new SSH installation inadvertently creates a new host key rather than preserving the old one. Therefore, if the HostKey of a server that you communicate with changes, you shouldn't assume that the server has been compromised or that a man-in-the-middle attack is taking place. But you might want to look into why the key was changed.

12.3.4.2 Client authentication with SSH

The SSH server runs as the superuser. When a client connects to the SSH server, the client provides the username of the account that it wishes to use. It then provides a suitable authentication credential to prove that it is entitled to the account. If the server is satisfied by the client's credentials, it changes its UID to the user's UID, starts up a copy of the user's shell, and logs in the user.

SSH offers a variety of methods for authenticating clients to the server's operating system:

  • Clients can provide a valid password for the account on the remote server.

  • Clients can prove their identities using public key cryptography if the client presents a public key that is in the file ~/.ssh/authorized_keys and can decrypt information that is encrypted with that public key.

  • Clients can provide a username and come from a host that is listed in the user's ~/.rhosts or ~/.shosts file. The host must be a host that is listed in the user's ~/.ssh/known_hosts file.

  • Clients can provide a username and come from "trusted hosts" listed in the /etc/hosts.equiv or /etc/ssh/shosts.equiv file. The hosts can be authenticated solely on the basis of DNS, in which case this authentication system is equivalent to the authentication system used by the Berkeley "r" commands (rsh, rcp, and rlogin). The host can also be authenticated using its SSH host key if the public key is stored in the file /etc/ssh_known_hosts on the server's computer.

  • Clients can authenticate using Kerberos.

Some or all of these authentication modes can be controlled through commands in the sshd_config file. Table 12-5 contains a sampling of commands implemented by the OpenSSH server.

Table 12-5. sshd_config commands

Command

Meaning

HostKey filename

Specifies the location of the host's RSA key.

HostDsaKey filename

Specifies the location of the host's DSA key.

ServerKeyBits nnn

Specifies the number of bits in the server's RSA key. Longer keys offer more security but increase the amount of time required to log in to the remote hosts. In 2002, a typical compromise between speed and security was 768 bits; by 2004, a better value might be 1,024 bits or even 2,048 bits.

PermitRootLogin [yes|no]

Specifies whether or not the superuser should be allowed to log into the system using SSH. Unless you have a specific reason to allow the superuser to log in remotely (for example, so that a script can be automatically run as root from a remote machine), this value should be no.

IgnoreRhosts [yes|no]

If yes, users may not specify trusted hosts in their ~/.rhosts and ~/.shosts files.

RhostsAuthentication [yes|no]

If yes, use the trusted host mechanism to allow remote authentications. Applies only to SSH1. Not recommended.

RHostsRSAAuthentication [yes|no]

If yes, use the trusted host mechanism for hosts in rhosts files with keys in /etc/ssh_known_hosts. Applies only to SSH1.

HostbasedAuthentication [yes|no]

If yes, use the trusted host mechanism for hosts in rhosts files with keys in /etc/ssh_known_hosts. Applies only to SSH2.

RSAauthentication [yes|no]

Allows users to authenticate using a personal RSA public key. Applies only to SSH1.

PubkeyAuthentication [yes|no]

Allows users to authenticate using a personal RSA or DSA public key. Applies only to SSH2.

PasswordAuthentication [yes|no]

Allows users to authenticate using a password.

ChallengeResponseAuthentication [yes|no]

Allows users to authenticate using a system-defined challenge/response protocol like S/Key or Kerberos. This feature requires operating system support.

PermitEmptyPasswords [yes|no]

If no, then accounts without passwords may not be accessed using SSH.

12.3.5 Telnet (TCP Port 23)

Telnet is a service designed to allow you to log onto a remote computer on the Internet. Telnet gives you a "virtual terminal" on the remote computer. The Unix version of Telnet is implemented with the telnet client and telnetd server programs. The client program is quite flexible: in addition to contacting the appropriate servers, the client can be used to open a connection to any TCP/IP-based server that uses a text-based protocol.

To use telnet, type the name of the command followed by the name of the computer to which you wish to connect. When you get the prompt, simply log in as if you had called your computer using a modem connected via a hardwired terminal:

% telnet prose
Trying...
Connected to prose
Escape character is '^]'

4.3 BSD Unix (prose.cambridge.ma.us)

login: nancy
password: T wrink

The Telnet protocol poses significant risks to its users. The username, password, and all other session data are transmitted over the network without encryption. On many kinds of networks, such as Ethernet, the packets sent between computers are actually delivered to every computer on the physical piece of wire. The computers on the network are programmed to respond only to the packets that are intended for them. But it is possible to program a computer to force it to listen to and record every packet transmitted. Special programs can capture the first hundred characters (or more) sent in both directions on a Telnet connection and thereby capture your username and password. (Wireless networks pose an even worse risk!)

Packet sniffing is more than a danger on your local area network because the Telnet session packets are vulnerable throughout their journey. In recent years, there have been many cases of Internet Service Providers who have had a single computer on their internal network compromised; every Telnet connection passing through that ISP had its password captured as a result. The best ways to defeat packet sniffing are through the use of one-time passwords and encryption.

A second danger of Telnet is that an attacker can sometimes (especially on older versions of Unix without adequate sequence number randomization) take control of a Telnet session that is in progress using a technique called session hijacking . For example, after you log in using your password, the attacker can seize control of the session and type whatever commands he wishes. The only way to eliminate the possibility of Telnet hijacking is through the use of encryption.

Because of the risk of packet sniffing, logging into your computer with Telnet poses a significantly greater security risk than dialing into a computer system using a modem over the public-switched telephone network.

Because of the dangers of eavesdropping, password sniffing, and connection hijacking, the Telnet protocol should not be used for remote login to any service that requires authentication or that passes confidential information. Instead, you should use the Secure Shell service (TCP port 22).

12.3.6 SMTP: Simple Mail Transfer Protocol (TCP Port 25)

The Simple Mail Transfer Protocol (SMTP) is an Internet standard for transferring electronic mail between computers. Unix systems implement the SMTP protocol with programs or systems called Message Transfer Agents (MTAs). MTAs usually implement both the client and server sides of the SMTP protocol, although this is not a requirement.

It is possible for a user to send email directly using an MTA, but it can be awkward. Instead, users more often employ programs called Message User Agents (MUAs) to send, download, and read their email. Popular MUAs include Eudora, GNU Emacs, MacOS Mail, and Microsoft Outlook. Optimized for interacting with users, rather than for dealing with the vagaries of Internet email, these programs are configured for interacting with a single MTA, and simply dump all of their outgoing email to the designated "SMTP server."

Traditionally, Unix systems used the program sendmail as an MTA, although today there are many alternatives, including:

exim

A popular MTA developed at the University of Cambridge. Because it is distributed under the GPL, exim is the default mailer on many Linux systems. exim is designed to be scalable, secure, and easy to configure.

postfix

A full-featured Internet email system for Unix developed by Wietse Venema as a drop-in replacement for sendmail. postfix was designed to be a secure mailer capable of high throughput. Unlike sendmail, the postfix system is implemented with many small programs, each of which is designed to perform a specific task. postfix is used by many ISPs.

qmail

A full-featured Internet email system for Unix developed by Dan Bernstein. Like postfix, qmail was designed as a secure MTA capable of high throughput. If you use qmail, we recommend that you replace inetd with Bernstein's tcpserver program.

sendmail

Written by Eric Allman, the first Unix mail system to implement Internet standard mail protocols. This program was distributed as part of the original Berkeley 4.2 Unix distribution and since that time has been distributed with the vast majority of Unix distributions since. By many accounts, sendmail remains the most widely used mailer on the Internet today. Because of its long history, sendmail has undergone numerous revisions.

All of these mailers can perform the following functions:

  • Deliver mail to individual user mailboxes or to files.

  • Implement a list of aliases that specify rewriting rules for email addresses. Aliases can also be used to create simple mailing lists. Aliases are traditionally located in the aliases file, usually in the /usr/lib, /etc, /etc/mail, or /etc/sendmail directories. Some Unix mailers can also use aliases that are stored in databases.

  • Determine if an email message should be sent to another machine, and automatically send it to that machine using SMTP.

  • Pipe mail messages to programs as standard input.

  • Provide a command-line utility for sending email. This program, traditionally called sendmail, is used primarily by scripts and programs to send email.

  • Allow individual users to set up an alias for their accounts by placing a file with the name .forward in their home directories.

Each of these mail systems has a complex set of configuration files and accessory programs, and each has security risks and advantages. All of them can be run securely, and all of them can be run in a manner that compromises your system's security.

SMTP servers have historically been a source of security problems for Unix systems. No matter which SMTP server you use, you should be absolutely sure that you are running the most recent version of the server, and that you monitor the appropriate web site or security mailing list for news of newly discovered vulnerabilities.

When security flaws are announced, potential intruders are often much quicker to attack than system administrators are to upgrade. (In many cases, sites have been attacked within hours of vulnerability announcements.) We advise you to upgrade as quickly as possible.

Because of their importance and position on the network, email systems have become an important location for implementing additional security features. For example:

  • Many viruses for Windows-based computers propagate by sending themselves to other Windows users via email. By automatically scanning all email messages for known viruses and dropping messages that contain viruses, it is possible to protect users of Microsoft operating systems from some hostile programs that might otherwise compromise their computer systems.

  • Many individuals who send out unwanted email, otherwise known as spam, do so using "throw-away" accounts that they purchase on a "trial" basis from ISPs. By limiting the number of email messages that a user can send to 500 or 1,000 per day, ISPs and other organizations can effectively prevent their users from engaging in spamming.

SMTP and TLS

The best way to assure the confidentiality of email moving over the Internet is to encrypt the messages using a system like PGP or S/MIME. Such systems provide for end-to-end encryption and assure that even if a mail server is compromised, the content of the encrypted message will remain protected. However, it can be difficult for users to deploy the necessary keys and software to use PGP or S/MIME. SMTP TLS provides a more convenient alternative.

SMTP TLS provides encryption of email as it passes over the Internet, which primarily protects the messages from monitoring by ISPs and, to a lesser extent, government agencies. If this sort of monitoring is a concern to you, then you may wish to deploy SMTP TLS on your mail servers.

Messages sent via SMTP TLS are encrypted only when one TLS-equipped MTA is communicating with another similarly equipped MTA. Messages are not encrypted when they're stored on disk in a server's mail queue. This is a far cry from end-to-end encryption but still represents an improvement over no encryption at all, particularly if you send a lot of messages directly from one TLS-equipped system to another.

The SMTP STARTTLS command allows two compatible servers to automatically switch from a cleartext conversation into a conversation that is encrypted with the TLS encryption protocol.

The TLS protocol provides for strong authentication, protection from eavesdropping, and integrity assurances. When used with SMTP, TLS can be used to authenticate SMTP users (for anti-spam measures) and to complicate eavesdropping. Using TLS requires that the MTA be equipped with a SSL/TLS library (such as OpenSSL) and the appropriate keys and certificates.

Support for SMTP TLS was added to sendmail Version 8.11.6 and exim Version 3.2; as of this writing there are patches for SMTP TLS available for postfix and qmail.

  • In a similar manner, many different mechanisms exist to detect spam in incoming email. The various filters and database lookups required can be added to a mail system to prevent some spam from getting through to end users.

There are a number of security issues arising with SMTP and MTAs that we'll explore in the following sections. These include:

  • Configuration files

  • Security concerns with SMTP banners and commands

  • SMTP relaying and bulk email (a.k.a. spam)

  • Overflowing mailboxes

  • Delivery to programs

  • Overall security of Berkeley sendmail versus other MTAs

12.3.6.1 Configuration files

sendmail uses several configuration files to control its operation, including sendmail.cf, the master configuration file, and .forward files in each user's home directory. Many sendmail configuration files are maintained as text files but compiled into database files; for example, the aliases file is often compiled into aliases.dir and aliases.pag (or a single aliases.db file).

Modern versions of sendmail check ownership of all configuration files and directories that contain configuration files, as well as directories where messages are spooled. If a directory of questionable permission is found, sendmail will report an error, such as:[24]

[24] You can disable specific sendmail security checks using the DontBlameSendmail configuration option. You can find the list of checks that can be disabled in the sendmail documentation or at http://www.sendmail.org/tips/DontBlameSendmail.html. We strongly discourage disabling any checks.

WARNING: writable directory /etc/mail
WARNING: writable directory /usr/spool/mqueue
12.3.6.2 Security concerns with SMTP banners and commands

SMTP is a text-based, asynchronous protocol that has been in use since 1983; previous versions of SMTP and MTP were in used in the 1970s.[25] While the protocol itself is quite simple, the functions that an MTA needs to invoke on the host computer to properly satisfy the requirements of the protocol can be quite complex. For this reason, SMTP implementations have been a cause of many security vulnerabilities.

[25] RFC 821 (August 1982) defined the original SMTP protocol; RFC 822 (August 1982) defined the standard format for Internet email messages. RFC 974 (January 1986) defined how mailers should route messages based on DNS information. The SMTP Service Extension framework was defined in RFC 1869 (November 1995). RFC 2821 (April 2001) is a proposed standard that obsoletes RFC 821, RFC 974, and RFC 1869.

SMTP is also an evolving protocol. In recent years the protocol has been enhanced with mechanisms for sender authentication and encryption. Other functions remain in the protocol but are now largely blocked because of security concerns.

When an SMTP server receives a connection, it sends a banner to the SMTP client. Traditionally, this banner included the name and version of the MTA implementing the SMTP server. You can see what banner your SMTP server sends to clients by testing it using the telnet command. For example:

% telnet localhost smtp
Connected to localhost.
Escape character is '^]'.
220 ex.com ESMTP Sendmail 8.11.6/8.11.6 ready at Sat, 20 Jul 02 10:54:29 -0400 EDT

In general, it is not good practice for your server to reveal its identity in this fashion. Certain servers have well-known security flaws. By providing its version numbers to all SMTP clients, this server makes it easier for an attacker to scan for vulnerable servers. These banners can usually be changed; consult your SMTP server's documentation.

The SMTP protocol has a "help" command that causes the server to display an informative message. Sometimes help messages can contain version numbers as well. For example:

% telnet localhost smtp
Connected to localhost.
Escape character is '^]'.
220 ex.com ESMTP Sendmail at Sat, 20 Jul 2002 10:55:57 -0400 (EDT)
help
214-This is Sendmail version 8.11.6
214-Topics:
214-    HELO    EHLO    MAIL    RCPT    DATA
214-    RSET    NOOP    QUIT    HELP    VRFY
214-    EXPN    VERB    ETRN    DSN
214-For more info use "HELP <topic>".
214-To report bugs in the implementation send email to
214-    sendmail-bugs@sendmail.org.
214-For local information send email to Postmaster at your site.
214 End of HELP info

Besides leaking information about your MTA version, the SMTP protocol can leak significant information regarding the names and email addresses of users at your organization. Historically, this information has been used most often by individuals and organizations sending bulk email. Thus, you may wish to disable any SMTP commands that leak email addresses.

Table 12-6 lists some SMTP commands that have historically had security concerns. You should determine whether you wish to implement these commands at your site; security-conscious sites should implement none of them. You should then periodically test your SMTP servers to determine how they behave when presented with these commands. For example:

% telnet localhost smtp
Connected to localhost.
Escape character is '^]'.
220 rnitroba.com ESMTP Postfix
wiz
502 Error: command not implemented
debug
502 Error: command not implemented
expn simsong@nitroba.com
502 Error: command not implemented
vrfy simsong@nitroba.com
252 <simsong@nitroba.com>
vrfy nosuchaddress@nitroba.com
252 <nosuchaddress@nitroba.com>
help
502 Error: command not implemented
221 Bye
Connection closed by foreign host.

Table 12-6. SMTP commands with security concerns

Command

Purpose

Recommended action

EXPN

Expands an email address, revealing all of the users or mailboxes who will receive messages sent to this address.

Disable.

VRFY

Verifies whether email sent to a particular address will be accepted or rejected.

Always return the affirmative.

WIZ

Nonstandard SMTP extension in Berkeley sendmail designed to give remote superuser access to anyone knowing the "wizard password." This command is not present in modern versions of sendmail.

Disable.

DEBUG

Nonstandard SMTP extension in Berkeley sendmail designed to give remote superuser access for debugging purposes. This command is disabled by default in modern versions of sendmail.

Disable.

HELP

Displays a list of valid SMTP commands accepted by this MTA.

Disable.

Each MTA has its own system for configuring which SMTP commands are implemented. With sendmail, the specific commands are controlled with options that are placed in the file sendmail.cf. This file is usually built from a much shorter sendmail.mc file written in the m4 macro language. Example 12-4 shows a typical sendmail.mc file with several features enabled; this file generates a sendmail.cf file of about 1,500 lines.

Example 12-4. A typical sendmail.mc file
VERSIONID(`$Id: ch12.xml,v 1.5 2003/04/09 21:35:32 becki Exp $')
OSTYPE(linux)dnl
DOMAIN(generic)dnl
TRUST_AUTH_MECH(`CRAM-MD5')dnl
FEATURE(`access_db')dnl
FEATURE(`smrsh')dnl
FEATURE('nouucp',`reject')dnl
define(`confSMTP_LOGIN_MSG',`$j smtp service; $b')dnl
define(`confPRIVACY_FLAGS',`goaway,restrictmailq')dnl
MAILER(smtp)dnl
MAILER(local)dnl
MAILER(procmail)dnl

The confSMTP_LOGIN_MSG definition shows how the SMTP banner can be changed to display only the hostname ($j) and the current time ($b). The confPRIVACY_FLAGS definition specifies options that control information leakage; a list of some options that you might wish to use are contained in Table 12-7.

Table 12-7. Security options in sendmail

Option

Effect

Purpose

novrfy

Disables VRFY command

VRFY can be used by outsiders to determine the names of valid users; use novrfy to disable this command.

noexpn

Disables EXPN command

EXPN reveals the actual delivery addresses of mail aliases and mailing lists; noexpn disables this command.

needmailhelo

Requires HELO before a MAIL command

Refuses mail unless the sending site has properly identified itself.

needvrfyhelo

Requires HELO before VRFY command

Allows the use of the VRFY command, but only after the network user has identified himself.

needexpnhelo

Requires HELO before EXPN command

Allows use of the EXPN command, but only after the network user has identified himself.

authwarnings

Enables several authentication warnings

Causes an X-Authentication-Warning header to be inserted in email messages when hosts or users claim to be who they're not or when local users run sendmail with their own configuration file.

noverb

Disables VERB command

VERB causes sendmail to be more verbose in its responses to SMTP commands, which may provide more information that you want; noverb disables this command.

goaway

All of the above

An easy way to minimize information leakage. Recommended.

restrictmailq

Restricts use of the mailq command

If set, allows only users who belong to the group that owns the mail queue directory to view the mail queue. This restriction can prevent others from monitoring mail that is exchanged between your computer and the outside world. Recommended.

If you are using sendmail and the system responds to the WIZ command with anything other than an error, then you should upgrade to the most recent version of sendmail available.

12.3.6.3 SMTP relaying and bulk email (a.k.a. spam)

By design, SMTP servers accept email from the Internet and deliver the mail to its intended destination. When the email is destined for a local mailbox, the mail should be delivered. When the mail is destined for another host, the mail is relayed.

Relaying is an integral part of the SMTP protocol and vital to the proper functioning of Internet email. A large organization might have hundreds of individual users with desktop computers that wish to be able to send mail. Managing hundreds of MTAs can be a very hard task; that task can be made manageable if each computer is configured to send outgoing email messages to a single computer, which then relays the messages to the rest of the Internet as appropriate. Relaying can also improve the reliability of receiving Internet messages: many domains will designate secondary mail servers that can receive their mail if the primary mail server is down. This allows for all of the mail to be spooled in a single location and to be delivered in an orderly fashion when the computer comes back up.

Unfortunately, SMTP relaying has been exploited by individuals and organizations that send large amounts of bulk electronic mail (sometimes known as spam). These so-called spammers have programs that will connect to another organization's SMTP server and send a single message that has dozens or even hundreds of recipients. Following the design of the protocol, the victim organization's SMTP server will then methodically copy the message and deliver it to each of the recipients, whether they want it or not. To make matters worse, many of the addresses on the spammer's list may no longer be valid. These undeliverable messages frequently end up in the mailbox of the system administrator.

Because of abuse by spammers, modern MTAs have provisions designed to prevent or severely restrict the use of the SMTP server for sending third-party email. Here is a typical set of rules:

  • Users who are authenticated members of the organization that runs the computer system are allowed unlimited use of the SMTP server. Users are typically authenticated through one of three techniques:

    Through IP address

    The system is configured with a set of IP addresses that are allowed unrestricted relaying.

    Through a username and password

    Authentication mechanisms that are part of Extended SMTP are used here.

    Through an external mechanism

    One of the most common mechanisms is called "POP before SMTP." This mechanism requires that a user be able to download a message using POP before he is allowed unrestricted SMTP access.

  • These rules allow authenticated users to send email to anywhere on the Internet.

  • Messages that are delivered over SMTP connections that are not authenticated are accepted only for a preconfigured set of domains. This rule allows anybody on the Internet to send email to users of the server.

The configuration technique is different for each MTA. postfix, for example, is configured with a set of "trusted" networks using the mynetworks variable and a mydestination variables; both are set in the file main.cf.

12.3.6.4 Overflowing system mailboxes

The Unix operating system uses accounts without corresponding real users to perform many system functions. Examples of these accounts include uucp, news, and root. Unfortunately, the mail system will happily receive email for these "users."

Email delivered to one of these accounts normally goes only to a mail file. There, it resides in your /var/spool/mail directory until it is finally read. On some systems, there is mail waiting for users with the names news or ingres that is more than five years old.

Is this a problem? Absolutely:

  • These mail files can grow to be several megabytes long, consuming valuable system resources.

  • Many programs that run autonomously will send mail to an address such as http or daemon when they encounter a problem. If this mail is not monitored by the system administrator, problems can go undiagnosed.

You can avoid the problem of phantom mail by creating mail aliases for all of your system, nonuser accounts. To make things easy for future system administrators, you should put these aliases at the beginning of your aliases file. For example:

#
# System aliases
#

root:           debby
Postmaster:     root
usenet:         root
news:           root
agent:          root
sybase:         root
MAILER-DAEMON:  postmaster
abuse:          postmaster

All Internet hosts that run email servers must define a postmaster alias, and mail sent to the postmaster should be promptly read by a human being. Defining an abuse alias is also good practice; if one of your users should send spam through your server, recipients will often expect to be able to report it to this alias.

System mailboxes can also be configured so that their messages are gatewayed to locally-managed newsgroups or web pages. Such configuration has the advantage of providing for access by multiple individuals, archiving, and searching.

12.3.6.5 Delivery to programs

Mail does not have to be delivered to a mailbox; it can also be delivered to a program. One such program is the vacation program, which sends out a polite message telling the sender of the mail that the recipient is on vacation and is not able to respond to messages immediately. Many mailing list programs, such as majordomo and mailman, also work by having the received mail sent to a program, rather than to a mailbox.

Because programs that receive mail messages frequently run as a privileged user, they can be a source of security vulnerabilities. These programs potentially receive unrestricted input, so their authors must take extra precautions to validate arguments.

Here are some specific recommendations for configuring your email system with respect to mail delivery to programs:

  • If you do not specifically need the ability to deliver mail to programs, disable this feature in your mailer system. With sendmail, you can disable this feature by defining confLOCAL_SHELL_PATH to a program such as /bin/false. If you do need progmailer functionality, use smrsh (bundled with sendmail 8.7.x and above). smrsh restricts the allowed programs to a small set that you maintain in a special directory.

  • Inspect your aliases file and verify that it does not have a decode alias. The decode alias is a single line that looks like this:

    decode: "|/usr/bin/uudecode"

    The decode alias allows mail to be sent directly to the uudecode program. This ability has been shown to be a security hole and, in any event, is no longer needed (it was created in the days before MIME extensions to email). Examine carefully every alias that points to a file or program instead of a user account. Remember to run newaliases after changing the aliases file.

12.3.6.6 Overall security of Berkeley sendmail versus other MTAs

Eric Allman's sendmail mail system has a long history of security problems. This is not so surprising considering the span of years it has been in use. The first version of sendmail was written as a student project at a time when the Internet was very different from what it is today. When sendmail was originally written, Windows did not exist, uucp over phone lines was the most common form of email transport, the World Wide Web did not exist, there was no commercial use of the network allowed, Ethernets had a maximum speed of 10 Mbps, and the IP-reachable network had a few hundred thousand machines, at most. Some of the problems with sendmail weren't even possible to conceive of when it was written!

Be that as it may, there have been dozens of major flaws discovered and publicized in sendmail over the last 20 years. In the 1990s there were so many problems with the program that many security professionals (including us) recommended against using the program. In recent years, sendmail's security has been significantly improved based on a top-to-bottom review and rewrite.

Should you use sendmail today? There are many factors that should go into the answering this question:

  • Sending and receiving email is a complicated process that has traditionally been a source of security problems on all operating systems. For many years, sendmail was the only Unix mailer available. Thus, on Unix, those security problems were destined to be discovered in the sendmail program. Today those security problems have generally been fixed.

  • sendmail was developed at a time when security was not a primary concern to most developers. sendmail was certainly not the only network server to have security problems; similar problems were discovered with the finger daemon and the Apache web server. Those problems have now been addressed, and people are using those programs. sendmail's proponents argue that there is no reason not to use sendmail, as well.

  • sendmail is an extremely complicated system that implements a complex configuration language and a rich command language. Many of the program options and commands were documented only after sendmail had been in use for a decade or longer. On the other hand, other MTAs are similarly complicated. And while it is true that sendmail alone has a complex configuration language, that language has not been the source of the program's security problems.

  • sendmail originally ran as superuser in an environment that had full access to all of the computer's resources (i.e., not in a chroot( ) or jail( ) environment.) At the same time, sendmail accepted connections from any host on the Internet. Thus, if a vulnerability was discovered in sendmail, that vulnerability could be rapidly exploited. Modern versions of sendmail allow you to specify three users (DefaultUser, TrustedUser, and RunAsUser) that sendmail will use instead of the daemon and root users. sendmail can also now operate in a chroot( ) environment. Although it is more difficult to configure a sendmail system to operate properly if you use these "users," employing them will reduce the chances that an attacker will be able to use a sendmail exploit to compromise your entire system. You should consult the sendmail documentation for instructions on how to use these advanced features.[26]

    [26] A particularly good article on securing sendmail can be found at http://www.sendmail.net/000705securitygeneral.shtml.

  • sendmail had many features specifically designed to allow for the remote exploitation of machines, including a "wizard's password" and a "debug" mode. On several occasions these features were enabled in versions of sendmail that were widely distributed by vendors. On the other hand, modern versions of sendmail do not have these features compiled in.

  • Like many programs developed at the same time, sendmail for years did a poor job of validating its arguments, thus allowing users to overwrite arbitrary locations in memory, or provide input that resulted in very bad side effects. Modern versions of sendmail do a better job of validating their arguments and inputs.

In the late 1990s many of the sendmail security problems were systematically corrected. Today, sendmail appears to be a reasonably stable and secure email system that enjoys enduring popularity. Only one author of this book is willing to run sendmail on any of his systems, but you may be better off using it if you are familiar with sendmail and you are not familiar with the other systems. As a standard practice in security, if you are familiar with something and can find good documentation and support for it, you are often better off using it than switching to something new in which there is a large learning curve and the potential for dangerous mistakes.

12.3.7 TACACS and TACACS+ (UDP Port 49)

TACACS (the Terminal Access Controller Access Control Server) protocol was developed by Cisco and is used to authenticate logins to terminal servers. TACACS defines a set of packet types that can be sent from the terminal server to an authentication server. The LOGIN packet is a query indicating that a user wishes to log into the terminal server. The TACACS server examines the username and password that are present in the LOGIN packet and sends back an ANSWER packet that either accepts the login or rejects it. Additional information, such as assigned IP addresses, can be provided as well. Passwords are not encrypted with TACACS and are thus susceptible to packet sniffing.

TACACS+ modifies the TACACS protocol by adding support for encryption. Encryption is performed with a symmetric algorithm using a shared key between the TACACS+ client and server.

Although TACACS and TACACS+ are still widely used, many organizations are migrating away from them to RADIUS and LDAP.

12.3.8 Domain Name System (DNS) (TCP and UDP Port 53)

The Domain Name System (DNS) is a distributed database that is used so that computers may determine IP addresses from hostnames, determine where to deliver mail within an organization, and determine a hostname from an IP address. The process of using this distributed system is called resolving.

When DNS looks up a hostname (or other information), the computer performing the lookup contacts one or more nameservers seeking records that match the hostname that is currently being resolved.[27] One or more nameserver records can be returned in response to a name lookup. Table 12-8 lists some of the kinds of records that are supported.

[27] Most Unix DNS implementations use a file called /etc/resolv.conf to specify the IP addresses of the nameservers that should be queried, a default domain, and optionally a set of domains that should be searched for hostnames that are not fully qualified.

Table 12-8. DNS-supported record types

Record type

Purpose

A

Authoritative address. For the IN domain, this is an IP address.

AAAA

IP Version 6 authoritative address.

CNAME

Canonical name of an alias for a host.

NS

Nameserver record; specifies the name of the nameserver responsible for resolving a domain.

SOA

Source of authority; specifies the name of the primary nameserver for the domain, the email address of the person responsible for it, and several configuration values for the domain.

PTR

Pointer record; maps IP addresses to a hostname (for IP host).

MX

Mail exchange; specifies a different computer that should actually receive mail destined for this host.

For example, using DNS, a computer on the Internet might look up the name www.cs.purdue.edu and receive an A record indicating that the computer's IP address is 128.10.19.20. An MX query about the address cs.purdue.edu might return a record indicating that mail for that address should actually be delivered to the machine newman.cs.purdue.edu. You can have multiple MX records, sorted by priority, for robustness; if the first host is unavailable, the program attempting to deliver your electronic mail will try the second, and then the third. Of course, a program trying to deliver email would then have to resolve each of the MX hostnames to determine that computer's IP address.

DNS also makes provision for mapping IP addresses back to hostnames. This reverse translation is accomplished with a special domain called IN-ADDR.ARPA, which is populated primarily by PTR records. In this example, attempting to resolve the address 20.19.10.128.IN-ADDR.ARPA would return a PTR record pointing to the hostname, which is lucan.cs.purdue.edu (the CNAME of www.cs.purdue.edu).

Besides individual hostname resolutions, DNS also provides a system for downloading a copy of the entire database from a nameserver. This process is called a zone transfer , and this is the process that secondary servers use to obtain a copy of the primary server's database.

DNS communicates over both UDP and TCP. Because UDP is a quick, packet-based protocol that allows for limited data transfer, it is typically used for the actual process of hostname resolution. TCP, meanwhile, is most commonly used for transactions that require large, reliable, and sustained data transfer—that is, zone transfers. However, individual queries can be made over TCP as well.

12.3.8.1 DNS zone transfers

Zone transfers can be a security risk, as they potentially give outsiders a complete list of all of an organization's computers connected to the internal network. Many sites choose to allow UDP DNS packets through their firewalls and routers but explicitly block DNS zone transfers originating at external sites. This design is a compromise between safety and usability: it allows outsiders to determine the IP addresses of each internal computer, but only if the computer's name is already known.

You can block zone transfers with a router that can screen packets by blocking incoming TCP connections on port 53.[28] Modern versions of the BIND nameserver implement an allow-transfers directive that allows you to specify the IP addresses of hosts that are allowed to perform zone transfers. This option is useful if you wish to allow zone transfers to a secondary nameserver that is not within your organization, but you don't want to allow zone transfers to anyone else.

[28] In rare cases, this may block DNS queries, which are also permitted to use TCP. So use this approach with caution.

For example, this portion of a named.conf file allows zone transfers from the server's IP address 64.1.2.3 to secondary servers located at 18.4.4.4 and 19.3.2.1. (The addresses 127.0.0.1 and 64.1.2.3 allow transfers to be made to the local machine, which is useful for debugging.)

options {
                directory "/etc/namedb";
                transfer-source 64.1.2.3;
                allow-transfer {
                127.0.0.1;
                64.1.2.3;
                18.4.4.4;
                19.3.2.1;
                };
                notify yes;
};
12.3.8.2 DNS nameserver attacks

Because many Unix applications use hostnames as the basis for access control lists, an attacker who can gain control of your DNS nameserver or corrupt its contents can use it to break into your systems.

There are three fundamental ways that an attacker can cause a nameserver to serve incorrect information:

Loading erroneous information

Incorrect information can be fraudulently loaded into your nameserver's cache over the network, as a false reply to a query. This is often referred to as cache poisoning.

If your nameserver has contact with the outside network, there is a possibility that attackers can exploit a programming bug or a configuration error to load your nameserver with erroneous information. The best way to protect your nameserver from these kinds of attacks is to isolate it from the outside network so that management operations (including DNS updates) are handled over a different interface from the one used to serve DNS query responses.

If you have an internal network and a firewall, you can limit the damage that an outsider can do to your internal network by running two nameservers: one in front of the firewall, and one behind it. The nameserver in front of the firewall contains only the names and IP addresses of your gateway computer; the nameserver behind the firewall contains the names and IP addresses of all of your internal hosts. If you couple these nameservers with static routing tables, damaging information will not likely find its way into your nameservers. (Of course, depending on how you have built your firewall and what you allow your users to do on the network, this may not be a workable solution!)

Changing the configuration files

An attacker can change the nameserver's configuration files on the computer where your nameserver resides. To change your configuration files, an attacker must have access to the filesystem of the computer on which the nameserver is running and be able to modify the files. After the files are modified, the nameserver must be restarted (by sending it a kill -HUP signal). As the nameserver must run as superuser, an attacker would need to have superuser access on the server machine to carry out this attack. By having control of your nameserver, a skillful attacker could use that control as a stepping stone to controlling your entire network. Furthermore, if the attacker does not have root access but can modify the nameserver files, then he can simply wait until the nameserver is restarted by somebody else, or until the system crashes and every program is restarted.

Using dynamic DNS

An attacker can use the DNS dynamic update facility to provide your DNS server with a fraudulent update.

Modern DNS servers have facilities for dynamically updating DNS tables. This feature is very useful when IP addresses are dynamically assigned or shared among large numbers of people. Dynamic DNS allows a running DNS server to update its DNS tables without manually uploading a domain text file and asking the server to restart.

To be secure, dynamic DNS updates must be properly authenticated—otherwise, an attacker could attack your system by simply changing the mapping between your domain names and IP addresses. Most dynamic DNS servers make provisions for authentication by IP address (only certain IP addresses are allowed to provide updates) through the use of a shared key or updates that are signed with a public key algorithm. In general, combining an IP source address with one of the two cryptographic techniques provides for the highest level of security.

If you enable dynamic DNS and it is not correctly implemented, an attacker may use it to update your server without your permission. Many domain nameservers suffer a constant stream of fraudulent dynamic DNS update attacks.

12.3.8.3 DNSSEC

DNSSEC (RFC 2535 and 3130) is an extension of DNS that provides for the creation of a DNS-based Public Key Infrastructure (PKI) and the use of this infrastructure in the signing of DNS responses.

DNSSEC is an interesting protocol. Proponents have argued convincingly that the use of DNSSEC provides an easy way to bootstrap a global PKI that is not dependent upon certificates sold at high prices by centralized certificate authorities. Unfortunately, because of its populist nature and the fact that nobody really makes money when DNSSEC servers are deployed, there has been very little interest in deploying DNSSEC on a widespread scale.

12.3.8.4 DNS best practices

You can minimize the possibility of an attacker's modifying or subverting your nameserver by following these recommendations:

  • Run your nameserver on a special computer that does not have user accounts.

  • If you must run the nameserver on a computer that is used by ordinary users, make sure that the nameserver's files are all owned by root and have their protection mode set to 444 or 400 (depending on your site's policy). Any directories that are used to store nameserver files should be owned by root and have their protection mode set to 755 or 700 (again, depending on your site's policy). And all parent directories of those directories should be owned by root, mode 755 or 700. If your nameserver can be configured to run as a nonprivileged user (as modern versions of BIND can), you should take advantage of this option and keep the nameserver's file accessible only to that user.

  • If your nameserver can be configured to run in a chroot or jail area of the filesystem (as modern versions of BIND can), use this option to limit its access to other files on your host.

  • Configure your nameserver to ignore requests from bogus IP ranges (such as 10.0.0.0/8 if your subnet doesn't use these addresses). In BIND, the blackhole directive in named.conf can be used to do this.

  • Configure your nameserver not to perform recursive DNS queries for outsiders. In a recursive query, if your DNS server can't find the information for the client, it issues its own queries to try to resolve it. When recursive queries are not allowed, it is up to the client to do the follow-up work. Recursive queries consume nameserver resources and should not be performed for outsiders. In BIND, the allow-recursion directive controls which client hosts may request a recursive query.

  • Remember that there are many files that are used by the nameserver. For example, the Berkeley named nameserver (by far the most common on Unix systems) first looks at the file /etc/named.conf when it starts up. This file specifies other files and other directories that may be located anywhere on your computer. Be sure that all of these files are properly protected.

  • If you know of a specific site that is attempting to attack your nameserver, you can use BIND's bogusns directive to prevent the program from sending nameserver queries to that host.

  • If you use dynamic DNS updating facilities, require that updates be appropriately encrypted or cryptographically signed. Do not rely on IP addresses for appropriate authentication.

You can further protect yourself from nameserver attacks by using IP addresses in your access control lists, rather than by using hostnames. Unfortunately, raw IP addresses can be somewhat harder to manage, as IP addresses can change more frequently than hostnames. Furthermore some programs do not allow the use of IP addresses instead of hostnames.

12.3.9 BOOTP: Bootstrap Protocol, and DHCP: Dynamic Host Configuration Protocol (UDP Ports 67 and 68)

The Bootstrap Protocol (BOOTP) and the Dynamic Host Configuration Protocol (DHCP) are designed to dynamically configure devices on a local area network. These protocols are typically used to assign IP addresses to workstations, laptops, and network appliance devices. BOOTP is the original variant of this protocol and dates back to the 1980s. DHCP extended the BOOTP protocol by allowing clients to be assigned leases on specific IP addresses for a certain period of time, and by allowing the delivery of arbitrary name/value pairs to the client as part of the protocol. It dates back to the 1990s and is now widely used.

Clients that are configured to use BOOTP transmit a broadcast BOOTREQUEST when they start up. This packet is received by a computer that is running a BOOTP server. The server examines the Ethernet MAC address of the computer making the request, constructs an appropriate response, and sends it in a BOOTREPLY packet.

DHCP transactions involve four steps:

  1. The client broadcasts DHCPDISCOVER to ask for an assignment.

  2. Listening servers broadcast DHCPOFFERs to offer IP addresses.

  3. The client chooses a server and sends a DHCPREQUEST for the offered address.

  4. The server responds with a DHCPACK to acknowledge the request and assign the address (or DHCPNAK to refuse to do so).

Although DHCP can be used to deliver a wide array of information, it is typically used for assigning a host IP address, the IP address of a gateway, one or two DNS servers, and a default domain that the client should use.

Because there is no server authentication with DHCP, any DHCP server on the network can answer any DHCP request. A common problem at organizations that use DHCP is that a person who has a copy of Windows 2000 or Windows XP will inadvertently enable the built-in DHCP server. Once this server is enabled, it will invariably send out DHCPOFFER and DHCPACK packets that contain errorneous information. A sufficiently skilled attacker can easily disable or spy on desktops by setting up a rogue DHCP server that provides the wrong IP addresses for nameservers or gateways. If you must use dynamic IP assignment, exercising vigilance—and regularly scanning your network for rogue or accidental DHCP servers—may be your best defense.

12.3.10 TFTP: Trivial File Transfer Protocol (UDP Port 69)

The Trivial File Transfer Protocol (TFTP) is a UDP-based file transfer program that provides no security. There is a set of files that the TFTP program is allowed to transmit from your computer, and the program will transmit them to anybody on the Internet who asks for them. One of the main uses of TFTP is to allow workstations to boot over the network; the TFTP protocol is simple enough to be programmed into a small read-only memory chip and is used to download a bootable OS image from a server.

Although the TFTP protocol itself has no security, there are two ways that security has been added to tftpd, the TFTP daemon:

  • The daemon is normally run in a restricted environment so that it can only transfer files to or from a certain directory.

  • The daemon is configured so that it will respond only to TFTP requests from particular IP addresses. This is typically done using the TCP Wrappers system and the /etc/hosts.allow file.

You can test your version of tftpd for this restriction with the following sequence:

% tftp localhost
tftp> get /etc/passwd /tmp/passwd
Error code 1: File not found
tftp> quit
%

If the tftp client downloads a copy of your /etc/passwd file, then you have a problem. You should disable the TFTP service immediately.

12.3.11 finger (TCP Port 79)

The finger program has three uses:

  • If you run finger with no arguments, the program prints the username, full name, location, login time, and office telephone number of every user currently logged into your system (assuming that this information is stored in the /etc/passwd file or equivalent, and in the proper format).

  • If you run finger with a name argument, the program searches through the /etc/passwd file and prints detailed information for every user with a first name, last name, or username that matches the name you specified.

  • If you run finger with an argument that contains the at sign (@), the program connects to the finger server on the remote machine, submits a finger query, and displays the results. In the 1980s and 1990s some organizations set up finger servers that used this facility to allow remote users to query publicly-accessible directories. Although the Web has largely supplanted the finger-based directory service, many of these systems are still operational.

finger provides a simple, easy-to-use system for making personal information (such as telephone numbers) available to other people. Novice users are often surprised, however, that information that is available on their local machine is also available to anyone on any network to which their local machine is connected. Thus, users should be cautioned to think twice about the information they store using the chfn command, and in their files printed by finger. Likewise, finger makes it easy for intruders to get a list of the users on your system, which dramatically increases the intruders' chances of breaking into your system.[29]

[29] Various "safer" versions of finger provide access controls like TCP Wrappers that limit the kind of information that is shown and run as a nonprivileged user. As with other third-party software, replacing your operating system's finger daemon may complicate the maintaining of your system in the future. In most cases, we feel that you're better off eschewing finger altogether.

12.3.11.1 The .plan and .project files

Most versions of the Unix finger program display the contents of the .plan and .project files in a person's home directory when that person is "fingered." On older versions of Unix, the finger daemon ran as root. As a result, an intrepid user could read the contents of any file on the system by making her .plan a symbolic link to that file, and then running finger against her own account.

One easy way that you can check for this problem is to create a .plan file and change its file mode to 000. Then run finger against your own account. If you see the contents of your .plan file, then your version of fingerd is unsecure and should be replaced or disabled.

12.3.11.2 Disabling finger

The finger system reveals information that could be used as the basis for a social-engineering attack. For example, an attacker could "finger" a user on the system, determine his name and office number, then call up the system operator and say "Hi, this is Jack Smith. I work in office E15, but I'm at home today. I've forgotten my password; could you please change my password to foo*bar so that I can log on?"[30]

[30] N.B. This exposes a problem that is not caused by finger! If your operators are willing to do something like this without careful and exact authentication, then any source of such information will suffice—running finger only makes it simpler.

Many system administrators choose to disable the finger system. There are three ways that you can do this:

  • You can remove (or comment out) the finger server line in the file /etc/inetd.conf. This change will send a "Connection refused" error to people trying to finger your site. Disabling finger in this way can cause problems for those trying to determine mail addresses or phone numbers. Outsiders may attempt to contact you to warn you that your site has been broken into by others. Therefore, completely disabling finger in this way might actually decrease your overall security, in addition to causing an overall inconvenience for everybody.

  • You can replace the finger server with a program that prints a static message that explains how to get directory information. For example, you might create a message link such as the following in /usr/local/etc/finger.txt:

    Welcome to Big Whammix Inc.
    
    For information on contacting a specific employee, please call our
    company operator at 1-999-555-1212 or send electronic mail to
    the address postmaster@whammix.com
    
    Thank you.

    Make a symbolic link to /bin/cat from /usr/local/sbin/no_finger. Then in the file /etc/inetd.conf, replace the normal finger entry with this line:

    finger  stream  tcp  nowait  nobody
    /usr/local/sbin/no_finger no_finger
    /usr/local/etc/finger.txt

    Remember to restart inetd.

  • Finally, you can use the TCP Wrappers facility to provide different finger daemons for different users, depending on their IP addresses. Alternatively, you can replace the finger daemon with another directory server. One popular server is ph, the phone book server. You can also write your own server.

12.3.12 HTTP, HTTPS: HyperText Transfer Protocol (TCP Ports 80, 443)

The HyperText Transfer Protocol is the protocol that is used to request and receive documents from servers on the World Wide Web. Access to the Web has been a driving force behind the growth of the Internet, and many sites that have Internet connectivity are pressured to provide both client applications and web servers for their users. HTTP servers typically listen on port 80; HTTPS servers, which implement secure HTTP by using SSL/TLS, typically listen on port 443.

One of the reasons for the success of HTTP is its simplicity. When a client contacts a web server, the client requests a filename to which the server responds with a MIME document formatted in either plain ASCII or HTML (HyperText Markup Language). The document is then displayed.[31]

[31] HTML is a simple use of SGML (Standard Generalized Markup Language).

Web browsers can implement as much (or as little) of HTML as they wish; the documents displayed will still be viewable. HTML documents can have embedded tags for images (which are separately retrieved) and for hypertext links to other documents. The servers are configured so that a specified directory on the system (for example, /usr/local/etc/httpd/htdocs) corresponds with the root directory of the web client (for example, http://www.ora.com/). In many cases, servers are configured so that users can publish HTML documents in a specified subdirectory of their home directories.

Because there are many specific security considerations when setting up a web server and using a web client, we have written an entire book on the subject. For further information, consult Web Security, Privacy & Commerce (O'Reilly).

12.3.13 POP, POPS: Post Office Protocol, and IMAP, IMAPS: Internet Message Access Protocol (TCP Ports 109, 110, 143, 993, 995)

The Post Office Protocol (POP) is a system that provides users on client machines a way to retrieve their electronic mail from a server. POP Version 3 (also called POP3) allows users to access individual mail messages, set limits on the maximum length of the message that the client wishes to retrieve, and leave mail on the server until the message has been explicitly deleted. POP runs on ports 109 and 110. The POP protocol can be run over SSL/TLS, in which case it is typically called POPS and runs on port 995.

The Internet Message Access Protocol (IMAP) performs a similar function, although this protocol allows the client to manage mail messages in multiple mailboxes. IMAP runs on port 143. The IMAP protocol can be run over SSL/TLS, in which case it is typically called IMAPS and runs on port 993.

Both POP and IMAP require that users authenticate themselves before they can access their mail. With POP there are several ways to authenticate:

  • You can use simple resuable passwords sent unencrypted over the network. This is by far the most common way for POP users to authenticate themselves to POP servers. It also means that the passwords can be intercepted with a password sniffer and reused by an attacker. POP passwords are an easy target because the password is always sent to the same port, and it is sent frequently—typically every few minutes.

  • You can use POP's APOP option. Instead of passwords, APOP uses a simple challenge/response system. It is described in RFC 1725, the same RFC that describes POP3.

    When a client program connects to a POP3 server, the server sends a banner that must include a unique timestamp string located within a pair of angle brackets. For example, the Unix POP server might return the following:

    +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us>

    When using simple passwords, the client program would next send through the username and the password, like this:[32]

    [32] This example is taken from RFC 1725.

    +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us>
    user mrose
    +OK Password required for mrose.
    pass tanstaaf
    +OK maildrop has 1 message (369 octets)

    With APOP, the client program does not send the USER and PASS commands; instead, it sends an APOP command that contains the username and a 128-bit hexadecimal number that is the MD5 hash code of the timestamp (including the angle brackets) and a secret passphrase that is known to both the user and the POP server. For example, the user might have the password tanstaaf. To determine the appropriate MD5 code, the user's client program would compute the MD5 hash of:

    <1896.697170952@dbc.mtview.ca.us>tanstaaf

    which is:

    c4c9334bac560ecc979e58001b3e22fb

    Thus, the APOP message sent to the server would be:

    APOP mrose c4c9334bac560ecc979e58001b3e22fb
    +OK maildrop has 1 message (369 octets)

    Note that because the POP3 server must know the shared secret, it should not be the same phrase as your password.

  • You can use a version of POP that has been modified to work with Kerberos. (Kerberos is described in Chapter 14.)

  • You can tunnel the POP protocol over TLS. This protects against password sniffing over the network, although the POP server will still have access to the reusable password.

IMAP has an integral authentication system that can use Kerberos, GSSAPI (RFC 1508), or S/Key one-time passwords for authentication. It can also be tunneled over TLS.

Note that both your mail server and your mail client must support the authentication system that you wish to use. For example, early Eudora email clients supported only traditional passwords, but later versions include support for both APOP and Kerberos. Outlook Express 5.0 doesn't support Kerberos but does support POP over TLS.

12.3.14 Sun RPC's portmapper (UDP and TCP Ports 111)

The portmapper program is used as part of Sun Microsystems' Remote Procedure Call (RPC) system to dynamically assign the TCP and UDP ports used for remote procedure calls. portmapper is thus similar to the inetd daemon, in that it mediates communications between network clients and network servers. Solaris systems are supplied with a version called rpcbind, while most BSD and Linux systems use a reimplementation of portmapper written by Wietse Venema.

The RPC portmapper is primarily used by Sun's Network Filesystem. If you wish to use NFS, then you need to run a portmapper. (See Chapter 15 for details.)

There is a long history of security flaws with Sun's portmapper. As a result, many security-conscious Solaris sites have replaced Sun's portmapper with Venema's because it allows for finer-grained access control and logging. On the other hand, many of the problems with Sun's portmapper have now been addressed, so you shouldn't be too worried if you don't replace Sun's code. See Chapter 13 for detailed information on RPC.

Many sites further restrict access to their portmappers by setting their firewalls to block packets on port 111.

12.3.15 Identification Protocol (TCP Port 113)

The Identification Protocol (RFC 1413)—commonly called ident, but sometimes called auth—provides a mechanism to query remote systems for the username that corresponds to a particular TCP connection. Although many protocols provide for the transmission of a username, the Identification Protocol is unique in that the username is provided by the remote operating system itself, rather than by a TCP client or server that is involved in the actual connection. The information is thus constructed and delivered out of band and may be more reliable.

For example, if the user albert on computer K1 attempts to open an SSH connection to computer J1 as the user bruce, the SSH server will attempt to log the user into the bruce account. However, the SSH server on J1 can make a request of the computer K1 for the username that was responsible for initiating the connection. Even though albert provided the username bruce to his SSH client, the computer K1 will respond with the username albert to J1's Identification Protocol query (if K1's software is so enabled).

Some Unix systems still use the ident daemon to offer this service. Other systems use a built-in server for the Identification Protocol that is part of the Unix inetd daemon.

The Identification Protocol can be very useful if you run a timesharing environment with large numbers of Unix users on the same machine. If a remote site reports that one of your users is attempting to break into their system, you can ask the remote site to check their logs. If that remote site initiated Identification Protocol requests for each break-in attempt, you will be provided with the name of the account that was involved in these attempts.

Some sites believe that the ident daemon reveals too much information about local users. The ident daemon has an option by which it will respond with user numbers rather than usernames. The theory is that user numbers do not violate the privacy of users and, if the remote site administrator asks politely, they can always be translated back to usernames. The daemon can also be configured to respond with an encrypted string containing the user and connection information as well as the date and time. This encrypted string can later be decrypted if it becomes necessary to investigate an abuse report.[33]

[33] Some site administrations are morally opposed to the entire concept of the Identification Protocol. For these sites, identd can be run with the -g option, which causes the daemon to respond to Ident requests with randomly generated information. This is certainly not very helpful in an investigation if you are being attacked from their sites, but some people would rather make a point than be helpful. Whatever the reasoning, you should not place great faith in the accuracy of returned Ident data.

12.3.16 NNTP: Network News Transport Protocol (TCP Port 119)

The Network News Transport Protocol (NNTP) is used by many large sites to transport Usenet Netnews articles between news servers. The protocol also allows users on distributed workstations to read news and post messages to the Usenet. There are many servers that implement NNTP, including DNews, WebNews, Diablo, INN, Cyclone NewsRouter, and others.

NNTP servers should be configured with an access control list (ACL) that determines which computers are allowed to use which features and access which newsgroups. The ACLs specify which hosts your server will exchange news with and which clients within your organization are allowed to read and post messages. Many organizations have a mix of confidential and nonconfidential information on their news servers; you should use the ACL rules to assure that confidential information does not leave your organization.

A compromised NNTP server can represent a serious security threat:

  • If you have special newsgroups for your own organization's internal discussions, there is a chance that a compromised NNTP server could reveal confidential information to outsiders.

  • If an outsider can post from your NNTP server, that outsider could post a message that is libelous, scandalous, or offensive—potentially causing liability for your organization.

Because many of the information feeds that were once available only over Usenet are now available by mailing list or over the Web, many organizations have decided to discontinue the operation of their NNTP servers.

There are other hazards involved in running Netnews:

  • The volume of news postings is huge, and increasing. Unless you devote considerable storage resources and management care to the news system, you can easily fill your disk(s). This can result in degraded operation, or more severe problems if you were so incautious as to co-locate your news spool with some critical application.

  • Some of the information sent over the Netnews "binary" groups is pornographic, legally obscene, or infringes upon the copyrights of third parties. Having this information on your computer, in your workplace, or transmitting it to third parties may make you legally culpable.

  • Your users may become so involved in reading and replying to news that it makes significant inroads on their productivity. If news is interfering with assigned responsibilities, it can present a major problem. Note that this comment also applies to web browsing; the combination of Netnews and the Web can be worse than either alone.

  • Your own users may be careless about what they post. The result could be accidental disclosure of proprietary information, posting of libelous material resulting in legal action, posting of copyrighted materials resulting in legal action, or simply being involved in salacious and offensive acts that reflect poorly on your organization.

  • Most virus scanning does not extend to news feeds. Thus, malicious software may find its way past your defenses via Netnews.

We recommend caution if you decide to bring a Usenet feed into your organization without a strong business need.

12.3.17 NTP: Network Time Protocol (UDP Port 123)

There is an old proverb that a person with two clocks doesn't know what time it is. That proverb assumes that the clocks are not running NTP.

The Network Time Protocol (NTP) is a set of protocols that can be used to synchronize the clocks on multiple computers, taking into account issues such as network delay and the fact that different computers are closer (in a network sense) to absolute time standards than other computers. When properly deployed, NTP can be used to synchronize the clocks on large numbers of computers to within a fraction of a second of each other.

Clock synchronization is very important:

  • Unless the clocks on your servers are properly synchronized, it can be difficult or even impossible to compare the log files on different computers and establish the exact sequence of events.

  • If the clocks of file servers and file server clients are not properly synchronized, programs that consider the timestamps on files will not function properly. For example, a clock skew of only a few seconds may be enough to prevent make from compiling a program because it may calculate that the source code was modified in the future.

  • If clocks are widely divergent, email that is generated on one computer may not be sorted properly on the systems that receive the mail messages.

  • Widely divergent clocks may also prevent Kerberos, SSH, and other cryptographic protocols that rely on absolute time from functioning properly.

  • In commercial environments where it is important to determine the sequence of sales orders with each other or with the stock market, a difference of a few seconds can be the difference between rags and riches.

Fortunately, time synchronization is not only possible, it is easy. The major industrialized governments of the world have agreed on an absolute time standard called International Atomic Time, or TAI. UTC (formerly GMT) is determined relative to the TAI, with the addition of a leap second every few years to bring them back in sync. In the United States, the TAI and the UTC are maintained by the National Institute for Standards and Technology (NIST), and UTC is provided by radio and over the Internet. (See also the sidebar, Telling Time.)

With NTP, the system's clock is usually first set when the computer boots using the ntpdate command. After the time is set, the computer runs the ntpd daemon. This daemon constantly monitors the computer's time and exchanges timing information with several other computers. Using some sophisticated algorithms, the daemon then adjusts the computer's clock as necessary.

To use NTP properly, you should have a plan for how the correct time is brought into and distributed throughout your network. Ideally, you should have two or three central time servers within your organization. These time servers receive the UTC time signal directly from a special radio, obtain the time from GPS satellites, or receive a time signal from an external network source. The servers then peer with each other—if one server drifts, the data from the others can be used to correct it. Finally, other computers within your organization can receive a time signal from these servers.

Telling Time

The determination of exact time is arcane. At high levels of precision, it even requires that you take relativity into account! Synchronizing clocks to a universal standard is an area that involves incredible engineering as well as complex mathematics and physics. The major world standards bodies have spent a great deal of time to get time right because all kinds of issues involving science, commerce, and government depend on correct time.

So, if you don't have a large enough budget to buy an atomic clock for your workstation, but you want something more reliable than NTP via the Internet, what can you do? It turns out that you can get a very accurate time signal via radio. A number of national agencies (in different nations) broadcast highly accurate time signals at various frequencies. If you are willing to tolerate an error of at most a few dozen nanoseconds,[34] then you can also use the time signal from GPS satellites (if selected and averaged appropriately). Thus, you can probably get a time signal accurate enough for almost any computer-based use you might have for it.

Several vendors make NTP appliances. These are systems that include all the necessary circuitry to receive time signals from a radio time source (NIST in the U.S.) or GPS satellites. They run NTP and have RS232 serial or Ethernet connections. Some of the more advanced models can be configured to receive several time signals and peer with other servers, all the while maintaining a crystal clock accurate to within fractions of a second per year. Thus, even if radio reception is interrupted (e.g., by sunspots, equipment failure, or passing UFOs) the appliance can keep—and serve—a highly accurate time standard. What's more, these systems can be purchased and installed behind your firewall, in a standard 19-inch rack, for only a few thousand dollars.

If spending a few thousand dollars is beyond your means, then setting up NTP and connecting to some external servers isn't such a bad idea. A typical installation can keep your computer clock accurate to within a few milliseconds of UTC, and this should be enough for everything but the most demanding needs.

You can find a tremendous wealth of information about time, time standards, servers, software, appliance vendors, and more at http://www.ntp.org. This site includes links to a list of network servers at stratum 1[35] (systems getting original time signals) and stratum 2 (systems getting time signals from stratum 1 hosts), along with NTP software and some pointers to vendors. Thus, you can find out how to really tell time, what to buy as a trusted time source for your network, how to download the NTP software, and how to find network NTP servers to peer with.

That is, if you have the time.

[34] That would be 10-15 instruction clock cycles on a 500 MHz machine.

[35] NTP uses the term stratum to signify how many hops a time server is away from the world's official time standard. (UTC is considered stratum 0.)

The NTP protocol provides for a rich number of configuration options, including the broadcasting of a time signal on local area networks. Consult the NTP documentation for further information regarding configuration.

Three primary security concerns arise when using NTP:

  • Because ntpd runs as root, a vulnerability with the NTP server may result in an attacker being able to compromise the computer on which NTP is running.[36] To protect against this venue of attack, you should make sure that you are running the most recent version of NTP.

    [36] Strictly speaking, NTP does not need to run as root: it only needs to be able to change the time. On a Unix system with capabilities, NTP could be given the capability to change the time but no other capabilities. Likewise, other processes could be denied the capability to change the time.

  • An attacker might be able to send your system a fraudulent NTP update and significantly change your computer's clock. With the NTP configuration file, you can specify the specific hosts from which your computer will accept NTP time updates. You can also require that those updates be encrypted with a symmetric key. An attacker who does not have the key is then unable to provide your system with fraudulent updates.

  • Your NTP servers might become wildly popular with a group of users. This popularity might cause the computer to run slowly and could eat up your network's bandwidth. To prevent against this adversity, the NTP server allows you to create access control lists that specify the IP addresses of clients that will be provided with NTP service.

12.3.17.1 Sudden changes in time

Many problems can arise if a system's clock is suddenly changed:

  • If a system's clock moves backward in time, an attacker might be able to launch a successful replay attack. For example, if your system uses Kerberos, old Kerberos tickets may work. If you use a time-based password system, old passwords may work.

  • Your system's log files will no longer accurately indicate the correct time at which events took place. If your attacker can move the system's clock far into the future, she might even be able to cause your system to erase all of its log files as the result of a weekly or monthly cleanup procedure.

  • Batch jobs run from the cron daemon may not be executed if your system's clock jumps over the time specified in your crontab file or directory. This type of failure in your system's clock may have an impact on your security.

For these reasons, the ntpd daemon never adjusts the computer's clock forward by more than a second and never adjusts it backward at all. (Instead of moving the clock backward, it will simply slow the system clock if the system is running too fast.) The ntpd daemon is thus compatible with BSD's higher security levels, at which even the superuser is prevented from making significant changes to the system time.[37]

[37] The ntpdate program, however, will move the time forward if it's off by more than half a second, and thus should be used with care. Typically, this program is used only at boot to initially set the clock before running ntpd. On systems with kernel security levels, ntpdate must be run before the security level is raised.

12.3.17.2 An NTP example

Here is a sample NTP configuration file that implements many of the requirements we've discussed:

# File:         ntp.conf

server ntp2.usno.navy.mil
server time.mit.edu

server 18.26.0.36       # ntp-0.lcs.mit.edu
server 18.24.10.177     # ntp-1.lcs.mit.edu
server 18.111.0.2       # ntp-2.lcs.mit.edu
server 18.26.4.10       # ntp-3.lcs.mit.edu

peer 192.168.1.2
peer 192.168.1.3

#----- Security
# By default, don't let anyone do anything.
restrict    default notrust nomodify ignore

# Trust our sources for time, but not reconfig.
restrict    192.5.41.209    nomodify  # ntp2.usno.navy.mil
restrict    18.72.0.144     nomodify  # time.mit.edu
restrict 18.26.0.36 nomodify
restrict 18.24.10.177 nomodify
restrict 18.111.0.2 nomodify
restrict 18.26.4.10 nomodify

# Local time servers
restrict   192.168.1.0 mask 255.255.255.0 nomodify

# Trust ourselves for modifications.
restrict        127.0.0.1                       # Ourselves

logfile /var/log/ntp.log
logconfig clockall peerall sysall syncall

#----- Drift history
# Save drift information in a file so NTP converges more quickly
# the next time it runs.

driftfile       /etc/ntp.drift

This configuration file takes time service from the U.S. Navy and from five servers at MIT. It peers with two other computers on the local area network. The server can respond to commands that originate on the local host, but no other hosts. Security is based entirely on IP addresses. (In high-security environments, NTP can handle shared secret keys.)

12.3.18 SNMP: Simple Network Management Protocol (UDP Ports 161 and 162)

The Simple Network Management Protocol (SNMP) is a protocol designed to allow the remote management of devices on your network. To be managed with SNMP, a device must be able to send and receive UDP packets over a network.

SNMP allows for two types of management messages:

  • Messages that monitor the current status of the network (for example, the current load of a communications link)

  • Messages that change the status of network devices (for example, move a communications link up or down)

SNMP can be of great value to attackers. With carefully constructed SNMP messages, an attacker can learn the internal structure of your network, change your network configuration, and even shut down your operations. Although some SNMP systems include provisions for password-based security, others don't. SNMP Version 2.0 was intended to include better security features, but the proposals never made it past the experimental stage. SNMP Version 3.0 includes standards for improved authentication but is not widely deployed. Each site must therefore judge the value of each particular SNMP service and weigh the value against the risk.

If you don't plan to use SNMP, be sure that it's not installed, or at least not enabled, on your Unix system. In 2002, several vulnerabilities were discovered in SNMP implementations that were in wide use (see http://www.cert.org/advisories/CA-2002-03.html for CERT's report).

If you must use SNMP, here are some important steps to take:

  • SNMP uses community strings to determine whether an SNMP agent will provide information to a monitoring program. The default community is often "public." Change this immediately.

  • SNMP can not only read status information but can also write configuration changes to agents remotely. Seriously consider disallowing SNMP write access. If you must allow it, set up two different communities for read and write access to each agent.

  • Use access control lists on SNMP devices (or host-based firewalls on SNMP-managed Unix systems) to restrict SNMP access to only hosts that are explicitly allowed.

  • Block all SNMP traffic from outside your organization's network at your border router/firewall. This can also include TCP port 199 and 705, as well as UDP ports 161 and 162.

  • Don't run SNMP on firewalls, intrusion detection systems, or other security infrastructure systems!

12.3.19 rexec (TCP Port 512)

The remote execution daemon /usr/sbin/rexecd allows users to execute commands on other computers without having to log into them. The client opens up a connection and transmits a message that specifies the username, the password, and the name of the command to execute. As rexecd does not use the trusted host mechanism, it can be issued from any host on the network. However, because rexecd requires that the password be transmitted without encryption over the network, it is susceptible to the same password snooping as telnet.

Unlike login and telnet, rexecd provides different error messages for invalid usernames and invalid passwords. If the username that the client program provides is invalid, rexecd returns the error message "Login incorrect." If the username is correct and the password is wrong, however, rexecd returns the error message "Password incorrect." Because of this flaw, an attacker can use rexecd to probe your system for the names of valid accounts and then target those accounts for password-guessing attacks.

Unless you have a specific reason for using this service, we strongly recommend that you disable rexec in /etc/inetd.conf. SSH is a better solution.

12.3.20 rlogin and rsh (TCP Ports 513 and 514)

The rlogin and rlogind programs provide remote terminal service that is similar to telnet. rlogin is the client program, and rlogind is the server. There are two important differences between rlogin and telnet:

  • rlogind does not require that the user type his username; the username is automatically transmitted at the start of the connection.

  • If the connection is coming from a "trusted host" or "trusted user" (described in the next section), the receiving computer lets the user log in without typing a password.

rsh/rshd are similar to rlogin/rlogind, except that instead of logging in the user, they simply allow the user to run a single command on the remote system. rsh is the client program, while rshd is the server. If used from a trusted host or trusted user, rsh/rshd will run the command without requiring a password. Otherwise, a password will be prompted for and, if the password is correct, the program will be run.

Because rlogin and rsh potentially send passwords without encryption over the Internet, and because the TCP connection used by rlogin and rsh is subject to eavesdropping and TCP connection hijacking, we recommend that these protocols not be used. Use SSH instead.

12.3.20.1 Trusted hosts and users

Trusted host is a term that was invented by the people who developed the Berkeley Unix networking software. If one host trusts another host, then any user who has the same username on both hosts can log in from the trusted host to the other computer without typing a password. Trusted hosts are specified with entries in the file /etc/hosts.equiv or in an individual user's ~/.rhosts file (discussed later).

Trusted users are like trusted hosts, except they are users, not hosts. If you designate a user on another computer as a trusted user for your account, then that user can log into your account without typing a password. A user can trust users on other hosts by creating an entry for each (host/user) pair in the user's file ~/.rhosts.

This notion of trust was developed in a small, closed networked environment, and in that environment it had a lot of advantages. Trust allowed a user to provide a password once, the first time he signed on, and then use any other machine in the cluster without having to provide a password a second time. If one user sometimes used the network to log into an account at another organization, then that user could set up the accounts to trust each other, thus speeding up the process of jumping between the two organizations.

But trust is also dangerous because there are numerous ways that it can be compromised, especially on today's Internet:

  • Because the trusted hosts are frequently listed by hostname, an attacker who controls the DNS system could effectively log into any Unix computer or account that relies on trusted hosts.

  • Because the trusted-host mechanism uses IP addresses for authentication, it is also vulnerable to IP spoofing. There have been incidents in which IP spoofing attacks were successfully used to break into a computer system.

  • .rhosts files are easily exploited for unintended purposes. For example, attackers who break into computer systems frequently add their usernames to unsuspecting users' .rhosts files so that they can more easily break into the systems again in the future. For this reason, you may not want to allow these files on your computer.

  • Because the trusted-host mechanism relies on the security of the trusted computers, any person who has unauthorized use of a trusted system could misuse that trust to log into a trusting system. If that trusting system is, in turn, trusted by other systems, those systems are vulnerable as well. This is known as "the problem of transitive trust."

    The problem of transitive trust is actually much worse than you might think at first. Most workstations can be booted in single-user mode with relative ease. As the superuser, the attacker can su to any account at all. If the server trusts the workstation—perhaps to let users execute commands on the server with rsh—then the attacker can use rlogin to log into the server and thereby gain access to anybody's files.

Even worse, a non-Unix system can exploit the trust mechanism by sending packets originating from low-numbered ports structured according to the protocols. Thus, shutting down a system and booting something else in its place, such as a Windows box with custom software, may allow the system to be exploited.

Because of the security problems with trusted hosts, this mechanism should not be used. In general, the Berkeley "r" commands are unsafe and should be disabled. Use SSH instead.

12.3.20.2 Specifying trusted hosts with /etc/hosts.equiv and ~/.rhosts

The /etc/hosts.equiv file contains a list of trusted hosts for your computer. Each line of the file lists a different host. Any hostname listed in hosts.equiv is considered completely trusted; a user who connects with rlogin or rsh from that host will be allowed to log in or execute a command from a local account with the same username without typing a password—with the exception of the root user. The file is scanned from beginning to end, and the scanning stops after the first match.

If you have Sun's NIS (or use another system that supports netgroups), you can also extend or remove trust from entire groups of machines. When using Sun's NIS (described in Chapter 14), a line of the form +@hostgroup makes all of the hosts in the network group hostgroup trusted; likewise, a line that has the form -@anotherhostgroup makes all of the hosts in the network group anotherhostgroup specifically not trusted.[38]

[38] Beware that +@hostgroup and -@hostgroup features were broken in some older NIS implementations. Check to be sure they are doing what you intend.

Consider this example file:

gold.acs.com
silver.acs.com
platinum.acs.com
-@metals
+@gasses

This file makes your computer trust the computers gold, silver, and platinum in the acs.com domain. Furthermore, your computer will trust all of the machines in the gasses netgroup, except for the hosts that are also in the metals netgroup.

After scanning the hosts.equiv file, the rlogind and rshd programs scan the user's home directory for a file called .rhosts. A user's .rhosts file allows each user to build a set of trusted hosts applicable only to that user.

For example, suppose that the ~keith/.rhosts file on the math.harvard.edu computer contains the lines:

prose.cambridge.ma.us
garp.mit.edu

With this .rhosts file, a user named keith on prose or on garp can rlogin into keith's account on math without typing a password.

A user's .rhosts file can also contain hostname/username pairs extending trust to other usernames. For example, suppose that keith's .rhosts file also contains the line:

hydra.gatech.edu lenny

In this case, the user named lenny at the host hydra could log into keith's account without providing a password.

Because of the obvious risks posted by .rhosts files, many system administrators have chosen to disallow them entirely. There are various approaches to doing this:

  • Remove (or comment out) the entries for rshd and rlogind in the inetd.conf file, thus disabling the commands that might use the files.

  • Use Wietse Venema's logdaemon package.

  • Obtain the source code for the rshd and rlogind programs and remove the feature directly.[39]

    [39] Before you hack the code, try checking your rshd documentation. Some vendors have a flag to limit .rhosts (usually to only the superuser).

  • Scan your system periodically for users who have these files and take appropriate action when you find them.

Many older SunOS systems were distributed with a single line containing only a plus sign (+) as their hosts.equiv file. The plus sign has the effect of making every host a trusted host, which is precisely the wrong thing to do. This line is a major security hole because hosts outside the local organization (over which the system administrator has no control) should never be trusted. If you have a plus sign on a line by itself in your hosts.equiv file, remove it!

12.3.20.3 /etc/hosts.lpd file

One lasting vestige of the trusted-hosts mechanism is that the Unix lpd system allows only trusted hosts to print on local printers. This restriction presents a security problem because you may wish to let some computers use your printer without making them equivalent hosts. To allow this lesser amount of trust, lpd considers two files: /etc/hosts.equiv and /etc/hosts.lpd. By placing a hostname in the file /etc/hosts.lpd, you let that host use your printers without making it an equivalent host.

For example, if you want to let the machines dearth and black use your computer's printer, you can insert their names in /etc/hosts.lpd:

% cat /etc/hosts.lpd
dearth
black
%

The hosts.lpd file has the same format as the hosts.equiv file. Thus, to allow any computer on the Internet to print on your printer, you could use the following entry:

% cat /etc/hosts.lpd
+
%

We do not recommend that you do this, however!

12.3.21 RIP Routed: Routing Internet Protocol (UDP Port 520)

The RIP routing protocol is used by Internet gateways to exchange information about new networks and gateways. Several Unix servers have been written to implement this protocol, including routed, gated, and zebra.

There are two versions of the RIP protocol. RIPv1 has no security. If your routing daemon is configured to use this protocol, it will happily honor a packet from another computer on the network that says, in effect, "I am the best gateway to get anywhere; send all of your packets to me." Clearly, this trust presents even inexperienced attackers with a simple way to confound your network. Even worse, it gives sophisticated attackers a way to eavesdrop on all of your communications.

RIPv2 adds security to the protocol in the form of a shared key. If the routing update is not signed with the shared key, it is not honored.

For computers on a network that have a single gateway, there is no reason to run a routing protocol; use static routes instead. If dynamic updates are required, run a DHCP server.

12.3.22 The X Window System (TCP Ports 6000-6063)

X is a popular network-based window system that allows many programs to share a single graphical display. X-based programs display their output in windows, which can be either on the same computer on which the program is running or on any other computer on the network.

Each graphical device that runs X is controlled by a special program called the X Window Server. Other programs, called X clients, connect to the X Window Server over the network and tell it what to display. Two popular X clients are xterm (the X terminal emulator) and xclock (which displays an analog or digital clock on the screen).

12.3.22.1 /etc/logindevperm

Multiuser workstations provide a challenge for X security. On early implementations of X, the logical devices for the keyboard, screen, and sound devices were world-readable and world-writable. This availability caused security problems because it meant that anybody could read the contents of the user's screen or keyboard, or could listen to the microphone in his office.

Some versions of Unix have a special file that is used to solve this problem. For example, the file—called /etc/security/console.perms under Red Hat Linux, and /etc/logindevperm under Solaris—specifies a list of devices that should have their owner changed to the account that has logged into the Unix workstation. This approach is similar to the way that /bin/login changes the ownership of tty devices to the person who has logged in using a serial device.

Here is a portion of the Solaris /etc/logindevperm file. Under Solaris, the file is read by the /bin/ttymon program. When a person logs onto the device that is listed in the first field, the program sets the device listed in the third field to the UID of the user that has logged in. The mode of the device is set to the value contained in the second field:

/dev/console    0600    /dev/mouse:/dev/kbd
/dev/console    0600    /dev/sound/*        # audio devices
/dev/console    0600    /dev/fbs/*          # frame buffers
/dev/console    0600    /dev/rtvc0          # nachos capture device 0
/dev/console    0400    /dev/rtvcctl0       # nachos control device 0
12.3.22.2 X security

The X Window System has a simple security model: all or nothing. The X security mechanisms are used to determine whether a client can connect to the X Window Server. After a client successfully connects, that client can exercise complete control over the display.

X clients can take over the mouse or the keyboard, send keystrokes to other applications, or even kill the windows associated with other clients. This capability allows considerable flexibility in the creation of new clients. Unfortunately, it also creates a rich opportunity for Trojan horse programs: the multiuser tank war game that you are running in a corner of your screen may actually be covertly monitoring all of the email messages that you type on your keyboard, or may be making a copy of every password that you type.

The simplest way for an X client program to monitor your keystrokes is to overlay the entire screen with a transparent, invisible window. Such a program records keystrokes, saves them for later use, and forwards each event to the appropriate subwindows so that the user can't tell if she is being monitored. Release X11R4 introduced a "secure" feature on the xterm command that grabs the input from the keyboard and mouse in such a way that no transparent overlay can intercept the input. The xterm window changes color to show that this is in effect. The option is usually on a pop-up menu that is selected by holding down both the Ctrl key and the left mouse button. This is a partial fix, but it is not complete.

Rather than develop a system that uses access control lists and multiple levels of privilege, X instead developed increasingly sophisticated mechanisms for granting or denying this all-or-nothing control. These are listed in Table 12-9.

Table 12-9. X access control systems

System

Technique

Advantages

Disadvantages

xhost

User specifies the hosts from which client connections are allowed; all others are rejected.

Simple to use and understand.

Not suited to environments in which workstations or servers are used by more than one person at a time. Server is susceptible to IP spoofing.

MIT-MAGIC-COOKIE-1

Xdm or user creates a 128-bit "cookie" that is stored in the user's .Xauthority file at login. Each client program reads the cookie from the .Xauthority file and passes it to the server when the connection is established.

Access to the user's display is limited to processes that have access to the user's .Xauthority file.

Cookies are transmitted over the network without encryption, allowing them to be intercepted. Cookies are stored in the user's .Xauthority file, making it a target.

XDM-AUTHORIZATION-1

Xdm creates a 56-bit DES key and a 64-bit random "authenticator" that are stored in the user's .Xauthority file. Each client uses the DES key to encrypt a 192-bit packet that is sent to the X server to validate the connection.

X authenticator is not susceptible to network eavesdropping.

The authenticator is stored in the .Xauthority file, making it a target. If the user's home directory is mounted using NFS or another network filesystem, the 56-bit DES can be eavesdropped from the network when it is read by the X client program.

SUN-DES-1

Authentication based on Sun's Secure RPC. Uses the xhost command as its interface.

Communication to the X server is encrypted with the X server's public key; the secret key is not stored in the .Xauthority file, which removes it as a target.

Runs only on systems that have Sun Microsystems' Secure RPC (mostly on Solaris).

MIT-KERBEROS-5

Xdm obtains Kerberos tickets when the user logs in; these tickets are stored in a special credentials cache file that is pointed to by the KRB5CCNAME environment variable.

Extends the Kerberos network-based authentication system to the X Window System.

Credentials file is a target. Stolen tickets can be used after the user logs out. Kerberos can be a challenge to install.

12.3.22.3 The xhost facility

X maintains a host access control list of all hosts that are allowed to access the X server. The host list is maintained via the xhost command. The host list is always active, no matter what other forms of authentication are used. Thus, you should fully understand the xhost facility and the potential problems that it can create.

The xhost command lets users view and change the current list of xhosted hosts. Typing xhost by itself displays a list of the current hosts that may connect to your X Window Server:

% xhost
prose.cambridge.ma.us
next.cambridge.ma.us
%

You can add a host to the xhost list by supplying a plus sign followed by the host's name on the command line after the xhost command. You can remove a host from the xhost list by supplying its name preceded by a hyphen:

% xhost +idr.cambridge.ma.us 
idr.cambridge.ma.us being added to access control list
% xhost
next.cambridge.ma.us
prose.cambridge.ma.us
idr.cambridge.ma.us
% xhost -next.cambridge.ma.us
next.cambridge.ma.us being removed from access control list
% xhost
prose.cambridge.ma.us
idr.cambridge.ma.us

If you xhost a computer, any user on that computer can connect to your X server and issue commands. If a client connects to your X Window Server, removing that host from your xhost list will not terminate the connection. The change will simply prevent future access from that host.

If you are using SUN-DES-1 authentication, you can use the xhost command to specify the network principals (users) who are allowed to connect to your X server. The xhost command distinguishes principals from usernames because principals contain an at sign (@). For example, to allow the network principal debby@ora to access your server, you could type:

prose% xhost debby@ora

If you are using MIT-KERBEROS-5 authentication, you can use the xhost command to specify the Kerberos users who are allowed to connect to your server. Kerberos usernames must be preceded by the string krb5:. For example, if you want to allow the Kerberos user alice to access your server, you would use the command:

prose% xhost krb5:alice

The file /etc/X0.hosts contains a default list of xhost hosts for X display 0. This file contains a list of lines that determine the default host access to the X display. The format is the same as the xhost command. If a hostname appears by itself or is preceded by a plus sign, that host is allowed. If a hostname appears preceded by a minus sign, that host is denied. If a plus sign appears on a line by itself, access control is disabled.

For example, this file allows default access to X display 0 for the hosts oreo and nutterbutter:

% cat /etc/X0.hosts
-
+oreo
+nutterbutter

If you have more than one display, you can create files /etc/X1.hosts, /etc/X2.hosts, and so forth.

12.3.22.4 Using Xauthority magic cookies

Normally, the Xauthority facility is automatically invoked when you use the xdm display manager. However, you can also enable it manually if you start the X server yourself.

To start, you should preload your .Xauthority file with an appropriate key for your display. If you have the Kerberos or Sun Secure RPC mechanisms available, you should use those. Otherwise, you need to create a "magic cookie" for your current session. This cookie should be a random value that is not predictable to an attacker. (The script given in Chapter 19 can be used for this.) You should generate your "cookie" and store it in your .Xauthority file (normally, $HOME/.Xauthority):

$ typeset -RZ28 key=$(randbits -n 14)
$ EXPORT XAUTHORITY=${XAUTHORITY:=$HOME/.Xauthority}
$ umask 077
$ rm -f $XAUTHORITY
$ cp /dev/null $XAUTHORITY
$ chmod 600 $XAUTHORITY
$ xauth add $HOSTNAME:$displ . $key 
$ xauth add $HOSTNAME/unix:$displ . $key
$ xauth add localhost:$displ . $key 
$ unset key

Next, when you start your X server, do so with the -auth option:

$ xinit -- -auth $XAUTHORITY

All your local client programs will now consult the .Xauthority file to identify the correct "magic cookie" and then send it to the server. If you want to run a program from another machine to display on this one, you will need to export the "cookies" to the other machine. If your home directory is exported with NFS, the file should already be available—you simply need to set the XAUTHORITY environment variable to the pathname of the .Xauthority file (or whatever else you've named it).

Otherwise, you can do something similar to:

$ xauth extract - $DISPLAY | ssh otherhost xauth merge -

Keep in mind that the "magic cookies" in this scheme can be read from your account or found by anyone reading network packets if you're using MIT-MAGIC-COOKIE-1. However, this method is considerably safer than using the xhosts mechanism, and you should use it instead of xhosts when feasible.

Versions of X11R6 xdm prior to public patch 13 contain a weakness in the xauth generation method, which allows an intruder to access its display. For details, see "CERT advisory VB-95:08.X_Authentication_Vul" at http://www.cert.org/summaries/CS-95.03.html.

12.3.22.5 Tunneling X with SSH

One of the best ways that you can significantly increase the security of X is by tunneling servers on remote X displays to your local display using SSH. Doing this is quite easy: simply log into the remote system with SSH, then start up an X client. When you log into the remote system, SSH can set up an X tunnel and open up a socket on the remote system. Your DISPLAY variable will be set up to use the socket.

To use X tunnels, the SSH server must be configured to allow them and the SSH client must request them. For the OpenSSH server, X tunnels are allowed by adding this line to sshd_config:

X11Forwarding yes

For the OpenSSH client, an X tunnel is requested by giving the -X command-line option or including "ForwardX11 yes" in the ssh_config file.

SSH provides a more secure way to use X clients from remote systems. However, if you use X tunneling, be careful: if your remote shell times out or otherwise exits, all of the clients using the tunnel will be killed.

12.3.23 RPC rpc.rexd (TCP Port 512)

The rpc.rexd service is a Sun RPC server that allows for remote program execution. Using rpc.rexd, any user who can execute RPC commands on your machine can run arbitrary shell commands.

The rpc.rexd daemon is usually started from the /etc/inetd.conf file with the following line:

# We are being stupid and running the rexd server without secure RPC:
#
rexd/1          tli  rpc/tcp wait root /usr/sbin/rpc.rexd     rpc.rexd

As the comment indicates, you should not run the rexd server. We make this warning because running rexd without secure RPC basically leaves your computer wide open, which is why Sun distributes its /etc/inetd.conf file with rexd commented out:

# The rexd server provides only minimal 
# authentication and is often not run.
#
#rexd/1          tli  rpc/tcp wait root /usr/sbin/rpc.rexd     rpc.rexd

We think that vendors should remove the rexd line from the /etc/inetd.conf file altogether. It would be even better if they didn't install rexd at all.

12.3.24 Communicating with MUDs, Internet Relay Chat (IRC), and Instant Messaging

Multiuser Dungeons or Dimensions (MUDs) are text-based virtual world servers that allow many people over a network to interact in the same virtual environment. Most MUDs are recreational, although some MUDs have been created to allow scientists and other professionals to interact.

Internet Relay Chat (IRC) is the Citizen's Band radio of the Internet. IRC permits real-time communication between many different people on different computers. Messages can be automatically forwarded from system to system.

Instant Messaging (IM) protocols provide for real-time communications between two or more people. Although some IM systems use HTTP as their transport protocol, most use proprietary protocols. AOL Instant Messager, Yahoo! Messenger, and ICQ are three popular Instant Messaging systems.

While MUDs, IRC and IM can be useful and entertaining, these systems can also have profound security implications:

  • Because these systems permit unrestricted communication between people on your computer and others on the Internet, they create an excellent opportunity for social engineering. Often an attacker will tell a naïve user that there is some "great new feature" that they can enable simply by typing a certain command—a command that then allows the attacker to log in and take over the user's account. There is no simple way to protect users from this kind of attack other than to educate them to be suspicious of what they are told by strangers on the Internet.

  • Most MUDs and IM systems require users to create an account with a username and a password. Many users will blindly type the same username and password that they use for their Unix account. This creates a profound security risk, as it permits anybody who has access to the remote server (such as its administrator) to capture this information and use it to break into the user's Unix account.

  • Although many MUDs and IRCs can be used with telnet, they are more fun when used with specially written client programs. Most IM systems require a specially written client, too. Some of these programs have been distributed with intentional security holes and back doors. Determining whether a client program is equipped with this kind of "feature" is very difficult.

  • Even if the client doesn't have a built-in back door, many of these clients will execute commands from remote machines if such a feature is enabled by the user. The world is rife with attackers who attempt to get unsuspecting users to enable these features. Similarly, some IRC systems include a peer-to-peer file transfer facility. If you're using such a system, you should be sure that no one can transfer your private files!

  • The server programs for some of these protocols can place a significant load on the computers on which they reside. As these servers do not use "trusted ports," users can run their own servers even if they don't have root access. Likewise, because they can be configured to use any port (or even tunnel over HTTP), these services are not readily blocked by a firewall.

    Previous Section Next Section