Locking Down Ubuntu - Securing Your System - Hacking Ubuntu (2007)

Hacking Ubuntu (2007)

Part IV: Securing Your System

Chapter List

Chapter 10: Locking Down Ubuntu

Chapter 11: Advanced Networking

Chapter 12: Enabling Services

Chapter 10: Locking Down Ubuntu

From a fresh install, Ubuntu Dapper Drake starts as a very secure operating system. Without applying any security patches, it poses few risks from external and remote attackers. However, maintaining security after the installation is your responsibility. There are a couple of tricks you can do to keep your files and data secure. These include using Sudo for root privileges, GPG to encode messages, enabling encrypted files systems, and even log file and cache management. Ubuntu is usually safe enough from the start, but with a few hacks, it can be made much safer.

Outside of the security field, many people view encryption and cache removal as a sign of guilt. The basic feeling is usually, "why are you covering your tracks if you have nothing to hide?" Just because you are encrypting data and cleaning temporary files does not mean you are doing anything illegal. Consider it like closing curtains on your bedroom window-it means you want privacy, not that you're doing anything wrong. Privacy is also preventative. If your laptop gets stolen, do you want the thief to see all your bank account information in your web cache? How about the source code from some big project you're working on? The same goes for your computer(s) at home. Thieves are just as likely to steal your desktop workstation, as they are your TV and stereo.

Locking down your system limits the amount of damage a bad guy can cause. Furthermore, many of these preventative steps require no additional work beyond installation and initial configuration.

Understanding Ubuntu Security Defaults

Ubuntu installs using a basic security model that consists of no network accessible services, and no root logins. These basic principles ensure that a clean install cannot lead to a remotely compromised host. If you need a network service, then you will need to explicitly install it (see Chapter 12). Even after installing the network services, it usually takes a couple of steps to fully enable it.

There are a few basic steps to maintaining a secure Ubuntu system:

§ Don't use root-The default Ubuntu installation does not assign a root password and you cannot log in as root. Instead, the default user account can use Sudo (see the next section) to run commands as root. Additional user accounts cannot even run Sudo unless they are given explicit permission. Restricting root access limits your ability to accidentally (or intentionally) screw up the entire operating system.

§ Limit network services-Only enable services that you need. If you don't need a mail server, then don't install one. If you do not host web pages, then don't install a web server. Attackers can only exploit network services that are running on your system.

§ Use trusted software sources-Chapter 4 describes how to modify /etc/apt/ sources.list in order to change the supported repository list. The default repositories come from a trusted location: the four official Ubuntu repositories. However, there are literally hundreds of unofficial repositories. Installing software from an unknown and untrusted repository could result in the installation of hostile software. Don't change the default repository settings or install software from untrusted providers unless you know what you are doing. Remember: just because they say it is safe does not mean it really is safe.

§ Limit scripts-web browsers, chat room software, and other programs can transfer potentially hostile software from the network, download files, and run programs. If you don't need this functionality, then disable it. For example, if you don't need Java or JavaScript in your web browser, then disable it (see Chapter 5).

§ Use strong passwords-If you are the only person with physical access to your computer and you do not allow remote network access, then you can probably get away with having abcd or your pet's name as your password. (One of my home computers is usually logged in and the screen saver does not demand a password-this is as effective as having no password.) However, if you are in a corporate environment with many users, or enable remote access, or are at home with young kids (or cats) who like to press the delete button, then consider a strong password. Remote access and physical access attacks can use brute force approaches that include:

o Dictionary words-If your password is found in a dictionary (English, French, Chinese, and so on) then it can be easily guessed.

o Words with numbers-Simple word-number combinations, like apple12 or 288cereal can be easily guessed. The same goes for punctuation (hello! and ?what?).

o Keyboard patterns-Sequences like asdfghjk (adjacent keys on the keyboard) are very easy to guess.

o Common data-License plates, dates (birthday, anniversary, and so on), kids names, and other types of public information are very easy to guess.

§ Programs like John the Ripper (sudo apt-get install john) are designed to crack passwords through dictionary attacks and common password patterns like the ones listed above. In my experience, John can crack about 20 percent of user-chosen passwords in the first few minutes, and up to 80 percent in a few hours. The best passwords will not be based on dictionary words or simple patterns, and will be memorable. Good passwords should make sense to only you and not anyone else.


If you are an administrator with lots of users on your system, consider using John the Ripper to look for weak passwords. It is much safer if you find the weak ones and ask the users to proactively change their passwords than wait for a hostile user to find them and exploit the accounts.

§ Don't compromise your security. Telling people "I have a really cool password-it's my student ID number from high school and nobody will guess that!" is a huge hint to an attacker. Don't hint at your password, don't e-mail it, and don't tell it to anyone in public. If you think that somebody might have a clue about your password, then change it immediately. Remember: the only person inconvenienced by a password change will be you. Beyond passwords, don't give accounts with Sudo access to anyone, don't install software from strangers, and don't run with scissors. Your security is as strong as its weakest link, and that is often the user.


Don't use your Ubuntu system's password anywhere else. Many people use the same password for their Yahoo!, Gmail, and eBay accounts as well as other online services. If you use your password everywhere, then one compromised site will compromise all of your accounts. Most people underestimate the blackhat hacker's ability to find your other accounts. I'm a good guy (whitehat) and I spend a lot of time tracking people online-believe me, finding your other accounts is easy.

Secure by Default

The default Ubuntu server and desktop installations do not include any remote network services. This way, a clean install can be patched and prepared without the risk of an external attacker compromising the system. You can place a clean install of Dapper Drake on the Internet without a firewall and not risk any remote compromises. (You cannot compromise a network service when no network services exist.)

After the installation, you can update the system (sudo apt-get update; sudo apt-get upgrade) and begin adding in services and user accounts. This minimizes the risk from remote exploitation.

The basic idea of "no default network services" is a concept that could benefit other operating systems. For example, Microsoft Windows, HP-UX, and RedHat Fedora Linux all enable some basic network services during the installation. This can lead to big problems. For example, if you work for a large company that has a few infected Windows systems, then installing a new Windows system on the network could face a problem: the new system may be infected over the open network services before the first security patch is applied.

Hacking with Sudo

Throughout this book we have used the sudo command for running commands as root. Sudo allows you to run a command with root privileges. The default installation of Ubuntu includes the Sudo command (sudo) and gives the default user account access to this command. If you need something to run as root, you can use sudo. A related command, sudoedit, allows you to edit a file as root. For example, to edit the root-only file /var/spool/anacron/ cron.daily, you can use wither of the following commands:

sudo vi /var/spool/anacron/cron.daily

sudoedit /var/spool/anacron/cron.daily


The sudoedit command uses the editor defined in the $EDITOR environment variable. If this editor is not defined, the nano editor is used. See "Tuning the Shell" in Chapter 2 for setting the $EDITORvariable.

Sudo Coup

When Unix was young (circa 1970), administrators needed a way to change between user access privileges. This was accomplished with the su command. Although originally designed to switch user access, it was mainly used to change privileges from a regular user to root. (The su command is sometimes called the super-user command for this reason.)

There are a couple of huge risks with using su to run commands as root. Most notably, all commands are executed with root privileges. Many times, only one command within a long list of commands really needs root access. Also, when a terminal is logged in as root, users may forget which user they are running as. Accidentally deleting files from a directory as root can be much more devastating than doing so as a regular user.

Sudo was created to limit the commands that can run as root. Rather than changing all privileges, only the privileges for a specific command are changed. Furthermore, Sudo can even limit which commands can be run as root. When the command completes, you are back to your regular user access. This way, only the required steps run as root, and you won't accidentally leave a terminal logged in a root.

Although very old Unix systems still rely on su to change access levels, it is being forcefully replaced by sudo. Furthermore, in most BSD and Linux distributions (including Ubuntu), Sudo has become standard for using root privileges. Although the su command is included with the Ubuntu installation, you cannot use it to run commands as root unless you first set a root password using sudo passwd root.

Adding Users to Sudo

The configuration file for sudo is /etc/suders. This lists who can run commands as root, which commands they can run, and any configuration preferences. Listing 10-1 shows the default /etc/sudoers file. Although this file can be edited using sudo vi /etc/sudoers or sudoedit /etc/sudoers, this is not recommended. Instead, the command sudo visudo (short for vi sudo) is the preferred approach. The visudo command ensures that only one person edits the file at a time. It also checks for syntax errors before installing the new file. (The last thing you need is to corrupt /etc/sudoers and lose the ability to run sudo for fixing the problem.)

The default /etc/sudoers file gives access to everyone who is part of the admin group. Non-admin users are blocked from running commands as root. If you want to add someone to the admin group, use:

1. Use the vigr command to edit the /etc/groups file.

2. sudo vigr

3. The /etc/groups file lists each group name, group ID number, and a comma-separated list of users. Search for the line that begins with admin. It should list one account name (your default Ubuntu account). For example, my default account name is neal and the line says:

4. admin:x:112:neal

5. Add the new user name to this line. Use a comma to separate usernames. For example, if I want to add the user marc to this line, I would have:

6. admin:x:112:neal,marc

7. Save your changes and quit the editor.


Changes to /etc/groups do not propagate to running applications. If the user is currently logged in, he or she will need to log out before noticing the group changes.

If you want to give a user Sudo access without adding them to a group, then you can add them as a privileged user.

1. Edit the /etc/suderers file using sudo visudo.

2. Look for the line that says root ALL=(ALL) ALL.

3. Create a similar line with the user's account name. For example, if I want to give the account "marc" access, I will use:

4. root ALL=(ALL) ALL

5. marc ALL=(ALL) ALL

This addition says that the users "root" and "marc" can use sudo and can run any command with root privileges.

6. Save your changes and exit the visudo command.

Listing 10-1: The Default /etc/sudoers File

# /etc/sudoers


# This file MUST be edited with the 'visudo'


# See the man page for details on how to write a sudoers file.

# Host alias specification

# User alias specification

# Cmnd alias specification

# Defaults

Defaults !lecture,tty_tickets,!fqdn

# User privilege specification

root ALL=(ALL) ALL

# Members of the admin group may gain root privileges

%admin ALL=(ALL) ALL

Tweaking other Sudo Options

The default sudo command has three options enabled: !lecture, tty_tickets, and !fqdn. These options are flags-the ! in front of any flag disables the option. Other options can be added that include values. All the options belong on the Defaults line in the /etc/suders file (use sudo visudo to edit this file). Some command options that you might want to tweak include:

§ lecture-When this flag is enabled, the sudo command will display a warning about running commands as root. This can be useful if there are lots of administrators on a system. However, people usually ignore the warning. The default installation disables the lecture message: !lecture.

§ timestamp_timeout-This option lists the number of minutes before sudo requires you to re-enter your password. If you are running many sudo commands in a row, then it can become very inconvenient to re-enter your password after every command. The default configuration is 15 minutes (timestamp_timeout=15)-if your last sudo command was executed more than 15 minutes ago, then you will need to re-enter your password to run sudo. Setting the value to zero will always prompt for a password; setting the value to a negative number disables the timeout. If you are in a very sensitive environment, then you may want to lower this value (or set it to zero).

§ tty_tickets-If you have lots of windows open, then you will notice that you need to enter your password the first time you run sudo in any window. This is due to the tty_tickets flag-every terminal (tty) has its own sudo environment. If you disable this flag (!tty_tickets), then entering your password for sudo in one window will stop the sudo password prompts in all other windows.

§ fqdn-When host names are used in the sudoers file, this flag specifies the use of fully qualified domain names (fqdns).

§ passwd_tries-This sets how many password attempts the user gets before sudo fails. The default is passwd_tries=3.

§ insults-This is a fun flag. If the user enters in a bad password, then sudo will generate a random message. (The default is !insults.) For example:

§ $ sudo id

§ Password: [wrong]

§ Just what do you think you're doing Dave?

§ Password: [wrong]

§ It can only be attributed to human error.

§ Password: [wrong]

§ My pet ferret can type better than you!

§ sudo: 3 incorrect password attempts


There are many other advanced configuration options including logging and user-based restrictions. If you have specific needs, look at the manual for sudoers (man sudoers).

Becoming Root

Although the Ubuntu security model has all administrative commands issued through sudo, there are some times when you really would be better off with a command prompt as root. Fortunately, there are many ways to accomplish this with sudo. A few examples:

sudo -s # run a shell as root

sudo bash -o vi # run a specific shell as root

sudo -i # set root's initial login environment

sudo su - root # become root and run root's login environment

In the first two cases, the shell runs as root, but environment variables (for example, $HOME) are inherited. In the other two cases, the environment is replaced with root's real environment settings.

If you really need to be able to login as root, then you can use sudo passwd root to give the root account a password. As soon as you set the password, the root account can log in. You can always undo this change with sudo passwd -l root to lock the account.


Enabling root logins is usually a bad idea. Logins give a trail of accountability. If someone logs in without a personalized account, then there is no way to identify the person who really logged in. sudo gives an audit trail in /var/log/auth.log (even though users with sudo access have the ability to blow away the logs).

Using Gnu Privacy Guard (GPG)

Security and encryption are frequently used in the same sentence. If you want to keep something private, use cryptography. In 1991, Phil Zimmerman made public a cryptographic system called Pretty Good Privacy (PGP). This became the basis of his company, PGP, Inc. The PGP system was rewritten and licensed under the Gnu Public License (GPL). This new system, the Gnu Privacy Guard (GnuPG or GPG), has become a de facto standard for file and e-mail encryption among Linux and Unix systems. As such, it is included during the default Ubuntu installation.


Many people use the names GPG and PGP interchangeably. Both systems use the same encryption method and the tools have similar use models. A file encrypted with PGP can be decrypted with GPG. The most significant differences are licensing and availability; GPG is open source, GPL, and more widely used.

GPG is included with every Ubuntu installation, even a minimal install. GPG enables you to create public and private keys, securely exchange keys, and encrypt and decrypt messages. Many e-mail programs either natively integrate with PGP (and GPG) or have plug-ins available. For example, Dapper Evolution mailer natively supports GPG. The mutt text-based mailer also supports PGP, and even Microsoft Outlook users can get a plug-in for PGP encryption.

There are many parts to using GPG:

§ Key generation

§ Searching keys

§ Exchanging keys

§ Defining trust for keys

§ File encryption and decryption

§ Cryptographic signatures

§ E-mail integration

Creating Keys

GPG uses asymmetrical key cryptography. This means that one key is used to encrypt the data, and a different key is required to decrypt the data. The two keys are called private and public. Basically, the private key is never passed out (it is kept private), while anyone and his dog can have a copy of the public key. Messages that are encrypted with the private key can only be decrypted with the public key.

Creating keys under GPG is pretty painless: gpg –gen-key. This provides a series of text prompts for creating a private-public key pair (see Listing 10-2). All users have their own set of keys (called a key ring) that are stored in $HOME/.gnupg/. The main key rings are $HOME/.gnupg/pubring.gpg and secring.gpg. The former stores public keys, whereas the latter stores private keys.

Although giving out your public keys is expected, your private keys should be kept as secret as possible. During the generation of your key pair, GPG prompts you for a password. Although this password is not used during the cryptography (only the keys are used for that), it is used to encrypt your private keys while they are on the hard drive. This deters some other user on the system from stealing your private keys and using them to access your encoded data (or impersonating you-see the section on Signing Data).


Passwords are not required. Many automated tools use GPG, so it can be very desirable to not use a password at all. If you leave the password blank (just hit enter when generating the key), then you will never be prompted for a password.

Listing 10-2: Generating GPG Public and Private Keys

$ gpg --gen-key

gpg (GnuPG); Copyright (C) 2005 Free Software Foundation, Inc.

This program comes with ABSOLUTELY NO WARRANTY.

This is free software, and you are welcome to redistribute it

under certain conditions. See the file COPYING for details.

Please select what kind of key you want:

(1) DSA and Elgamal (default)

(2) DSA (sign only)

(5) RSA (sign only)

Your selection? 1

DSA keypair will have 1024 bits.

ELG-E keys may be between 1024 and 4096 bits long.

What keysize do you want? (2048) 2048

Requested keysize is 2048 bits

Please specify how long the key should be valid.

0 = key does not expire

<n> = key expires in n days

<n>w = key expires in n weeks

<n>m = key expires in n months

<n>y = key expires in n years

Key is valid for? (0) 2y

Key expires at Mon 10 Nov 2008 10:56:00 AM MST

Is this correct? (y/N) y

You need a user ID to identify your key; the software constructs the user ID

from the Real Name, Comment and Email Address in this form:

"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"

Real name: John Travolta

Email address: travolta@discomania.tv


You selected this USER-ID:

"John Travolta <travolta@discomania.tv>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O

You need a Passphrase to protect your secret key.

Enter passphrase: *******

Repeat passphrase: *******

We need to generate a lot of random bytes. It is a good idea to perform

some other action (type on the keyboard, move the mouse, utilize the

disks) during the prime generation; this gives the random number

generator a better chance to gain enough entropy.




public and secret key created and signed.

gpg: checking the trustdb

gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model

gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u

gpg: next trustdb check due at 2008-11-10

pub 1024D/EB66D0E2 2006-11-11 [expires: 2008-11-10]

Key fingerprint = 6D01 42F6 C58E CC52 6B32 CEC7 475E 92D3 EB66 D0E2

uid John Travolta <travolta@discomania.tv>

sub 2048g/50AFB0BA 2006-11-11 [expires: 2008-11-10]

Can You Repeat That?

Private keys are supposed to be unique, and GPG uses some of the strongest cryptographic algorithms available. If you lose your password, delete your private key, or corrupt your key ring without a backup available, then you are screwed. You will not be able to recover the data.

Similarly, don't delete private keys unless you are positive that you will never need them ever again. Since they are unique, there is no going back after you make this decision. My key ring contains many old and expired keys because they are needed to decode some old messages and verify signatures.

When sending GPG-encoded e-mails, be sure to send a copy to yourself. Otherwise, you won't be able to decode your sent mail. Simply saving a copy of the sent message is not enough since your key is not added to the encryption. I occasionally receive e-mails where the sender asks me to send them back the e-mail so they can have a copy of their own text.

Searching Keys

After you create the keys, you can view them using the –list-keys option. The gpg – list-keys command will list every public key in your key ring. You can also specify filter words for searching the key ring. For example, gpg –list-keys EB66D0E2 returns the key matching this unique identifier. You can also specify words, like gpg –list-keys disco to list every key where the string discoappears in the person's name or e-mail address.


Since keys contain e-mail addresses, I use gpg –list-keys as a cheap Rolodex. For example, if I need to remember Marc See's e-mail address, then I use gpg –list-keys marc and his entry (Marcus T. See <msee@test.lan>) comes right up.

Other search options include gpg –list-secret-keys and gpg –fingerprint. The former lists all of your private keys and the latter shows key-unique hashes that can be used to validate keys. Since anyone can create any key with anyone's name and e-mail address, the unique fingerprint allows you to make sure the key is from the right person (see Transferring Keys).


You can delete keys using –delete-key and –delete-secret-key. However, you probably will never need to delete keys, and deleting a secret key is irreversible unless you have a backup.

Search for keys based on name, e-mail address, or unique ID is used by most of the GPG operations. For example, when encrypting a message you will be asked to provide a list of keys for encrypting the message. These can be found by searching names, e-mail addresses, or IDs.


You can specify multiple search terms on the gpg command line. These terms form a logical OR-any key that matches any of the terms will be displayed.

Transferring Keys

After you create your keys, you will need to pass around your public key. Only people with your public key can encrypt messages to you. To do this, you will need to export the public key from your key ring. The command gpg –export -a will export all of your private keys. You can use the search strings to narrow down the keys being exported. For example, gpg –export - a travolta will export my public key for John Travolta. The result from this command is an ASCII-encoded text block that can be e-mailed or passed to other people. The block should look similar to this one:


Version: GnuPG v1.4.2.2 (GNU/Linux)




























When you receive a message like this, you can import it using gpg –import. For example:

gpg --export -a travolta > travolta.pub # export public key

gpg --import travolta.pub # import public key

gpg --import < travolta.pub # inline import public key

The import command looks for the BEGIN and END markers, so you don't even need to separate it from the rest of the file before doing the import. For example, if you have a bunch of keys in an e-mail file (for example, e-mail.mbox), then you can import all of them using:

gpg --import e-mail.mbox

Defining Trust

GPG has a well-defined notion of trust. Although a new key that you import can be used to decode a message, you shouldn't communicate with keys you do not trust. Using the gpg command, you can set an explicit trust level for a key. The basic levels are:

§ Undefined-You can use the key to decode messages, but probably shouldn't use it for encryption.

§ Do not trust-This key is a known forgery or is otherwise evil.

§ Marginal trust-The key is probably authentic.

§ Fully trust-You know the key is valid. Most likely, you were given a hash fingerprint and have compared it using gpg –fingerprint and you know it is correct.

§ Ultimately trust-This usually means it is your own key.

Listing 10-3 shows an example for setting the trust level on the example Travolta key.


Few programs that use GPG actually use the trust level. The main one that I have found is Evolution. If a public key is not explicitly trusted, then you cannot send an encrypted e-mail to that user.

Listing 10-3: Setting the Trust Level

$ gpg --edit-key travolta trust

gpg (GnuPG); Copyright (C) 2005 Free Software Foundation, Inc.

This program comes with ABSOLUTELY NO WARRANTY.

This is free software, and you are welcome to redistribute it

under certain conditions. See the file COPYING for details.

Secret key is available.

gpg: checking the trustdb

gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model

gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u

gpg: next trustdb check due at 2008-11-10

pub 1024D/EB66D0E2 created: 2006-11-11 expires: 2008-11-10 usage: CS

trust: undefined validity: unknown

sub 2048g/50AFB0BA created: 2006-11-11 expires: 2008-11-10 usage: E

[ unknown] (1). John Travolta <travolta@discomania.tv>

pub 1024D/EB66D0E2 created: 2006-11-11 expires: 2008-11-10 usage: CS

trust: undefined validity: unknown

sub 2048g/50AFB0BA created: 2006-11-11 expires: 2008-11-10 usage: E

[ unknown] (1). John Travolta <travolta@discomania.tv>

Please decide how far you trust this user to correctly verify other users' keys

(by looking at passports, checking fingerprints from different sources, etc.)

1 = I don't know or

2 = I do NOT trust

3 = I trust marginally

4 = I trust fully

5 = I trust ultimately

m = back to the main menu

Your decision? 4

pub 1024D/EB66D0E2 created: 2006-11-11 expires: 2008-11-10 usage: CS

trust: full validity: unknown

sub 2048g/50AFB0BA created: 2006-11-11 expires: 2008-11-10 usage: E

[ unknown] (1). John Travolta <travolta@discomania.tv>

Please note that the shown key validity is not necessarily correct

unless you restart the program.

Command> q

Encrypting Files

GPG has two ways to encrypt files. The first way, gpg -e file, will prompt you to select all of the public keys that should be use to encrypt the data. If you select three public keys, then any of those three people (with the private keys) can decrypt the data. The output from this command is a binary file with the .gpg extension. If you use file, then the output becomes file.gpg, and if you use cow.txt, then the output is cow.txt.gpg. Because this is a binary file, the contents will look like random gibberish. When you transfer the file, be sure to use a system that can transfer binary files-pasting file.gpg into an e-mail will likely corrupt the data.


If you have a file encrypted with GPG and you lose the keys, then the file will be unreadable.

A second encryption method uses ASCII armoring. In this approach, the binary data is encoded into text characters. The content is wrapped with BEGIN and END labels and is ready for e-mailing. Using gpg -e -a file or gpg -e –armor file will create file.asc, containing the ASCII armored encrypted message. An armored message should look like a random jumble of characters within the BEGIN and END labels:


Version: GnuPG v1.4.2.2 (GNU/Linux)

















Don't modify anything between the BEGIN and END markers or you will corrupt the data.

Decoding a GPG message is a snap. The -d parameter means decode and the command line specifies the file to decrypt. The decoded contents are sent to standard-out.

gpg -d file.gpg > file # decoding a binary GPG file

gpg -d file.asc > file # decoding an ASCII armored GPG file

During the decryption, you will be asked to provide your private key's password.

Signing Data

Usually public keys are used to encrypt data, so only the private key can decrypt the file. This way, anyone can encrypt a message and only you can decrypt it. However, GPG does allow you to reverse the process. GPG can be used to sign messages using the private key-anyone with the public key can validate the cryptographic signature. This allows recipients to know that the data has not been tampered and that it is authentic. To sign a file, use:

gpg -s file # creates a signed binary file.gpg

gpg -a -s file # creates a signed ASCII armored file.asc

gpg -e -a -s file # creates a signed and encrypted ASCII armored file.asc

When signing a file, you will be asked to provide your private key's password. During the decoding process (gpg -d), the signature will be tested and validated.


Even if you don't have a copy of the public key, you can still view the signed contents using gpg -d. However, you will not be able to authenticate the signature without the public key, and if the file is encrypted then you will not even be able to view the contents.

Although signing data may sound like a neat idea, it serves a critical purpose. In some jurisdictions, a digital signature is legal and binding. If you are sending contracts or making business agreements, consider using GPG to digitally sign a document. Doing this will prevent forgeries and is much more secure than faxing your signature on a piece of paper. (Be sure to first check with your legal council to make sure a digital signature is binding.)

Integrating with e-mail

PGP and GPG are most commonly used for encrypted e-mail. The Ubuntu mail program, Evolution, natively supports GPG (although it calls it PGP). When composing an e-mail, select the PGP options from the Security menu (see Figure 10-1).

Image from book
Figure 10-1: Enabling PGP encryption and digital signatures

Evolution has one big limitation when using PGP: you will only be able to send encrypted e-mail when the trust level is defined on the public key. If the trust for a key is not defined, or a public key is unavailable for the recipient, then you will be unable to send an encrypted e-mail. (See the section on "Defining Trust" earlier in this chapter.) This can become a big problem if the key is associated with one e-mail address, but the user has a couple of different e-mail addresses.

Evolution is not the only e-mail program that supports PGP. I frequently use mutt (see Figure 10-2). This is a text-only mail program (sudo apt-get install mutt). This program enables me to easily send my public key to other people (by pressing Esc, then k) and I can enable encryption or signing by pressing p. Unlike Evolution, if mutt cannot find the appropriate keys, then it allows me to search for alternate keys. However, mutt is not a graphical application-HTML contents and images cannot be viewed using this tool.

Image from book
Figure 10-2: Sending an e-mail with using mutt. In this example, a public key is being forwarded as an attachment

PGP does have one large limitation when used with e-mail: different e-mail programs may be incompatibility. A PGP e-mail sent with Microsoft Outlook may not be immediately readable with mutt or Evolution. This is because different mailers use different mail headers to identify an encrypted message. With mutt, you can usually resolve incompatible formats by pressing Ctrl+E and changing the Content-Type to application/pgp. In contrast, with Evolution you will need to save the e-mail to a file and decrypt it by hand.

Encrypting File Systems

Why encrypt individual files, when you can encrypt entire file systems? Although Ubuntu does not provide any built-in cryptographic systems for this, you can install EncFS, the Encrypted File System. Using EncFS, you can encrypt directories and files. The decrypted file systems only exist as long as the encrypted system is mounted.

Installing and Configuring EncFS

EncFS is not an independent file system. Instead, it is a file system plug-in that encrypts and decrypts files on the fly. It uses the existing file system for storing data, but all data is encrypted on a file-by-file basis. File names are also cloaked to ensure that the encrypted directory has limited usefulness to someone without the password.

1. Install EncFS. This will also install the FUSE (Filesystem in Userspace) utilities.

2. sudo apt-get install encfs

3. Make sure the command fusermount can run as root.

4. sudo chmod u+s /usr/bin/fusermount

5. Each user who will need to use EncFS must be added to the fuse group. Use sudo vigr to add users to this group. Find the line that starts with fuse and add user names to the end of the line.

6. Changes to /etc/groups do not impact current logins. Make sure the user is in the group fuse by running the command groups. If the group fuse is not listed, then the user must log out and log back in for the change to take effect.

7. Make sure the FUSE kernel module is loaded. You may also want to add fuse to /etc/modules so it is always loaded after a reboot.

8. sudo modprobe fuse

9. Using the encfs command, create the encryption and decryption directories. For example, I use encrypt/ and decrypt/. If the directories do not exist, then you will be prompted to create them. You will also be prompted for a password.


The encfs command tries to run in the background. To do this, you must use absolute paths. If you specify a relative path, then you will need to use the -f option and it will not run in the background.

$ encfs 'pwd'/encrypt 'pwd'/decrypt

The directory "/.../encrypt/" does not exist. Should it be created? (y,n) y

The directory "/.../decrypt" does not exist. Should it be created? (y,n) y

Creating new encrypted volume.

Please choose from one of the following options:

enter "x" for expert configuration mode,

enter "p" for pre-configured paranoia mode,

anything else, or an empty line will select standard mode.

?> [enter]

Standard configuration selected.

Configuration finished. The filesystem to be created has

the following properties:

Filesystem cipher: "ssl/blowfish", version 2:1:1

Filename encoding: "nameio/block", version 3:0:1

Key Size: 160 bits

Block Size: 512 bytes

Each file contains 8 byte header with unique IV data.

Filenames encoded using IV chaining mode.

Now you will need to enter a password for your filesystem.

You will need to remember this password, as there is absolutely

no recovery mechanism. However, the password can be changed

later using encfsctl.

New Encfs Password: [password]

Verify Encfs Password: [password]


Do not forget your password! There is no way to recover a lost password.

Now you have two directories: decrypt/ contains the decoded file system, and encrypt/ contains the real encrypted files. If you copy files into the decrypt/ directory, then you will see encrypted counterparts in the encrypt/ directory.


An attacker who views the encrypt/ directory can see the number of files, owner's name, permissions, and timestamps. He can also see the approximate file sizes. However, he cannot see the actual file names or file contents.

Maintaining EncFS

When you are all done with the decrypted directory, you un-mount it using fusermount -u decrypt. Although the encrypted files still exist in the encrypt/ directory, the decrypt/ directory will appear empty (because it is not mounted). Later, when you need to access the encrypted files, you can use: encfs ‘pwd‘/encrypt ‘pwd‘/decrypt. This will only ask you for your password. The files will only appear in the decrypted/ directory if you enter the correct password.

If you ever need to change the password, you can use the encfsctl passwd encrypt/ command. This will prompt you for your old and new passwords.


You do not need to un-mount the directory in order to change the password. The password is only used during the initial file mounting. However, if you change the password, then you will need the new password in order to re-mount the encrypted files.

Using EncFS

EncFS is great for storing files if you are worried about someone stealing the media or accessing the stored data. Here are some sample situations where you might want to use EncFS:

§ Encrypt an entire directory-If you have a directory that you don't want people to access, then you can encrypt it. For example, I have a source code repository containing sensitive information. The actual files are stored using EncFS. If you are worried about your web cache, consider encrypting $HOME/.mozilla/.

§ Encrypt your home directory for more privacy-Using EncFS, you can encrypt your entire home directory. This can become a little complicated since you cannot mount and un-mount without logging in multiple times. However, this is an option. The secret is to mount the encrypted file system over your existing file system.

1. You will need a directory outside of your home directory for storing the encrypted files. If my home directory is /home/neal then I can use /home/neal2. For example:

2. sudo mkdir ${HOME}2

3. sudo chown 'id -un':'id -gn' ${HOME}2

4. mkdir ${HOME}2/encrypt

5. Create a temporary encrypted directory and copy your home directory into it.

6. encfs ${HOME}2/encrypt $HOME/tmp

7. [Answer the prompts and give it a password]

8. mv $HOME/* $HOME/tmp # ignore error about copying same directory

9. Un-mount $HOME/tmp

10. fusermount -u $HOME/tmp

At this point, you have all of your file encrypted at ${HOME}2/encrypt, and no files in your home directory.

11. After you log in, mount your directory using:

12. encfs ${HOME}2/encrypt $HOME -- -o nonempty,use_ino,allow_root

The options tell EncFS to place the decrypted home directory over the regular home directory.

13. Now log out and log back in. The decrypted home directory will be visible.

14. To un-mount, you will need to log out, log in as a different user, and use Sudo to un-mount the directory.

§ Encrypt a CD-ROM-Rather than burning a regular directory to a CD-ROM, you can burn an encrypted directory. The CD-ROM will appear to have garbage file names and random data in each file. However, you can then use encfs to mount it and access the decrypted data. If you are worried about someone stealing a CD-ROM that contains sensitive information, then this is an excellent solution. The CD-ROM is as secure as your password.

§ Encrypt a USB drive-You can specify a USB thumb drive for storing the encrypted files. This is similar to the CD-ROM solution, except you can read and write to the drive.

§ Encrypt a networked file system-NFS does not offer encryption, and SMB provides few security options. Rather than exporting unprotected files, you can export the encrypted file system. Network clients can mount the NFS (or SMB) partition containing the encrypted files, and then use encfs to access the decrypted files. This way, the file system's data is encrypted as it is passed along the network. (See Chapter 6 for configuring NFS and Samba.)

Knowing EncFS Limitations

EncFS is very flexible and is supported by a variety of file systems. You can download EncFS for Windows and other versions of Linux-see http://arg0.net/encfs/ for details. However, there are some limitations with this type of encrypted file system.

§ Supported platforms-EncFS is not supported on every operating system. BSD and Mac OS X are just two examples. If you need EncFS on these platforms, consider running a supported platform using a virtual machine like Qemu (see Chapter 6) and exporting the decrypted directory to the host operating system.

§ EncFS does not un-mount when you log out-Unmounting needs to be a conscious effort. Consider placing fusermount -u -z decoded/ in your $HOME/.bash_logout script. This will un-mount the directory after all processes end.

§ EncFS does not protect the decrypted directory-If you successfully run encfs and can access the decrypted files, then anyone on the system can access the decrypted files.

§ EncFS is not for automated systems-Some people have tried to configure EncFS to mount automatically, when the system boots (or when a user logs in). Doing this defeats the security. For example, if the encrypted file system is mounted when the system powers up, then a thief who steals the system only needs to power up the computer in order to access the sensitive files.

Managing Logs and Caches

Backups are essential for security, but not everything needs to be backed up. For example, cache files and really old logs probably do not need to be archived. Some files, like logs, also need to be maintained. Without the occasional pruning, logs may expand to fill all available disk space.

Besides consuming unnecessary disk space and slowing down backup systems, temporary files and cache files can pose a security risk. Cache files allow someone to look at a history of your activities and possibly recover sensitive information. While deleted files may be recoverable with forensic tools, this is usually more effort than a simple attacker can manage. Deleting an unnecessary cache file is better than leaving it around.

Clearing Temporary Files

Many applications need to use temporary files for storage. Although some programs write to the current directory, others write to /tmp or /var/tmp. Without periodic maintenance, these directories can become cluttered. In addition, because /tmp is usually part of the / partition, temporary files can consume all available space on the root partition.

By default, Ubuntu flushes most files from /tmp during boot. This happens during the initial file mounting: init calls /etc/rcS.d/S35mountall.sh, which calls /etc/init.d/boot- clean.sh, which deletes files from /tmp. However, nothing cleans files from /var/tmp. Also, the bootclean.sh script only runs during boot up, not during shutdown. To clean both temporary directories during shutdown and boot up, I use my own init script called cleantmp (see Listing 10-4). This script deletes all temporary files except root-owned system files.

Listing 10-4: /etc/init.d/cleantmp for Cleaning Temporary Directories



. /lib/lsb/init-functions



# EXCEPT list for system files

for i in /tmp /var/tmp ; do

EXCEPT="! ( -path $i )

! ( -path $i/lost+found -uid 0 )

! ( -path $i/quota.user -uid 0 )

! ( -path $i/aquota.user -uid 0 )

! ( -path $i/quota.group -uid 0 )

! ( -path $i/aquota.group -uid 0 )

! ( -path $i/.journal -uid 0 )

! ( -path $i/.clean -uid 0 )

! ( -path '$i/...security*' -uid 0 )"

# Find everything in the directory (except the exceptions)

find $i -maxdepth 1 $EXCEPT -exec rm -rf "{}" \;



case "$1" in


log_begin_msg "Cleaning tmp directories..."




log_success_msg "Usage: /etc/init.d/cleantmp" \


exit 1


exit 0

To make the cleantmp script run during boot and shutdown, I added it to /etc/rcS.d/ and /etc/rc0.d/.

sudo chmod a+rx /etc/init.d/cleantmp

cd /etc/rcS.d

sudo ln -s ../init.d/cleantmp S36cleantmp # for startup

cd /etc/rc0.d

sudo ln -s ../init.d/cleantmp K78cleantmp # for shutdown

Erasing Web Caches

Web browsers store lots of cache files. The default setting for Firefox is 50 MB per profile per user! (See Chapter 5 for managing profiles and configuring browsers.) Most of the time, these cache files do not need to be kept by backup systems. For a list of the Firefox cache files, use:

sudo ls -d /home/*/.mozilla/firefox/*/Cache

Most of the time, you can safely blow away (or not back up) these files. However, you should leave the empty cache directory so that Mozilla won't need to re-create it next time you start the browser.


If you installed Konquerer (part of the Kubuntu desktop), then look for user-owned cache files in /var/tmp/kdecache*/.

Firefox stores a history of every URL accessed. This can also become a very big file and is usually not critical to system operation. All history files can be found using:

sudo ls -d /home/*/.mozilla/firefox/*/history.dat

If you want to remove the cache files during boot, you can add them to find command in the /etc/init.d/cleantmp script (see Listing 10-4) by changing the for-loop to:

for i in /tmp /var/tmp /home/*/.mozilla/firefox/*/Cache ; do

You may also want to add a line to zero-out history files. For example:

for i in /home/*/.mozilla/firefox/*/history.dat ; do cat /dev/zero > $i ; done

Cleaning APT Cache

The APT command can be another source of large, unnecessary files. For example, if you install some software and then remove it, the installation files may still be on the system. By default, APT does not automatically remove these files. However, the command sudo apt-get autoclean will remove these residues.

You can also configure APT to periodically remove old files by editing: /etc/apt/apt. conf.d/10periodic. For example, you can tell APT to periodically remove old files by adding different command directives:

§ Set the auto-clean interval to once a week (the interval is specified in days).

§ APT::Periodic::AutocleanInterval "7";

§ Tell APT to remove cache packages older than seven days.

§ APT::Periodic::MaxAge "7";

§ If you disabled the periodic Synaptic update check (or installed the minimal Ubuntu server and don't have Synaptic installed), then you can enable a weekly (seven days) check for new packages:

§ APT::Periodic::Update-Package-Lists "7";

These changes are processed by anacron in /etc/cron.daily/apt. (See Chapter 7 for configuring anacron.)

Rotating Logs

There are many different system log files. Some are rotated daily, others are rotated weekly, and some are never rotated. If you don't manage your log files, then they can grow indefinitely. And since most log files are stored in /var/log, filling the disk can lead to system failures.

The basic command for rotating a log file is savelog. This will rename the log file. So, savelog test.log will move test.log to test.log.0 (or test.log.0.gz if it is big enough to compress), and any old test.log.0 will become test.log.1, test.log.1 becomes test.log.2, and so on. The default settings keep seven levels of backups (test.log.0 to test.log.7). Anything older is deleted. You can change the number of rotated copies with the -c parameter. For example, savelog -c 20 test.log will keep 20 rotations.

If you want to create your own log file then you should add it to a rotation system. The main rotation system is logrotate, and is called by anacron (see /etc/cron.daily/logrotate). This command consults a directory of rotation command scripts: /etc/logrotate.d/.In this directory are a bunch of files that define log files and rotation schedules. For example, /etc/logrotate.d/acpid looks like:

/var/log/acpid {


rotate 4




/etc/init.d/acpid restart >/dev/null



This specifies four log rotations of /var/log/acpid on a weekly basis. After rotating the log, the service /etc/init.d/acpid is restarted. Everything between the postrotate and end- script lines form a script that will be executed. For some processes, you may need to use prerotate … endscript to stop a process before rotating the logs.

Some log files don't always need to be rotated. In the logrotate configuration file you can add a size parameter. For example, size 10M will only rotate the log if it is bigger than 10 MB. You can also use other sizes such as 50k or 1G. The single letters k, M, and G are recognized as kilobytes, megabytes, and gigabytes. If no size modifier is specified, bytes are assumed.

If you run a high-volume service, like a web server that gets millions of hits per day, then you will probably want to rotate logs more often than daily or weekly. I'd suggest putting the logrotate command in your crontab (see Chapter 7) so it runs more often. For example, to rotate logs hourly (at 1 minute after the hour):

1 * * * * logrotate /etc/logrotate.d/mylog

Alternately, you can use savelog:

1 * * * * savelog -c 48 /var/log/mylogfile # save last 48 hours as 0..47

If you notice a log that is growing too large, or never being rotated, then look for a log configuration files in /etc/logrotate.d/. If it does not exist, consider adding it. If it does exist, then maybe it needs to be rotated more often.


The default Dapper Drake installation is a good start for a secure system. Although it does reduce risks from remote attackers, it is vulnerable to local data exposure. Restricting root access, encrypting files, and removing unnecessary files all provide additional security. Tools such as Sudo, GPG, and EncFS help protect files and access, while savelog and logrotate manage files that would otherwise grow without bounds.