ARCH GENTU LUCKS Encriptar Particiones

75
SXmmaU\ TKLV WXWRULDO ZLOO VKRZ \RX KRZ WR VHW XS V\VWHP HQFU\SWLRQ ZLWK LUKS IRU GP FU\SW. S\VWem EncU\pWion ZiWh LUKS FURP AUFKWLNL ConWenWV 1 IQWURGXFWLRQ 1.1 WK\ UVH EQFU\SWLRQ? 1.2 WKDW MHWKRGV DUH AYDLODEOH IRU S\VWHP

Transcript of ARCH GENTU LUCKS Encriptar Particiones

Page 1: ARCH GENTU LUCKS Encriptar Particiones

Summary

This tutorialwill showyou how toset upsystemencryptionwith LUKSfor dm­crypt.

System Encryption withLUKSFrom ArchWiki

Contents

1 Introduction1.1 Why Use Encryption?1.2 What Methods are Available for System

Page 2: ARCH GENTU LUCKS Encriptar Particiones

Encryption?1.3 Caveats

1.3.1 Key Complexity and Availability1.3.2 Encryption Algorithm1.3.3 discard/TRIM support for solidstate disks1.3.4 System Encryption1.3.5 Data Encryption

1.3.5.1 Encryption of datapartitions on the same physicaldisk as the system1.3.5.2 Encryption of datapartitions on separate physicaldisks from the system

2 Initial Setup2.1 Overview and Preparation2.2 Secure Erasure of the Hard Disk Drive

2.2.1 Why perform secure of erasure ofa drive?2.2.2 Overwriting a hard disk drive withrandom data

2.2.2.1 Using urandom2.2.2.2 Using badblocks

2.3 Partitioning2.3.1 Standard Partitions2.3.2 LVM: Logical Volume Manager

Page 3: ARCH GENTU LUCKS Encriptar Particiones

2.3.3 How does LVM fit into the overallsystem?2.3.4 Creating Disk Partitions

2.3.4.1 Single Disk Systems2.3.4.2 Multiple Disk Systems

3 Configuring LUKS3.1 Mapping Physical Partitions to LUKS

3.1.1 Using LUKS to Format Partitionswith a Passphrase3.1.2 Using LUKS to Format Partitionswith a Keyfile3.1.3 Adding Additional Passphrases orKeyfiles to a LUKS Encrypted Partition

3.2 Storing the Key File3.2.1 External Storage on a USB Drive

3.2.1.1 Preparation for permanentdevice names3.2.1.2 Quick method

3.2.2 Using udev3.2.3 Generating the keyfile3.2.4 Storing the keyfile3.2.5 Configuration of initcpio3.2.6 Storing the key as plain (visible)file3.2.7 Storing the key between MBR and1st partition

Page 4: ARCH GENTU LUCKS Encriptar Particiones

3.3 Encrypting the Swap partition3.3.1 Encrypting Swap without SuspendSupport3.3.2 Using UUIDs with encrypted swappartitions3.3.3 Encrypted swap with suspend­to­disk support

4 Installing the system4.1 Prepare hard drive4.2 Select and Install packages4.3 Configure System4.4 Install Bootloader4.5 Exit Install

5 Remote unlocking of the root (or other) partition6 Backup the cryptheader

6.1 Backup6.1.1 Manually6.1.2 Using cryptsetup

6.2 Restore6.2.1 Manually6.2.2 Using cryptsetup

7 Encrypting a loopback filesystem7.1 Preparation and mapping7.2 Encrypt using a key­file7.3 Resizing the loopback filesystem

8 Encrypting a LVM setup

Page 5: ARCH GENTU LUCKS Encriptar Particiones

8.1 LVM with Arch Linux Installer (>2009.08)8.1.1 The partition and filesystem choice8.1.2 The configuration stage

8.2 Applying this to a non­root partition8.3 LVM and dm­crypt manually (shortversion)

8.3.1 Notes8.3.2 Partitioning scheme8.3.3 The commands8.3.4 Install Arch Linux8.3.5 Configuration

8.3.5.1 /etc/rc.conf8.3.5.2 /etc/mkinitcpio.conf8.3.5.3 /boot/grub/menu.lst8.3.5.4 /etc/fstab8.3.5.5 /etc/crypttab

8.3.6 After rebooting8.3.6.1 The commands8.3.6.2 /etc/crypttab8.3.6.3 /etc/fstab

8.4 / on LVM on LUKS9 Resources

Introduction

Page 6: ARCH GENTU LUCKS Encriptar Particiones

Why Use Encryption?

In the simplest terms encryption is a method for establishingprivacy.

There are presently two approaches to partition levelencryption data encryption and system encryption.

Data encryption, defined as encrypting a users data,provides for many benefits including:

Preventing unauthorized physical access toprivate data.Some confidence in data disposal whendiscarding obsolete systems.

However data encryption alone has some significantdrawbacks. In modern computing systems, there are manybackground processes that may store information aboutencrypted data or parts of the encrypted data itself in non­encrypted areas of the hard drive. Thus reducing theeffectiveness of any data encryption system in place.

System encryption, defined as the encryption of theoperating system and user data, helps to address some of theinadequacies of data encryption. The benefits of systemencryption over data encryption alone include:

Page 7: ARCH GENTU LUCKS Encriptar Particiones

Preventing unauthorized physical access tooperating system filesPreventing unauthorized physical access toprivate data that may cached by thesystem.

In the context of overall system security, system encryptionshould be viewed as an adjunct to the existing securitymechanisms of the operating system that focuses on physicalattempts to breach system security which includes:

Attempts to bypass the operating system byinserting a boot CD/USBCopying, modifying, or removing the harddisk drives when the computer is off

Despite the use of system encryption, there are still points ofphysical insecurity. These issues revolve around the /bootpartition which must remain unencrypted in order for themachine to properly boot. However, system encryption ispresently the best way to minimize the loss of data privacy byphysical attempts at invasion.

Warning: Any encryption method employed is only asgood as its associated key management. Partition levelencryption does not protect you from all forms of security

Page 8: ARCH GENTU LUCKS Encriptar Particiones

compromise. There are ways to break into computers whilethey are powered on that are unaffected by disk levelencryption. Read the caveats section below!

What Methods are Available for SystemEncryption?

There are multiple current methods that can be employed forsystem encryption, including:

loop­AES (loop­AES (http://loop­aes.sourceforge.net/) )loop­AES is a descendant of cryptoloop and is a secureand fast solution to system encryption.However loop­AES is considered less user­friendlythan other options as it requires non­standard kernelsupport.

standard device­mapper encryption (dm­crypt(http://www.saout.de/misc/dm­crypt/) )

This is the standard device mapper which can be usedfor those who like to have control over all aspectspartition management.

LUKS for dm­crypt (LUKS(http://code.google.com/p/cryptsetup/) )

LUKS stores all of the needed setup information for

Page 9: ARCH GENTU LUCKS Encriptar Particiones

dm­crypt on the disk itself and abstracts partition andkey management in an attempt to improve ease of use.

Briefly some key features that LUKS provides include:

Support for either passphrase or keyfiles asencryption keysPer partition key creation and revocationMultiple passphrases or keyfiles for aparticular partition

Caveats

For any type of encryption the security of your privacy isdependent on two things:

The complexity/availability of your key(see Wikipedia:Kerckhoffs's principle)The usage of a proven encryptionalgorithm

Key Complexity and Availability

The user provided key used for encryption, whether apassphrase or a keyfile, must be complex enough that is it noteasy to guess. Having a strong encryption algorithm does

Page 10: ARCH GENTU LUCKS Encriptar Particiones

nothing to provide privacy if the key used for encryption istoo simple. The tenets of strong keys are based on length andrandomness. There are many sources available withinstructions on how to create strong encryption keys.

Part of key complexity is key availability. For example acomplex key written on a sticky note pasted to the computer'skeyboard would not provide much in the way privacy.Therefore in addition to creating a strong key, maintaining itin a secure location is necessary as well.

Encryption Algorithm

There are many peer­reviewed encryption algorithms inexistence. The encryption algorithms and block ciphers usedin any of the mentioned methods for applying encryption inthis wiki page are considered strong algorithms that havebeen subjected to cryptographic review by the cryptographycommunity.

discard/TRIM support for solid state disks

Solid state disk users should be aware that by default, Linux'sfull­disk encryption mechanisms will not forward TRIMcommands from the filesystem to the underlying disk. Thedevice­mapper maintainers have made it clear that TRIM

Page 11: ARCH GENTU LUCKS Encriptar Particiones

support will never be enabled by default on dm­crypt devicesbecause of the potential security implications; if TRIMsupport were enabled, an attacker may be able to tell whichblocks have been used, how many blocks have been used,and other information that is exposed directly to the devicewhen a TRIM is issued.

It may be possible to determine the filesystem utilized byyour encrypted device through the data that is leaked byTRIM. Furthermore, any information that may be derived bya profile of block usage may be exposed by enabling TRIMsupport on an encrypted device.

As of linux (https://www.archlinux.org/packages/?name=linux) version 3.1, support for dm­crypt TRIM pass­through can be toggled upon device creation or mount withdmsetup. Support for this option also exists in cryptsetup(https://www.archlinux.org/packages/?

name=cryptsetup) version 1.4.0 and up. To add supportduring boot, you will need to add ":allow­discards " to the cryptdevice option. The option should look like this:

cryptdevice=/dev/mapper/root:root:allow­discards

For more information, including specific commands anddetails on dm­crypt TRIM pass­through, see these mailing list

Page 12: ARCH GENTU LUCKS Encriptar Particiones

threads:

* http://article.gmane.org/gmane.linux.kernel.device­mapper.devel/14134* http://article.gmane.org/gmane.linux.kernel.device­mapper.dm­crypt/5166

System Encryption

System encryption provides security against unauthorizedphysical access to a machine that is powered off. It does noteffect any security advantages for a system that is powered onwith its partitions mounted in an unencrypted state. For apowered on user accessible system the normal precautions toprevent viruses, trojans, worms, or other attempts to accessprivate data should be exercised. Furthermore, systemencryption has been shown to be penetrable in cases where asystem has been recently shutdown. This is due to the factthat cessation of power does not immediately degrade datathat was stored in RAM prior to shutdown. Thereforesomeone with physical access to your computer within a fewmoments of shutdown could cool the RAM modules and usethem extract your encryption key ­ thus obtaining access toyour data.

Note: System Encryption assume encryption of all mountedpartitions this includes all partitions except for /boot ­

Page 13: ARCH GENTU LUCKS Encriptar Particiones

meaning that the root file system, swap partition, and allother partitions must be encrypted. If the swap, /tmp , orroot filesystems are unencrypted, only Data Encryptionlevel of security has been accomplished.

Data Encryption

There are two common forms of data encryption:

Encryption of data partitions on the samephysical disk as the system.Encryption of data partitions on separatephysical disks from the system.

Encryption of data partitions on the same physical disk as the system

The most common form of data encryption is encrypting the /home partition.

In cases where the encrypted data are located on the samephysical disk as the system accessing the drive the privacy ofdata has already been decreased by orders of magnitude whencompared to system encryption. The reason for this is that thehost operating systems employ background methods to assistthe user in the access and management of their data. Theproblem lies in where these processes store this data which is

Page 14: ARCH GENTU LUCKS Encriptar Particiones

most commonly in the unencrypted system partition.

For example, mlocate(https://www.archlinux.org/packages/?name=mlocate)

will scan all currently mounted file systems regularly andwrite the list of filenames to /var/lib/mlocate/mlocate.db, which is located in the non­encrypted root or /var partition.Thus an attacker will have a list of all filenames for thatcomputer, even the ones on the encrypted /home partition,readily available to assist them in accessing the encrypteddata present on the disk.

Some have compared this to reducing the level of securityfrom partition­based encryption to filesystem level encryptionlike System Encryption with eCryptfs.

Encryption of data partitions on separate physical disks from thesystem

Popular forms of data encryption on physically separatepartitions include the encryption of removable media such as:

USB Flash DrivesExternal Hard Disk Drives or SeparateInternal Hard Disk DrivesCD/DVD/Blu­Ray Optical Media

Page 15: ARCH GENTU LUCKS Encriptar Particiones

Magnetic Storage Media

The most important part of this form of data encryption is toremember that the encryption protects the privacy of the datathat is located within the encrypted media only when it is notmounted. Data encryption does not protect the privacy of dataonce it is made accessible to a system. For example, attachingan encrypted USB flash drive, and subsequently decrypting afile for use temporarily on a non­secured system could resultin remnants of that file existing on the host system in anunencrypted form.

Initial Setup

Overview and Preparation

The Arch installer comes with all the tools required forsystem encryption. Setup of encrypted partitions can beaccomplished either manually prior to executing the archinstaller or using the menu interface from the arch installeritself. The installation of an encrypted system is largely thesame as installing an unencrypted system, so you can followthe Official Arch Linux Install Guide or the Beginners' Guideafter the encrypted partitions are setup.

Routine creation of an encrypted system follows these

Page 16: ARCH GENTU LUCKS Encriptar Particiones

general steps:

Secure erasure of the harddisk drive(s)Partitioning and setup of encryption (LVMoptional)Routine package selection and installationSystem Configuration

Warning: Encrypting a partition will erase everythingcurrently on that partition. Please make appropriate databackups prior to starting.

Secure Erasure of the Hard Disk Drive

Secure erasure of the hard disk drive involves overwriting theentire drive with random data.

Note: Overwriting a hard disk drive multiple times withrandom data serves no purpose. Data existing prior tooverwriting cannot be recovered after it has beenoverwritten. Overwriting Hard Drive Data: The GreatWiping Controversy(http://www.springerlink.com/content/408263ql11460147/)

Why perform secure of erasure of a drive?

Page 17: ARCH GENTU LUCKS Encriptar Particiones

There are two types of hard disk drives, new and used, bothkinds should be securely overwritten. The reasoning isslightly different for each but the goal is to help ensure theprivacy of data located within the encrypted partitions.

New Hard Disk Drives

In hard drives that have been directly purchasedfrom a manufacturer there is no preexistingprivate data to protect. The problem is that thereis no consistency in what is presently on thedrive. Ideally the drive should be completelyfilled with random bits. However some driveshave been overwritten completely with zeros.Therefore once the drive is used to writeencrypted data, it is relatively simple to identifywhere the encrypted data ends and the zeroeddata begins compared to a drive that was writtenwith random data before usage as an encrypteddrive. Since an encrypted partition is supposed tobe indistinguishable from random data, the lackof random data on a zeroed drive makes anencrypted drive an easier target for cryptanalysis.

Used Hard Disk Drives

Repartitioning or reformatting a used hard drive

Page 18: ARCH GENTU LUCKS Encriptar Particiones

removes the file system structure for identifyingwhere the original data was located while leavingthe actual data intact on the drive itself. It isrelatively straight forward using data tools likeForemost (http://foremost.sourceforge.net/) toaccess the remnant data. Therefore hard drivesshould be securely overwritten with random dataprior to encryption to prevent unintentional datarecovery.

Overwriting a hard disk drive with random data

There are two sources of random data commonly used forsecurely overwritting hard disk partitions.

/dev/urandom

badblocks

Using urandom

#dd if=/dev/urandom of=/dev/<drive> bs=1M

Where /dev/<drive> is the drive to be encrypted.

Note: Using /dev/urandom will take a long time to

Page 19: ARCH GENTU LUCKS Encriptar Particiones

completely overwrite a drive with "random" data. In thestrictest sense, /dev/urandom is less random than /dev/random ; however, /dev/random uses the kernelentropy pool and will halt overwriting until more inputentropy once this pool has been exhausted. This makes theuse of /dev/random for overwriting hard disks impractical.

Note: Users may also find that /dev/urandom takes anexcessively long time on large drives of several hundredgigabytes or more (more than twenty­four hours). Frandomoffers a faster alternative.

Note: You can retrieve progress of the dd command withthis command: kill ­USR1 $(pidof dd)

Using badblocks

#badblocks ­c 10240 ­wsvt random /dev/<drive>

Where /dev/<drive> is the drive to be encrypted.

Note: The badblocks command overwrites the drive at amuch faster rate by generating data that is not truly random.

See also badblocks.

Page 20: ARCH GENTU LUCKS Encriptar Particiones

Tip: In deciding which method to use for secure erasure ofa hard disk drive, remember that this will not need to beperformed more than once for as long as the drive is used asan encrypted drive.

Partitioning

After the drive has been securely overwritten, it is time tocreate partitions and begin setting up an encrypted system.

There are multiple ways to create disk partitions:

Standard partitionsLVMRAID

LUKS is compatible in systems that require both LVM and/orRAID as well as with with standard primary, extended, andlogical partitions.

Standard Partitions

These are the partitions that most people are familiar with.They come in 3 flavors: primary partitions, extendedpartitions, and logical partitions.

Page 21: ARCH GENTU LUCKS Encriptar Particiones

Primary PartitionsThese are the normal partitions recognized by thesystem BIOS. There can be up to 4 of these stored inthe MBR.

Extended PartitionsThese are primary partitions that also define anotherpartition within themselves. Extended partitions werecreated to work around the original 4 partition limit ofprimary partitions.

Logical PartitionsThese are the partitions that are defined withinextended partitions.

LVM: Logical Volume Manager

The LVM allows for creation of volume groups for systemsthat require complex combinations of multiple hard diskdrives and partitions that are not possible with standardpartitions. LVM is covered in detail in the Arch Linux LVMWiki Article which is recommended reading prior tocontinuing with the instructions on setting up LUKS withLVM located below.

How does LVM fit into the overall system?

Page 22: ARCH GENTU LUCKS Encriptar Particiones

There is a growing preference towards logical volumemanagement of LUKS encrypted physical media (LVM onLUKS). It is possible there may exist usage scenarios whereencrypting logical volumes rather than physical disks isrequired (LUKS on LVM). However, the deployment ofLVM on LUKS is considered much more generalizable. Onereason for this is that using LUKS as the lowest level ofinfrastructure most closely approximates the deployment ofphysical disks with built­in hardware encryption. In whichcase, logical volume management would be layered on top ofthe hardware encryption ­­ usage of LUKS would besuperfluous.

Creating Disk Partitions

Disk partitions are created using:

# cfdisk

This will display a graphical interface for creating diskpartitions.

There are 2 required partitions for any encrypted system:

A root file system

Page 23: ARCH GENTU LUCKS Encriptar Particiones

/

Will be encrypted and store allsystem and user files (/usr , /bin , /var , /home , etc.)

An initial boot partition

/boot

Will not be encrypted; thebootloader needs to access the /boot directory where it will loadthe initramfs/encryption modulesneeded to load the rest of the systemwhich is encrypted (see Mkinitcpiofor details). For this reason, /bootneeds to reside on its own,unencrypted partition.

Note: A swap partition is optional; it can be encrypted withdm­crypt/LUKS. See Encrypting the Swap Partition fordetails.

Single Disk Systems

Depending on the system demands, there may be additionalpartitions desired. These partitions can be individually

Page 24: ARCH GENTU LUCKS Encriptar Particiones

created at this level by defining separate primary orextended/logical partitions. However, if LVM is to be used,the space unoccupied by /boot and swap should be definedas single large partition which will be divided up later at theLVM level.

Multiple Disk Systems

In systems that will have multiple hard disk drives, the sameoptions exist as a single disk system. After the creation of the /boot and swap partitions, the remaining free space onphysical disks can divided up into their respective partitionsat this level, or large partitions can define all free space perphysical disk with intent to partition them within the LVM.

Configuring LUKS

Creating LUKS partitions with a passphrase is supported bythe /arch/setup program.

This section of the Wiki will cover how to manually utilizeLUKS from the command line to encrypt a system.

The steps for accomplishing this through the graphicalinstaller are very similar and can be located in the dialoguefor manual configuration of the hard drive.

Page 25: ARCH GENTU LUCKS Encriptar Particiones

Mapping Physical Partitions to LUKS

Once the desired partitions are created it is time to formatthem as LUKS partitions and then mount them through thedevice mapper.

When creating LUKS partitions they must be associated witha key.

A key is either a:

PassphraseKeyfile

It is possible to define up to 8 different keys per LUKSpartition.

Using LUKS to Format Partitions with a Passphrase

Cryptsetup is used to interface with LUKS for formatting,mounting and unmounting encrypted partitions.

A full list of options cryptsetup accepts can be found in the[Cryptsetup Manpage(http://www.linuxcommand.org/man_pages/cryptsetup8.html)]

Page 26: ARCH GENTU LUCKS Encriptar Particiones

The options used here are:

­c defines the cipher type­y prompts for password confirmation onpassword creation­s defines the key size

luksFormat addresses the LUKS extensions builtinto cryptsetup.

In the following examples for creating LUKS partitions, wewill use the AES cipher in XTS mode, at present this is mostgenerally used preferred cipher. Other ciphers can be usedwith cryptsetup, and details about them can be found here:Wikipedia:Block_cipher

Formatting LUKS Partitions

First of all make sure the device mapper kernel module isloaded by executing the following: # modprobe dm_mod

In order to format a desired partition as an encrypted LUKSpartition execute:

# cryptsetup ­c <cipher> ­y ­s <key size> luksFormat /dev/<partition name>

Enter passphrase: <password>

Page 27: ARCH GENTU LUCKS Encriptar Particiones

Verify passphrase: <password>

This should be repeated for all partitions except for /bootand possibly swap.

The example below will create an encrypted root partitionusing the AES cipher in XTS mode (generally referred to asXTS­AES).

cryptsetup ­c aes­xts­plain ­y ­s 512 luksFormat /dev/sda2

Note: If hibernation usage is planned, swap must beencrypted in this fashion; otherwise, if hibernation is not aplanned feature for the system, encrypting the swap file willbe performed in a alternative manner.

Warning: Irrespective of the chosen partitioning method,the /boot partition must remain separate and unencryptedin order to load the kernel and boot the system.

Unlocking/Mapping LUKS Partitions with the DeviceMapper

Once the LUKS partitions have been created it is time tounlock them.

Page 28: ARCH GENTU LUCKS Encriptar Particiones

The unlocking process will map the partitions to a new devicename using the device mapper. This alerts the kernel that /dev/<partition name> is actually an encrypted device andshould be addressed through LUKS using the /dev/mapper/<name> so as not to overwrite the encrypteddata.

In order to open an encrypted LUKS partition execute:

# cryptsetup luksOpen /dev/<partition name> <device­mapper name>

Enter any LUKS passphrase: <password>key slot 0 unlocked.Command successful.

Usually the device mapped name is descriptive of thefunction of the partition that is mapped, example:

cryptsetup luksOpen /dev/sda2 swap

Once opened, the swap partitiondevice address would be /dev/mapper/swap instead of /dev/sda2 .

cryptsetup luksOpen /dev/sda3 root

Page 29: ARCH GENTU LUCKS Encriptar Particiones

Once opened, the root partitiondevice address would be /dev/mapper/root instead of /dev/sda3 .

Note: Since /boot is not encrypted, it does not need adevice mapped name and will be addressed as /dev/sda1 .

Warning: In order to write encrypted data into the partitionit must be accessed through the device mapped name.

Using LUKS to Format Partitions with a Keyfile

What is a Keyfile?

A keyfiles is any file in which the data contained within isused as the passphrase to unlock an encrypted volume.Therefore if these files are lost or changed, decrypting thevolume will no longer be possible.

Tip: Define a passphrase in addition to the keyfile forbackup access to encrypted volumes in the event thedefined keyfile is lost or changed.

Why use a Keyfile?

Page 30: ARCH GENTU LUCKS Encriptar Particiones

There are many kinds of keyfiles, each type of keyfile usedhas benefits and disadvantages summarized below:

keyfile.passphrase:

this is my passphrase I would have typed duringboot but I have placed it in a file instead

This is a keyfile containing a simple passphrase. The benefitof this type of keyfile is that if the file is lost the data itcontained is known and hopefully easily remembered by theowner of the encrypted volume. However the disadvantage isthat this does not add any security over entering a passphraseduring the initial system start.

keyfile.randomtext:

fjqweifj830149­57 819y4my1­ 38t1934yt8­91m34co3;t8y;9p3y­

This is a keyfile containing a block of random characters. Thebenefit of this type of keyfile is that it is much more resistantto dictionary attacks than a simple passphrase. An additionalstrength of keyfiles can be utilized in this situation which isthe length of data used. Since this is not a string meant to bememorized by a person for entry, it is trivial to create filescontaining thousands of random characters as the key. The

Page 31: ARCH GENTU LUCKS Encriptar Particiones

disadvantage is that if this file is lost or changed, it will mostlikely not be possible to access the encrypted volume withouta backup passphrase.

keyfile.binary:

where any binary file, images, text, video couldbe chosen as the keyfile

This is a binary file that has been defined as a keyfile. Whenidentifying files as candidates for a keyfile, it isrecommended to choose files that are relatively static such asphotos, music, video clips. The benefit of these files is thatthey serve a dual function which can make them harder toidentify as keyfiles. Instead of having a text file with a largeamount of random text, the keyfile would like a regularimage file, or music clip to the casual observer. Thedisadvantage is that if this file is lost or changed, it will mostlikely not be possible to access the encrypted volume withouta backup passphrase. Additionally, there is a theoretical lossof randomness when compared to a randomly generated textfile. This is due to the fact that images, videos, music havesome intrinsic relationship between neighboring bits of datathat is not existent for a text file. However this iscontroversial and has never been exploited publicly.

Creating a Keyfile with Random Characters

Page 32: ARCH GENTU LUCKS Encriptar Particiones

Here dd is used to generate a keyfile of 2048 bits of randomcharacters.

# dd if=/dev/urandom of=mykeyfile bs=512 count=4

The usage of dd is similar to initially wiping the volume withrandom data prior to encryption. While badblocks may alsobe used, most key files are on the order of a few kilobytes andthere is no noticable speed difference between dd, orbadblocks.

Creating a new LUKS encrypted partition with a Keyfile

When creating a new LUKS encrypted partition, a keyfilemay be associated with the partition on its creation using:

# cryptsetup ­c <desired cipher> ­s <key size> ­v luksFormat /dev/<volume to encrypt>

This is accomplished by appending the bold area to thestandard cryptsetup command which defines where thekeyfile is located.

Adding Additional Passphrases or Keyfiles to a LUKSEncrypted Partition

Page 33: ARCH GENTU LUCKS Encriptar Particiones

LUKS supports the association of up to 8 keys with anysingle encrypted volume. Keys can be either keyfiles orpassphrases.

Once an encrytped partition has been created, the initial keyis associated at slot0. Additional keys will occupy slots 1 ­ 7.

The addition of new keys to an encrypted partition isaccomplished using cryptsetup with the luksAddKeyextension.

# cryptsetup luksAddKey /dev/<encrypted volume> /path/to/mykeyfile

Where /dev/<encrypted volume> is the volume that is tohave the new key associated with it.

If the bolded area is present, cryptsetup will look for thekeyfile defined at that location to associate with the encryptedvolume specified.

Storing the Key File

External Storage on a USB Drive

Preparation for permanent device names

Page 34: ARCH GENTU LUCKS Encriptar Particiones

For reading the file from an USB stick it is important toaccess it through a permanent device name. The numberingof the normal device names e.g. /dev/sdb1 is somewhatarbitrary and depends on how many storage devices areattached and in what order, etc. So in order to assure that the encrypt HOOK in the initcpio finds your keyfile, you mustuse a permanent device name.

Quick method

A quick method (as opposed to setting up a udev rule) fordoing so involves referencing your removable device by itslabel (or UUID). To find your label or UUID, plug in yourUSB drive and run the following:

# ls ­l /dev/disk/by­label/

lrwxrwxrwx 1 root root 10 12. Feb 10:11 Keys ­> ../../sdb1

or

# ls ­l /dev/disk/by­uuid/

lrwxrwxrwx 1 root root 10 12. Feb 10:11 4803­8A7B ­> ../../sdb1

Page 35: ARCH GENTU LUCKS Encriptar Particiones

In this case, I labeled the vfat partition on my USB drive as"Keys" so my device is always symlinked in /dev/disk/by­label/Keys , or if I had wanted to use theUUID I would find /dev/disk/by­uuid/4803­8A7B . Thisallows me to have a consistent naming of my USB devicesregardless of the order they are plugged into the system.These device names can be used in the "cryptkey" kerneloption or any where else. Filesystem UUIDs are stored in thefilesystem itself, meaning that the UUID will be the same ifyou plug it into any other computer, and that a dd backup ofit will always have the same UUID since dd does a bitwisecopy.

Note: If you plan to store the keyfile between MBR and the1st partition you cannot use this method, since it onlyallows access to the partitions (sdb1 , sdb2 , ...) but not tothe USB device (sdb ) itself. Create a udev rule instead asdescribed in the following section.

Using udev

Optionally you may choose to set up your flash drive with audev rule. There is some documentation in the Arch wikiabout that already; if you want more in­depth, structural info,read this guide

Page 36: ARCH GENTU LUCKS Encriptar Particiones

(http://reactivated.net/writing_udev_rules.html) . Here isquickly how it goes.

Get the serial number from your USB flash drive:

lsusb ­v | grep ­A 5 Vendor

Create a udev rule for it by adding the following to a file in /etc/udev/rules.d/ , such as 8­usbstick.rules :

KERNEL=="sd*", ATTRSserial=="$SERIAL", SYMLINK+="$SYMLINK%n"

Replace $SYMLINK and $SERIAL with their respective values.%n will expand to the partition (just like sda is subdividedinto sda1, sda2, ...). You do not need to go with the 'serial'attribute. If you have a custom rule of your own, you can putit in as well (e.g. using the vendor name).

Rescan your sysfs:

udevadm trigger

Now check the contents of /dev :

Page 37: ARCH GENTU LUCKS Encriptar Particiones

ls /dev

It should show your device with your desired name.

Generating the keyfile

Optionally you can mount a tmpfs for storing the temporarykeyfile.

# mkdir ./mytmpfs# mount tmpfs ./mytmpfs ­t tmpfs ­o size=32m# cd ./mytmpfs

The advantage is that it resides in RAM and not on a physicaldisk, so after unmounting your keyfile is securly gone. Socopy your keyfile to some place you consider as securebefore unmounting. If you are planning to store the keyfile asa plain file on your USB device, you can also simply executethe following command in the corresponding directory, e.g. /media/sdb1

The keyfile can be of arbitrary content and size. We willgenerate a random temporary keyfile of 2048 bytes:

# dd if=/dev/urandom of=secretkey bs=512 count=4

Page 38: ARCH GENTU LUCKS Encriptar Particiones

If you stored your temporary keyfile on a physical storage,remember to not just (re)move the keyfile later on, but usesomething like

cp secretkey /destination/pathshred ­­remove ­­zero secretkey

to securely overwrite it. (However due to journalingfilesystems this is also not 100% secure.)

Add the temporary keyfile with cryptsetup:

# cryptsetup luksAddKey /dev/sda2 secretkeyEnter any LUKS passphrase:key slot 0 unlocked.Command successful.

Storing the keyfile

To store the key file, you have two options. The first is lessrisky than the other, but perhaps a bit more secure (if youconsider security by obscurity as more secure). In any caseyou have to do some further configuration, if not alreadydone above.

Configuration of initcpio

Page 39: ARCH GENTU LUCKS Encriptar Particiones

You have to add two extra modules in your /etc/mkinitcpio.conf , one for the drive's file system andone for the codepage. Further if you created a udev rule, youshould tell mkinitcpio about it:

MODULES="ata_generic ata_piix nls_cp437 vfat"FILES="/etc/udev/rules.d/8­usbstick.rules"

In this example it is assumed that you use a FAT formattedUSB drive. Replace those module names if you use anotherfile system on your USB stick (e.g. ext2) or anothercodepage. Users running the stock Arch kernel should stick tothe codepage mentioned here.

Additionally, insert the usb hook somewhere before the encrypt hook.

HOOKS="... usb encrypt ... filesystems ..."

Generate a new image (maybe you should take a copy ofyour old kernel26.img before):

mkinitcpio ­g /boot/kernel26.img

Page 40: ARCH GENTU LUCKS Encriptar Particiones

Storing the key as plain (visible) file

Be sure to choose a plain name for your key ­ a bit of'security through obscurity' is always nice ;­). Avoid usingdots (hidden files) and similar characters ­ the encrypt hookwill fail to find the keyfile during the boot process.

You have to add a kernel parameter in your /boot/grub/menu.lst (GRUB), it should look somethinglike this:

kernel /vmlinuz26 root=/dev/hda3 ro vga=791 cryptkey=/dev/usbstick:vfat:/secretkey

This assumes /dev/usbstick is the FAT partition of yourchoice. Replace it with /dev/disk/by­... or whatever yourdevice is.

That is all, reboot and have fun!

Storing the key between MBR and 1st partition

We will write the key directly between the Master BootRecord (MBR) and the first partition.

Warning: You should only follow this step if you know

Page 41: ARCH GENTU LUCKS Encriptar Particiones

what you are doing ­­ it can cause data loss and damageyour partitions or MBR on the stick!

If you have a bootloader installed on your drive you have toadjust the values. E.g. GRUB needs the first 16 sectors(actually, it depends on the type of the file system, so do notrely on this too much), you would have to replace seek=4with seek=16 ; otherwise you would overwrite parts of yourGRUB installation. When in doubt, take a look at the first 64sectors of your drive and decide on your own where to placeyour key.

Optional If you do not know if you have enough free spacebefore the first partition, you can do

dd if=/dev/usbstick of=64sectors bs=512 count=64 # gives you copy of your first 64 sectorshexcurse 64sectors # determine free spacexxd 64sectors | less # alternative hex viewer

Write your key to the disk:

dd if=secretkey of=/dev/usbstick bs=512 seek=4

If everything went fine you can now overwrite and deleteyour temporary secretkey as noted above. You should not

Page 42: ARCH GENTU LUCKS Encriptar Particiones

simply use rm as the keyfile would only be unlinked fromyour filesystem and be left physically intact.

Now you have to add a kernel parameter in your /boot/grub/menu.lst file (GRUB); it should looksomething like this:

kernel /vmlinuz26 root=/dev/hda3 ro vga=791 cryptkey=/dev/usbstick:2048:2048

Format for the cryptkey option:

cryptkey=BLOCKDEVICE:OFFSET:SIZE

OFFSET and SIZE match in this example, but this is justcoincidence ­ they can differ (and often will). An otherpossible example could be

kernel /vmlinuz26 root=/dev/hda3 ro vga=791 cryptkey=/dev/usbstick:8192:2048

That is all, reboot and have fun! And look if your partitionsstill work after that ;­).

Encrypting the Swap partition

Page 43: ARCH GENTU LUCKS Encriptar Particiones

Encrypting Swap without Suspend Support

In systems where suspend to disk is not a desired feature, it ispossible to create a swap file that will have a randompassphrase with each boot.

This is accomplished by using dm­crypt directly withoutLUKS extensions.

Execute the following command to setup a randomlyencrypted swap partition:

# echo <device­mapper name> <swap physical partition> SWAP "­c aes­xts­plain ­h whirlpool ­s 512" >> /mnt/etc/crypttab

This command adds the following swap partition details to /mnt/etc/crypttab :

'echo' and '>> /mnt/etc/crypttab' adds thecommand to the file /mnt/etc/crypttabdirectlySWAP identifies the partition as a swappartition­c defines a cipher­h defines a hash algorithm­s defines the key size

Page 44: ARCH GENTU LUCKS Encriptar Particiones

Example (/dev/sda2 is the physical swap partition and /dev/mapper/swapmapper is the device­mapper):

echo swapmapper /dev/sda2 SWAP "­caes­xts­plain ­h whirlpool ­s 512" >>/mnt/etc/crypttab

Maps /dev/sda2 to /dev/mapper/swapmapper as a swappartition which is encrypted by AES withWhirlpool as the hash algorithm.

There are many hash algorithms that can be employed. Forfurther details, read Wikipedia:Cryptographic_hash_function.

Tip: Many people prefer Whirlpool as it is patent free. Onmodern hardware there is minimal performance differencebetween algorithms.

If the partition chosen for swap was previously a LUKSpartition, crypttab will not overwite to partition to create aswap partition. This is safetly measure to prevent data lossfrom accidental miss identification of the swap partition incrypttab. In order to use such a partition the LUKS headermust be removed. This can be accomplished by

Page 45: ARCH GENTU LUCKS Encriptar Particiones

# dd if=/dev/zero of=/dev/sdaX # where X is your swap partition number

Using UUIDs with encrypted swap partitions

If there are multiple hard drives installed in the system, theirnaming order (sda, sdb,...) can occasionally be scrambledupon boot. When /etc/rc.sysinit parses the /etc/crypttab file and sees the SWAP line, it will create anew dm­crypt mapping backed by that device partition andinitialize encrypted swap space on top of it. This operationdestroys all data on the partition, which can be catastrophic ifthe disk names have been switched upon reboot. To preventsuch mistakes on multi­drive systems, always reference diskpartitions using UUIDs rather than device names. /etc/rc.sysinit will refuse to overwrite any known filesystem, partition table, RAID/LVM volume or valid LUKSpartition.

Create a regular swap partition with a new UUID:

# mkswap /dev/sdaX # where X is your swap partition number

Note the new random UUID and edit /etc/crypttab

Page 46: ARCH GENTU LUCKS Encriptar Particiones

swap /dev/disk/by­uuid/<your UUID> SWAP ­­offset 8 ­c aes­xts­plain ­h whirlpool ­s 512

The ­­offset parameter will prevent the UUID (storedwithin the first eight 512 byte blocks) from being overwrittenby cryptsetup each time new encrypted swap space isinitialized.

Edit your /etc/rc.sysinit , find the following lines

local _overwriteokay=0if [[ ­b $2 && ­r $2 ]]; then # This is DANGEROUS! If there is any known file system, # partition table, RAID or LVM volume on the device # we do not overwrite it. # # 'blkid' returns 2 if no valid signature has been found. # Only in this case we should allow overwriting the device. # # This sanity check _should_ be sufficient, but it might not. # This may cause dataloss if it is not used carefully. blkid ­p "$2" &>/dev/null (( $? == 2 )) && _overwriteokay=1fi

and replace it with

if [[ ­b $2 && ­r $2 ]]; then # This is DANGEROUS! If there is any known file system, # partition table, RAID or LVM volume on the device

Page 47: ARCH GENTU LUCKS Encriptar Particiones

# we do not overwrite it. # # 'blkid' returns 2 if no valid signature has been found. # Only in this case we should allow overwriting the device. # # This sanity check _should_ be sufficient, but it might not. # This may cause dataloss if it is not used carefully. blkid ­p "$2" &>/dev/null (( $? == 2 )) && _overwriteokay=1

#Allow overwrite if $2 has TYPE swap(useful for LUKS swap partition using UUID) ( blkid ­p ­s TYPE "$2" 2> /dev/null | grep ­q swap) && _overwriteokay=1fi

You can now use /dev/mapper/swap as swap device in /etc/fstab .

An additional advantage of this method is that the swappartition can be shared among several operating systems, inencrypted and unencrypted forms.

Encrypted swap with suspend­to­disk support

Warning: Do not use this setup with a key file, please readabout the issue reported here

To be able to resume after suspending the computer to disk(hibernate), it is required to keep the swap filesystem intact.Therefore, it is required to have a presistent LUKS swap

Page 48: ARCH GENTU LUCKS Encriptar Particiones

partition, which can be stored on the disk or input manually atstartup. Because the resume takes place before /etc/crypttab can be used, it is required to create a hook in/etc/mkinitcpio.conf to open the swap LUKS devicebefore resuming. The following setup has the disadvantage ofhaving to insert a key manually for the swap partition.

If you want to use a partition which is currently used by thesystem, you have to disable it, first:

# swapoff /dev/<device>

To create the swap partition, follow steps similar to thosedescribed in mapping partitions above.

Format the partition you want to use as swap with the cryptsetup command. For performance reasons, youmight want to use different ciphers with different keysizes.

# cryptsetup ­c aes­xts­plain ­s 512 ­h sha512 ­v luksFormat /dev/<device>

Check result with:

# cryptsetup luksDump /dev/<device>

Page 49: ARCH GENTU LUCKS Encriptar Particiones

Open the partition in /dev/mapper :

# cryptsetup luksOpen /dev/<device> swapDevice

Create a swap filesystem inside the mapped partition:

# mkswap /dev/mapper/swapDevice

Now you should have a LUKS swap partition which asks forthe passphrase before mounting. Make sure you remove anyline in /etc/crypttab which uses this device. Now you haveto create a hook to open the swap at boot time.

Create a hook file containing the open command:

/lib/initcpio/hooks/openswap

# vim: set ft=sh: run_hook () cryptsetup luksOpen /dev/<device> swapDevice

Then create and edit the hook setup file:

Page 50: ARCH GENTU LUCKS Encriptar Particiones

/lib/initcpio/install/openswap

# vim: set ft=sh: build () MODULES="" BINARIES="" FILES="" SCRIPT="openswap" help () cat<<HELPEOF This opens the swap encrypted partition /dev/<device> in /dev/mapper/swapDevice HELPEOF

Add the hook openswap in the HOOKS array in /etc/mkinitcpio.conf , before filesystem , but afterencrypt which is mandatory as well. Do not forget toadd the resume hook between openswap and filesystem as well.

Regenerate the boot image:

# mkinitcpio ­p linux

Add the mapped partition to /etc/fstab by adding thefollowing line:

Page 51: ARCH GENTU LUCKS Encriptar Particiones

/dev/mapper/swapDevice swap swap defaults 0 0

Set­up your system to resume from /dev/mapper/swapDevice . For example, if you useGRUB with kernel hibernation support, add resume=/dev/mapper/swapDevice to the kernel line in/boot/grub/menu.lst . A line with encrypted root andswap partitions can look like this:

kernel /vmlinuz26 cryptdevice=/dev/sda2:rootDevice root=/dev/mapper/rootDevice resume=/dev/mapper/swapDevice ro

At boot time, the openswap hook will open the swap partitionso the kernel resume may use it. If you use special hooks forresuming from hibernation, make sure they are placed after openswap in the HOOKS array. Please note that because ofinitrd opening swap, there is no entry for swapDevice in /etc/crypttab needed in this case.

Installing the system

Now that /dev/mapper/root and /dev/mapper/home are inplace, we can enter the regular Arch setup script to install thesystem into the encrypted volumes.

Page 52: ARCH GENTU LUCKS Encriptar Particiones

# /arch/setup

Note: Most of the installation can be carried out normally.However, there are a few areas where it is important tomake certain selections these are marked below.

Prepare hard drive

Skip the Partitioning and Auto­Prepare business and gostraight to manually configuration. Instead of choosing thehardware devices (/dev/sdaX ) directly, you have to selectthe mapper devices created above: Choose /dev/mapper/root for your root and /dev/mapper/home as /home partition respectively and format them with anyfilesystem you like. The same is valid for a swap partitionwhich is set up like the /home partition. Make sure youmount /dev/sda1 as the /boot partition or else the installerwill not properly set up the bootloader.

Select and Install packages

Select and install the packages as usual, the base packagecontains all required programs.

Configure System

Page 53: ARCH GENTU LUCKS Encriptar Particiones

Note|The encrypt hook is only needed if your rootpartition is a LUKS partition (or for a LUKS partition thatneeds to be mounted before root). The encrypt hook is notneeded in case any other partition (swap, for example) isencrypted. System initialization scripts (/etc/rc.sysinitand /etc/crypttab among others) take care of those.

Afterwards you can check the files presented to you by theinstaller, the most important one being /etc/mkinitcpio.conf . For detailed info on mkinitcpio (andits configuration) refer to Mkinitcpio. You have to make surethat your HOOKS array in /etc/mkinitcpio.conf lookssomething like this:

HOOKS="... encrypt ... filesystems ..."

It is important that the encrypt hook comes before the filesystems one. If you store your key on an external USBdevice (e.g. a USB stick), you need to add the USB hook too:

HOOKS="... usb encrypt ... filesystems ..."

For safety, add in usb before encrypt because the hooks arerun in the order they appear. If you need support for foreign

Page 54: ARCH GENTU LUCKS Encriptar Particiones

keymaps for your encryption password, you have to specifythe hook keymap as well. I suggest to put this in /etc/mkinitcpio.conf right before encrypt .

If you have a USB keyboard, you need the usbinput hook in/etc/mkinitcpio.conf . Without it, no USB keyboard willwork in early userspace.

If your root partition is a LUKS partition, add the usedfilesystem to the MODULES section.

MODULES="... ext3 ext4 xfs ..."

Install Bootloader

GRUB: You have to make some small changes to the entriesgenerated by the installer by replacing /dev/mapper/rootwith /dev/sda3 . The corrected config looks like this:

# (0) Arch Linuxtitle Arch Linuxroot (hd0,0)kernel /vmlinuz26 root=/dev/sda3 roinitrd /kernel26.img

For kernel >= 2.6.38:

Page 55: ARCH GENTU LUCKS Encriptar Particiones

# (0) Arch Linuxtitle Arch Linuxroot (hd0,0)kernel /vmlinuz­linux cryptdevice=/dev/sda3:root root=/dev/mapper/root roinitrd /initramfs­linux.img

LILO: On Lilo, edit the Arch Linux section on /etc/lilo.conf and include a line for the append option,over the initrd, with the root=/dev/sda3 parameter. The append section make the same kernel line on GRUB. Also,you can omit the root option, over the image option. Thesection look like this:

# Arch Linux lilo sectionimage = /vmlinuz26# root = /dev/sda3 label = Arch initrd = /kernel26.img append = "root=/dev/sda3" read­only

Note: If you want to use a USB flash drive with a keyfile,you have to append the cryptkey option. See thecorresponding section below.

Exit Install

Page 56: ARCH GENTU LUCKS Encriptar Particiones

Now that the install is finished the only thing left to do is addentries to the /etc/crypttab file so you do not have to enterthe passphrase for all encrypted partitions. This works onlyfor non­root partitions e.g. /home, swap, etc.

# vi /etc/crypttab

Add the following line for the /home partition

home /dev/sda5 "myotherpassword"

You can also use a keyfile instead of a passphrase. If notalready done, create a keyfile and add the key to thecorresponding LUKS partition as described above. Then addthe following information to the /etc/crypttab file forautomounting:

home /dev/sda5 /path/of/your/keyfile

After rebooting you should now be presented with the text

A password is required to access the root filesystem:

followed by a prompt for any LUKS password. Type it in and

Page 57: ARCH GENTU LUCKS Encriptar Particiones

everything should boot. Once you've logged in, have a look atyour mounted partitions by typing mount . You should have /dev/mapper/root mounted at / and, if you set up aseparate encrypted home partition, /dev/mapper/homemounted at /home . If you set up encrypted swap, swapon ­sshould have /dev/mapper/swap listed as your swap partition.

Note: Eventually the text prompting for the password ismixed up with other boot messages. So the boot processmay seem frozen at first glance, but it is not, simply enteryour password and press return.

Remote unlocking of the root (orother) partition

If you want to be able to reboot a fully LUKS encryptedsystem remotely or start it with a Wake­on­LAN service youwill need a way to enter a passphrase for the rootpartition/volume at startup. This can be achived by runningthe net hook along with an SSH server in initrd. Install thedropbear_initrd_encrypt

(https://aur.archlinux.org/packages.php?

K=dropbear_initrd_encrypt&SeB=x) package from theAUR and follow the post­installation instructions. Replace

Page 58: ARCH GENTU LUCKS Encriptar Particiones

the encrypt hook with dropbear encryptssh in /etc/mkinitcpio.conf . Put the net hook early in theHOOKS array if your DHCP server takes a long time to leaseIP addresses.

If you simply would like a nice solution to mount otherencrypted partitions (like /home ) remotely, you may want tolook at the this forum thread(https://bbs.archlinux.org/viewtopic.php?pid=880484) .

Backup the cryptheader

If the header of your crypted partition gets destroyed, youwill not be able to decrypt your data. Therefore, having abackup of the headers and storing them on another disk mightbe a good idea.

Attention: Many people recommend NOT to backup thecryptheader, even so it's a single point failure! In short, theproblem is that LUKS is not aware of the duplicatedcryptheader, which contains the masterkey which is used toencrypt all files on your partition. Of course this masterkey isencrypted with your passphrases or keyfiles. But if one ofthose gets compromised and you want to revoke it you haveto do this on all copies of the cryptheader! I.e. if someone hasgot your cryptheader and one of your keys he can decrypt the

Page 59: ARCH GENTU LUCKS Encriptar Particiones

masterkey and access all your data. Of course the same is truefor all backups you create of your partions. So you decide ifyou are one of those paranoids brave enough to go without abackup for the sake of security or not. See also [1](http://www.saout.de/tikiwiki/tiki­slideshow.php?page=LUKSFaq&slide=1%7CLUKSFaq) [dead link 2011­09­05]for further details on this.

Note: You can also back up the header into a tmpfs/ramfsand encrypt it with gpg or whatever before writing it to aphysical disk. Of course you can wrap your encryptedbackup into another encryption layer and so on until youfeel safe enough :­)

Backup

Manually

First you have to find out the payload offset of the cryptedpartition (replace sdaX with the corresponding partition)

cryptsetup luksDump /dev/sdaX | grep "Payload offset"Payload offset: 4040

Now that you know the value, you can backup the header

Page 60: ARCH GENTU LUCKS Encriptar Particiones

with a simple dd command

dd if=/dev/sdaX of=./backup.img bs=512 count=4040

Using cryptsetup

You can also use the luksHeaderBackup command instead:

cryptsetup luksHeaderBackup /dev/sdaX ­­header­backup­file ./backup.img

Restore

Be careful before restore: make sure that you chose the rightpartition (again replace sdaX with the correspondingpartition). Restoring the wrong header or restoring to anunencrypted partition will cause data loss.

Manually

Again, you will need to the same values as when backuping:

dd if=./backup.img of=/dev/sdX bs=512 count=4040

Page 61: ARCH GENTU LUCKS Encriptar Particiones

Using cryptsetup

Or you can use the luksHeaderRestore command:

cryptsetup luksHeaderRestore /dev/sdaX ­­header­backup­file ./backup.img

Note: All the keyslot areas are overwritten, only activekeyslots from backup file are available after issuing thiscommand.

Encrypting a loopback filesystem

[This paragraph has been merged from another page; itsconsistency with the other paragraphs should be improved]

Preparation and mapping

First, start start by creating an encrypted container!

dd if=/dev/urandom of=/bigsecret bs=1M count=10

This will create the file bigsecret with a size of 10megabytes.

Page 62: ARCH GENTU LUCKS Encriptar Particiones

losetup /dev/loop0 /bigsecret

This will create the device node /dev/loop0 , so that we canmount/use our container.

Note: If it gives you the error /dev/loop0: No such file or directory , you need tofirst load the kernel module with modprobe loop .

cryptsetup luksFormat /dev/loop0

This will ask you for a password for your new container file.

Note: If you get an error like Command failed: Failed tosetup dm­crypt key mapping. Check kernel for

support for the aes­cbc­essiv:sha256 cipher spec

and verify that /dev/loop0 contains at least 133

sectors , then run modprobe dm­mod .

cryptsetup luksOpen /dev/loop0 secret

The encrypted container is now available through the devicefile /dev/mapper/secret . Now we are able to create apartition in the container:

Page 63: ARCH GENTU LUCKS Encriptar Particiones

mkfs.ext2 /dev/mapper/secret

and mount it...

mkdir /mnt/secretmount ­t ext2 /dev/mapper/secret /mnt/secret

We can now use the container as if it was a normal partition!To unmount the container:

umount /mnt/secretcryptsetup luksClose secretlosetup ­d /dev/loop0 # free the loopdevice.

so, if you want to mount the container again, you just applythe following commands:

losetup /dev/loop0 /bigsecretcryptsetup luksOpen /dev/loop0 secretmount ­t ext2 /dev/mapper/secret /mnt/secret

Encrypt using a key­file

Let us first generate a 2048 byte random keyfile:

dd if=/dev/urandom of=keyfile bs=1k count=2

Page 64: ARCH GENTU LUCKS Encriptar Particiones

We can now format our container using this key

cryptsetup luksFormat /dev/loop0 keyfile

or our partition :

cryptsetup luksFormat /dev/hda2 keyfile

Once formatted, we can now open the LUKS device usingthe key:

cryptsetup ­d keyfile luksOpen /dev/loop0 container

You can now like before format the device /dev/mapper/container with your favorite filesystem andthen mount it just as easily.

The keyfile is now the only key to your file. I personallyadvise to encrypt your keyfile using your private GPG keyand storing an off­site secured copy of the file.

Resizing the loopback filesystem

Page 65: ARCH GENTU LUCKS Encriptar Particiones

First we should unmount the encrypted container:

umount /mnt/secretcryptsetup luksClose secretlosetup ­d /dev/loop0 # free the loopdevice.

After this we need to create a second file with the size of thedata we want to add:

dd if=/dev/urandom of=zeros bs=1M count=1024

You could use /dev/zero instead of /dev/urandom tosignificantly speed up the process, but /dev/zero yourencrypted filesystems will not be as secure.

Next we need to add the created file to our container. Becareful to really use TWO > , or you will override yourcurrent container!

cat zeros >> /bigsecret

Now we have to map the container to the loopdevice:

losetup /dev/loop0 /bigsecretcryptsetup luksOpen /dev/loop0 secret

Page 66: ARCH GENTU LUCKS Encriptar Particiones

After this we will resize the encrypted part of the container tothe maximum size of the container file:

cryptsetup resize secret

Finally, we can resize the filesystem. Here is an example forext2/3/4:

e2fsck ­f /dev/mapper/secret # Just doing a filesystem check, because it's a bad idea to resize a broken fsresize2fs /dev/mapper/secret

You can now mount your container again:

mount /dev/mapper/secret /mnt/secret

Encrypting a LVM setup

It's really easy to use encryption with LVM. If you do notknow how to set up LVM, then readInstalling_with_Software_RAID_or_LVM.

The easiest and best method is to set up LVM on top of theencrypted partition instead of the other way around. This linkhere is easy to follow and explains everything: Arch Linux:

Page 67: ARCH GENTU LUCKS Encriptar Particiones

LVM on top of an encrypted partition(http://www.pindarsign.de/webblog/?p=767)

The most important thing in setting LVM on top ofencryption is that you need to have the encrypt hook beforethe lvm2 hook (and those two before the filesystems hook,but that's repeating) because they are processed in order.

To use encryption on top of LVM, you have to first set upyour LVM volumes and then use them as the base for theencrypted partitions. That means in short that you have to setup LVM first. Then follow this guide, but replace alloccurrences of /dev/sdXy in the guide with its LVMcounterpart. (eg: /dev/sda5 ­> /dev/<volume group name>/home ).

Do not forget to add the encrypt hook in /etc/mkinitcpio.conf before the lvm2 hook, if you choseto set up encrypted partitions on top of LVM. Also rememberto change USELVM in /etc/rc.conf to "yes" .

LVM with Arch Linux Installer (>2009.08)

Since Arch Linux images 2009.08, LVM and dm_crypt issupported by the installer out of the box. This makes it veryeasy to configure your system for LVM on dm­crypt or vice

Page 68: ARCH GENTU LUCKS Encriptar Particiones

versa. Actually the configuration is done exactly as withoutLVM, see the corresponding section above. It differs only intwo aspects.

The partition and filesystem choice

Create a small, unencrypted boot partition and use theremaining space for a single partition which can later be splitup into multiple logic volumes by LVM.

For a LVM­on­dm­crypt system set up the filesystems andmounting points for example like this:

/dev/sda1 raw­>ext2;yes;/boot;no_opts;no_label;no_params/dev/sda2 raw­>dm_crypt;yes;no_mountpoint;no_opts;sda2crypt;­c_aes­xts­plain_­y_­s_512/dev/mapper/sda2crypt dm_crypt­>lvm­vg;yes;no_mountpoint;no_opts;no_label;no_params/dev/mapper/sda2crypt+ lvm­pv­>lvm­vg;yes;no_mountpoint;no_opts;cryptpool;no_params/dev/mapper/cryptpool lvm­vg(cryptpool)­>lvm­lv;yes;no_mountpoint;no_opts;cryptroot;10000M|lvm­lv;yes;no_mountpoint;no_opts;crypthome;20000M/dev/mapper/cryptpool­cryptroot lvm­lv(cryptroot)­>ext3;yes;/;no_opts;cryptroot;no_params/dev/mapper/cryptpool­crypthome lvm­lv(crypthome)­>ext3;yes;/home;no_opts;cryptroot;no_params

The configuration stage

In /etc/rc.conf set USELVM to "yes"In /etc/mkinitcpio.conf add the encrypt hookbefore the lvm2 hook in the HOOKS array, if you set upLVM on top of the encrypted partition.

Page 69: ARCH GENTU LUCKS Encriptar Particiones

That is it for the LVM & dm_crypt specific part. The rest isdone as usual.

Applying this to a non­root partition

You might get tempted to apply all this fancy stuff to a non­root partition. Arch does not support this out of the box,however, you can easily change the cryptdev and cryptnamevalues in /lib/initcpio/hooks/encrypt (the first one toyour /dev/sd* partition, the second to the name you want toattribute). That should be enough.

The big advantage is you can have everything automated,while setting up /etc/crypttab with an external key file(i.e. the keyfile is not on any internal hard drive partition) canbe a pain ­ you need to make sure the USB/FireWire/...device gets mounted before the encrypted partition, whichmeans you have to change the order of /etc/fstab (at least).

Of course, if the cryptsetup(https://www.archlinux.org/packages/?

name=cryptsetup) package gets upgraded, you will have tochange this script again. However, this solution is to bepreferred over hacking /etc/rc.sysinit or similar files.Unlike /etc/crypttab , only one partition is supported, butwith some further hacking one should be able to have

Page 70: ARCH GENTU LUCKS Encriptar Particiones

multiple partitions unlocked.

If you want to do this on a software RAID partition, there isone more thing you need to do. Just setting the /dev/mdXdevice in /lib/initcpio/hooks/encrypt is not enough; the encrypt hook will fail to find the key for some reason, andnot prompt for a passphrase either. It looks like the RAIDdevices are not brought up until after the encrypt hook isrun. You can solve this by putting the RAID array in /boot/grub/menu.lst , like

kernel /boot/vmlinuz26 md=1,/dev/hda5,/dev/hdb5

If you set up your root partition as a RAID, array you willnotice the similarities with that setup ;­). GRUB can handlemultiple array definitions just fine:

kernel /boot/vmlinuz26 root=/dev/md0 ro md=0,/dev/sda1,/dev/sdb1 md=1,/dev/sda5,/dev/sdb5,/dev/sdc5

LVM and dm­crypt manually (short version)

Notes

If you are enough smart enough for this, you will be smart

Page 71: ARCH GENTU LUCKS Encriptar Particiones

enough to ignore/replace LVM­specific things, if you do notwant to use LVM.

Note: This brief uses reiserfs for some of the partitions, sochange this accordingly if you want to use a more "normal"file system, like ext4.

Partitioning scheme

/dev/sda1 ­> /boot/dev/sda2 ­> LVM

The commands

cryptsetup ­d /dev/random ­c aes­xts­plain ­s 512 create lvm /dev/sda2dd if=/dev/urandom of=/dev/mapper/lvmcryptsetup remove lvmlvm pvcreate /dev/sda2lvm vgcreate lvm /dev/sda2lvm lvcreate ­L 10G ­n root lvmlvm lvcreate ­L 500M ­n swap lvmlvm lvcreate ­L 500M ­n tmp lvmlvm lvcreate ­l 100%FREE ­n home lvmcryptsetup luksFormat ­c aes­xts­plain ­s 512 /dev/lvm/rootcryptsetup luksOpen /dev/lvm/root rootmkreiserfs /dev/mapper/rootmount /dev/mapper/root /mntdd if=/dev/zero of=/dev/sda1 bs=1Mmkreiserfs /dev/sda1mkdir /mnt/boot

Page 72: ARCH GENTU LUCKS Encriptar Particiones

mount /dev/sda1 /mnt/bootmkdir ­p ­m 700 /mnt/etc/luks­keysdd if=/dev/random of=/mnt/etc/luks­keys/home bs=1 count=256

Install Arch Linux

Run /arch/setup

Configuration

/etc/rc.conf

Change USELVM="no" to USELVM="yes" .

/etc/mkinitcpio.conf

Put lvm2 and encrypt (in that order) before filesystems inthe HOOKS array. Again, note that you are setting encryptionon top of LVM.)

/boot/grub/menu.lst

Change root=/dev/hda3 to root=/dev/lvm/root .

For kernel >= 2.6.30, you should change root=/dev/hda3 to

Page 73: ARCH GENTU LUCKS Encriptar Particiones

the following:

cryptdevice=/dev/lvm/root:root root=/dev/mapper/root

/etc/fstab

/dev/mapper/root / reiserfs defaults 0 1/dev/sda1 /boot reiserfs defaults 0 2/dev/mapper/tmp /tmp tmpfs defaults 0 0/dev/mapper/swap none swap sw 0 0

/etc/crypttab

swap /dev/lvm/swap SWAP ­c aes­xts­plain ­h whirlpool ­s 512tmp /dev/lvm/tmp /dev/urandom ­c aes­xts­plain ­s 512

After rebooting

The commands

cryptsetup luksFormat ­c aes­xts­plain ­s 512 /dev/lvm/home /etc/luks­keys/homecryptsetup luksOpen ­d /etc/luks­keys/home /dev/lvm/home homemkreiserfs /dev/mapper/homemount /dev/mapper/home /home

Page 74: ARCH GENTU LUCKS Encriptar Particiones

/etc/crypttab

home /dev/lvm/home /etc/luks­keys/home

/etc/fstab

/dev/mapper/home /home reiserfs defaults 0 0

/ on LVM on LUKS

Make sure your kernel command line looks like this:

root=/dev/mapper/<volume­group>­<logical­volume> cryptdevice=/dev/<luks­part>:<volume­group>

For example:

root=/dev/mapper/vg­arch cryptdevice=/dev/sda4:vg

Or like this:

cryptdevice=/dev/<volume­group>/<logical­volume>:root root=/dev/mapper/root

Page 75: ARCH GENTU LUCKS Encriptar Particiones

Resources

Setup Archlinux on top of raid, LVM2 and encryptedpartitions(http://yannickloth.be/blog/2010/08/01/installing­archlinux­with­software­raid1­encrypted­filesystem­and­lvm2/)FreeOTFE (http://www.freeotfe.org/) ­ Supportsunlocking LUKS encrypted volumes in MicrosoftWindows.

Retrieved from "https://wiki.archlinux.org/index.php?title=System_Encryption_with_LUKS&oldid=172641"Categories: Security (English) File systems (English)Linkrot

This page was last modified on 7 December 2011, at15:47.Content is available under GNU Free DocumentationLicense 1.2.