个人工具

UbuntuHelp:EncryptedFilesystemHowto

来自Ubuntu中文

跳转至: 导航, 搜索

<<Include(Tag/ContentCleanup)>>

  1. title Encrypted filesystem with dm-crypt
{i} Please refer to EncryptedFilesystems for further documentation.

IconsPage?action=AttachFile&do=get&target=PicDocs.png

    These procedures could damage the information on your computer. Make backups first.

Encrypted file-systems

People store all kind of sensitive information on their computers, but much more sensitive information may be stored without your even realizing it in the form of cached web pages, cookies - even browser settings. Clicking "remember me" on a webpage is a convenient browser feature, but imagine a thief steals your computer and now has access to your ebay account, paypal, and everything else connected to your email address - possibly even your bank account information. This problem is magnified when using a laptop, since they are so very easy to steal or even just lose. Encryption can address this issue. Keep in mind no solution is perfect and a determined intruder might still be able to find a way in. Using encryption, however, greatly reduces the chance of this happening (because if you don't use encryption there is a chance your data is available to anyone who wants it - it's a matter of fact). Keep in mind that encrypting your data WILL lock it up in a reasonably secure vault. This means if you forget your passphrase you WILL be locked out. Likewise, if you write down your passphrase and stick it on a post-it note on your monitor you might as well not use encryption at all. Encryption is a method, not a black box solution to protecting your privacy.

A Bit of Theory

Please remember that any numbers used here are made up on the fly. They are meant as an exercise of the mind and to give a feeling for the numbers you are dealing with when using encryption. Do your own math based on your own data, habits and requirements if you need to rely on encryption: It is your data you are protecting and your problem should it get out into the open. From what I know at this point in time the encryption routines employed by the Linux kernel are secure and trustworthy. I have not examined them in depth, so do not blame me if they are not. But this does not mean that your data will stay secure for all times once encrypted: If somebody discovers a flaw in the algorithm used, then your data might end up in the open. If somebody discovers a flaw in the implementation, then your data might end up in the open. If somebody comes up with a breakthrough in technology and/or math, then your data might end up in the open. If you are stupid and lose your keys, then your data will be lost unless somebody finds a flaw in the algorithm or implementation of the crypto engine or someone makes a breakthrough in technology or math. You have been warned.

How does Linux encrypt my data?

Traditionally in Linux a beefed-up loopback device was used to mount a file. This loopback device then did de-/encrypt the data passing through to it. There were several different and incompatible versions of these loopback encryption engines, most supporting only one crypto algorithm. With the Linux 2.6 kernel the cryptoloop system was deprecated and might get dropped from the mainline kernels altogether at some point in the 2.6 development cycle. Its functionality is incorporated into the DeviceMapper, a generic framework used to map one blockdevice into another. Apart from encryption this DeviceMapper is the foundation of LVM, software RAIDs and offers additional features like doing snapshots of filesystems.

So how does DeviceMapper work?

The DeviceMapper is a filter, processing data passed in from a virtual blockdevice it provides, before passing it on to another blockdevice. When used to encrypt data the DeviceMapper is used to create a new blockdevice in /dev/mapper/. This virtual device can be used like any other blockdevice you have on your system (/dev/hdaX, etc). All data passed to this device is encrypted by the DeviceMapper (or better the dm-crypt module of it) using a symmetric encryption algorithm like AES. The encrypted data is then written to another blockdevice that does actually store the data.

So I can not use a file to hold my encrypted data? You keep referring to blockdevices...

You need a blockdevice for the DeviceMapper. Nobody stops you turning a file into one by using the (unencrypted) loopback facility. The loopback system will stay in the mainline kernel, even though the encryption functionality that was used to be build into it is removed.

OK, which encryption engines does the DeviceMapper support?

You can choose all those provided by the crypto-modules of your kernel. The Ubuntu-Kernels come with the full set, including Twofish, AES, DES and others.

Which of those engines should I choose?

I recommend AES. It is reasonably fast and believed to be secure. Avoid DES, it is considered too weak to offer decent protection nowadays.

How many bits should the key used by the algorithm have?

This depends on your needs for security: A longer key is more secure, but it takes longer to de-/encrypt data using it. With a good crypto algorithm a attacker must use brute force: He has to generate each key and then has to try to unlock the encrypted data with it. So the number of possible keys directly gives the average time needed to break the encryption. So let us play a bit with some numbers: A 256bit key gives about 1077^ (a 1 followed by 77 zeros) different keys while a 128bit key has "only" about 10^38^ (a 1 followed by 38 zeros). At the moment a typical PC can generate and test about 3*10^5^ (3 followed by 5 zeros) keys per second. So breaking a 128bit key would take a single average PC about 10^25 years (1 followed by 25 zeros), which is longer than the universe exists. That should be secure enough for most users. To understand how secure 128 bit keys are, you may read this analogy by Jon Callas: “Imagine a computer that is the size of a grain of sand that can test keys against some encrypted data. Also imagine that it can test a key in the amount of time it takes light to cross it. Then consider a cluster of these computers, so many that if you covered the earth with them, they would cover the whole planet to the height of 1 meter. The cluster of computers would crack a 128-bit key on average in 1,000 years.” Even if you don't believe that the NSA has another planet devoted to key cracking, you still may want to use a longer key. If a weakness in your chosen crypto-module is found, it may limit the keyspace that needs to be tested, and you will then have an effectivly shorter key. Using a 256 bit key will keep your data secure much longer if that should happen.

I decided on the key size now. How do I protect the key?

Protecting the key is vital: With it the attacker does have instant access to the data. So what can be done to protect this crucial string of bits?

  1. You can use a "one-time key" that is changed at each startup. These keys are usually created by reading /dev/Xrandom during dm-crypt setup. No key is stored this way and no passphrase needed, but this method can only be used on filesystems that can be formated at each reboot (like swap or maybe /tmp if you do not want to retain the information stored there). Using suspend to disk will be impossible with one-time keys used on the swap device.
  2. You can store the key on removable storage. That way it is only accessible when needed. Your data is in the open when the storage is stolen or copied.
  3. You can generate a hash value (== a pseudorandom number) from a keyphrase and use that as a key. The key is not stored on media that way at all, but you can not change the passphrase (a different key is generated then). All people with access to the encrypted data need to know this passphrase. This is a bit impractical in a multi user environment.
  4. You can encrypt the key. The encrypted key is stored on the computer with the encrypted device. You can change the passphrase by reencrypting the key with a different one and you can have several copies of the same key encrypted for several people.
  5. You can encrypt the key and store it on a removeable media.
  6. You can use smartcards, etc. This is the most secure option.

Unfortunately I do not have a smartcard reader, so I can not cover option 6.

I want to use a passphrase. How long does it need to be?

If you decide to use an hash of a passphrase or want to have an encrypted key that is unlocked by a passphrase then it is crucial to pick a long and strong one. As we have seen earlier it is close to impossible to guess the key itself, but an attacker does not have to do that if he can guess the passphrase. Let us do some more exercises of the mind: Assuming a passphrase can be made up out of letters (both cases), numbers and a limited number of punctuation. This gives about 64 different characters that can be used. 64 different characters can be encoded in 6bits. So if you were using a single letter passphrase then a attacker would need to try a maximum of 64 times to get your key. If your passphrase consists of several random letters, then each one makes the efford 64 times harder! Using words instead of a random sequence of letters makes it significantly easier for an attacker, so do not do that unless you make the passphrase much longer (I recommend at least doubling the length!). If you have a 128bit key and want a passphrase that is as strong you need at least 22 random characters in the passphrase. For a 256bit key you need twice the length: 42 characters. A really strong random 8-letter password gives a maximum of 240^ or 10^12^ (a 1 followed by 12 zeros) different passpharses (standard not-so-random-passwords are much weaker!), which is enough to protect a 40bit key. A single fast PC should be able to try those 10^12^ different passphrases in about 42days (assuming 300000 tries/s). Compare that to the 10^25 years it takes to break a 128bit key that might be protected by this passphrase.

Examples

{i} This article is somewhat out of date. As of Ubuntu 8.10 Intrepid, full disk encryption is supported through Luks. See EncryptedFilesystemOnIntrepid for more.

Using dm-crypt

Ubuntu includes the latest encryption widget right in the default install, but there is no easy to use interface (eg. Mandriva's 'drakloop' tool) to this widget included in the default install. Before we can use ubuntu's encryption capabilities we must install this interface.

  1. Install cryptsetup. This is a small download, it goes quickly.
        sudo apt-get install cryptsetup
  2. Then we load some needed modules. We need the ``dm_mod``, ``dm_crypt`` and a ``crypto-Module``. There are a variety included in the standard ubuntu-Kernel, the most optimal is likely chosen automatically and already installed.
If you would like to verify (or if this tutorial hasn't worked and you want to double-check things) enter the following commands at a terminal:
    /sbin/modinfo /lib/modules/`uname -r`/kernel/crypto/*           |grep description
    /sbin/modinfo /lib/modules/`uname -r`/kernel/arch/i386/crypto/* |grep description

This will list the modules available on your machine. The aes module is actually an alias for whatever is installed on your machine. Look for something with aes in it - aes, aes-i586, aes-i386, and so forth. So long as one of these is installed you should be fine.

To ensure that these modules are loaded when your computer restarts add them to /etc/modules:
    sudo -i  (to make yourself root)
    echo aes >> /etc/modules
    echo dm_mod   >> /etc/modules
    echo dm_crypt >> /etc/modules
  1. Choose the partition where you want to store the encrypted data (in this example we'll use the hard drive partition /dev/hda7) and create the cryptographic device mapper. This device is like a filter connected to the partition which automatically and transparently decrypts and encrypts the data as needed.
        sudo cryptsetup -y create crypt /dev/hda7
  2. Ensure that the partition (/dev/hda7 in our example) is NOT ALREADY MOUNTED. Otherwise, you will get a cryptic and unhelpful error message. If the partition is already mounted, unmount it with the 'sudo umount' command.
  3. Modify the /etc/crypttab and the /etc/fstab file so our crypt-device is restarted and mounted (to /crypt in our example) at boot-time. To do this we write the following lines to the files:
        sudo -i (do this as root) 
        echo "crypt /dev/hda7 none none" >> /etc/crypttab
        echo "/dev/mapper/crypt /crypt reiserfs defaults 0 1" >> /etc/fstab
  4. Instead of directly mounting /dev/hda7 when your computer restarts, now it will first restart the encryption "filter." This means every time you restart your computer you will be required to enter your passphrase before proceeding onto a desktop login. There are other options you can enter into the /etc/fstab file which will allow you to mount and unmount your encrypted data at any time (just as you are probably used to doing with CDs and USB drives) but for now we will focus on using the partition as one might use it to encrypt /home (which we will cover more in depth later in this howto)
  5. Now let's create a filesystem on the mapped device:
        sudo mkfs.reiserfs /dev/mapper/crypt
And you can mount the new (encrypted) drive by entering:
    sudo mount /crypt
If you get an error message that it cannot be mounted, make sure you have the target folder created (in this example it would be the folder /crypt)
    sudo mkdir /crypt
    sudo mount /crypt

It should now work. You can, of course, use any target folder you like. Which brings us to the next step: protecting your privacy via encryption of your home space.

So How Do I Encrypt My Home Directory?

People often ask about how to encrypt their /home directories. This is a good precaution, but not terribly meaningful by itself. For example, if you use kde you will find all sorts of cached webpage information in the /var folder! File system names, user information - all sorts of clues get stored in various other folders on your system. Many experienced admins take this to the next level and encrypt their entire linux installation, leaving only a small /boot partition available to anyone without the passphrase. While this is certainly a valid method, it is also much more complex and not at all easy to do at this point without purchasing non-free (and therefore unverifiable) security products such as drivecrypt or bestcrypt. A very good compromise is to encrypt all the folders that are likely to contain data as opposed to system files. These include /tmp, /home, /var, /temp (some systems have both) and the often overlooked /swap partition. On many systems this will also include /root, since that is the root user's desktop and is not stored in /home. Problem is if we lock this away and need to reboot the system without mounting the encrypted volume, we may find a system that doesn't work at all. Fortunately there are ways to overcome this, which we will (again) cover later. So, how to encrypt all this stuff without having to enter five passphrases every time we restart? Some howtos suggest using one "master" partition (usually /home) that contains "key files" which are used to successively unlock the other partitions. There are a couple of problems with this method: first, if one of those files (usually filled with random gibberish so as to make them "unguessable") is damaged it can render the whole system useless until a restore operation is performed (and how often do YOU backup your system?) The other problem is it isn't really "secure" at all since any time your /home partition is mounted the "keys" to all those other partitions are available to anyone who can get access to your computer (even remotely). This is really only slightly different than using those post-its we mentioned earlier. A better method (although a bit harder to follow) is to stick everything in one partition and mount that. But if we try to use a partition like /encrypted then we will find nothing works, since all those symbolic links to places like /usr/lib are broken. The folder for X11, for example, contains dozens of relative links that will break if we try to just move the /usr partition after the system has been built. So, we move everything to the one partition that cannot be easily moved: the /usr partition. Then we link everything we moved back to the root folder. If this all sounds complicated don't sweat it, there's a script available that will make it relatively easy. All we need to do is partition the system properly and follow the steps outlined above, reboot and run the script, then kick back with our newly protected system.

Partitioning the System

In order to build a properly protected system (the easy way) we need three partitions: a root, or / partition where everything else lives, a swap partition (encrypted), and a partition for our /home (which will actually be /usr/home). This means finding (or creating) three partitions during or after the installation of ubuntu. If you are putting ubuntu on its own disk this will be relatively easy. If you're one of those undecided souls who cannot commit to making ubuntu your only desktop, this part may not be quite as easy. At any rate that comes under the heading "installation" and is the subject of another howto.

Here is an example of how you would partition the system in order to use the easy-does-it script:
    partition mount point fs type
    /dev/hda1      /       reiserfs 
    /dev/hda2      /zzz    ext2
    /dev/hda3      swap    swap

Note the partition called /zzz. This is important! The script will look for this later and convert it to /usr. Why don't we make it /usr now? Because we want the system to be bootable even without the encrypted partition mounted. We will create the new /usr space, then swap it out from under the system like a three card monty dealer. Assuming you now have your partitions created, let's setup the encryption filters and launch the script. First, the encrypted swap. This is incredibly easy (and a good example of why you should use the device mapper for encryption in ubuntu and stop using the old loopback system). Enter the following commands at your terminal. If there is an error running cryptsetup, see the note below.

    sudo swapoff (to unmount the drive)
    sudo cryptsetup -d /dev/urandom create cryptoswap /dev/hda3
    sudo mkswap /dev/mapper/cryptoswap -L accessisdenied -v1

Keep in mind /dev/hda3 is only used here because it suits our example installation. Use whatever partition you set aside for swap during the installation we just covered. The above line tells our system to use the linux random number generator /dev/urandom to create a random key for swap when we reboot. Now, like any digital system this isn't really going to be completely random, but it's close enough (we hope) and avoids having to enter an extra passphrase every time we reboot. There are other methods (like using /dev/video0 if you have a tuner card, or using external random number generators) but those are well outside the scope of this tutorial. Note that cryptsetup might give an error. (I don't remember the text of the error, but I think it was something like "Invalid argument" or something "not found".) Anyway, in this case cryptsetup could not do anything with /dev/hda3. It seems that it was having trouble because the swap partition had a type of Linux swap (0x82). Before issuing cryptsetup, I had to change its type to Linux (0x83) using fdisk as follows on /dev/hda's partition #3. (Caution: Messing up the following could result in loss of data on the entire physical disk. Read ahead to find out what the following means, and do research on fdisk before performing the following if you're not already familiar with fdisk. Also, consider using gparted or qtparted for a friendly GUI interface.)

   sudo fdisk /dev/hda
   t
   3
   83
   w

In my case, I needed to reboot for the changes to take effect before issuing the cryptsetup and mkswap steps as indicated above. Regarding what happened with fdisk above. (Note: This was from memory since I did this the previous night, but it should be correct.) First, I launched fdisk with the following command:

   sudo fdisk /dev/hda

Note that we run it as root, and that it operates on the entire hda drive, not an individual partition. Inside fdisk, we are at the prompt:

   Command (m for help):

At this prompt, the "m" command will provide help on the "t" and "w" commands. At this point, I could type "p" followed by Enter to examine the current partitions, and note the type of Partition #3. I typed "t" followed by Enter to change a partition's system ID, or type. Then, I entered "3" for hda3. Finally, I was prompted to enter the new partition type. From the "p" command, I could tell hda3 was type 82, and now I want it to be 83. So I typed "83" and pressed Enter. Then, I was back at the Command prompt. At this point, I could still back out of what I was doing by entering "q", which would quit and abort all changes; however, I knew what I did was correct and I felt comfortable continuing with the changes, so I entered "w" instead. This wrote my changes to the /dev/hda disk and exited. In my case, it warned me that I needed to reboot for the changes to take effect. After rebooting, I issued the cryptsetup and the mkswap commands above, and I was ready to continue with the steps below. Now that we have created our swap partition with mkswap, we will create another mapped device for the encrypted user space. This one is a bit more important and we definitely do NOT want to forget the passphrase, so we have the program ask us twice to confirm the new passphrase:

   sudo umount /zzz - (again, make sure nothing's open to /zzz)
   sudo cryptsetup -y create cryptohome /dev/hda2

DO NOT forget this passphrase (at least not until you want to!) So now we have both the "mapper" devices for our new system. All we need to do is configure it to actually use them after a reboot:

    sudo mkfs.reiserfs /dev/mapper/cryptohome - (follow the prompts)
    sudo -i
    echo 'cryptohome /dev/hda2' >> /etc/crypttab
    echo 'cryptoswap /dev/hda3 /dev/urandom swap' >> /etc/crypttab

And then to make the system mount these mapped encryption devices, we edit the file /etc/fstab. The friendly, non geeky way to do this is to open a root terminal (or sudo) and type "gedit /etc/fstab". You should see something like this:

  # /etc/fstab: static file system information.
  #
  # <file system> <mount point>   <type>  <options>       <dump>  <pass>
  proc            /proc           proc    defaults        0       0
  /dev/hda1 /         reiserfs defaults 0 1
  /dev/hda2       /zzz            ext2    defaults        0       1
  /dev/hda3       none            swap    sw              0       0

We want to edit this file so it looks like this:

  # /etc/fstab: static file system information.
  #
  # <file system> <mount point>   <type>  <options>       <dump>  <pass>
  proc            /proc           proc    defaults        0       0
  /dev/hda1 /         reiserfs defaults 0 1
  /dev/mapper/cryptohome /zzz     reiserfs defaults       0       1
  /dev/mapper/cryptoswap none     swap    sw              0       0

Note that all we did was change the "type" of our home partition to use the more advanced reiserfs, and changed the two "file system" entries to point to the mapped virtual devices instead of the ``physical`` hard drive partitions. At this point we have done nothing that should alter your system's ability to restart. So, restart your system and test it out! Don't forget you will be prompted for at least one passphrase this time.

Finishing up

Hopefully your system restarted well and you now see an encrypted /zzz partition in your root folder. Double check this by opening the folder in nautilus and noting the "free disk space" number. Does it change when you enter the /zzz folder? It should - if it doesn't recheck your /etc/fstab and /etc/crypttab files and see where you went wrong. Open Nautilus and browse to /dev/mapper and make sure you have those two mapped devices cryptohome and cryptoswap. If all is well otherwise, it's a downhill coast from here. We will be using the scripts below, but because of errors introduced by the wiki I suggest you download this script package and untar it. http://poptones.f2o.org/buildsafe-md5-ubuntu.tar.gz

  #!/bin/sh
  # Module          : buildsafe
  # Version         : 0.1
  # Author          : "Poptones"
  # Created On      : Tuesday, September 28 2004
  #
  # This will build an encrypted userland file system from
  # an encrypted partition called /zzz.

 if [ `grep 'zzz' /etc/mtab -c` -gt 0 ]; then

 # NOTE: there is some sort of bug in the wiki that is causing a ? to appear in the above line
 # and I cannot get it to go away. This script will not work until you remove it!

  #if we have already run this script don't do this part again!
  if [ ! -d /usr/var ]; then

  #NOTE AGAIN; see above comment. There is supposed to be NO ? in the above line!
  
    echo 'editing /etc/fstab to mount /zzz at /usr'
    cp /etc/fstab /etc/fstab.zzz
    sed 's/zzz/usr/g' /etc/fstab.zzz > /etc/fstab

    echo 'moving /var partition to /usr/var...'
    cp --preserve=all -r /var /usr
    echo -n 'done'

    echo 'moving /home partition to /usr/home...'
    cp --preserve=all -r /home /usr
    echo -n 'done'

    echo 'moving /tmp partition to /usr/tmp...'
    rm -rf /usr/tmp
    cp --preserve=all -r /tmp /usr
    cd /usr/var
    rm -rf tmp
    ln -s ../tmp ./tmp
    cd /
    echo -n 'done'
    echo 'now building new /usr partition... relinking...'

    rm -rf /var
    rm -rf /home
    rm -rf /tmp
    ln -s /usr/tmp /tmp
    ln -s /usr/var /var
    ln -s /usr/home /home

    echo -n 'done'

  fi

  echo 'now moving /usr to encrypted partition...'
  echo 'please be patient. Depending on system speed'
  echo 'this may take a few minutes to more than an hour'

  cp --preserve=all -r /usr/* /zzz

  echo 'done'
  echo 'enter *reboot* for the changes to take effect'
 else 
  echo 'mount point /zzz cannot be found. make sure you have'
  echo 'created the mount point /zzz. If you are certain it'
  echo 'exists, run this script again after mounting it.'
 fi
 #file ends here

Reboot your system one more time, pressing ESC to enter the grub menu. Select "failsafe" mode and boot into single user mode, then go to your home directory (if you are not already there) Enter "ls" to get your bearings. See the file you just saved? Now hold your breath and invoke it by typing

    ./buildsafe

It should take off almost immediately doing all sorts of scary stuff. Moving the files WILL take some time. Don't get impatient and reboot in the middle of this script our you will find yourself having to reinstall ubuntu from scratch. This script won't overwrite any partitions you didn't give it access to, but if it's not allowed to complete it WILL munge your OS, which is the reason I strongly suggest running it on a fresh installation. Did you get the reboot prompt? Type "reboot" and press enter, then log in again.

Using Your Encrypted System

Now when you open Nautilus and look at the root of your file system you should see a few slight differences. Notice how the folders /home, /var, and /tmp now have link symbols on them. You will also see the old /zzz folder left behind there. (Don't remove this, we're not done with it.) Notice how your root reports xxxx amount of free space, but when you click into /home or /var it changes. There's still a /usr partition on the other / partition, but it is mounted over or hidden when we enter the passphrase at boot. If you just press enter at boot you will still get a desktop that works, but it will be the unprotected version. So long as you don't get too wild with the upgrades while using the encrypted partition you should have no troubles going back and forth into the unencrypted desktop. Just keep in mind nothing is protected when you are using that other desktop - every image thumbnailed in every folder you click on, every website you have your system "remember," every email you fetch will remain in that unencrypted space. If you want to perform an upgrade to the system, just log into the "unprotected" desktop (ie reboot and press enter at the password prompt) and run the upgrade as normal. Then reboot again into failsafe mode (entering the passphrase when asked) and mount your encrypted userland to /zzz by entering the following:

  sudo umount /usr
  sudo mount -t reiserfs /dev/mapper/cryptohome /zzz

Now run the buildsafe script again. It will see that the system has already been migrated and all the changes will be moved into your encrypted space.

Changes in Edgy

I've just finished following this Howto in a fresh Xubuntu 6.10 installation. A couple things have changed in Edgy that affect this:

  • You will get an error message about an incompatability in libdevmapper (IIRC). To fix this, you must modprobe dm_mod. See this page. You should only need to do this once.
  • Upstart will block the password from being entered; see [1]. Simply follow the fix in that bug, and remove 'quiet splash' from the default entry in /boot/grub/grub.conf.
  • This is the thorniest: the script won't correctly get rid of /var, and therefore can't link /var to /usr/var, which means GDM won't start and you'll be stuck in a shell. I have no idea why. In any case, I was able to fix it by booting into knoppix and deleting var off the unencrypted partition, then booting into single-user ("recovery") mode and linking it while the encrypted partition was correctly mounted. Be sure to boot into single-user mode at that point. A regular boot will leave you with a broken sudo command ( the error message mentions something in /var/log/sudo ((again, IIRC)), which of course won't exist until you do the linking) meaning the only way to reboot will be to power cycle. Once I did the link, I rebooted normally and it worked.

Panaceas and black boxes

Don't forget this is NOT a perfect system. It is still vulnerable to attack by a variety of ways, the most obvious being an attack while online. If you are able to access your encrypted data then anyone else who gets into the system will be as well. If you are on dsl and you leave the system logged into your encrypted space 24/7 and you are hacked, your data is still owned and this has all been for naught. If you are doing something suspicious and you live in a place where authorities can enter your home without your knowledge, and you leave the system up and running with your encrypted userland exposed, your data is still owned. Most importantly, even if you DON'T leave the system up and running when you are not around it can still be attacked by anyone with access to the machine. The simplest method would involve nothing more difficult than replacing your initialization script that mounts the encrypted partition with a version of the script that records your keystrokes before passing them onto the cryptsetup program. For example, by altering just two lines in the file /etc/init.d/cryptdisks from this:

 echo "..."
 $CRYPTCMD create $dst $src <&1

To something like this:

 echo "..."
 echo "password"
 read PASSWD
 echo $PASSWD >> /etc/YouAreNowOwned
 $CRYPTCMD create -d /etc/YouAreNowOwned $dst $src > /dev/null

You would never realize the difference when you rebooted, and the attacker would have your passphrase in a common text file. Get the idea? If someone has physical access to your machine, it's much more difficult (if not impossible) to keep them out. Now, the folks who encrypt their entire system would say "this is why encrypting the whole OS is better." But unless they are booting from a CD there's nothing to stop someone from doing exactly what's shown above. And even if they ARE booting from a CD there are boot sector programs and other attacks that could still come into play. In short, this system will reasonably protect your privacy - keep you safe from the kid in school or the common thief who steals your system, or the spouse you don't want seeing your collection of adult materials or your love notes to another - but it will NOT protect you from a knowledgeable attacker. If you live in a place where possession of certain types of data could cost you your freedom or your life, and you are or plan to be in possession of said data, you need a comprehensive security plan that goes well beyond the scope of this howto. This point cannot be stressed enough. Now, given the above truth, there are other steps we can take to help be reasonably sure our system has not been compromised. One thing we can do is make a snapshot of all the files on our system at the time it is ``fresh`` and then periodically check it for changes. And wouldn't you know it, we have a script for that as well. The following will NOT protect us from boot sector attacks, but it will keep the system fairly safe from online attacks or even from unsophisticated physical trojan attacks (which is what most people have to be more concerned about). Below is the other script we will be using (included in the package linked above).

 #!/usr/bin/perl
 # Module: md5logger.pl
 # Source: oneguycoding.com
 # Version:     unknown (ubuntu version 1.0)
 # Created On:  Wednesday, 10 November 2004
 #
 # This module will scan the directories listed below and
 # verify them against MD5 hashes of every file it finds
 # in the file md5.log

 use File::Find;
 use Digest::MD5;

 umask 0077;

 $verbose=0;
 $check_rpm = 0;
 $update_changed = 1;

 $md5dir="/var/log";
 $md5file="$md5dir/md5.log";

 @flist=();
 find(\&findfile, '/sbin' );
 find(\&findfile, '/bin' );
 find(\&findfile, '/lib' );
 find(\&findfile, '/boot' );
 find(\&findfile, '/root' );
 find(\&findfile, '/srv' );
 find(\&findfile, '/initrd' );
 find(\&findfile, '/usr/bin' );
 find(\&findfile, '/usr/etc' );
 find(\&findfile, '/usr/games' );
 find(\&findfile, '/usr/include' );
 find(\&findfile, '/usr/kerberos' );
 find(\&findfile, '/usr/lib' );
 find(\&findfile, '/usr/libexec' );
 find(\&findfile, '/usr/local' );
 find(\&findfile, '/usr/lost+found' );
 find(\&findfile, '/usr/sbin' );
 find(\&findfile, '/usr/tmp' );
 find(\&findfile, '/usr/X11R6' );
 find(\&findfile, '/etc' );
 find(\&findfile, '/vmlinuz' );
 find(\&findfile, '/initrd.img' );

 if ( -f "$md5file" ) {
   PrivoxyWindowOpen(MD5FILE, "<$md5file") || die "Error: could not open $md5file\n";

   # load the hash
   while(<MD5FILE>) {
      chomp;
      ($md5,$file) = split(':');
      $md5list{$file} = $md5;
   }

   close(MD5FILE);
 }

 $update=0;
 $filen=$#flist+1;
 foreach $file (@flist) {

   $filen--;

   chomp;
   
   $md5 = md5($file);
   next if ( $md5 eq "" );

   printf STDOUT "%06d:$md5:$file\n", $filen if $verbose;

   next if ( $md5list{$file} eq $md5 );

   if ( $md5list{$file} == NULL ) {
      $update=1;
      print STDERR "Warning: adding $file not found in $md5file\n";
      $md5list{$file} = $md5;
      if ($check_rpm) {
         $output = `rpm -qf $file`;
         print STDERR "         rpm: $output";
      }
   }
   else {
      print STDERR "DANGER: $file has changed";
      if ($update_changed) {
         print STDERR " (updated)\n";
         $md5list{$file} = $md5;
         $update = 1;
      }
      else {
         print STDERR " (not updated)\n";
      }
      if ($check_rpm) {
         $output = `rpm -qf $file`;
         print STDERR "         rpm: $output";
      }
   }
 }

 if ($update) {
   PrivoxyWindowOpen(MD5FILE,">$md5file") || die "Error: could not write to $md5file\n";

   foreach $file (@flist) {
      print MD5FILE "$md5list{$file}:$file\n";
   }

   close(MD5FILE);
 }

 # create file list
 sub findfile {
   if ( -f $_ ) {
      push @flist, $File::Find::name;
   }
 };

 sub makeFileDir
 {
 # recursively make a directory tree
 # up to the filename in a given file path
 #
 # If passed this,
 # /home/usrdir/Netscape/Users/usrdir/Mail/Inbox
 # it creates the subdir as in,
 # mkdir -p /home/usrdir/Netscape/Users/usrdir/Mail
 #
   # first get rid of the file
   my $dir = $_[0];
   my $path= "";
   my $rv;

   @dirs=split(/\//,$dir);
   $nd=$#dirs;
   for ($i = 0; $i < $nd; $i++) {
      if ( length($dirs[$i]) != 0 ) {
         $path="$path/$dirs[$i]";
         mkdir "$path", 0755;
      }
   }
 }

 sub md5 {
   my $file=$_[0];

   if (PrivoxyWindowOpen(FILE,"<$file")) {
      binmode(FILE);
      $fmd5 = Digest::MD5->new->addfile(*FILE)->hexdigest;
      close(FILE);
   }
   else {
      print STDERR "md5: error opening source $file\n";
      return "";
   }
   return "$fmd5";
 }

 #end of script

Now run the script as root:

    sudo perl md5logger.pl

Run this while you are mounted to your encrypted volume and it will be stored (reasonably) safely in the encrypted /usr/var/log folder (I suggest you tar it soon after and keep a copy somewhere safe - maybe encrypt the container it is tarred into). You may elect to add this to your login scripts (although it does take a couple of minutes to run) or you can just run it from time to time manually. It will warn you about every added file and every changed file it finds in the list of folders we have given it - which in this case is pretty much every unencrypted folder in your baseline ubuntu system. It will even report changes to the /root desktop. While many of these changes are normal (every time you enter a command from a root terminal, for example) it will at least give us a short list of files to check (if needed). What follows from here is the older material from this wiki entry. They are left here because more information is always better than less, but keep in mind the old lofs system (ie the loopback filesystem many of you may be familiar with) is on its way out. I hope the above demonstrated that the new system is really much easier as well as more logical in use, but choice is better than no choice and some people might have legacy data (although I will tell you that I was unable to access the data I had encrypted under Mandrake with any system other than Mandrake, so if you are contemplating a move this might be the time to adopt the new standard). Also keep in mind "loopback" mounting of file systems is NOT recommended at all anymore. If you need only to encrypt a few files or folders there are other utilities that will allow this AND provide greater accessibility (for example, encrypted RAR files or even PGP containers). If you are contemplating a move from one linux to another, however - and you have your encrypted data safely backed up elsewhere (at least temporarily) the following may prove helpful to you, as it would allow you to move everything to a space where it is "in the clear" but then immediately overwrite it.

  1. Converting the data goes like this:
  • Unmount the device to be converted: sudo umount /dev/vg01/data
  • Optional: fsck the device (to be sure there are no errors to start with): sudo fsck /dev/vg01/data
  • Start up the conversion process: sudo dd if=/dev/vg01/data of=/dev/mapper/crypt bs=4k
  • Check the command twice as this will overwrite the contents of devices involved
  • Wait, this could take some time.
  • Once the conversion has finished fsck the new device again: sudo fsck /dev/mapper/crypt

This can be used in reverse to move a device from being encrypted to be plain. In addition you can use this with 2 different mappings to re-encrypt the device with either a new passphrase or with different options including cypher and key size.

Links

Using losetup

To begin we will create a file, this file will be then mounted as an ext3 and filesystem encrypted with some algorithm.

  1. The first step is to load cryptoloop:
        sudo modprobe cryptoloop && lsmod | grep cryptoloop
You should see the following output:
    cryptoloop              3584  1
    loop                   16264  2
  1. The numbers might be different but you should see both cryptoloop and loop. The next step is checking what kind of encryption algorithms we have, use the following command (notice the backticks):
     sudo modinfo /lib/modules/`uname -r`/kernel/crypto/* | grep description
On a regular Ubuntu-kernel you will see something like:
    description:    ARC4 Cipher Algorithm
    description:    Blowfish Cipher Algorithm
    description:    Cast5 Cipher Algorithm
    description:    Cast6 Cipher Algorithm
    description:    CRC32c (Castagnoli) calculations wrapper for lib/crc32c
    description:    Null Cryptographic Algorithms
    description:    Deflate Compression Algorithm for IPCOMP
    description:    DES & Triple DES EDE Cipher Algorithms
    description:    Khazad Cryptographic Algorithm
    description:    MD4 Message Digest Algorithm
    description:    Michael MIC
    description:    Serpent Cipher Algorithm
    description:    SHA1 Secure Hash Algorithm
    description:    SHA256 Secure Hash Algorithm
    description:    SHA-512 and SHA-384 Secure Hash Algorithms
    description:    Quick & dirty crypto testing module
    description:    Twofish Cipher Algorithm
  1. We will use the Twofish cypher to encrypt our 100mb file as filesystem:
        dd if=/dev/zero bs=1M count=100 of=mycryptofile
  2. We create the targetfile, a 100mb sized empty file. The next step is mounting the file with the losetup command using the twofish cypher (be careful, it will ask for a password, do not confuse this with sudo asking for a password. We just authenticated against sudo so sudo does not need a password. Use a new one, and remember it!):
        sudo losetup -e twofish /dev/loop0  mycryptofile
  3. Create the ext3 filesystem (we use ext3 because it is the best filesystem for smaller filesystem, while still having a journal):
        sudo mkfs.ext3 /dev/loop0
  4. Make the directory where you want to mount the file system:
        sudo mkdir /mnt/cryptoloop
  5. And finally mount it:
       sudo mount -t ext3 /dev/loop0 /mnt/cryptoloop/
  6. If you do not get any error-messages then you just created a mount point for all your confidential information. Copy files to /mnt/cryptoloop/ and they will be encrypted on the fly. To umount and disable it, use the following commands:
        sudo umount /mnt/cryptoloop
        sudo losetup -d /dev/loop0

How do you start using it? Repeat step 4 and 7 (*not* 5, you'll erase your data) to start using and step 8 to stop using your encrypted filesystem-in-a-file. BTW remember your password, if you forget it your data will be secure forever, for everybody. You might want to write two function and an alias for these steps in your ~/.bashrc like:

It's also possible to let mount do the work of calling losetup. All you have to do is to add a entry similar to the following into you /etc/fstab:
    echo "mycryptofile /mnt/cryptoloop ext3 noauto,encryption=twofish,user,exec 0 0" >> /etc/fstab

Now you are able to mount/unmount the cryptoloop with a simple:

   
    mount /mnt/cryptoloop
    umount /mnt/cryptoloop

TODO Too much information? Split into sections?

Comment

From AskoKauppi Tue Dec 21 14:01:50 +0000 2004
From: Asko Kauppi
Date: Tue, 21 Dec 2004 14:01:50 +0000
Subject: 
Message-ID: <20041221140150+0000@https://www.ubuntulinux.org>


First of all, a great document, thanks.

Yes, it could do with some restructuring; I'd remove the (old) losetup section altogether, or at least move it to another doc. It only distracts here.

Also, the main 'thread' sort of has two solutions in one. Compare 'crypt', 'cryptohome', they're really the same thing?   First samples go with 'crypt', then move to doing essentially the same with 'cryptohome' and 'cryptoswap'. This was not so obvious at first?  Maybe add a "if you .. goto chapter .." to highlight this?

The only real issue (and this is Ubuntu code, not this doc) was:

1. Empty lines in /etc/crypttab

Currently, the /etc/init.d/cryptdisk script expects any non-data lines to be comments ('^#'). It should allow for empty lines, too:

grep -v '^#' < $TABFILE | grep -v '^[:space:]*$' | while read dst src key opt; do

Without this, empty lines in '/etc/crypttab' will cause weird "missing parameter" output in bootup. Non-destructive, but gives the "oops, all is not as it should!" feeling. Anyhow, this should be fixed?

-ak


From FrankHansen Fri Jan 14 19:40:14 +0000 2005
From: Frank Hansen
Date: Fri, 14 Jan 2005 19:40:14 +0000
Subject: Extra Partition?
Message-ID: <20050114194014+0000@https://www.ubuntulinux.org>

Hi,

just wanted to ask if I understand this: In the "Using dm-crypt" part I have to use an extra partition? Meaning: This doesn't work with a Ubuntu installation where Ubuntu uses all the space on my harddisc? And if so: Is there a workaround (like a loopback device with dm-crypt that a normal user can use without sudo-ing)?

From TobiasHunger Sat Apr 9 23:12:07 +0100 2005
From: TobiasHunger
Date: Sat, 09 Apr 2005 23:12:07 +0100
Subject: Re: Extra Partition?
Message-ID: <[email protected]>

You can use any blockdevice with dm-crypt. This can be a partition on your disk, RAID or LVM as well as a file mounted loop-back. In fact the crypttab allows for file to be given and sets up a loopback device for it, passing that to the dm-crypt config program.

-Hu

Another very useful howto, which looks easier for encrypting your home dir: [http://www.kiskeyix.org/index.php?submit=post&story_id=1151&parent_id=0 here]

Hi Tobias,

u wrote:
"So long as you don't get too wild with the upgrades while using the encrypted partition you should have no troubles going back and forth into the unencrypted desktop. .. If you want to perform an upgrade to the system, just log into the "unprotected" desktop (ie reboot and press enter at the password prompt) and run the upgrade as normal. Then reboot again into failsafe mode (entering the passphrase when asked) and mount your encrypted userland to /zzz by entering the following:

  sudo umount /usr
  sudo mount -t reiserfs /dev/mapper/cryptohome /zzz

Now run the buildsafe script again."

I'm sure its a good solution, so if i understand it correctly: Everytime i do an upgrade, which is weekly or so, or everytime when i install a program, i would have to do this process of "rebooting (sounds like another OS i know:), mounten and running this script"?

----

Tobias,
 Great document.  Have you looked at encFS (http://arg0.net/wiki/encfs)?  It runs on FUSE (http://freshmeat.net/projects/fuse, and it runs really great for me, plus it's easier to setup that DeviceMapper.  Well, easier that DeviceMapper seems.  I've used encFS a lot, but DevicerMapper not at all.

Regards,
-jon

----

Just a suggestion,
echo 'some info' | sudo tee /etc/file/location
Is a way of echoing info without needing to 'sudo -i' or go root.
Love this guide btw. :)
Tom.