nixfiles/presets/nixos/encryptedDrive.nix
2023-12-20 17:38:38 +00:00

110 lines
3.1 KiB
Nix

{
self,
config,
pkgs,
lib,
...
}: let
inherit (lib.modules) mkBefore;
encryptedUSB = import "${self}/data/drives/encryptedUSB.nix";
driveData = import "${self}/data/drives/encryptedDrive.nix";
in {
boot = {
initrd.availableKernelModules = [
# For USB w/ Encryption Key
"usb_storage"
"usbcore"
"uas"
"sd_mod"
# For USB Keyboards
"usbhid"
# For Cryptography
"aesni_intel"
"cryptd"
];
initrd.postDeviceCommands = mkBefore ''
mkdir -m 0755 -p /keys
mkdir -m 0755 -p ${encryptedUSB.mountpoint}
if grep --quiet "cryptsetup_password" /proc/cmdline; then
USE_PASSWORD=true
else
USE_PASSWORD=false
fi
while !(test -b ${encryptedUSB.encryptedPath}) && [ "$USE_PASSWORD" == "false" ]
do
${
if config.boot.plymouth.enable
then ''
${pkgs.plymouth}/bin/plymouth display-message --text="Please Plug In USB"
''
else ''
echo "Please Plug In USB"
''
}
sleep 1
done
${
if config.boot.plymouth.enable
then ''
${pkgs.plymouth}/bin/plymouth hide-message --text="Please Plug In USB"
if [ "$USE_PASSWORD" == "true" ]; then
${pkgs.plymouth}/bin/plymouth ask-for-password \
--prompt="Please Enter Password" \
--command="cryptsetup -T1 open ${driveData.encryptedPath} ${driveData.mapperName}" \
--number-of-tries=3
else
${pkgs.plymouth}/bin/plymouth ask-for-password \
--prompt="Please Decrypt USB" \
--command="cryptsetup -T1 open ${encryptedUSB.encryptedPath} ${encryptedUSB.preBootMapperName}" \
--number-of-tries=3
fi
''
else ''
if [ "$USE_PASSWORD" == "true" ]; then
echo "Please Decrypt Drive"
cryptsetup open ${driveData.encryptedPath} ${driveData.mapperName}
else
echo "Please Decrypt USB"
cryptsetup open ${encryptedUSB.encryptedPath} ${encryptedUSB.preBootMapperName}
fi
''
}
if [ "$USE_PASSWORD" == "false" ]; then
mount -n -t ${encryptedUSB.unencryptedFSType} -o ro ${encryptedUSB.preBootMapperPath} ${encryptedUSB.mountpoint}
cp ${encryptedUSB.encryptionKeysPath}/${config.networking.hostName}.key /keys
chmod 0755 /keys/${config.networking.hostName}.key
umount -f ${encryptedUSB.mountpoint}
cryptsetup close ${encryptedUSB.preBootMapperName}
fi
'';
initrd.luks.devices = {
"${driveData.mapperName}" = {
device = "${driveData.encryptedPath}";
keyFile = "/keys/${config.networking.hostName}.key";
preLVM = false;
allowDiscards = true;
fallbackToPassword = true;
};
};
};
fileSystems = {
"/" = {
device = "${driveData.decryptedPath}";
fsType = "${driveData.unencryptedFSType}";
};
"/boot" = {
device = "${driveData.bootPath}";
fsType = "${driveData.bootFSType}";
};
};
}