Securing Linux - Security - Linux All-in-One For Dummies, 5th Edition (2014)

Linux All-in-One For Dummies, 5th Edition (2014)

Book VI. Security

Chapter 2. Securing Linux

In This Chapter

arrow Securing passwords on your Linux system

arrow Protecting the system’s files and directories

arrow Using GnuPG to encrypt and sign files

arrow Monitoring the security of your system

arrow Hardening Internet services

arrow Using Secure Shell for secure remote logins

arrow Setting up simple firewalls and enabling packet filtering

To secure your Linux system, you have to pay attention to both host security and network security. The distinction between the two types of security is somewhat arbitrary because securing the network involves securing the applications on the host that relate to what Internet services your system offers.

This chapter first examines host security and then explains how you can secure network services (mostly by not offering unnecessary services), how you can use a firewall to stop unwanted network packets from reaching your network, and how to use Secure Shell for secure remote logins.

Host is the techie term for your Linux system — especially when you use it to provide services on a network. But the term makes sense even when you think of the computer by itself; it’s the host for everything that runs on it: the operating system and all applications. A key aspect of computer security is to secure the host.

Securing Passwords

Historically, Unix passwords are stored in the /etc/passwd file, which any user can read. For example, a typical old-style /etc/passwd file entry for the root user looks like this:

root:t6Z7NWDK1K8sU:0:0:root:/root:/bin/bash

The fields are separated by colons (:), and the second field contains the password in encrypted form. To check whether a password is valid, the login program encrypts the plain-text password the user enters and compares the password with the contents of the /etc/passwd file. If they match, the user is allowed to log in.

Password-cracking programs work just like the login program, except these programs choose one word at a time from a dictionary, encrypt the word, and compare the encrypted word with the encrypted passwords in the /etc/passwd file for a match. To crack the passwords, the intruder needs the /etc/passwd file. Often crackers use weaknesses of various Internet servers (such as mail and FTP) to get a copy of the /etc/passwd file.

Passwords have become more secure in Linux due to several improvements, including shadow passwords and pluggable authentication modules, or PAMs (described in the next two sections). You can install shadow passwords or a PAM easily while you install Linux. During Linux installation, you typically get a chance to configure the authentication. If you enable MD5 security and enable shadow passwords, you automatically enable more secure passwords in Linux.

Shadow passwords

Obviously, leaving passwords lying around where anyone can get at them — even if the passwords are encrypted — is bad security. So instead of storing passwords in the /etc/passwd file (which any user can read), Linux now stores them in a shadow password file,/etc/shadow. Only the superuser (root) can read this file. For example, here’s the entry for root in the new-style /etc/passwd file:

root:x:0:0:root:/root:/bin/bash

In this case, note that the second field contains an x instead of an encrypted password. The x is the shadow password; the actual encrypted password is now stored in the /etc/shadow file, where the entry for root is like this:

root:$1$AAAni/yN$uESHbzUpy9Cgfoo1Bf0tS0:11077:0:99999:7:-1:-1:134540356

The format of the /etc/shadow entries with colon-separated fields resembles the entries in the /etc/passwd file, but the meanings of most of the fields differ. The first field is still the username, and the second one is the encrypted password.

The remaining fields in each /etc/shadow entry control when the password expires. You don’t have to interpret or change these entries in the /etc/shadow file. Instead, use the chage command to change the password expiration information. For starters, you can check a user’s password expiration information by using the chage command with the -l option, as follows. (In such a case, you have to be logged in as root.)

chage -l root

This command displays expiration information, including how long the password lasts and how often you can change the password.

If you want to ensure that the user is forced to change a password at regular intervals, you can use the -M option to set the maximum number of days that a password stays valid. For example, to make sure that user kdulaney is prompted to change the password in 90 days, log in asroot and type the following command:

chage -M 90 kdulaney

You can use the command for each user account to ensure that all passwords expire when appropriate and that all users must choose new passwords.

Pluggable authentication modules (PAMs)

In addition to improving the password file’s security by using shadow passwords, Linux also improves the encryption of the passwords stored in the /etc/shadow file by using the MD5 message-digest algorithm described in RFC 1321 (www.ietf.org/rfc/rfc1321.txt orwww.cse.ohio-state.edu/cgi-bin/rfc/rfc1321.html). MD5 reduces a message of any length to a 128-bit message digest (or fingerprint) of a document so that you can digitally sign it by encrypting it with your private key. MD5 works quite well for password encryption, too.

Another advantage of MD5 over older-style password encryption is that the older passwords were limited to a maximum of eight characters; new passwords (encrypted with MD5) can be much longer. Longer passwords are harder to guess, even if the /etc/shadow file falls into the wrong hands.

You can tell that MD5 encryption is in effect in the /etc/shadow file. The encrypted passwords are longer and they all sport the $1$ prefix, as in the second field of the following sample entry:

root:$1$AAAni/yN$uESHbzUpy9Cgfoo1Bf0tS0:11077:0:99999:7:-1:-1:134540356

An add-on program module called a pluggable authentication module (PAM) performs the MD5 encryption. Linux PAMs provide a flexible method for authenticating users. By setting the PAM’s configuration files, you can change your authentication method on-the-fly, without modifying vital programs that verify a user’s identity (such as login and passwd).

Linux uses PAM capabilities extensively. The PAMs reside in many different modules (more on this momentarily); their configuration files are in the /etc/pam.d directory of your system. Check out the contents of this directory on your system by typing the following command:

ls /etc/pam.d

Each configuration file in this directory specifies how users are authenticated for a specific utility.

Protecting Files and Directories

One important aspect of securing the host is to protect important system files — and the directories that contain these files. You can protect the files through file ownership and the permission settings that control who can read, write, or (in the case of executable programs) execute the file.

The default Linux file security is controlled through the following settings for each file or directory:

· User ownership

· Group ownership

· Read, write, execute permissions for the owner

· Read, write, execute permissions for the group

· Read, write, execute permissions for others (everyone else)

Viewing ownerships and permissions

You can see settings related to ownership and permissions for a file when you look at a detailed listing with the ls -l command. For example, type the following command to see the detailed listing of the /etc/inittab file:

ls -l /etc/inittab

The resulting listing looks something like this:

-rw-r--r-- 1 root root 1666 Feb 16 07:57 /etc/inittab

The first set of characters describes the file permissions for user, group, and others. The third and fourth fields show the user and group that own this file. In this case, both user and group names are the same: root.

Changing file ownerships

You can set the user and group ownerships with the chown command. For example, if the file /dev/hda should be owned by the user root and the group disk, you type the following command as root to set up this ownership:

chown root.disk /dev/hda

To change the group ownership alone, use the chgrp command. For example, here’s how you can change the group ownership of a file from whatever it was earlier to the group named accounting:

chgrp accounting ledger.out

Changing file permissions

Use the chmod command to set the file permissions. To use chmod effectively, you have to specify the permission settings. One way is to concatenate one or more letters from each column of Table 2-1, in the order shown (Who/Action/Permission).

Table 2-1 File Permission Codes

Who

Action

Permission

u (user)

+ (add)

r (read)

g (group)

- (remove)

w (write)

o (others)

= (assign)

x (execute)

a (all)

s (set user ID)

To give everyone read and write access to all files in a directory, type chmod a+rw *. On the other hand, to permit everyone to execute a specific file, type chmod a+x filename.

Another way to specify a permission setting is to use a three-digit sequence of numbers. In a detailed listing, the read, write, and execute permission settings for the user, group, and others appear as the sequence

rwxrwxrwx

with dashes in place of letters for disallowed operations. Think of rwxrwxrwx as three occurrences of the string rwx. Now assign the values r=4, w=2, and x=1. To get the value of the sequence rwx, simply add the values of r, w, and x. Thus rwx = 7. With this formula, you can assign a three-digit value to any permission setting. For example, if the user can read and write the file but everyone else can only read the file, the permission setting is rw-r--r-- (that’s how it appears in the listing), and the value is 644. Thus, if you want all files in a directory to be readable by everyone but writable only by the user, use the following command:

chmod 644 *

Setting default permission

What permission setting does a file get when you (or a program) create a new file? The answer is in what is known as the user file-creation mask, which you can see and set by using the umask command.

Type umask, and the command prints a number showing the current file-creation mask. For the root user, the mask is set to 022, whereas the mask for other users is 002. To see the effect of this file-creation mask and to interpret the meaning of the mask, follow these steps:

1. Log in as root and type the following command:

touch junkfile

This command creates a file named junkfile with nothing in it.

2. Type ls -l junkfile to see that file’s permissions.

You see a line similar to the following:

-rw-r--r-- 1 root root 0 Aug 24 10:56 junkfile

Interpret the numerical value of the permission setting by converting each three-letter permission in the first field (excluding the very first letter) to a number between 0 and 7. For each letter that’s present, the first letter gets a value of 4, the second letter is 2, and the third is 1. For example, rw- translates to 4+2+0 (because the third letter is missing), or 6. Similarly, r-- is 4+0+0 = 4. Thus the permission string -rw-r--r-- becomes 644.

3. Subtract the numerical permission setting from 666 and what you get is the umask setting.

In this case, 666 – 644 results in a umask of 022.

Thus a umask of 022 results in a default permission setting of 666 – 022 = 644. When you rewrite 644 in terms of a permission string, it becomes rw-r--r--.

To set a new umask, type umask followed by the numerical value of the mask. Here is how you go about it:

1. Figure out what permission settings you want for new files.

For example, if you want new files that can be read and written only by the owner and no one else, the permission setting looks like this:

rw-------

2. Convert the permissions into a numerical value by using the conversion method that assigns 4 to the first field, 2 to the second, and 1 to the third.

Thus, for files that are readable and writable only by their owner, the permission setting is 600.

3. Subtract the desired permission setting from 666 to get the value of the mask.

For a permission setting of 600, the mask becomes 666 – 600 = 066.

4. Use the umask command to set the file-creation mask by typing

umask 066

remember.eps A default umask of 022 is good for system security because it translates to files that have read and write permission for the owner and read permissions for everyone else. The bottom line is that you don’t want a default umask that results in files that are writable by the whole world.

Checking for set user ID permission

Another permission setting can be a security hazard. This permission setting, called the set user ID (or setuid and/or suid for short), applies to executable files. When the suid permission is enabled, the file executes under the user ID of the file’s owner. In other words, if an executable program is owned by root and the suid permission is set, the program runs as if root is executing it — no matter who executed the program. The suid permission means that the program can do a lot more (for example, read all files, create new files, and delete files) than what a normal user program can do. Another risk is that if a suid program file has a security hole, crackers can do a lot more damage through such programs than through other vulnerabilities.

You can find all suid programs with a simple find command:

find / -type f -perm +4000

You see a list of files such as the following:

/bin/su
/bin/ping
/bin/eject
/bin/mount
/bin/ping6
/bin/umount
/opt/kde4/bin/fileshareset
/opt/kde4/bin/artswrapper
/opt/kde4/bin/kcheckpass
. . . lines deleted . . .

Many of the programs have the suid permission because they need it, but check the complete list and make sure that there are no strange suid programs (for example, suid programs in a user’s home directory).

For example, if you type ls -l /bin/su, you see the following permission settings:

-rwsr-xr-x 1 root root 25756 Aug 19 17:06 /bin/su

The s in the owner’s permission setting (-rws) tells you that the suid permission is set for the /bin/su file, which is the executable file for the su command that you can use to become root or another user.

Encrypting and Signing Files with GnuPG

Linux comes with the GNU Privacy Guard (GnuPG, or simply GPG) encryption and authentication utility. With GPG, you can create your public and private key pair, encrypt files using your key, and also digitally sign a message to authenticate that it’s really from you. If you send a digitally signed message to someone who has your public key, the recipient can verify that it was you who signed the message.

Understanding public key encryption

The basic idea behind public key encryption is to use a pair of keys — one private and the other public — that are related but can’t be used to guess one from the other. Anything encrypted with the private key can be decrypted only with the corresponding public key, and vice versa. The public key is for distribution to other people while you keep the private key in a safe place.

You can use public key encryption to communicate securely with others; Figure 2-1 illustrates the basic idea. Suppose Alice wants to send secure messages to Bob. Each of them generates public key and private key pairs, after which they exchange their public keys. Then, when Alice wants to send a message to Bob, she simply encrypts the message using Bob’s public key and sends the encrypted message to him. Now the message is secure from eavesdropping because only Bob’s private key can decrypt the message — and only Bob has that key. When Bob receives the message, he uses his private key to decrypt the message and read it.

Figure 2-1: Bob and Alice can communicate securely with public key encryption.

At this point, you need to stop and think and say, “Wait a minute! How does Bob know the message really came from Alice? What if someone else uses Bob’s public key and sends a message as if it came from Alice?” This situation is where digital signatures come in.

Understanding digital signatures

The purpose of digital, or electronic, signatures is the same as pen-and-ink signatures, but how you sign digitally is different. Unlike a pen-and-ink signature, your digital signature depends on the message you’re signing. The first step in creating a digital signature is to apply a mathematical function to the message and reduce it to a fixed-size message digest (also called a hash or a fingerprint). No matter how big your message, the message digest is usually 128 or 160 bits, depending on the hashing function.

The next step is to apply public key encryption. Simply encrypt the message digest with your private key, and you get the digital signature for the message. Typically, the digital signature is added to the end of the message, and voilà — you get an electronically signed message.

What good does the digital signature do? Well, anyone who wants to verify that the message is indeed signed by you takes your public key and decrypts the digital signature. What that person gets is the message digest (the encrypted hash) of the message. Then he or she applies the same hash function to the message and compares the computed hash with the decrypted value. If the two match, no one has tampered with the message. Because your public key was used to verify the signature, the message must have been signed with the private key known only to you. So the message must be from you!

In the theoretical scenario of Alice sending private messages to Bob, Alice can digitally sign her message to make sure that Bob can tell that the message is really from her. Figure 2-2 illustrates the use of digital signatures along with normal public key encryption.

Here’s how Alice sends her private message to Bob with the assurance that Bob can really tell it’s from her:

1. Alice uses software to compute the message digest of the message and then encrypts the digest by using her private key. This is her digital signature for the message.

2. Alice encrypts the message (again, using some convenient software and Bob’s public key).

3. She sends both the encrypted message and the digital signature to Bob.

4. Bob decrypts the message, using his private key.

5. Bob decrypts the digital signature, using Alice’s public key. This gives him the message digest.

Figure 2-2: Alice can digitally sign her message so that Bob can tell it’s really from her.

6. Bob computes the message digest of the message and compares it with what he got by decrypting the digital signature.

7. If the two message digests match, Bob can be sure that the message really came from Alice.

Using GPG

GPG includes the tools you need to use public key encryption and digital signatures. You can figure out how to use GPG gradually as you begin using encryption. The following shows you some of the typical tasks you can perform with GPG.

Generating the key pair

The steps for generating the key pairs are as follows:

1. Type gpg --gen-key.

If you’re using gpg for the first time, it creates a .gnupg directory in your home directory and a file named gpg.conf in that directory. Then GPG asks what kind of keys you want:

Please select what kind of key you want:
(1) DSA and ElGamal (default)
(2) DSA (sign only)
(4) RSA (sign only)
Your selection?

2. Press Enter for the default choice because it’s good enough.

GPG then prompts you for the key size (the number of bits).

3. Press Enter again to accept the default value of 2,048 bits.

GPG asks you when the keys expire. The default is to never expire.

4. If the default is what you want (and why not?), press Enter.

5. When GPG asks if you really want the keys to never expire, press the Y key to confirm.

GPG prompts you for your name, your e-mail address, and finally a comment to make it easier to associate the key pair with your name.

6. Type each piece of requested information and press Enter.

7. When GPG gives you a chance to change the information or confirm it as is, confirm by typing o and pressing Enter.

GPG next prompts you for a passphrase that protects your private key.

8. Type a long phrase that includes lowercase and uppercase letters, numbers, and punctuation marks — the longer the better — and then press Enter.

remember.eps Be careful to choose a passphrase that you can easily remember.

GPG generates the keys. It may ask you to perform some work on the PC so that the random-number generator can generate enough random numbers for the key-generation process.

Exchanging keys

To communicate with others, you have to give them your public key. You also have to get public keys from those who may send you a message (or someone who might sign a file and you want to verify the signature). GPG keeps the public keys in your key ring. (The key ring is simply the public keys stored in a file, but it sounds nice to call it a key ring because everyone has a key ring in the real world, and these are keys of a sort, right?) To list the keys in your key ring, type

gpg --list-keys

To send your public key to someone or to place it on a website, you have to export the key to a file. The best way is to put the key in what GPG documentation calls an ASCII-armored format, with a command like this:

gpg --armor --export kdualney@insightbb.com > kdulaneykey.asc

This command saves the public key in an ASCII-armored format (it basically looks like garbled text) in the file named kdulaneykey.asc. You would replace the e-mail address with your e-mail address (the one you used when you created the key) and replace the output filename to something different.

After you export the public key to a file, you can mail that file to others or place it on a website for use by others.

When you import a key from someone, you typically get it in an ASCII-armored format as well. For example, if you have a us-cert@us-cert.gov GPG public key in a file named uscertkey.asc (obtained from the link at www.us-cert.gov/pgp/email.html), you then import it into the key ring with the following command:

gpg --import uscertkey.asc

Use the gpg --list-keys command to verify that the key is in your key ring. For example, here’s what you might see when typing gpg --list-keys on the system:

/home/kdulaney/.gnupg/pubring.gpg
-----------------------------
pub 1024D/7B38A728 2013-08-28
uid Kristin Dulaney <kdulaney@insightbb.com>
sub 2048g/3BD6D418 2013-08-28
pub 2048R/F0E187D0 2014-09-08 [expires: 2014-10-01]
uid US-CERT Operations Key <us-cert@us-cert.gov>

The next step is to check the fingerprint of the new key. Type the following command to get the fingerprint of the US-CERT key:

gpg --fingerprint us-cert@us-cert.gov

GPG prints the fingerprint:

pub 2048R/F0E187D0 2013-09-08 [expires: 2014-10-01]
Key fingerprint = 049F E3BA 240B 4CF1 3A76 06DC 1868 49EC F0E1 87D0
uid US-CERT Operations Key <us-cert@us-cert.gov>

At this point, you need to verify the key fingerprint with someone at the US-CERT organization.

If you think the key fingerprint is good, you can sign the key and validate it. Here’s the command you use to sign the key:

gpg --sign-key us-cert@us-cert.gov

GPG asks for confirmation and then prompts you for your passphrase. After that, GPG signs the key.

warning.eps Because key verification and signing is a potential weak link in GPG, be careful about what keys you sign. By signing a key, you basically say that you trust the key to be from that person or organization.

Signing a file

You may find signing files useful if you send a file to someone and want to assure the recipient that no one tampered with the file and that you did, in fact, send the file. GPG makes signing a file easy. You can compress and sign a file named message with the following command:

gpg -o message.sig -s message

To verify the signature, type

gpg --verify message.sig

To get back the original document, simply type

gpg -o message --decrypt message.sig

Sometimes you don’t care about keeping a message secret, but you simply want to sign it to indicate that the message is from you. In such a case, you can generate and append a clear-text signature with the following command:

gpg -o message.asc --clearsign message

This command basically appends a clear-text signature to the text message. Here’s a typical clear-text signature block:

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)
iD8DBQFDEhAtaHWlHHs4pygRAhiqAJ9Qj0pPMgKVBuokDyUZaEYVsp6RIQCfaoBm
9zCwrSAG9mo2DXJvbKS3ri8=
=2uc/
-----END PGP SIGNATURE-----

When a message has a clear-text signature appended, you can use GPG to verify the signature with the following command:

gpg --verify message.asc

If you had indeed signed the message, the last line of the output says that it’s a good signature.

Encrypting and decrypting documents

To encrypt a message meant for a recipient, you can use the --encrypt (or -e) GPG command. Here’s how you might encrypt a message for US-CERT using its GPG key:

gpg -o message.gpg -e -r us-cert@us-cert.gov message

The message is encrypted using the US-CERT public key (without a signature, but you can add the signature with the -s command).

When US-CERT receives the message.gpg file, the recipient has to decrypt it using US-CERT’s private key. Here’s the command someone at US-CERT can use:

gpg -o message --decrypt message.gpg

GPG then prompts for the passphrase to unlock the US-CERT private key, decrypts the message, and saves the output in the file named message.

If you simply want to encrypt a file and no one else has to decrypt the file, you can use GPG to perform symmetric encryption. In this case, you provide a passphrase to encrypt the file with the following GPG command:

gpg -o secret.gpg -c somefile

GPG prompts you for the passphrase and asks you to repeat the passphrase (to make sure that you didn’t mistype anything). Then GPG encrypts the file using a key generated from the passphrase.

To decrypt a file encrypted with a symmetric key, type

gpg -o myfile --decrypt secret.gpg

GPG prompts you for the passphrase. If you enter the correct passphrase, GPG decrypts the file and saves the output (in this example) in the file named myfile.

Monitoring System Security

Even if you secure your system, you have to monitor the log files periodically for signs of intrusion. You may want to use Tripwire (a good tool for detecting any changes made to the system files) so that you can monitor the integrity of critical system files and directories. Your Linux system probably doesn’t come with the Tripwire package. To use Tripwire, you have to buy it from www.tripwire.com. After you purchase and install Tripwire, you can configure it to monitor any changes to specified system files and directories on your system.

Periodically examine the log files in the /var/log directory and its subdirectories. Many Linux applications, including some servers, write log information by using the logging capabilities of syslogd or rsyslogd. On Linux systems, the log files written by syslogd andrsyslogd reside in the /var/log directory. Make sure that only the root user can read and write these files.

remember.eps The syslogd configuration file is /etc/syslog.conf, and the rsyslogd configuration file (existing on many newer systems) is /etc/rsyslog.conf. The default configuration of syslogd generates the necessary log files; however, if you want to examine and understand the configuration file, type man syslog.conf for more information.

Securing Internet Services

For an Internet-connected Linux system (or even one on a TCP/IP LAN that’s not connected to the Internet), a significant threat is that someone could use one of many Internet services to gain access to your system. Each service — such as mail, web, or FTP — requires running a server program that responds to client requests arriving over the TCP/IP network. Some of these server programs have weaknesses that can allow an outsider to log in to your system — maybe with root privileges. Luckily, Linux comes with some facilities that you can use to make the Internet services more secure.

warning.eps Potential intruders can employ a port-scanning tool — a program that attempts to establish a TCP/IP connection at a port and then looks for a response — to check which Internet servers are running on your system. Then, to gain access to your system, the intruders can potentially exploit any known weaknesses of one or more services.

Turning off standalone services

To provide Internet services, such as web, e-mail, and FTP, your Linux system has to run server programs that listen to incoming TCP/IP network requests. Some of these servers start when your system boots, and they run all the time. Such servers are standalone servers. The web server and mail server are examples of standalone servers.

Another server, xinetd, starts other servers that are configured to work under xinetd. Some Linux systems use the inetd server instead of xinetd to start other servers.

Some servers can be configured to run standalone or under a super server such as xinetd. For example, the vsftpd FTP server can be configured to run standalone or to run under the control of xinetd.

 width= In Debian, Ubuntu, and Xandros, use the update-rc.d command to turn off standalone servers and use the invoke-rc.d command to start or stop servers interactively. To get a clue about the available services, type ls /etc/init.d and look at all the script files designed to turn services on or off. You have to use these filenames when you want to turn a service on or off. For example, to turn off Samba service, type update-rc.d -f samba remove. If the service was already running, type invoke-rc.d samba stop to stop the service. You can use theinvoke-rc.d command to stop any service in a similar manner.

 width= In Fedora and SUSE, you can turn standalone servers on or off by using the chkconfig command. You can get the names of the service scripts by typing ls /etc/init.d. Then you can turn off a service (for example, Samba) by typing chkconfig --del smb. If the service was already running, type /etc/init.d/smb stop to stop the service. You can run scripts from the /etc/init.d directory with the stop argument to stop any service in a similar manner.

Configuring the Internet super server

In addition to standalone servers such as a web server or mail server, other servers — inetd or xinetd — have to be configured separately. These servers are Internet super servers because they can start other servers on demand.

tip.eps Type ps ax | grep inetd to see which Internet super server — inetd or xinetd — your system runs.

 width= Debian, Ubuntu, and Xandros use inetd, and Fedora and SUSE use xinetd.

The inetd server is configured through the /etc/inetd.conf file. You can disable a service by locating the appropriate line in that file and commenting it out by placing a pound sign (#) at the beginning of the line. After saving the configuration file, type /etc/init.d/inetd restart to restart the inetd server.

Configuring the xinetd server is a bit more complicated. The xinetd server reads a configuration file named /etc/xinetd.conf at startup. This file, in turn, refers to configuration files stored in the /etc/xinetd.d directory. The configuration files in /etc/xinetd.d tellxinetd which ports to listen to and which server to start for each port. Type ls /etc/xinetd.d to see a list of the files in the /etc/xinetd.d directory on your system. Each file represents a service that xinetd can start. To turn off any of these services, edit the file in a text editor and add a disable = yes line in the file. After you make any changes to the xinetd configuration files, you must restart the xinetd server; otherwise, the changes don’t take effect. To restart the xinetd server, type /etc/init.d/xinetd restart. This command stops the xinetd server and then starts it again. When it restarts, it reads the configuration files, and the changes take effect.

Configuring TCP wrapper security

A security feature of both inetd and xinetd is their use of the TCP wrapper to start various services. The TCP wrapper is a block of code that provides an access-control facility for Internet services, acting like a protective package for your message. The TCP wrapper can start other services, such as FTP and TELNET; but before starting a service, it consults the /etc/hosts.allow file to see whether the host requesting the service is allowed to use that service. If nothing appears in /etc/hosts.allow about that host, the TCP wrapper checks the/etc/hosts.deny file to see if it denies the service. If both files are empty, the TCP wrapper provides access to the requested service.

Here are the steps to follow to tighten access to the services that inetd or xinetd are configured to start:

1. Use a text editor to edit the /etc/hosts.deny file, adding the following line into that file:

ALL:ALL

This setting denies all hosts access to any Internet services on your system.

2. Edit the /etc/hosts.allow file and add to it the names of hosts that can access services on your system.

For example, to enable only hosts from the 192.168.1.0 network and the localhost (IP address 127.0.0.1) to access the services on your system, place the following line in the /etc/hosts.allow file:

ALL: 192.168.1.0/255.255.255.0 127.0.0.1

3. If you want to permit a specific remote host access to a specific Internet service, use the following syntax for a line in /etc/hosts.allow:

server_program_name: hosts

Here server_program_name is the name of the server program, and hosts is a comma-separated list of the hosts that can access the service. You may also write hosts as a network address or an entire domain name, such as .mycompany.com.

Using Secure Shell (SSH) for Remote Logins

Linux comes with the Open Secure Shell (OpenSSH) software, a suite of programs that provides a secure replacement for the Berkeley r commands: rlogin (remote login), rsh (remote shell), and rcp (remote copy). OpenSSH uses public key cryptography to authenticate users and to encrypt the communication between two hosts, so users can securely log in from remote systems and copy files securely.

This section briefly describes how to use the OpenSSH software in Linux. To find out more about OpenSSH and read the latest news about it, visit www.openssh.com or www.openssh.org.

The OpenSSH software is installed during Linux installation. Table 2-2 lists the main components of the OpenSSH software.

Table 2-2 Components of the OpenSSH Software

Component

Description

/usr/sbin/sshd

This Secure Shell daemon must run on a host if you want users on remote systems to use the ssh client to log in securely. When a connection from the ssh client arrives, sshd performs authentication using public key cryptography and establishes an encrypted communication link with the ssh client.

/usr/bin/ssh

Users can run this Secure Shell client to log in to a host that is running sshd. Users can also use ssh to execute a command on another host.

/usr/bin/slogin

This component is a symbolic link to /usr/bin/ssh.

/usr/bin/scp

This secure-copy program works like rcp but securely. The scp program uses ssh for data transfer and provides the same authentication and security as ssh.

/usr/bin/ssh-keygen

You use this program to generate the public and private key pairs you need for the public key cryptography used in OpenSSH. The ssh-keygen program can generate key pairs for both RSA and DSA (Digital Signature Algorithm) authentication. (RSA comes from the initial of the last name of Ron Rivest, Adi Shamir, and Leonard Adleman — the developers of the RSA algorithm.)

/etc/ssh/sshd_config

This configuration file for the sshd server specifies many parameters for sshd, including the port to listen to, the protocol to use, and the location of other files. (There are two versions of SSH protocols: SSH1 and SSH2, both supported by OpenSSH.)

/etc/ssh/ssh_config

This configuration file is for the ssh client. Each user can also have an ssh configuration file named config in the .ssh subdirectory of the user’s home directory.

OpenSSH uses public key encryption, in which the sender and receiver both have a pair of keys — a public key and a private key. The public keys are freely distributed, and each party knows the other’s public key. The sender encrypts data by using the recipient’s public key. Only the recipient’s private key can then decrypt the data.

To use OpenSSH, you first need to start the sshd server and then generate the host keys. Here’s how:

· If you want to support SSH-based remote logins on a host, start the sshd server on your system. Type ps ax | grep sshd to see if the server is already running. If not, log in as root and turn on the SSH service.

· Generate the host keys with the following command:

ssh-keygen -d -f /etc/ssh/ssh_host_key -N ''

The -d flag causes the ssh-keygen program to generate DSA keys, which the SSH2 protocol uses. If you see a message saying that the file /etc/ssh/ssh_host_key already exists, it means that the key pairs were generated during Linux installation. You can use the existing file without having to regenerate the keys.

A user who wants to log in using SSH can simply use the ssh command. For example:

ssh 192.168.0.4 -l kdulaney

where 192.168.0.4 is the IP address of the other Linux system. SSH then displays a message:

The authenticity of host '192.168.0.4 (192.168.0.4)' can't be established.
RSA key fingerprint is 7b:79:f2:dd:8c:54:00:a6:94:ec:fa:8e:7f:c9:ad:66.
Are you sure you want to continue connecting (yes/no)?

Type yes and press Enter. SSH then adds the host to its list of known hosts and prompts you for a password on the other Linux system:

kdulaney@192.168.0.4's password:

After entering the password, you have a secure login session with that system. You can also log in to this account with the following equivalent command:

ssh kdulaney@192.168.0.4

If you simply want to copy a file securely from another system on the LAN (identified by its IP address, 192.168.0.4), you can use scp like this:

scp 192.168.0.4:/etc/X11/xorg.conf

This command prompts for a password and securely copies the /etc/X11/xorg.conf file from the 192.168.0.4 host to the system from which the scp command was typed, as follows:

kdulaney@192.168.0.4's password: (type the password.)
xorg.conf 100% 2814 2.8KB/s 00:00

Setting Up Simple Firewalls

A firewall is a network device or host with two or more network interfaces — one connected to the protected internal network and the other connected to unprotected networks, such as the Internet. The firewall controls access to and from the protected internal network.

If you connect an internal network directly to the Internet, you have to make sure that every system on the internal network is properly secured — which can be nearly impossible because a single careless user can render the entire internal network vulnerable. A firewall is a single point of connection to the Internet: You can direct all your efforts toward making that firewall system a daunting barrier to unauthorized external users. Essentially, a firewall is like a protective fence that keeps unwanted external data and software out and sensitive internal data and software in. (See Figure 2-3.)

Figure 2-3: A firewall protects hosts on a private network from the Internet.

The firewall runs software that examines the network packets arriving at its network interfaces, and then takes appropriate action based on a set of rules. The idea is to define these rules so they allow only authorized network traffic to flow between the two interfaces. Configuring the firewall involves setting up the rules properly. A configuration strategy is to reject all network traffic and then enable only a limited set of network packets to go through the firewall. The authorized network traffic would include the connections necessary to enable internal users to do things such as visit websites and receive electronic mail.

To be useful, a firewall has the following general characteristics:

· It must control the flow of packets between the Internet and the internal network.

· It must not provide dynamic routing because dynamic routing tables are subject to route spoofing — the use of fake routes by intruders. Instead, the firewall uses static routing tables (which you can set up with the route command on Linux systems).

· It must not allow any external user to log in as root. That way, even if the firewall system is compromised, the intruder is blocked from using root privileges from a remote login.

· It must be kept in a physically secure location.

· It must distinguish between packets that come from the Internet and packets that come from the internal protected network. This feature allows the firewall to reject packets that come from the Internet but have the IP address of a trusted system on the internal network.

· It acts as the SMTP mail gateway for the internal network. Set up the sendmail software so that all outgoing mail appears to come from the firewall system.

· Its user accounts are limited to a few user accounts for those internal users who need access to external systems. External users who need access to the internal network should use SSH for remote login (see “Using Secure Shell (SSH) for Remote Logins,” earlier in this chapter).

· It keeps a log of all system activities, such as successful and unsuccessful login attempts.

· It provides DNS name-lookup service to the outside world to resolve any hostnames that are known to the outside world.

· It provides good performance so that it doesn’t hinder the internal users’ access to specific Internet services (such as HTTP and FTP).

A firewall can take many different forms. Here are three common forms of a firewall:

· Packet filter firewall: This simple firewall uses a router capable of filtering (blocking or allowing) packets according to a number of their characteristics, including the source and destination IP addresses, the network protocol (TCP or UDP), and the source and destination port numbers. Packet filter firewalls are usually placed at the outermost boundary with an untrusted network, and they form the first line of defense. An example of a packet filter firewall is a network router that employs filter rules to screen network traffic.

Packet filter firewalls are fast and flexible, but they can’t prevent attacks that exploit application-specific vulnerabilities or functions. They can log only a minimal amount of information, such as source IP address, destination IP address, and traffic type. Also, they’re vulnerable to attacks and exploits that take advantage of flaws within the TCP/IP protocol, such as IP address spoofing, which involves altering the address information in network packets to make them appear to come from a trusted IP address.

· Stateful inspection firewall: This type of firewall keeps track of the network connections that network applications are using. When an application on an internal system uses a network connection to create a session with a remote system, a port is also opened on the internal system. This port receives network traffic from the remote system. For successful connections, packet filter firewalls must permit incoming packets from the remote system. Opening up many ports to incoming traffic creates a risk of intrusion by unauthorized users who abuse the expected conventions of network protocols such as TCP. Stateful inspection firewalls solve this problem by creating a table of outbound network connections, along with each session’s corresponding internal port. This state table is then used to validate any inbound packets. This stateful inspection is more secure than a packet filter because it tracks internal ports individually rather than opening all internal ports for external access.

· Application-proxy gateway firewall: This firewall acts as an intermediary between internal applications that attempt to communicate with external servers such as a web server. For example, a web proxy receives requests for external web pages from web browser clients running inside the firewall and relays them to the exterior web server as though the firewall was the requesting web client. The external web server responds to the firewall, and the firewall forwards the response to the inside client as though the firewall was the web server. No direct network connection is ever made from the inside client host to the external web server.

Application-proxy gateway firewalls have some advantages over packet filter firewalls and stateful inspection firewalls. First, application-proxy gateway firewalls examine the entire network packet rather than only the network addresses and ports. This enables these firewalls to provide more extensive logging capabilities than packet filters or stateful inspection firewalls. Another advantage is that application-proxy gateway firewalls can authenticate users directly, whereas packet filter firewalls and stateful inspection firewalls normally authenticate users on the basis of the IP address of the system (that is, source, destination, and protocol type). Given that network addresses can be easily spoofed, the authentication capabilities of application-proxy gateway firewalls are superior to those found in packet filter and stateful inspection firewalls.

The advanced functionality of application-proxy gateway firewalls, however, results in some disadvantages when compared with packet filter or stateful inspection firewalls. First, because of the full packet awareness found in application-proxy gateways, the firewall is forced to spend significant time reading and interpreting each packet. Therefore application-proxy gateway firewalls are generally not well suited to high-bandwidth or real-time applications. To reduce the load on the firewall, a dedicated proxy server can be used to secure less time-sensitive services, such as e-mail and most web traffic. Another disadvantage is that application-proxy gateway firewalls are often limited in terms of support for new network applications and protocols. An individual application-specific proxy agent is required for each type of network traffic that needs to go through the firewall. Most vendors of application-proxy gateways provide generic proxy agents to support undefined network protocols or applications. However, those generic agents tend to negate many of the strengths of the application-proxy gateway architecture, and they simply allow traffic to tunnel through the firewall.

Most firewalls implement a combination of these firewall functionalities. For example, many vendors of packet filter firewalls or stateful inspection firewalls have also implemented basic application-proxy functionality to offset some of the weaknesses associated with their firewalls. In most cases, these vendors implement application proxies to provide better logging of network traffic and stronger user authentication. Nearly all major firewall vendors have introduced multiple firewall functions into their products in some manner.

tip.eps In a large organization, you may also have to isolate smaller internal networks from the corporate network. You can set up such internal firewalls the same way that you set up Internet firewalls.

Using NAT

Network Address Translation (NAT) is an effective tool that enables you to hide the network addresses of an internal network behind a firewall. In essence, NAT allows an organization to use private network addresses behind a firewall while maintaining the ability to connect to external systems through the firewall.

Here are the three methods for implementing NAT:

· Static: In static NAT, each internal system on the private network has a corresponding external, routable IP address associated with it. This particular technique is seldom used because unique IP addresses are in short supply.

· Hiding: With hiding NAT, all systems behind a firewall share the same external, routable IP address, while the internal systems use private IP addresses. Thus, with a hiding NAT, a number of systems behind a firewall still appear to be a single system.

· Port address translation: With port address translation, you can place hosts behind a firewall system and still make them selectively accessible to external users.

In terms of strengths and weaknesses, each type of NAT — static, hiding, or port address translation — is applicable in certain situations; the variable is the amount of design flexibility offered by each type. Static NAT offers the most flexibility, but it’s not always practical because of the shortage of IP addresses. Hiding NAT technology is seldom used because port address translation offers additional features. Port address translation is often the most convenient and secure solution.

Enabling packet filtering on your Linux system

The Linux kernel has built-in packet filtering software in the form of something called netfilter. You use the iptables command to set up the rules for what happens to the packets based on the IP addresses in their header and the network connection type.

tip.eps To find out more about netfilter and iptables, visit the documentation section of the netfilter website at www.netfilter.org/documentation.

The built-in packet filtering capability is handy when you don’t have a dedicated firewall between your Linux system and the Internet. This is the case, for example, when you connect your Linux system to the Internet through a DSL or cable modem. Essentially, you can have a packet filtering firewall inside your Linux system, sitting between the kernel and the applications.

Using the security level configuration tool

Some Linux distributions, such as Fedora and SUSE, include GUI tools to turn on a packet filtering firewall.

 width= In Fedora, you can turn on different levels of packet filtering through the graphical Firewall Configuration tool. To run the tool, log in as root and choose Activities then type in Firewall. The Firewall Configuration window appears (see Figure 2-4) along with an authentication window.

Figure 2-4: In Fedora, you can configure the firewall with this tool.

From the Firewall Configuration dialog box, you can select two predefined levels of simple firewalling (more precisely, packet filtering):

· Disabled: This option doesn’t perform any filtering and allows all connections. (You can still turn off Internet services by not running the servers or disabling them in the xinetd configuration files.) This security level is fine if your Linux system is inside a protected local area network or if you have a separate firewall device.

· Enabled: This option turns on packet filtering. You can then select the services that you want to allow and the network devices that you trust.

You can allow incoming packets meant for specific Internet services such as SSH, TELNET, and FTP. If you select a network interface such as eth0 (the first Ethernet card) as trusted, all network traffic over that interface is allowed without any filtering.

 width= In SUSE, to set up a firewall, choose Main Menu⇒System⇒YaST. In the YaST Control Center window that appears, click Security and Users on the left side of the window and then click Firewall on the right side. YaST opens a window that you can use to configure the firewall.

You can designate network interfaces (by device name, such as eth0, ppp0, and so on) to one of three zones: internal, external, or demilitarized zone. Then, for that zone, you can specify what services (such as HTTP, FTP, and SSH) are allowed. If you have two or more network interfaces and you use the Linux system as a gateway (a router), you can enable forwarding packets between network interfaces (a feature called masquerading). Figure 2-5 shows an example of this feature in the Firewall Configuration tool included with Fedora.

Figure 2-5: In Fedora, you can turn on masquerading with a single click.

You can also turn on different levels of logging (for example, logging all dropped packets that attempt connection at specific ports). If you make changes to firewall settings, click the Startup category and click Save Settings and Restart Firewall Now.

Using the iptables command

The GUI firewall configuration tools use the iptables command to implement the firewall. If your Linux system doesn’t have a GUI tool, you can use iptables directly to configure firewalling on your Linux system.

Using the iptables command is somewhat complex. The iptables command uses the concept of a chain, which is a sequence of rules. Each rule says what to do with a packet if the header contains certain information (such as the source or destination IP address). If a rule doesn’t apply, iptables consults the next rule in the chain. By default, there are three chains:

· INPUT chain: The first set of rules against which packets are tested. The packets continue to the next chain only if the INPUT chain doesn’t specify DROP or REJECT.

· FORWARD chain: Contains the rules that apply to packets attempting to pass through this system to another system (when you use your Linux system as a router between your LAN and the Internet, for example).

· OUTPUT chain: Includes the rules applied to packets before they are sent out (either to another network or to an application).

When an incoming packet arrives, the kernel uses iptables to make a routing decision based on the destination IP address of the packet. If the packet is for this server, the kernel passes the packet to the INPUT chain. If the packet satisfies all the rules in the INPUT chain, the packet is processed by local processes such as an Internet server that is listening for packets of this type.

If the kernel has IP forwarding enabled and the packet has a destination IP address of a different network, the kernel passes the packet to the FORWARD chain. If the packet satisfies the rules in the FORWARD chain, it’s sent out to the other network. If the kernel doesn’t have IP forwarding enabled and the packet’s destination address isn’t for this server, the packet is dropped.

If the local processing programs that receive the input packets want to send network packets out, those packets pass through the OUTPUT chain. If the OUTPUT chain accepts those packets, they’re sent out to the specified destination network.

You can view the current chains, add rules to the existing chains, or create new chains of rules by using the iptables command. When you view the current chains, you can also save them to a file. For example, if you had configured nothing else and your system has no firewall configured, typing iptables -L should show the following:

Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination

In this case, all three chains — INPUT, FORWARD, and OUTPUT — show the same ACCEPT policy, which means everything is wide open.

If you’re setting up a packet filter, the first thing you do is specify the packets that you want to accept. For example, to accept packets from the 192.168.0.0 network address, add the following rule to the INPUT chain:

iptables -A INPUT -s 192.168.0.0/24 -j ACCEPT

Now add a rule to drop everything except local loopback (the lo network interface) traffic and stop all forwarding with the following commands:

iptables -A INPUT -i ! lo -j REJECT
iptables -A FORWARD -j REJECT

The first iptables command, for example, appends to the INPUT chain (-A INPUT) the rule that if the packet does not come from the lo interface (-i ! lo), iptables rejects the packet (-j REJECT).

Before rejecting all other packets, you may also add more rules to each INPUT chain to allow specific packets in. You can select packets to accept or reject based on many parameters, such as IP addresses, protocol types (TCP, UDP), network interface, and port numbers.

You can do all sorts of specialized packet filtering with iptables. For example, suppose you set up a web server and want to accept packets meant for only HTTP (port 80) and Secure Shell (SSH) services. The Secure Shell service (port 22) is for you to securely log in and administer the server. Suppose the server’s IP address is 192.168.0.10. Here is how you might set up the rules for this server:

iptables -P INPUT DROP
iptables -A INPUT -s 0/0 -d 192.168.0.10 -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -s 0/0 -d 192.168.0.10 -p tcp --dport 22 -j ACCEPT

In this case, the first rule sets up the default policy of the INPUT chain to DROP, which means that if none of the specific rules match, the packet will be dropped. The next two rules say that packets addressed to 192.168.0.10 and meant for ports 80 and 22 are accepted.

warning.eps Don’t type iptables commands from a remote login session. A rule that begins denying packets from all addresses can also stop what you type from reaching the system; if that happens, you may have no way of accessing the system over the network. To avoid unpleasant surprises, always type iptables rules at the console — the keyboard and monitor connected directly to your Linux PC that is running the packet filter. If you want to delete all filtering rules in a hurry, type iptables -F to flush them. To change the default policy for the INPUT chain to ACCEPT, type iptables -t filter -P INPUT ACCEPT. This causes iptables to accept all incoming packets by default.

remember.eps Not every iptables command is discussed in this section. You can type man iptables to read a summary of the commands. You can also read about netfilter and iptables at www.iptables.org.

After you define the rules by using the iptables command, they’re in memory and are gone when you reboot the system. Use the iptables-save command to store the rules in a file. For example, you can save the rules in a file named iptables.rules by using the following command:

iptables-save > iptables.rules

Here’s a listing of the iptables.rules file generated on a Fedora system:

# Generated by iptables-save v1.3.0 on Sun Dec 28 16:10:12 2014
*filter
:FORWARD ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [6:636]
-A FORWARD -j REJECT --reject-with icmp-port-unreachable
-A INPUT -s 192.168.0.0/255.255.255.0 -j ACCEPT
-A INPUT -i ! lo -j REJECT --reject-with icmp-port-unreachable
COMMIT
# Completed on Sun Dec 28 16:10:12 2014

These rules correspond to the following iptables commands used to configure the filter:

iptables -A INPUT -s 192.168.0.0/24 -j ACCEPT
iptables -A INPUT -i ! lo -j REJECT
iptables -A FORWARD -j REJECT

If you want to load these saved rules into iptables, use the following command:

iptables-restore < iptables.rules

Security Files to Be Aware Of

Table 2-3 lists eleven files, or directories, that security administrators should be aware of and able to explain the purpose of.

Table 2-3 Key Security Files

File

Description

/etc/nologin

If this file exists, it denies login to all users except root. This can be handy when maintenance needs to be done and users need to stay off the system for a period of time. Removing the file restores login capability for all users. The file can be created as a text file with any editor, or you can often use the nologin command to create it.

/etrc/passwd

This file holds much of the user account information and is addressed heavily in this chapter.

/etc/shadow

When shadowing is turned on – which it almost always is – then password values (hashes) are stored in this file (which is more secure) as opposed to in /etrc/passwd.

/etrc/xinetd.d/*

This directory can be used to store configuration files used by xinetd, the server daemon.

/etrc/xinetd.conf

This is the main configuration file used by xinetd, the server daemon.

/etrcxinetd.d/*

This directory can be used to store configuration files used by inetd, the Internet daemon. In almost all distributions, inetd has been replaced by xinetd.

/etrc/inetd.conf

This is the main configuration file used by inetd, the Internet daemon.

/etrc/inittab

This is the initial startup (initialization) table used to identify what starts and stops as the system is booted and changes run states.

/etrc/init.d/*

This directory can hold configuration files that are used during the change of run states/level and referenced by the inittab file.

/etrc/hosts.allow

If this file exists, then it specifically lists the hosts that are allowed to network with this one. If the file does not exist, then the default is that all hosts are allowed to network with this one.

/etrc/hosts.deny

If this file exists, then it specifically lists the hosts that are not allowed to network with this one. If the file does not exist, then the default is that all hosts are allowed to network with this one. The three possibilities are that there is an allow file identifying only hosts that can, a deny file that identifies only hosts that cannot, or neither file – in which case all other hosts are allowed to network with this one.