- OK, which encryption engines does the DeviceMapper support?
- RUN THESE COMMANDS IN THE CHROOT
- How many bits should the key used by the algorithm have?
- Enable Health Monitoring
- Installing into the encrypted partition
- Encrypted ZFS Ubuntu Installation
- ZFS on LUKS Installation
- Boot LiveCD
- Configure Storage
- SSD 256GB (/dev/sda)
- HDD(s) (/dev/sd?)
- Install Ubuntu
- Install ZFS Packages
- Create LUKS Containers
- Open LUKS Containers
- Add Derived LUKS Keys
- Create File Systems
- Create /boot File System
- Create ZFS Pools
- Create ZFS Datasets
- Create ZFS Volume for SWAP
- Prepare ZFS Mountpoints
- Mount Ubuntu Installation
- Copy Ubuntu Installation
- CHROOT Into Target ZFS Environment
- Setup ZFS in CHROOT Environment
- Create FSTAB Entries
- Create `/etc/crypttab` Entries
- Create `/etc/initramfs-tools/conf.d/cryptroot` Entries
- Add `boot=zfs` to GRUB
- Update the Initramfs Boot Images
- Exit the CHROOT ZFS Environment
- Завершение
- Changes in Edgy
- So How Do I Encrypt My Home Directory?
- Which of those engines should I choose?
- Prerequisites
- Подготовка
- Диск
- Утилиты и модули
- Форматирование
- Finishing up
- Troubleshooting
- Caveats
- ZFS Integrity When Using LUKS
- Hibernation
- UEFI Booting
- Mount your crypt
- Using dm-crypt
- Using losetup
- Distro Release Upgrade
- Encryption with Cryptoloop
- Prearrangement
- Setting up the harddisk
- Installing Ubuntu
- Setting up the OS loader
- EXIT Chroot
- Creative Commons License
- I want to use a passphrase. How long does it need to be?
- I decided on the key size now. How do I protect the key?
- A Bit of Theory
- New installations of Ubuntu 12. 10 and later
- How to set up a fully encrypted disk with Ubuntu
- Encrypted file-systems
- Перенос системы
- Копирование
- Ядро новой системы
- GRUB
- FSTAB
- Partitioning the System
- How does Linux encrypt my data?
- Using Your Encrypted System
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.
RUN THESE COMMANDS IN THE CHROOT
apt-get install ubuntu-desktop lvm2 cryptsetup linux-generic grub2
# Add and configure your user
useradd your_user
passwd your_user
usermod usermod -a -G admin,users
Configure the chroot. You will need to edit /etc/fstab
, /etc/crypttab
In /etc/crypttab
define your crypt
crypt /dev/sda1 none luks
In /etc/fstab
make sure you define your partitions, swap, etc
/dev/mapper/crypt_root / ext4 defaults,errors=remount-ro 0 1
MAKE SURE YOUR FSTAB IS COMPLETE , including swap, proc, home (if you use a separate home, tmpfs, etc. Use the live desktop cd as a template if needed.
Exit the chroot
exit
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:
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.
Enable Health Monitoring
Install and configure a cron entry for the excellent zfs-health utility from calomel.org-zfs-health. Copy/create in /usr/local/bin/zfs_health.sh or wherever suited. This provides email notifications of missed scrubs, file system utilization > 80% and other health checks.
Setup zfs-health of the ZFS pools via cron. An example created in /etc/cron.d/zfs-health:
PATH="/usr/bin:/bin:/usr/sbin:/sbin" 0 14 * * 0-7 root /usr/local/bin/zfs_health.sh
Installing into the encrypted partition
I have not done this manually from an Ubuntu live CD and honestly I am not sure it will work, sort of depends on how much you already know, and how much I forget. This is going to be a long post, so I may not cover each and every detail ;).
You can try running the graphical installer and try to use /dev/mapper/root as your root ( / ) partition. You will need to unmount it first.
If that fails , you can install the long way with chroot
Installing into a chroot is fairly easy, you need to make any other partitions you are using , including /boot (you already have), swap, and if you so desire /home
You then install a base system with debootstrap, use /media/crypt_root as the chroot.
Typing all the commands for a chroot is going to be too long for an already long post, but DebootstrapChroot will walk you through how to do this step — by — step
After installing the base with debootstrap, we will chroot in and install / configure the rest.
sudo -i
#mount your boot partition in the chroot
mount /dev/sda2 /media/chroot_root/boot
#mount home also if you have a separate home
#If you do not have a separate home, skip this
mount /dev/your_home_partition
chroot /media/crypt_root
Encrypted ZFS Ubuntu Installation
You know all the goodness ZFS provides. You know all the goodness Ubuntu provides. You know all the goodness LUKS whole disk encryption provides. That is why you are here.
ZFS on LUKS Installation
Boot LiveCD
Boot to Ubuntu LiveCD, open a terminal and sudo to root. ALT-F1, enter, and search for ‘terminal’ or Windows Start Key, and search for ‘terminal’. All command references assume you are root for this process.
sudo -i
Configure Storage
Zero out the storage devices, label and partition.
SSD 256GB (/dev/sda)
dd if=/dev/zero of=/dev/sda bs=1M count=10
parted -a optimal /dev/sda mklabel msdos unit MB mkpart primary 1 513 mkpart primary 513 -1 toggle 1 boot
HDD(s) (/dev/sd?)
dd if=/dev/zero of=/dev/sd? bs=1M count=10
parted -a optimal /dev/sd? mklabel gpt unit MB mkpart vpool 1 -1
Install Ubuntu
Install Ubuntu onto the 8GB USB storage or other temporary storage volume. You can skip providing a swap partition and my also install Ubuntu in its entirety to a single / partition. Select ‘download updates during installation’ and ‘3rd party applications’ as desired.
When installation is complete be sure to select «CONTINUE TESTING«.
Install ZFS Packages
While still in the live environment install the ZFS repository and ubuntu-zfs packages. This will take some time to install and compile the DKMS ZFS modules for the running kernel.
apt-add-repository --yes ppa:zfs-native/stable apt-get update apt-get -y install ubuntu-zfs
Create LUKS Containers
If you are adventuresome, or have iterated through this process a number of times, you can open another terminal tab CTRL-SHIFT-T, sudo -i and create the LUKS containers while the ubuntu-zfs packages are installing and compiling. Otherwise wait until the previous step is completed.
cryptsetup luksFormat -c aes-xts-plain64 -s 512 -h sha512 /dev/sda2 cryptsetup luksFormat -c aes-xts-plain64 -s 512 -h sha512 /dev/sdb1 cryptsetup luksFormat -c aes-xts-plain64 -s 512 -h sha512 /dev/sdc1 cryptsetup luksFormat -c aes-xts-plain64 -s 512 -h sha512 /dev/sdd1 (repeat for each additional luks container) ...
Open LUKS Containers
cryptsetup luksOpen /dev/sda2 root_crypt cryptsetup luksOpen /dev/sdb1 vault1_crypt cryptsetup luksOpen /dev/sdc1 vault2_crypt cryptsetup luksOpen /dev/sdd1 vault3_crypt (repeat for each additional luks container) ...
Once complete, you can affirm the containers are opened with ls /dev/mapper. The LUKS container names that you provided should be listed.
Add Derived LUKS Keys
To avoid multiple passphrase prompts at boot time for unlocking all the LUKS containers, add the derived key for the root_crypt container to the other LUKS containers. This derived key will be generated from the root_crypt container in the initramfs at boot time. Obtaining the derived key from root_crypt at boot is covered in later sections. Using a derived key is relatively secure since it can only be generated after the root_crypt container has been opened with the proper passphrase.
/lib/cryptsetup/scripts/decrypt_derived root_crypt > /tmp/key
cryptsetup luksAddKey /dev/sdb1 /tmp/key cryptsetup luksAddKey /dev/sdc1 /tmp/key cryptsetup luksAddKey /dev/sdd1 /tmp/key (repeat for each additional luks container) ...
If the master key for the LUKS container root_crypt ever changes you will need to add the new derived master key to the other LUKS containers again.
!! BACKUP EACH LUKS CONTAINERS HEADER FOR PROTECTION !! While optional, this is highly recommended.
cryptsetup luksHeaderBackup /dev/sda2 --header-backup-file <pathToSave>/luks_sda2_header_backup cryptsetup luksHeaderBackup /dev/sdb1 --header-backup-file <pathToSave>/luks_sdb1_header_backup cryptsetup luksHeaderBackup /dev/sdc1 --header-backup-file <pathToSave>/luks_sdc1_header_backup cryptsetup luksHeaderBackup /dev/sdd1 --header-backup-file <pathToSave>/luks_sdd1_header_backup (repeat for each additional luks container) ...
Create File Systems
Create /boot File System
mkfs.ext4 -m 0 -L /boot -j /dev/sda1
Create ZFS Pools
root_crypt will service the / partition and vault_crypt is the ‘other’ storage pool for miscellaneous content.
!! IT IS IMPERATIVE THAT THE root POOL BE NAMED rpool !! Other naming conventions will not properly boot. (I know. I tried. It failed). Pool names for anything else are abitrary. Use ashift=12 to support the newer storage devices with 4096K sectors. Use ashift=9 for older storage devices using the smaller 512K sectors.
zpool create -O mountpoint=none -o ashift=12 rpool /dev/mapper/root_crypt zpool create -O mountpoint=none -o ashift=12 vpool raidz /dev/mapper/vault1_crypt /dev/mapper/vault2_crypt /dev/mapper/vault3_crypt
Create ZFS Datasets
I’m using compression. The lz4 compression is fast and clever. It will compress compressable content and skip uncompressable content. HDD read performance is increased and storage utilization is decreased (for compressable content). Compression MUST be set before you poplulate the dataset to assure all compressable content is compressed. You can enable compression later, but any prior content put into the dataset will remain uncompressed. The dataset names are arbitrary and can be changed to suit your purposes.
zfs create -o compression=lz4 rpool/ROOT zfs create -o compression=lz4 vpool/VAULT
For an added performance tweak, disable atime; unless of course your applications rely on the access times.
zfs set atime=off rpool/ROOT zfs set atime=off vpool/VAULT
Create ZFS Volume for SWAP
I have not dedicated a specific storage partition for SWAP. Instead create a ZFS volume that will be used for SWAP. This configuration will not support hibernation. (see caveat above). Replace -V 1024M with the sizing that is right for you. I use less swap space as the host has significant physical RAM capacity. This volume setting is courtesy of ArchLinux-ZFS-SwapVolume. The auto-snapshot=false will prevent this dataset from being included in any automated snapshots. See zfs-auto-snapshot later in the guide.
zfs create -V 1024M -b $(getconf PAGESIZE) \ -o compression=off \ -o primarycache=metadata \ -o secondarycache=none \ -o sync=always \ -o com.sun:auto-snapshot=false rpool/SWAP
Prepare ZFS Mountpoints
This will set the ZFS dataset mountpoints. They do not get listed in /etc/fstab in the traditional sense. For datasets other than rpool/ROOT you can set the mountpoint to service your environment.
zfs set mountpoint=/ rpool/ROOT zfs set mountpoint=/vault vpool/VAULT
Importantly, this step identifies the boot file system in the ZFS pool.
zpool set bootfs=rpool/ROOT rpool
Export the pools so they can be re-imported to a temporary mount point.
zpool export rpool zpool export vpool
Re-import the ZFS pools to a temporary mount point in the Ubuntu LiveCD environment. The mountpoints /mnt/zfs are arbitrary. The temporary mount mounts will become the chroot target. This target will be populated with the previously installed Ubuntu 8GB volume contents.
zpool import -d /dev/mapper -R /mnt/zfs rpool zpool import -d /dev/mapper -R /mnt/zfs vpool
Mount Ubuntu Installation
Mount the Ubuntu installation that was installed on the temporary 8GB storage volume. Replace /dev/sd? with the 8GB temporary storage label.
mkdir /mnt/raring mount /dev/sd? /mnt/raring
Copy Ubuntu Installation
Create a boot directory in the previously mounted ZFS dataset and mount the real target /dev/sd? storage partition onto it. In my case sda1.
mkdir /mnt/zfs/boot mount /dev/sda1 /mnt/zfs/boot
Copy the Ubuntu installation from the temporary storage to the ZFS datasets.
cd /mnt/raring tar cfp - . | ( cd /mnt/zfs/; tar xvfp -)
You may likely need to copy the current live environment resolv.conf into the ZFS dataset so that networking will function once you chroot into the ZFS dataset. When you chroot into the ZFS dataset and you can’t host www.google.com you’ll need to perform this step.
cp /etc/resolv.conf /mnt/zfs/etc/resolv.conf
Once the TAR create/extract is complete, un-mount the temporary Ubuntu installation to keep on hand if this process needs to be repeated.
umount /mnt/raring
CHROOT Into Target ZFS Environment
Mount the system references.
mount -o bind /proc /mnt/zfs/proc mount -o bind /dev /mnt/zfs/dev mount -o bind /dev/pts /mnt/zfs/dev/pts mount -o bind /sys /mnt/zfs/sys
Change root and pivot onto the ZFS environment which now contains a complete copy of the previous Ubuntu installation.
chroot /mnt/zfs /bin/bash --login
Setup ZFS in CHROOT Environment
Set the hostid (which doesn’t exist). Without it the ubuntu-zfs installation and compile will error. You will be prompted later to overwrite it with the maintainers package version. You may choose to do so or not.
hostid > /etc/hostid
Preapre a symbolic link to the root LUKS container. Without this symbolic link update-grub will complain that is can’t find the canonical path and error. (Replace root_crypt with your named root LUKS container).
ln -s /dev/mapper/root_crypt /dev/root_crypt
Assure that future kernel updates will succeed by always creating the symbolic link. (Replace root_crypt with your named root LUKS container).
echo 'ENV{DM_NAME}=="root_crypt", SYMLINK+="root_crypt"' > /etc/udev/rules.d/99-local.rules
Install the ubuntu-zfs packages. This will take some time to install and compile the DKMS ZFS modules for the current kernel. cryptsetup must be installed in the chroot environment has it was not installed previously. zfs-initramfs is required to put the ZFS utilities for managing ZFS file systems in the initramfs booting images. I intentionally did not install the zfs-native/grub packages.
apt-add-repository --yes ppa:zfs-native/stable apt-get update apt-get -y install ubuntu-zfs zfs-initramfs cryptsetup
Create FSTAB Entries
vi /etc/fstab
/dev/sda1 /boot auto defaults 0 0 /dev/mapper/root_crypt / zfs defaults 0 0 /dev/zvol/rpool/SWAP none swap defaults 0 0
Create `/etc/crypttab` Entries
blkid ... /dev/sda2: UUID="94581034-2545-2c1e-93bf-f89ab32b9d8e" TYPE="crypto_LUKS" ...
To allow cryptsetup to properly identify the root LUKS container during update-initramfs add this entry to /etc/crypttab. This file did not previously exist. Use the UUID you just retrieved without quotes. (You could use /dev/sd? naming conventions, but using UUID’s will assure consistent behavior). discard is added here to pass the TRIM commands to the SSD.
vi /etc/crypttab
root_crypt UUID=<uuid-/dev/sd?-root_crypt-crypto_LUKS-no-quotes> none luks,discard
Create `/etc/initramfs-tools/conf.d/cryptroot` Entries
For cryptsetup to properly identify the LUKS containers to unlock at boot time pick one of these entries; multiple or single passphrase prompts. Note that vault_crypt was not listed in /etc/crypttab. It is not necessary in that file. /etc/crypttab is largely referenced after the pivot from the initramfs to the ‘real’ root. All LUKS containers that need to be unlocked for ZFS MUST be listed in this file. Get the UUID for each crypto_LUKS container with blkid as before. The file MUST be named cryptroot as the cryptsetup routines reference that file explicitly. If named differently, cryptsetup will not identify the LUKS containers to unlock.
Single: If you want a single passphrase prompt, use this configuration. This file did not previously exist.
Get the derived master key. The root_crypt LUKS container must be open. Add the derived key to each LUKS container that you want to unlock at boot.
/lib/cryptsetup/scripts/decrypt_derived root_crypt > /tmp/key cryptsetup luksAddKey /dev/sdb1 /tmp/key cryptsetup luksAddKey /dev/sdc1 /tmp/key cryptsetup luksAddKey /dev/sdd1 /tmp/key (repeat for each additional luks container) ...
Copy the decrypt_derived shell script into the initramfs-tools so that it will be available in the initramfs boot environment.
mkdir /etc/initramfs-tools/scripts/luks cp /lib/cryptsetup/scripts/decrypt_derived /etc/initramfs-tools/scripts/luks/get.root_crypt.decrypt_derived
Adapt the get.root_crypt.decrypt_derived shell script to fetch the master key without arguments.
vi /etc/initramfs-tools/scripts/luks/get.root_crypt.decrypt_derived
Add to top of /etc/initramfs-tools/scripts/luks/get.root_crypt.decrypt_derived
CRYPT_DEVICE=root_crypt
Then replace $1 with the new variable.
:1,$s/\$1/\$CRYPT_DEVICE/gc
Write out and quit.
:wq
Create cryptroot to be referenced in the boot image.
vi /etc/initramfs-tools/conf.d/cryptroot
Note: I was unable to find a way to define key=root_crypt,keyscript=/scripts/luks/decrypt_derived for vault#_crypt and have the ‘key’ passed to the script as it does with /etc/crypttab behavior.
target=root_crypt,source=UUID=<uuid-/dev/sd?-root_crypt-crypto_LUKS--no-quotes>,key=none,rootdev,discard target=vault_crypt,source=UUID=<uuid-/dev/sd?-vault1_crypt-crypt_LUKS-no-quotes>,keyscript=/scripts/luks/get.root_crypt.decrypt_derived target=vault_crypt,source=UUID=<uuid-/dev/sd?-vault2_crypt-crypto_LUKS-no-quotes>,keyscript=/scripts/luks/get.root_crypt.decrypt_derived target=vault_crypt,source=UUID=<uuid-/dev/sd?-vault3_crypt-crypto_LUKS-no-quotes>,keyscript=/scripts/luks/get.root_crypt.decrypt_derived (repeat for each additional luks container) ...
Multiple: At boot you will be prompted for passphrases for each LUKS container.
target=root_crypt,source=UUID=<uuid-/dev/sd?-root_crypt-crypt_LUKS-no-quotes>,key=none,rootdev,discard target=vault_crypt,source=UUID=<uuid-/dev/sd?-vault1_crypt-crypto_LUKS-no-quotes>,key=none target=vault_crypt,source=UUID=<uuid-/dev/sd?-vault2_crypt-crypto_LUKS-no-quotes>,key=none target=vault_crypt,source=UUID=<uuid-/dev/sd?-vault3_crypt-crypto_LUKS-no-quotes>,key=none (repeat for each additional luks container) ...
Add `boot=zfs` to GRUB
Perhaps because I did not install the zfs-native/grub packages, you must add boot=zfs to the grub.cfg stanzas. You MUST have boot=zfs in the linux line. If it is absent Ubuntu will not boot.
vi /etc/default/grub
Add boot=zfs to the default grub configuration file.
GRUB_CMDLINE_LINUX_DEFAULT="boot=zfs quiet splash"
Until certain that everything is working — remove quiet splash.
GRUB_CMDLINE_LINUX_DEFAULT="boot=zfs"
If your Ubuntu system will not boot make sure boot=zfs is in the linux stanza line in /boot/grub/grub.cfg
Update the Initramfs Boot Images
Update the boot images which will now contain the ZFS utilities, cryptsetup, cryptroot definitions and custom decrypt_derived shell script (if you chose single passphrase prompting).
update-initramfs -c -k all update-grub grub-install /dev/sda
Check the /boot/grub/grub.cfg and make sure your menu stanzas look something like this.
menuentry 'Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-/dev/mapper/root_crypt' { recordfail load_video gfxmode $linux_gfx_mode insmod gzio insmod part_msdos insmod ext2 set root='hd0,msdos1' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 <UUID#> else search --no-floppy --fs-uuid --set=root <UUID#> fi linux /vmlinuz-3.8.0-29-generic root=ZFS=/ROOT ro boot=zfs quiet splash $vt_handoff initrd /initrd.img-3.8.0-29-generic }
Especially the linux line which MUST have root=ZFS=/ROOT and boot=zfs.
linux /vmlinuz-3.8.0-29-generic root=ZFS=/ROOT ro boot=zfs quiet splash $vt_handoff
Exit the CHROOT ZFS Environment
Exit the chroot environment and unmount the system references. Unmount in reverse order in which they were mounted.
exit umount /mnt/zfs/boot umount /mnt/zfs/sys umount /mnt/zfs/dev/pts umount /mnt/zfs/proc umount /mnt/zfs/dev
Export the ZFS pools (which will unmount /mnt/zfs).
zpool export vpool zpool export rpool
Завершение
Выход из виртуального окружения
exit
cd / umount /tmp/root/dev/ umount /tmp/root/proc/ umount /tmp/root/boot/ umount /tmp/root/
reboot
Не забыть в BIOS выбрать загрузку с диска sdb.
Ничего не загрузилось с первого раза — это нормально. Посмотрите внимательно сообщения, логи, что-то где-то пропустили.
Changes in Edgy
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.
So How Do I Encrypt My Home Directory?
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.
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.
Prerequisites
- Ubuntu 64bit operating system (ZFS will NOT run with any reliability on 32bit systems)
CPU(s) with AES capabilities (lshw to show the cpu capabilities and confirm aes). You can utilize cpus without the AES capabilities but you will incur a performance penalty. Reports are ~20% decrease in throughput.
- Adequate host RAM
- Storage with ~20% or more free space after installation and data migration
- 8GB USB flash drive (preferably USB 3.0 capable flash drive). You can substitute the flash drive for any other temporary storage device. e.g. ~8GB disk partition on target root disk that can be re-purposed, a secondary HDD/SSD, etc.
- Internet connectivity
- Ubuntu LiveCD on a bootable CD/DVD/USB device.
Подготовка
Диск
Разобьем диск следующим образом:
Имя Флаги Тип раздела Тип ФС [Метка] Размер (МБ) ---------------------------------------------------------------- sdb1 Загрузочный Основной Linux 509,97 # Загрузочный ext2 sdb2 Основной Linux 3997,49 # SWAP sdb3 Основной Linux 100002,96 # Зашифрованный корень sdb4 Основной Linux 395597,46 # Не зашифрованный раздел для файл помойки
Утилиты и модули
emerge sys-fs/cryptsetup -av
modprobe dm_crypt
Если данного модуля у вас нету, то включите его я ядре
Device Drivers ---> [*] Block devices ---> [*] Multiple devices driver support (RAID and LVM) ---> <*> Device mapper support <M> Crypt target support -*- Cryptographic API ---> <M> SHA224 and SHA256 digest algorithm <M> SHA384 and SHA512 digest algorithms
Пересобрать ядро и перезагрузить
reboot
modprobe dm_crypt
Форматирование
Создание шифрованного раздела
cryptsetup luksFormat /dev/sdb3
cryptsetup luksOpen /dev/sdb3 root
mkfs.ext2 /dev/sdb1 mkswap /dev/sdb2 mkfs.ext3 -j /dev/mapper/root
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.
#!/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
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.
Troubleshooting
If you boot into the recovery mode Ubuntu will likely not boot as boot=zfs is likely not on the linux menu stanza line. Manually add boot=zfs as an edit during grub. (Hold right-shift-key during boot to enter and edit the recovery menu).
If troubles, check for typos. I often transposed crypt as cyrpt because I was typing to haphazardly.
If you enabled splash screen for plymouth, but don’t see it and have to blindly type the passphrase, you may need to enable FRAMEBUFFER=y and change the screen geometry. See this askubuntu thread GNOME-Broken-Splash. Boot without splash until you are certain the boot process is successful.
The ZFS root pool MUST be named rpool.
boot=zfs MUST be on the linux grub.cfg menu stanza line.
root=ZFS=/ROOT MUST be on the linux grub.cfg menu stanza line. If you chose a different ZFS dataset name replace ROOT with your version.
Reboot back to the Ubuntu LiveCD, re-install the ubuntu-zfs packages, re-open the LUKS containers, re-import the ZFS pools to /mnt/zfs, chroot to the ZFS environment, adjust whatever you need to adjust, exit chroot, un-mount file systems, reboot. Rinse and repeat.
If the additional storage is not mounting automatically on booting, once boot is complete zpool import -d /dev/mapper vpool to mount the additional storage. This will ‘refresh’ the /etc/zfs/zpool.cache. df -mh to confirm the mounted pool. Then update-initramfs -c -k all to recreate the boot images which will have a reference to the most recent zpool.cache. Reboot and the additional storage pool should mount.
Caveats
ZFS Integrity When Using LUKS
Hibernation
I have not documented a mechanism to support hibernation. This configuration will support suspend. Supporting hibernation would require a seperate partition equal to or greater than physical RAM. It could be a LUKS container or LUKS container with a ZFS Volume.
UEFI Booting
This guide will need to be adjusted to support UEFI booting. Most notable would be creating an unencrypted /boot/efi 1MB partition (which will be vfat), unencrypted /boot 512MB partition and then encrypted / partition.
Mount your crypt
This assumes your crypt is called crypt
, the physical partition is /dev/sda1
, and the root partition partition in /dev/mapper is called root
, adjust accordingly to your setup.
Boot the live (Desktop) CD and install lvm2 and cryptsetup.
sudo apt-get update && sudo apt-get install lvm2 cryptsetup
Load the cryptsetup module.
sudo modprobe dm-crypt
Decrypt your file system.
sudo cryptsetup luksOpen /dev/sda1 crypt
Get the live CD to recognize (activate) your LVM.
sudo vgscan --mknodes sudo vgchange -ay
You can now access / mount the crypt
sudo mkdir /media/crypt_root sudo mount /dev/mapper/root /media/crypt_root
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.
Install cryptsetup. This is a small download, it goes quickly.
sudo apt-get install cryptsetup
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.
/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
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
- 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.
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
- 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)
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.
Using losetup
To begin we will create a file, this file will be then mounted as an ext3 and filesystem encrypted with some algorithm.
The first step is to load cryptoloop:
sudo modprobe cryptoloop && lsmod | grep cryptoloop
cryptoloop 3584 1 loop 16264 2
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
We will use the Twofish cypher to encrypt our 100mb file as filesystem:
dd if=/dev/zero bs=1M count=100 of=mycryptofile
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
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
Make the directory where you want to mount the file system:
sudo mkdir /mnt/cryptoloop
And finally mount it:
sudo mount -t ext3 /dev/loop0 /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.
You might want to write two function and an alias for these steps in your ~/.bashrc like:
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?
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: <20050409231207+0100@www.ubuntulinux.org> 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. ---- Hi, this guide is of course already useful and I could use it to create encrypted partitions and also use them. However, using ubuntu, I do not end up with the solution that I wanted to have. Although I already got comments that it is not a good idea to create crypto partitions on external usb drives, it is still my most preferred way to protect at least the Linux data on an external hard drive. Using the information in this guide it is of course not a problem to create an encrypted partition on an external hard drive. However, what I do not manage to achieve with the information that I could get out of this howto with reasonable effort is: How do I get the device manger of KDE notice that there is an encrypted container on the usb drive. The only way how I mange to do this is actually to used the portioning tool of some SuSE distribution. There I just need to say that I would like to format a specific partition and activate the checkbox which says that the partition should be crypted, finished, and by some magic the KDE device manager recognizes the partition as encrypted container that I can open by clicking on it. At least for now it seems that I have to use a SuSE live CD to get to this to this state. It would be great if some body had the knowledge about the magic that is going on to include it in this howto. Cheers, Klaus
Distro Release Upgrade
Here is an upgrade scenario that takes some of the pain away from doing a distro upgrade. It avoids the chicken and the egg problem with the zfs third party module. I attempted to do an upgrade of the system by selectively re-enabling the zfs third party repo after the release upgrade had disabled all third party repo’s. While the zfs was updated, when it came to re-building the dkms modules the kernel panicked and the upgrade failed miserably. (Having ZFS snapshots to rollback to was a god send)! Below is a way to do a relatively painless release upgrade.
Make sure ZFS repo supports the distro release you are upgrading to https://launchpad.net/~zfs-native/+archive/stable
- Install the newer Ubuntu Desktop ##.## version you want to upgrade to on a bootable USB drive.
- Boot from USB and ‘Try Ubuntu’ (If your system is using UEFI make sure to boot in that mode).
Open a terminal window; sudo -i
apt-add-repository --yes ppa:zfs-native/stable apt-get update apt-get -y install ubuntu-zfs zfs-initramfs cryptsetup
- Then open the encrypted target media, import the zpool’s, mount, chroot and upgrade.
cryptsetup luksOpen /dev/sda2 root_crypt cryptsetup luksOpen /dev/sdb1 vault1_crypt cryptsetup luksOpen /dev/sdc1 vault2_crypt cryptsetup luksOpen /dev/sdd1 vault3_crypt (repeat for each additional luks container) ...
zpool import -f -d /dev/mapper -R /mnt/zfs rpool zpool import -f -d /dev/mapper -R /mnt/zfs vpool
If using UEFI make sure to add mount /dev/sda* /mnt/zfs/boot/efi after mounting /mnt/zfs/boot sda* being the boot_efi labeled device.
mount /dev/sda1 /mnt/zfs/boot mount -o bind /proc /mnt/zfs/proc mount -o bind /dev /mnt/zfs/dev mount -o bind /dev/pts /mnt/zfs/dev/pts mount -o bind /sys /mnt/zfs/sys
chroot /mnt/zfs /bin/bash --login
- (Optional) To reduce the upgrade time, I removed all previous and unused kernel versions to avoid delete/rebuild dmks for each kernel.
During the do-release-upgrade when prompted to confirm the disable of third party repo’s, before continuing, open another terminal tab and vi /etc/apt/sources.list.d/zfs-native-stable-raring.list and un-comment the deb. (Make sure the deb entry has the name of the release you are upgrading to).
ln -s /dev/mapper/root_crypt /dev/root_crypt apt-get update apt-get dist-upgrade do-release-upgrade
If all goes well you can exit, unmount and export the pools. If all does not go well you can use zfs rollback to revert to a snapshot time before the upgrade and re-attempt with whatever things need to be tweaked.
- Add umount /mnt/zfs/boot/efi if you are using UEFI boot.
exit umount /mnt/zfs/boot umount /mnt/zfs/sys umount /mnt/zfs/dev/pts umount /mnt/zfs/proc umount /mnt/zfs/dev
zpool export vpool zpool export rpool
- Reboot, remove USB and enjoy your upgrade!
Encryption with Cryptoloop
WARNING! We use the cryptoloop module in this howto. This module has well-known weaknesses.
Prearrangement
To set up Ubuntu the described way, you will need
- a KNOPPIX CD
- internet access
Insert the KNOPPIX CD into your computer and boot. Set up KNOPPIX so that it is able to connect to the internet.
Setting up the harddisk
We need three partitions:
You can use fdisk to set up the partition table. The results should look similiar to
Disk /dev/hda: 20.0 GB, 20003880960 bytes 255 heads, 63 sectors/track, 2432 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System /dev/hda1 * 1 2 16033+ 83 Linux /dev/hda2 3 2312 18555075 83 Linux /dev/hda3 2313 2432 963900 82 Linux swap / Solaris
sudo badblocks -c 10240 -s -w -t random -v /dev/hda2 losetup -T -e aes128 /dev/loop0 /dev/hda2 mkreiserfs /dev/loop0 mkdir /mnt/ubuntu mount /dev/loop0 /mnt/ubuntu
Installing Ubuntu
The installation procedure from KNOPPIX is described in Installation/FromKnoppix.
You need a different fstab. Instead of a normal partition, the device for the / mountpoint is /dev/loop0. The swap entry needs more arguments to provide encrypted swap.
/proc /proc proc defaults 0 0 /sys /sys sysfs defaults 0 0 /dev/hda1 /osloader ext3 defaults,noauto 0 0 /dev/loop0 / reiserfs defaults 0 1 /dev/hda3 none swap sw,loop=/dev/loop1,encryption=aes128 0 0 /dev/cdrom /mnt/cdrom auto user,noauto,exec,ro 0 0
After setting up the base system, install loop-aes-utils.
apt-get install loop-aes-utils
When installing the kernel and GRUB, quit the GRUB configuration assistent.
Setting up the OS loader
After installing the base system, we set up a small partition that mounts the encrypted root and kicks off init.
mke2fs -j /dev/hda1 mkdir /osloader mount /dev/hda1 /osloader
Copy the kernel image there.
cp /vmlinuz /osloader/vmlinuz
We need to edit the mkinitrd configuration so that it supports loading the encrypted root partition.
First edit /etc/mkinitrd/mkinitrd.conf, set ROOT=probe to ROOT= since it would complain about our /dev/loop0 root.
Add some required modules to /etc/mkinitrd/modules:
ide-generic loop cryptoloop aes sha256 reiserfs
mknod -m 600 $INITRDDIR/dev/loop0 b 7 0 mknod -m 600 $INITRDDIR/dev/hda2 b 3 2 mkdir $INITRDDIR/loopcheck cat > $INITRDDIR/scripts/losetup.sh << EOF #!/bin/sh mount -nt proc proc proc losetup -e aes128 /dev/loop0 /dev/hda2 mount -nr /dev/loop0 /loopcheck >/dev/null 2>/dev/null while [ \$? -ne 0 ] do echo "Try again." losetup -d /dev/loop0 2>/dev/null losetup -e aes128 /dev/loop0 /dev/hda2 mount -nr /dev/loop0 /loopcheck >/dev/null 2>/dev/null done umount -n /loopcheck # loop0 = 7, 0 echo 1792 > /proc/sys/kernel/real-root-dev umount -n proc EOF chmod a+x $INITRDDIR/scripts/losetup.sh
chmod a+x /etc/mkinitrd/scripts/losetup
Now generate the initial ram disk with mkinitrd -o /osloader/initrd 2.6.10-5-386.
mkdir /osloader/boot mkdir /osloader/boot/grub
default 0 timeout 0 title Ubuntu root (hd0,0) kernel /vmlinuz ro quiet splash root=/dev/loop0 acpi=off nolapic initrd /initrd boot
Install the MBR by running grub-install --root-directory=/osloader /dev/hda.
To make sure the osloader partition is clean, add a little check script to /etc/rcS.d/S00checkosloader.
if [ "`md5sum /dev/hda1`" != "`cat /etc/osloader_checksum`" ] then echo "** FATAL SECURITY ERROR ************************************" echo "* *" echo "* The OS loader was modified! *" echo "* This could have leaked your encryption password. You are *" echo "* advised to install a new encryption setup. *" echo "* *" echo "* Press Enter to boot up the system. *" echo "************************************************************" read junk fi
chmod a+x /etc/rcS.d/S00checkosloader md5sum /dev/hda1 > /etc/osloader_checksum
Now exit the chroot, reboot and you should have a fully encrypted environment.
EXIT Chroot
You now need to install grub, run this command from the live CD
sudo grub-install --root-directory=/media/crypt_root /dev/sda
That is about it, I do not think I forgot anything major. I can not fill in all the details of all your partitions as I do not know your layout and do not know how much or how little you know about /etc/fstab.
If you need further assistance or I forgot something post back or perhaps someone will chime in.
If all the seems overwhelming , well that is why people use the alternate CD, it automates the process.
Those links will have gentoo and arch specific information, which you can ignore as you are on Ubuntu. But they contain more detailed descriptions on how to set up LVM and your crypt, including examples of crypttab and fstab.
Hope that helps.
Creative Commons License
Author: James B. Crocker
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!).
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?
- 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.
- 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.
- 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.
- 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.
- You can encrypt the key and store it on a removeable media.
- 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.
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.
New installations of Ubuntu 12. 10 and later
During installation, check the checkbox “Encrypt the new Ubuntu installation for security”. See also the Electronic Frontier Foundation’s notes.
How to set up a fully encrypted disk with Ubuntu
This page describes a way to set up an Ubuntu installation with a encrypted root partition and encrypted Swap.
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.
Перенос системы
Копирование
mkdir /tmp/root mount /dev/mapper/root /tmp/root/ mkdir /tmp/root/boot mount /dev/sdb1 /tmp/root/boot/
Скопировать корень системы на новый диск
rsync -AaHSxv / /tmp/root/
Команда rsync скопирует данные с сохранением всех прав.
Копирование с ключом x, это значит, содержимое каталогов примантированных в текущей момент к корню не будет скопировано в корень новой системы.
Будьте внимательны если /usr /home и т.п. каталоги у вас примантированны с других разделов.
Папка /tmp/root/dev/ сейчас пуста, необходимо создать устройства
mknod /tmp/root/dev/console -m 0600 c 5 1 mknod /tmp/root/dev/null -m 0666 c 1 5
Ядро новой системы
mount -t proc none /tmp/root/proc/ mount -o bind /dev/ /tmp/root/dev/ chroot /tmp/root/ /bin/bash
<note warning >
Переход в окружение новой системы
</WRAP>
env-update && source /etc/profile
Настройки ядра будут немного отличаться:
Все модули должны быть включены в само ядро
Для возможности загрузиться, необходим образ initramfs, для этого нам и нужна утилита genkernel.
emerge sys-kernel/genkernel -av
... SAVE_CONFIG="yes" LUKS="yes" DISKLABEL="yes"
Что бы genkernel не испортил текущий конфиг, своими настройками по умолчанию, мы укажем ему, что нужно использовать только наш конфиг, но для этого необходимо обязательно сделать копию.
cd /usr/src/linux cp .config .config_my genkernel --kernel-config=./.config_my --menuconfig all
General setup ---> [*] Initial RAM filesystem and RAM disk (initramfs/initrd) support Device Drivers ---> Generic Driver Options ---> [*] Maintain a devtmpfs filesystem to mount at /dev [*] Automount devtmpfs at /dev, after the kernel mounted the rootfs [*] Block devices ---> <*> Loopback device support <*> Cryptoloop Support <*> RAM block device support [*] Multiple devices driver support (RAID and LVM) ---> <*> Device mapper support <M> Crypt target support -*- Cryptographic API ---> -*- CBC support <*> SHA224 and SHA256 digest algorithm <*> SHA384 and SHA512 digest algorithms <*> AES cipher algorithms File systems ---> <*> Second extended fs support
После сборки ядра должны появиться файлы
gentoo linux # ls -la /boot/ итого 7319 drwxr-xr-x 4 root root 1024 Сен 7 13:44 . drwxr-xr-x 21 root root 4096 Сен 7 10:12 .. -rw-r--r-- 1 root root 1676834 Сен 7 16:19 initramfs-genkernel-x86_64-2.6.38-gentoo-r6 -rw-r--r-- 1 root root 3656720 Сен 7 16:19 kernel-genkernel-x86_64-2.6.38-gentoo-r6 -rw-r--r-- 1 root root 2107782 Сен 7 16:19 System.map-genkernel-x86_64-2.6.38-gentoo-r6
Конфиг текущего ядра genkernel сохранит
/etc/kernels/kernel-config-x86_64-2.6.38-gentoo-r6
и будет использовать его по умолчанию, поэтому в дальнейшем достаточно команды
genkernel --menuconfig all
GRUB
По прежнему находимся в окружении новой системы
emerge sys-boot/grub -av
Установка загрузчика на sdb (это hd1)
grub >root (hd1,0) >setup (hd1) >quit
gentoo linux # blkid /dev/sdb1: UUID="3ba6aaa8-c58b-48d7-a8eb-9a3062bf7514" TYPE="ext2" /dev/sdb2: UUID="4bce9506-2067-4642-878a-f13a36077179" TYPE="swap" /dev/sdb3: UUID="66482f3a-d8e4-47a0-8385-6b0a1ca9aefb" TYPE="crypto_LUKS" # crypt_root /dev/mapper/root: UUID="24222a99-f949-4e6c-9c9e-b1c73f1bf794" TYPE="ext3" # real_root
title Gentoo Linux 2.6.38-r6 root (hd1,0) kernel /boot/kernel-genkernel-x86_64-2.6.38-gentoo-r6 crypt_root=UUID="66482f3a-d8e4-47a0-8385-6b0a1ca9aefb" real_root=UUID="24222a99-f949-4e6c-9c9e-b1c73f1bf794" root=/dev/ram0 initrd /boot/initramfs-genkernel-x86_64-2.6.38-gentoo-r6 # Или так #title Gentoo Linux 2.6.38-r6 #root (hd1,0) #kernel /boot/kernel-genkernel-x86_64-2.6.38-gentoo-r6 crypt_root=/dev/sdb3 real_root=/dev/mapper/root root=/dev/ram0 udev #initrd /boot/initramfs-genkernel-x86_64-2.6.38-gentoo-r6
Now, you use crypt_root=/dev/blah instead of real_root=luks:/dev/blah.
FSTAB
По прежнему находимся в окружении новой системы
... # /boot = /dev/sdb1 UUID="3ba6aaa8-c58b-48d7-a8eb-9a3062bf7514" /boot ext2 noauto,noatime 1 2 # / = /dev/mapper/root UUID="24222a99-f949-4e6c-9c9e-b1c73f1bf794" / ext3 noatime 0 1 # swap = /dev/sdb2 UUID="4bce9506-2067-4642-878a-f13a36077179" none swap sw 0 0
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).
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.
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.
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 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.
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.
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.
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.
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.