HOWTO: Automatically Unlock LUKS Encrypted Drives With A Keyfile

Author: Stephan Jau
Revision: v1.0
Last Change: July 3 2008


Well, I have written so far two tutorials with LUKS/dm_crypt involved. First one was how to enable encryption on Feisty Fawn (wasn't included back then by default) and the other one was how to reboot/unlock through a remote connection.

This howto was then written because of a question in the second howto. The problem there was how to unlock multiple devices in the intial ramdisk remotely. I suggested instead to use a keyfile for automatic unlocking. The keyfile should be stored in the normally encrypted root partition - so you still have to unlock that one. During boot process it will then be used to unlock all the other devices.

Of course one could also use an encrypted LVM so that all space is encrypted but only one password is required. I have not seen a usage for LVM so far and it seems, that others do not also but prefer to have individual encrypted devices. That way you could easily move an encrypted harddisk to another computer. I'm not sure if that works with LVM encrypted drives also because I have no experience with it.

One might ask how secure is this setup? I'd say pretty safe. During this howto the keyfile will be made read-only to root. So, if someone can access the keyfile you have more serious problems anyway on your computer.


Step 1: Create a random keyfile

sudo dd if=/dev/urandom of=/root/keyfile bs=1024 count=4

This will create a file with random content with the size of 4096 bits (better than a 20/30 character password....). You can use any file to act as keyfile but I think a 4kb file with random content is good suited.


Step 2: Make the keyfile read-only to root

sudo chmod 0400 /root/keyfile

That will make the keyfile readable only by root. If someone get access to this keyfile, then you have a bigger problem on your computer anyway.

Alternatively chown your desired keyfile to root:root and move it into the /root folder


Step 3: Add the keyfile to LUKS

LUKS/dm_crypt enabled devices may hold up to 10 different keyfiles/passwords. So, next to having the already setup password we're going to add this keyfile as additional authorization method.

sudo cryptsetup luksAddKey /dev/sdX /root/keyfile

sdX is of course your LUKS device.

First you'll be prompted to enter an (existing) password to unlock the drive. If everything works well, you should get an output like this:

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


Step 4: Create a mapper

LUKS devices need to create a mapper that can then be referenced in the fstab. Open /etc/crypttab

sudo nano /etc/crypttab

and add then a line like this:

sdX_crypt      /dev/sdX  /root/keyfile  luks

or you can use the UUID of the device:

sdX_crypt      /dev/disk/by-uuid/247ad289-dbe5-4419-9965-e3cd30f0b080  /root/keyfile  luks

sdX_crypt is the name of the mapper that is being created. You can use here any name e.g. "music" or "movies" or "sfdsfawe" ....

Save and close the file by issuing ctrl-x, enter, enter. Ctrl-x closes nano but first it asks to save the file [yes = enter] and what the name shall be [same name = enter].

What we have done there actually is telling that /root/keyfile shall be used instead of password entry to unlock the drive.


Step 5: Mount the device in fstab

Now, we have an unlocked device (well, not yet but when the system is being booted up) and we just need to mount it now. Open /etc/fstab:

sudo nano /etc/fstab

and add a new entry like:

/dev/mapper/sdX_crypt  /media/sdX     ext3    defaults        0       2

Make sure you have the correct mapper name that you added in step 4. Also make sure that the mount point/folder exists. After having added it, save again the file and close it (ctrl-x, enter, enter).


Step 6: Reboot or remount

That's it. Now you can reboot and the additional devices should be auto-unlocked and mounted. You can also test it by remounting all devices:

sudo mount -a

Share this page:

16 Comment(s)

Add comment


From: Mike

One reason this is still useful is to protect a USB device that might get stolen. This way it would be auto-mounted, and then if it's ever stolen you're covered. It seems logical enough to me!

From: Philip Jägenstedt

Unless the root file system is encrypted this is a terrible idea. Everything that encryption protects you against would be negated. Somebody who gains remote access to your computer wouldn't need the keys since the disks would probably already be mounted. If, on the other hand, somebody gets local access (for example by stealing your disks) then the permissions on the file doesn't matter at all, the data is there on the disk and can be read by simply putting it in another computer. Don't store the keyfiles unencrypted unless the medium itself is reasonably safe (e.g. stored in a bank vault)

From: Stephan

A Bank vault is not a safe place anymore!


From the howto: "The keyfile should be stored in the normally encrypted root partition - so you still have to unlock that one."

From: Anonymous

from the reply: "Somebody who gains remote access to your computer wouldn't need the keys since the disks would probably already be mounted"

that means they ARE unlocked already when a bad guy comes in.

From: Tof

This is exactly what I wanted (my USB drives are crypted in case they are stolen but as long they are on the server, I don't care), but I had an issue on Fedora with USB drives.

At boot time /etc/rc.d/rd.sysinit should use fstab and crypttab to issue a luksOpen. The issue is that at that time the usb drive is not yet detected in /dev/disk/by-uuid. The only solution I found here so far, is to add a delay before using cryptsetup. For that I have created a module (/etc/sysconfig/modules/waitForExtraDrives.modules) that wait for extra disk(s) with a timeout of 10s. This module will be run automatically by /etc/rc.d/rd.sysinit before trying to mount crypted drives (TBD: We should find an other solution !):




echo -n "Waiting for extra disk(s) to be detected: "
while [ $(ls /dev/disk/by-uuid/ 2>/dev/null | wc -l) -le ${nbInternalDrives} -a ${count} -lt ${timeout} ]
       count=$(( $count + 1 ))
       echo -n "."
       sleep 1
if [ $(ls /dev/disk/by-uuid/ 2>/dev/null | wc -l) -gt ${nbInternalDrives} ]
       echo " Done"
       echo " TimeOut"

From: Anonymous

I tried pretty hard to get this tutorial to work, but I could never get the mapper to work no matter how I tried.

I eventually wrote a script that lived in /etc/rc.local, and that ran the cryptsetup luksOpen command manually upon boot. That worked pretty well until the system crashed (for another reason), and now the USB drive seems to be shot. I'm guessing the encrypted partition needed to be properly closed, not crashed.

In any case, this config is simply too complicated. Looks like I'll have to live with a lack of encryption on my backup drive...for now.

From: prairiedog

I have a Mythbuntu PVR which does double duty as a backup device because it has extra disk space, but it's a sitting duck in case of a break-in.  If it ever went missing then it would be preferable if the personal data on it became inaccessible.

It should work to encrypt the volume and put the keyfile elsewhere on the network, like on a server in a closet.  Even if both machines went missing, the odds of a thief figuring the system out are pretty low.

From: Anonymous

This would be a useful technique for me, if it could be adapted to work within an initrc for booting. Then, if a computer is plugged into my network, I could do a network boot that would supply the keyfile, and the boot could proceed automatically. If the computer was not plugged into my network, I could boot from the local hard drive and supply a manual decryption key. I suppose someone could also do something similar with a USB stick. Even better would be if there was a way to require 2 out of 3. Either it is plugged into my network and I have the USB stick, or I supply the password. Or it is not plugged into my network and I need both the USB stick and the password. Bill

From: Anonymous

In step 3, I don't get any confirmation, even though the keyfile is successfully added. (Xubuntu 12.04, cryptsetup 1.4.1).

 And, sudo mount -a won't mount it in my case, only reboot helped.

From: agubernatorov

I was using russian ecryption instruction

From: Anonymous

I'd not use /dev/urandom for key file generation. Those few bytes should better be squeezed out of /dev/random I think.


From: David Rader

To mount your new partition without rebooting you can use cryptdisks_start to decrypt the partition specified in /etc/crypttab and create your mapper device. From your example above, Step 4b would be: * decrypt the encrypted partition and create the mapper device: $ cryptdisks_start sdX_crypt * mount the decrypted partition (mapper device) $ mount /media/sdX Its also worth pointing out that if you use the UUID in the /etc/crypttab to identify your encrypted partition it cannot have doublequotes surrounding the UUID (e.g. the standard output of `blkid /dev/sdX1`).

From: Brent

Doing everything listed in your tutorial, verbatim... except for changing certain parameters for device names. Not working for me.

From: Carlo Wood

I thought I'd add the following information here, now that I figured out how to do that.

I have my keyfiles on a non-root partition, so when upstart is started that partition isn't already mounted (like root is). This gives a problem: you need to unlock AND mount the encrypted partition with the keyfiles before you attempt to unlock the other encrypted partitions, something that isn't supported out of the box.

What I ended up doing is the following: I added 'noauto' to for those partitions to both /etc/fstab as well as /etc/crypttab (next to specifying the keyfiles in /etc/crypttab of course). For example, my crypttab ends on:

# Using 'noauto' because these are unlocked and mounted from /etc/init/mounted-encrypted.conf.

ata-OCZ-VERTEX4_OCZ-5T94F27KZ830YPJT-part8_crypt /dev/disk/by-uuid/2fcd8841-aae5-4d5f-9d91-78275e74689b /encrypted/.homekeyfile luks,noauto

ata-WDC_WD40EFRX-68WT0N0_WD-WCC4E7CR9HX8-part1_crypt /dev/disk/by-uuid/39e8aa7e-d87a-4fd6-a91f-48b8dd96df7e /encrypted/.epickeyfile luks,noauto


And then I added the following file as /etc/init/mounted-encrypted.conf :


# mounting-encrypted - Decrypt and mount depending filesystems.


# Written by Carlo Wood - 2016.


# Start crypt disks that have their key stored on /encrypted.


description     "Mount other crypted filesystems"


start on mounted MOUNTPOINT=/encrypted





    PARTS="$(cat /etc/crypttab | sed -e 's/#.*//' | grep 'noauto' | sed -e 's%  *%|%;s% .*%%' | sed -e ':a;N;$!ba;s/\n/ /g')"

    for p in $PARTS; do

      NAME="$(echo $p | sed -e 's/|.*//')"

      DEVICE="$(echo $p | sed -e 's/.*|//')"

      if [ ! -e "/dev/mapper/$NAME" ]; then

        echo "/dev/mapper/$NAME does not exist. Attempting to create it..."

        cryptdisks_start "$NAME"


      if ! grep "^/dev/mapper/$NAME " /proc/mounts >/dev/null; then

        echo "/dev/mapper/$NAME is not mounted. Attempting to mount it..."

        mount "/dev/mapper/$NAME" && echo "Success"



end script


Note that those echo's (and possible errors) end up in /var/log/upstart/mounted-encrypted.log

For example, I get:

/dev/mapper/ata-OCZ-VERTEX4_OCZ-5T94F27KZ830YPJT-part8_crypt does not exist. Attempting to create it...

 * ata-OCZ-VERTEX4_OCZ-5T94F27KZ830YPJT-part8_crypt (starting)..

 * ata-OCZ-VERTEX4_OCZ-5T94F27KZ830YPJT-part8_crypt (started)...         [ OK ]  * Starting crypto disk...       

/dev/mapper/ata-OCZ-VERTEX4_OCZ-5T94F27KZ830YPJT-part8_crypt is not mounted. Attempting to mount it...


/dev/mapper/ata-WDC_WD40EFRX-68WT0N0_WD-WCC4E7CR9HX8-part1_crypt does not exist. Attempting to create it...

 * ata-WDC_WD40EFRX-68WT0N0_WD-WCC4E7CR9HX8-part1_crypt (starting)..

 * ata-WDC_WD40EFRX-68WT0N0_WD-WCC4E7CR9HX8-part1_crypt (started)...     [ OK ]  * Starting crypto disk...       

/dev/mapper/ata-WDC_WD40EFRX-68WT0N0_WD-WCC4E7CR9HX8-part1_crypt is not mounted. Attempting to mount it...



From: TheFuzzyFish

I did my setup slightly differently. I use my Raspberry Pi at home as an SFTP (SSHFS) server to use as a cloud server in an encrypted fashion, but it occurred to me that someone could easily pick up the Pi and have all of my data. My preferred method of encryption is LUKS with Cryptsetup, so a lot of this is the same for me. The following method only protects your information if the LUKS device is taken from the Raspberry Pi (or whereever you put it). If they take the whole unit, your data is vulnerable because they'd have access to the keyfile.

First, I made my keyfile in the same manner this tutorial shows, but I extended my keyfile to be 1 megabyte of /dev/urandom as opposed to 4 kilobytes.

I configured my LUKS drive to have a secondary 256 character password that I can remember just in case I lose my keyfile

I connected the drive to my Raspberry Pi and gathered the necessary data to manually unlock the drive with Cryptsetup using fdisk

I edited /etc/rc.local with nano (just because I prefer it over vim) and entered the following lines:

   cryptsetup open /dev/sda1 cryptstorage -d /root/keyfile

   mount /dev/mapper/cryptstorage /mnt/cryptstorage

These commands unlock the device under the mapping "cryptstorage", then mounts it under the /mnt/ directory for easy access via sshfs.

The only reason that this method works is because LUKS uses transparent encryption, meaning whenever you access the data, it is unencrypted live, not all at once. This means that, while you have the device mounted and you can edit the filesystem, even if you quickly pull out the drive, all data is still encrypted. Of course, if they were to steal my Raspberry Pi (which I have prevented from happening) or the SD card which runs it (which I have also prevented), all they would have to do is plug it in and boot up the machine, and the encrypted device would already be mapped and mounted. Only use this method if you know all the implications.