I have a shell script I’m trying to bundle into a derivation. However, my shell script requires a loopback device (Stage 3 below) and it doesn’t seem like these are available in the nix-build
sandbox.
What’s the best way to accomplish what I want?
default.nix
{ pkgs ? (import <nixpkgs> {}) }:
pkgs.stdenv.mkDerivation {
name = "enc_squashfs.img";
squashFile = ./file.squashfs;
nativeBuildInputs = with pkgs; [ squashfsTools cryptsetup utillinux];
buildCommand = ./mkencsquashfs.sh;
}
mkencsquashfs.sh
### Stage 1: Create .squashfs ###
SIZE=$(ls -l ${SQUASHFS} | cut -f 5 -d ' ')
echo "squashfs file length (bytes): " $SIZE
### Stage 2: Allocate file for storing encrypted squashfs ###
BLOCK_SIZE_BYTES=1024
LUKS_HEADER_BYTES=$((2*(1<<20))) # needed for luksFormat
CRYPTSETUP_LUKSOPEN_BYTES=1024 # needed for luksOpen
ENC_SQUASHFS="enc_${SQUASHFS}"
dd if=/dev/urandom of=${ENC_SQUASHFS} count=$((($LUKS_HEADER_BYTES + $SIZE + $CRYPTSETUP_LUKSOPEN_BYTES)/$BLOCK_SIZE_BYTES)) bs=$BLOCK_SIZE_BYTES
echo "encrypted squash file size (bytes): " $(ls -l ${ENC_SQUASHFS} | cut -f 5 -d ' ')
### Stage 3: Copy data into encrypted block device ###
echo "finding a loopback device"
LO=$(losetup -f)
echo "using loopback device ${LO}"
losetup $LO $ENC_SQUASHFS
cryptsetup -q luksFormat --type luks1 $LO
HDEV=squash
cryptsetup luksOpen $LO $SQUASHDEV
### Stage 4: Copy plaintext squashfs into the encrypted device and close it ###
dd if=$SQUASHFS of=/dev/mapper/$SQUASHDEV bs=$BLOCK_SIZE_BYTES
cryptsetup luksClose $SQUASHDEV
losetup -d $LO