Skip to content

Instantly share code, notes, and snippets.

@NiceRath
Last active April 18, 2024 18:23
Show Gist options
  • Save NiceRath/c794caa26a28fc90fc628a047648722b to your computer and use it in GitHub Desktop.
Save NiceRath/c794caa26a28fc90fc628a047648722b to your computer and use it in GitHub Desktop.
Luks Cryptmount - Create encrypted LVM volume
#!/bin/bash
set -eE -o pipefail
# script to encrypt an existing LVM volume
# to move the encryption keys to a remote host - use: https://gist.github.com/NiceRath/65511409c8dbbbbb98ae6f1a668b7d5d
ENC_PATH='<PATH-TO-KEY-DIR>'
KEY_SIZE='8192'
PASS_FILE="${ENC_PATH}/<GPG-PASSPHRASE-FILE>"
MAPPER_DIR='/dev/mapper'
if [ $# -eq 0 ]
then
echo 'You must provide the lv-mapper-name as argument #1; Available:'
ls -l $MAPPER_DIR
exit 1
fi
set -u
LV_NAME=$1
LV_DEV="$MAPPER_DIR/$LV_NAME"
echo "You are about to format the volume '$LV_DEV'. ARE YOU SURE? (yes/any other = no)"
read really
if ! [ $really = "yes" ]
then
echo "User stopped exection"
exit 1
fi
mkfs.ext4 $LV_DEV
LV_UUID=`blkid /dev/mapper/$LV_NAME -s UUID -o value`
KEY_FILE="$ENC_PATH/$LV_UUID.key"
# generating key
tr -dc A-Za-z0-9\!_*+?=%.\;: </dev/urandom | head -c$KEY_SIZE > $KEY_FILE
# signing key
gpg --batch --symmetric --armor --passphrase-file=$PASS_FILE $KEY_FILE
# encrypting logical volume
cryptsetup luksFormat $LV_DEV --key-file=$KEY_FILE --cipher aes-xts-plain64 --key-size 512 --hash sha512
cryptsetup luksOpen $LV_DEV crypt-$LV_NAME --key-file=$KEY_FILE
mkfs.ext4 $MAPPER_DIR/crypt-$LV_NAME
cryptsetup luksClose $MAPPER_DIR/crypt-$LV_NAME
# rename key to new uuid
LV_NEW_UUID=`cryptsetup luksUUID $LV_DEV`
mv $KEY_FILE "$ENC_PATH/$LV_NEW_UUID.key"
mv $KEY_FILE.asc "$ENC_PATH/$LV_NEW_UUID.key.asc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment