87 lines
2.7 KiB
Nix
87 lines
2.7 KiB
Nix
{
|
|
parted,
|
|
cryptsetup,
|
|
e2fsprogs,
|
|
dosfstools,
|
|
writeShellApplication,
|
|
}: let
|
|
driveData = import ../data/drives/encryptedDrive.nix;
|
|
in
|
|
writeShellApplication {
|
|
name = "mk-encrypted-drive";
|
|
runtimeInputs = [
|
|
parted
|
|
cryptsetup
|
|
e2fsprogs
|
|
dosfstools
|
|
];
|
|
text = ''
|
|
if [ -z "''${BIOS-}" ]; then
|
|
echo "If making a drive for bios then you will need to set BIOS env variable"
|
|
fi
|
|
|
|
if [ -z "''${PASSWORD_FILE-}" ]; then
|
|
echo "If the drive is for a encrypted server then password will need to be set with PASSWORD_FILE"
|
|
fi
|
|
|
|
if [ -z "''${1-}" ]; then
|
|
echo "Please specify a path to device as first argument"
|
|
exit 1
|
|
fi
|
|
|
|
if [ -z "''${2-}" ]; then
|
|
echo "Please specify a path to key file as second argument"
|
|
exit 1
|
|
fi
|
|
|
|
DRIVE_PATH=$1
|
|
KEY_FILE=$2
|
|
|
|
if echo "$DRIVE_PATH" | grep -q "[0-9]$"; then
|
|
PARTITION_SEPARATOR="p"
|
|
else
|
|
PARTITION_SEPARATOR=""
|
|
fi
|
|
|
|
if [ "$EUID" -ne 0 ]; then
|
|
echo "Please run as root"
|
|
exit
|
|
fi
|
|
|
|
echo "Creating Partitions..."
|
|
if [ -n "''${BIOS-}" ]; then
|
|
# EFI Install
|
|
parted "$DRIVE_PATH" -- mklabel gpt
|
|
parted "$DRIVE_PATH" -- mkpart ESP fat32 1MiB 512MiB
|
|
parted "$DRIVE_PATH" -- mkpart primary 620MiB -1MiB
|
|
parted "$DRIVE_PATH" -- set 1 esp on
|
|
parted "$DRIVE_PATH" -- name 1 "${driveData.bootLabel}"
|
|
parted "$DRIVE_PATH" -- name 2 "${driveData.encryptedPartLabel}"
|
|
else
|
|
parted "$DRIVE_PATH" -- mklabel gpt
|
|
parted "$DRIVE_PATH" -- mkpart ESP fat32 1MiB 512MiB
|
|
parted "$DRIVE_PATH" -- mkpart primary 620MiB -1MiB
|
|
parted "$DRIVE_PATH" -- set 1 boot on
|
|
parted "$DRIVE_PATH" -- name 1 "${driveData.bootLabel}"
|
|
parted "$DRIVE_PATH" -- name 2 "${driveData.encryptedPartLabel}"
|
|
fi
|
|
|
|
echo "Formatting boot partition"
|
|
mkfs.fat -n "${driveData.bootLabel}" "''${DRIVE_PATH}''${PARTITION_SEPARATOR}1"
|
|
|
|
echo "Creating Encrypted Partition"
|
|
cryptsetup luksFormat "''${DRIVE_PATH}''${PARTITION_SEPARATOR}2" --key-file "$KEY_FILE"
|
|
if [ -n "''${PASSWORD_FILE-}" ]; then
|
|
cryptsetup luksAddKey "''${DRIVE_PATH}''${PARTITION_SEPARATOR}2" --key-file "$KEY_FILE" < "$PASSWORD_FILE"
|
|
fi
|
|
|
|
echo "Opening Encrypted Partition"
|
|
cryptsetup open "''${DRIVE_PATH}''${PARTITION_SEPARATOR}2" "mk_encrypted_drive" --key-file "$KEY_FILE"
|
|
|
|
echo "Formatting Encrypted Root Filesystem"
|
|
mkfs.ext4 -L "${driveData.unencryptedLabel}" /dev/mapper/mk_encrypted_drive
|
|
|
|
echo "mount /dev/mapper/mk_encrypted_drive to install"
|
|
'';
|
|
}
|