Last active
January 12, 2026 08:02
-
-
Save NiceRath/7fc47f0b6f9e73af01f686eb34e0d4fb to your computer and use it in GitHub Desktop.
Script to create LUKS-encrypt existing LVM-volume (deletes all data on it) and creates decryption-key that can be stored on remote server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| 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 -euo pipefail | |
| # you might want to change these | |
| ENC_PATH='/etc/crypt' | |
| PASS_FILE='/etc/crypt/gpg_passphrase_backup.txt' | |
| LV_NAME=$1 | |
| LV_DEV="${MAPPER_DIR}/${LV_NAME}" | |
| KEY_SIZE='8096' | |
| ENC_CIPHER='aes-xts-plain64' | |
| ENC_KEY_SIZE='512' | |
| ENC_HASH='sha512' | |
| 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 "$ENC_CIPHER" --key-size "$ENC_KEY_SIZE" --hash "$ENC_HASH" | |
| 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