Skip to content

Instantly share code, notes, and snippets.

@NiceRath
Last active April 18, 2024 18:23
Show Gist options
  • Save NiceRath/65511409c8dbbbbb98ae6f1a668b7d5d to your computer and use it in GitHub Desktop.
Save NiceRath/65511409c8dbbbbb98ae6f1a668b7d5d to your computer and use it in GitHub Desktop.
Luks Cryptmount - Mount with key from remote host
#!/bin/bash
set -eE -o pipefail
# to create such a volume - use: https://gist.github.com/NiceRath/c794caa26a28fc90fc628a047648722b
# move the created key from <PATH-TO-KEY-DIR> to the remote host and securly delete them (p.e. using 'shred')
# run example: "bash /usr/local/sbin/cryptmount/cryptmount.sh vg0-lv1 crypt-lv1 /data"
ENC_LV_NAME="$1"
DECRYPT_LV_NAME="$2"
MOUNT_POINT="$3"
if [ -z "$4" ]
then
ENC_VG_NAME=''
else
ENC_VG_NAME="$4"
fi
set -u
KEY_HOST='<KEY-HOST>'
KEY_HOST_KEY_DIR='<KEY-HOST-DIR>'
KEY_SSH_USER='<KEY-HOST-USER>'
KEY_SSH_PORT='<KEY-HOST-SSH-PORT>'
KEY_SSH_KEY='<KEY-HOST-USER-SSH-KEY>'
GPG_FILE='<PATH-TO-GPG-PASSPHRASE>'
MAPPER_DIR='/dev/mapper'
echo '#######################'
echo "Starting mounting process for volume $ENC_VG_NAME$ENC_LV_NAME"
if mount | grep -q "$MAPPER_DIR/$DECRYPT_LV_NAME"
then
echo "$DECRYPT_LV_NAME already mounted"
exit 2
fi
if ! cat '/etc/fstab' | grep -q "$MAPPER_DIR/$DECRYPT_LV_NAME"
then
echo "$DECRYPT_LV_NAME has no entry in /etc/fstab"
exit 1
fi
UUID=$(cryptsetup luksUUID "$MAPPER_DIR/$ENC_VG_NAME$ENC_LV_NAME")
KEY_FILE="$KEY_HOST_KEY_DIR/$UUID.key.asc"
KEY=$(ssh -p "$KEY_SSH_PORT" $KEY_SSH_USER@$KEY_HOST -i "$KEY_SSH_KEY" "cat $KEY_FILE" | gpg --batch --yes --ignore-mdc-error --no-mdc-warning --no-tty --passphrase-file "$GPG_FILE" --quiet --decrypt)
echo "$KEY" | tr -d "\n" | cryptsetup luksOpen "$MAPPER_DIR/$ENC_VG_NAME$ENC_LV_NAME" "$DECRYPT_LV_NAME" --key-file=-
mount "$MOUNT_POINT"
echo "Finished mounting process for volume $ENC_VG_NAME$ENC_LV_NAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment