EncryptedFilesystemHowto

来自Ubuntu中文
跳到导航跳到搜索

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

This is not finished (but then isn't this the nature of the web?)
These procedures could damage the information on your computer. Make backups first.
Be careful. Read the documentation, again. You have been warned. Twice.
本文尚未最终定稿(但这不正是网络的特点吗?)
文中所描述的操作可能损坏您的计算机中储存的信息。请事先作好备份。
请您重复阅读本段文字。我在此再次提醒您,操作时务必小心谨慎。

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.

人们有意识地把各种各样的敏感信息存储在他们的计算机上,然而可能有比这多得多的敏感信息是在他们不知情的情况下,以网页快照、cookie甚或浏览器设置等形式被存储在计算机上的。某些网页提供“记住我的信息”选项,这是一个很方便的浏览器特性。但是试想一下,万一您的计算机被盗,那么窃贼就可以访问您的ebay帐户,paypal以及其它一切与您的电子邮箱地址相关的内容,其中甚至可能包括您的银行帐户信息。如果您使用的是膝上电脑,您所面临的问题可能会更严重,因为它们太容易被盗或者丢失了。

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 tool, 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 loose 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.

就我目前所了解的情况来看,Linux内核中的加密程序是安全可靠、值得信赖的。(我没有详细检查过这些程序,所以万一它们真有什么漏洞,您可不要怪我。)但这并不意味着只要对数据进行了加密,它们就一直是安全的:如果有人找到了加密算法中的缺陷,或者有人找到了加密程序中的漏洞,再或者有人在技术或者数学方面取得了突破性的进展,在上述所有情况下,您的数据都有可能会被曝光。如果您犯了把密码弄丢这样的低级错误,那么您的数据也跟着一块完蛋了,除非前面提到的三种可能性成为现实。

You have been warned.

How does Linux encrypt my data?

Linux如何对数据进行加密

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.

一直以来,在linux系统中,功能强大的环回设备被用来挂载文件。环回设备可以使用多种互不兼容的加密引擎对通过它自身的数据流进行加密和解密,这些引擎大多只支持唯一的加密算法。

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.

linux 2.6内核不再提倡通过环回设备进行加密的做法。并且,这套加密系统可能在2.6内核开发周期中的某个阶段被从主线内核中剔除。它的功能被整合到了设备映射器中(DeviceMapper)。设备映射器用于将一个块设备映射到另一个块设备。除了提供加密功能,设备映射器还为LVM、软RAID提供支持,并为系统添加了一些诸如文件系统快照之类的附加特性。

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.

当设备映射器被用于数据加密时,它会在/dev/mapper/目录下创建一个新的块设备。对于用户来说,这个虚拟设备和系统上的其它任何块设备在使用时没有区别。设备映射器(更确切地说是设备映射器的dm-crypt模块)使用对称加密算法,如AES,对输入该虚拟设备的所有数据进行加密。加密后的数据被传输到另一个块设备加以保存。

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. 我推荐AES。它速度很快,并且安全。不建议使用DES,它不能提供足够的保护。

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 PC can generate and test about 3*10^5^ (3 followed by 5 zeros) keys per second. So breaking a 128bit key will take about 10^25 years (1 followed by 25 zeros), which is longer than the universe exists. That should be secure enough for most users.

总共有大约1077^(1后面77个零)个256位密钥,相比之下128位密钥仅有10^38^(1后面38个零)个。在现有的技术条件下,PC机每秒能够生成并尝试约3*10^5^(3后面5个零)个密钥。由此可以算出,破解一个使用128位密钥的系统大约需要10^25(1后面25个零)年。这比宇宙的年龄还要长。因此,对于大多数用户来说,128位密钥已经足够了。

But according to Moore's Law the performance of computers will double each 18 month, so a PC will grow in performance by a factor of about 1000 each 15 years. So if you are a goverment and need to make sure that documents are still secret in 150 years time you must assume that a single PC will be able to generate and test 3*1033 (3 followed by 33 zeros) at that time. So a single PC can break your 128bit key less than 30 minutes, while a 256bit key would still stall an attacker for 1036 years (1 followed by 36 zeros).

但是,根据摩尔定律,计算机的性能每18个月增长一倍。由此可以推出,PC机的性能每15年增长到原来的1000倍。因此如果您在政府机构中工作,并且希望确保档案在今后150年不会被破解。那么您就应该考虑到,到那时PC机有可能以每秒3*1033^(3后面33个零)个密钥的速度进行破解。也就是说,一台PC机可以在30分钟之内找出您使用的128为密钥。而对于256位密钥这个时间则要增加到10^36(1后面36个零)年。

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?

保护好密钥至关重要:得到了它入侵者就得到了数据的访问权。

0. 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. 0. 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. 0. 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. 0. 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. 0. You can encrypt the key and store it on a removeable media. 0. You can use smartcards, etc. This is the most secure option.

0. 您可以使用“一次性密钥”,这种密钥在每次系统启动时都不一样。这类密钥一般是在使用设备映射器进行加密的过程中通过读取/dev/Xrandom设备的方法建立起来的。它们不会被存储在计算机中,因而也不需要为它们设置密码。但是这种方法只能用于那些每次重启时可以被格式化而不会影响系统正常使用的文件系统(例如swap或者/tmp目录,如果您不希望保留存储在该目录下的信息的话)。此外,在swap设备上使用一次性密钥时,对磁盘进行挂起操作是不可能的。 0. 您可以将密钥存放在可移动存储设备上。

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 or 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 1025 years it takes to break a 128bit key that might be protected by this passphrase.

Examples

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.

0. Install cryptsetup. This is a small download, it goes quickly

sudo apt-get install cryptsetup

0. 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 su -  (to make yourself root)
echo aes >> /etc/modules
echo dm_mod   >> /etc/modules
echo dm_crypt >> /etc/modules

0. 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

0. 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.

0. 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 su - (do this as root) 
echo "crypt /dev/hda7" >> /etc/crypttab
echo "/dev/mapper/crypt /crypt reiserfs defaults 0 1" >> /etc/fstab

0. 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)

0. 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 these commands at your terminal:

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.

Now 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 su -
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.

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.

0. 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.首先,我们先创建一个文件,这个文件稍后将会以EXT3的文件系统格式挂载以及以一定算法加密。

0. The first step is to load cryptoloop:第一步是加载cryptoloop:

sudo modprobe cryptoloop && lsmod | grep cryptoloop

You should see the following output:你将看到类似下面的输出结果:

cryptoloop              3584  1
loop                   16264  2

0. 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):cryptoloop和loop的数字可能会有不同,但是你应该能够看到cryptoloop和loop。下一步就是用下面的命令检查我们拥有的加密算法种类(注意不要丢了'uname -r'的单引号)

sudo modinfo /lib/modules/`uname -r`/kernel/crypto/* | grep description

On a regular Ubuntu-kernel you will see something like:在常规的UBUNTU内核中,你会看到类似下面的输出结果:

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

0. We will use the Twofish cypher to encrypt our 100mb file as filesystem:我们将用Twofish cypher以文件系统的形式来加密我们的100mb的文件:

dd if=/dev/zero bs=1M count=100 of=mycryptofile

0. 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!):我们先创建一个目标文件——一个100mb的空文件,接着用losetup命令和twofish cypher来挂载文件(注意,期间会要求你输入密码,不要将该密码和sudo时输入的密码混淆了。We just authenticated against sudo so sudo does not need a password. 创建一个新密码,然后记住它!)


sudo losetup -e twofish /dev/loop0  mycryptofile

0. Create the ext3 filesystem (we use ext3 because it is the best filesystem for smaller filesystem, while still having a journal):创建一个ext3的文件系统(我们之所以使用EXT3的文件系统,是因为它是轻量级日志型文件系统中最好的选择。

sudo mkfs.ext3 /dev/loop0

0. Make the directory where you want to mount the file system:创建文件系统的挂载点

sudo mkdir /mnt/cryptoloop

0. And finally mount it:最后,挂载文件系统

sudo mount -t ext3 /dev/loop0 /mnt/cryptoloop/

0. 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:如果系统没有提示任何错误的话,那么你刚才创建的文件系统挂载点就创建好了。当你拷贝文件到/mnt/cryptoloop/的时候,文件就被加密了。下面的两条命令用于取消挂载和卸载:


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.那么如何开始使用它呢?重复步骤4和7(*不要重复*步骤5,否则你会擦除你的数据)来使用,按照步骤8来停止使用加密的文件系统。请务必记住你的密码,如果你忘记了密码,意味着你的数据将被永远被保护,对于任何人都如此。

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:当然你也可以让mount调用lostup来达到相同的效果。你只需要将下面的入口点加入到你的/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:现在,你已经可以用下面的命令简单地挂载/卸载cryptoloop了。

   
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 '<sup>#' < $TABFILE | grep -v '</sup>[[UbuntuHelp: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