Jérôme Belleman
Home  •  Tools  •  Posts  •  Talks  •  Travels  •  Graphics  •  About Me

Encrypted filesystems, loop devices, cryptsetup

5 Mar 2011

The GNU Privacy Guard is a common tool for encrypting files. An alternative approach for encrypting file hierarchies involves encrypting entire filesystems.

Encrypting whole hierarchies of files typically means tarring them up and encrypting the tarball, which quickly becomes cumbersome. A more natural approach would be altogether encrypting filesystem files.

1 Procedure

This is loosely based on a recipe suggested in the Debian reference. We're supposed to use a command called cryptsetup to cover the basic operations. This command normally only deals with devices, not regular files. A workaround is to associate a loop device with a regular file.

  1. Start by creating a file to hold the filesystem. You may want to use /dev/urandom as input file as shown here:

    dd if=/dev/urandom of=secrets bs=1M count=4
    I also once gave /dev/random a spin, as suggested in some Debian README file, but I couldn't get the filesystem size I wanted and it was impossibly slow.
  2. Map a loop device to the file for cryptsetup to use with losetup, as shown here:

    losetup /dev/loop0 secrets
    You can check if it worked with losetup -a. If you happen to get an error looking like ioctl: LOOP_SET_FD: Device or resource busy but the loop device doesn't look busy, it may be because a kernel module still has a grab on it (e.g. if you've previously been playing around with cryptoloop).
  3. Initialise the LUKS partition with this command, which will ask for a passphrase.

    cryptsetup luksFormat /dev/loop0
  4. Map the newly-initialised LUKS partition to a device which should encouragingly show up as /dev/mapper/secrets. You'll be asked for the passphrase you just supplied:

    cryptsetup luksOpen /dev/loop0 secrets
  5. You may now treat the mapped device as pretty much any block device and, for instance, write any filesystem of your liking to it. For instance, write an ext2 filesystem, which is suitably compact for small block devices:

    mkfs.ext2 /dev/mapper/secrets
    mount /dev/mapper/secrets mp
    Likewise, you may want to try and mount it to check that everything is fine. Now may also be a good time to change ownership of the root directory.
  6. Once you are done, you should of course unmount the filesystem:

    umount mp
    cryptsetup luksClose secrets
    losetup -d /dev/loop0

    You may then remove the device mapping and detach the file mapped with the loop device.

2 References