Encrypted Volumes in WSL2
This is a quick guide on how to setup dm_crypt under WSL2 for working with encrypted volumes. I use an encrypted volume to store things like password recovery codes and 2nd factor backup codes etc. I recently switched over to using WSL2 and wanted to figure out how to enable this functionality there. This is the distilled howto for getting it to work.
First thing you have to do is create a custom WSL2 kernel. Inside your already installed and running WSL2 (ubuntu) installation:
- Install some required packages.
$ sudo apt install build-essential flex bison libssl-dev libelf-dev libncurses5-dev git
- Clone the WSL2 kernel
$ git clone https://github.com/microsoft/WSL2-Linux-Kernel.git $ cd WSL2-Linux-Kernel
- Export the current (running) kernel configuration
$ cat /proc/config.gz | gunzip > .config
- Edit the .config file replacing...
#CONFIG_DM_CRYPT is not set with CONFIG_DM_CRYPT=y
- Compile the kernel
$ sudo make $ sudo make modules_install
- Copy the resulting kernel image out to your Windows Drive
$ cp ./arch/x86_64/boot/bzImage /mnt/c/Users/<your username>
- Create a .wslconfig
$ vim /mnt/c/Users/<your user name>/.wslconfig [wsl2] kernel=C:\\Users\\<your user name>\\bzImage swap=0 localhostForwarding=true
- Exit and Restart WSL2 (In powershell)
PS C:\Users\<your user name>\wsl --shutdown
Using the New Feature
Now you should be able to create open and close encrypted disks
- Create an encrypted disk image file
$ fallocate -l 1024M mysecrets.img $ sudo cryptsetup -y luksFormat mysecrets.img
- Open the newly created disk image
$ sudo cryptsetup open mysecrets.img mysecrets
- give the new disk a filesystem (you only have to do this once)
$ sudo mkfs.ext4 /dev/mapper/mysecrets
- Mount the new disk image
$ mkdir -p ~/mysecrets $ sudo mount -t ext4 /dev/mapper/mysecrets ~/mysecrets
- When you are done using the encrypted disk
$ sudo umount ~/mysecrets $ sudo cryptsetup close mysecrets
When you want to use it again just open and mount it again.