Create encrypted and redundant storage with btrfs and LUKS
Use btrfs for redundancy on the filesystem level and LUKS for encryption. The raid1 mode of btrfs differs from classical raid 1 as btrfs stores 2 copies of each block on 2 different devices, not a copy of each block on each device. Btrfs may also be configured to store 3 or 4 copies of each block with modes raid1c3 and raid1c4. Disks don’t have to be equal in size, however, with 2 copies of each block no disk can provide more than 50% of the total capacity.
One can either encrypt the entire disk or create and encrypt a partition. The former is less complex, the later let’s us more easily identify the disk as not empty.
If desired, create a partition with type 0x83 on each disk that should be used for the pool.
Setup encrypted disk/partition, partitions /dev/sd[a-c]1 used in this example
1
2
3
| $ sudo cryptsetup luksFormat --type luks2 /dev/sda1
$ sudo cryptsetup luksFormat --type luks2 /dev/sdb1
$ sudo cryptsetup luksFormat --type luks2 /dev/sdc1
|
Add second keys for automatic decryption during boot. Assumption: The storage to be created will not be the boot device and the boot device itself is also encrypted.
1
2
3
4
5
6
7
8
9
| $ sudo mkdir -p /etc/secrets && sudo chmod 700 /etc/secrets
$ sudo dd if=/dev/urandom of=/etc/secrets/pool0-key bs=4k count=1
$ sudo dd if=/dev/urandom of=/etc/secrets/pool1-key bs=4k count=1
$ sudo dd if=/dev/urandom of=/etc/secrets/pool2-key bs=4k count=1
$ sudo cryptsetup luksAddKey /dev/sda1 /etc/secrets/pool0-key
$ sudo cryptsetup luksAddKey /dev/sdb1 /etc/secrets/pool1-key
$ sudo cryptsetup luksAddKey /dev/sdc1 /etc/secrets/pool2-key
|
Get disk/partition UUIDs
1
2
3
| $ sudo blkid /dev/sda1
$ sudo blkid /dev/sdb1
$ sudo blkid /dev/sdc1
|
Edit /etc/crypttab to decrypt disks/partitions during boot
1
2
3
4
| ...
pool0_crypt UUID=5a9200f3-d967-47d5-b897-4471d4969d1f /etc/secrets/pool0-key luks
pool1_crypt UUID=022ad8d6-06ff-4eac-b2a7-3502f8f48daa /etc/secrets/pool1-key luks
pool2_crypt UUID=af64274e-69b1-4870-8ee7-8a21f0e2ee11 /etc/secrets/pool2-key luks
|
Mount encrypted disks/partitions manually or reboot
1
2
3
| $ sudo cryptsetup luksOpen -d /etc/secrets/pool0-key /dev/sda1 pool0_crypt
$ sudo cryptsetup luksOpen -d /etc/secrets/pool1-key /dev/sdb1 pool1_crypt
$ sudo cryptsetup luksOpen -d /etc/secrets/pool2-key /dev/sdc1 pool2_crypt
|
Create btrfs filesystem, use 2 copies for both data (-d) and metadata (-m)
1
| $ sudo mkfs.btrfs --csum blake2 -m raid1 -d raid1 /dev/mapper/pool0_crypt /dev/mapper/pool1_crypt /dev/mapper/pool2_crypt
|
Edit /etc/fstab to mount storage during boot, doesn’t matter which pool device is used
1
2
| ...
/dev/mapper/pool0_crypt /mnt/pool btrfs defaults 0 2
|