Wednesday, April 25, 2012

Encrypt Partitions with dm-crypt LUKS


Encrypt Partitions with dm-crypt LUKS

These instructions use the Linux dm-crypt (device-mapper) facility available on the 2.6 kernel. In this example, lets encrypt the partition /dev/sdc1, it could be however any other partition or disk, or USB or a file based partition created with losetup. In this case we would use /dev/loop0. The device mapper uses labels to identify a partition. We use sdc1 in this example, but it could be any string.

dm-crypt with LUKS

LUKS with dm-crypt has better encryption and makes it possible to have "multiple passphrase" for the same partition or to change the password easily. To test if LUKS is available, simply type

# cryptsetup --help

if nothing about LUKS shows up, use the instructions below Without LUKS. First create a partition if necessary:

# fdisk /dev/sdc

Create encrypted partition

# dd if=/dev/urandom of=/dev/sdc1          # Optional. For paranoids only (takes days)
# cryptsetup -y luksFormat /dev/sdc1       # This destroys any data on sdc1
# cryptsetup luksOpen /dev/sdc1 sdc1
# mkfs.ext3 /dev/mapper/sdc1               # create ext3 file system
# mount -t ext3 /dev/mapper/sdc1 /mnt
# umount /mnt
# cryptsetup luksClose sdc1                # Detach the encrypted partition

Attach

# cryptsetup luksOpen /dev/sdc1 sdc1
# mount -t ext3 /dev/mapper/sdc1 /mnt

Detach

# umount /mnt
# cryptsetup luksClose sdc1

Using multiple passphrase for same partition

We can store another password in a file (say ~mitesh/temp/key_file.txt) and use it.

# cryptsetup luksAddKey /dev/sdc1 ~mitesh/temp/key_file.txt 
Enter any passphrase: 
# cryptsetup luksOpen --key-file  ~mitesh/temp/key_file.txt /dev/sdc1 sdc1

dm-crypt without LUKS

# cryptsetup -y create sdc1 /dev/sdc1      # or any other partition like /dev/loop0
# dmsetup ls                               # check it, will display: sdc1 (254, 0)
# mkfs.ext3 /dev/mapper/sdc1               # This is done only the first time!
# mount -t ext3 /dev/mapper/sdc1 /mnt
# umount /mnt/
# cryptsetup remove sdc1                   # Detach the encrypted partition

Do exactly the same (without the mkfs part!) to re-attach the partition. If the password is not correct, the mount command will fail. In this case simply remove the map sdc1 (cryptsetup remove sdc1) and create it again.

No comments: