Mounting a LUKS-encrypted volume at boot time

This is a automated LUKS decrypting “quick fix” that I’m running at /etc/hotplug.d/block/99-lukscrypt:

#!/bin/bash
# Perform tasks when called by BLOCK hotplug (/etc/hotplug.d/block/99-lukscrypt)
# CC0: 21JUL18 by WaLLy3K, updated 09AUG18
[[ -z "${DEVNAME}" ]] && DEVNAME="${1##*/}"
msg() { logger -st "$(basename "${0%.*}")($DEVNAME)[$$]" -- "$@"; }

# Hotplug Vars: $ACTION (add/remove), $DEVICE (?), $DEVNAME (sdx)
BID_RAW="$(blkid "/dev/$DEVNAME" | awk -v RS=' ' '{gsub("[:\"]",""); print $0}')"
BID_UUID="$(awk -F= '/UUID/ {print $2}' <<< "$BID_RAW")"
BID_TYPE="$(awk -F= '/TYPE/ {print $2}' <<< "$BID_RAW")"

# Determine whether drive needs to be decrypted
[[ ! -r "/etc/crypttab" ]] && { msg "Unable to read file: /etc/crypttab"; exit 1; }
CT_RAW="$(grep "$BID_UUID" /etc/crypttab)"

if [[ -n "${CT_RAW:-}" ]]; then
  CT_LABEL="$(awk '{print $1}' <<< "$CT_RAW")"
  CT_KEYFILE="$(awk '{print $3}' <<< "$CT_RAW")"
  CT_TYPE="$(awk -F '[ ,]+' '{print $4}' <<< "$CT_RAW")"
  #CT_SCRIPT="$(awk -F "keyscript=" '{print $2}' <<< "$CT_RAW")"

  if [[ -e "/dev/mapper/${CT_LABEL,,}" ]]; then
    msg "Drive already decrypted: $CT_LABEL"
    exit 0
  fi

  # Error Handling
  if [[ ! -e "$CT_KEYFILE" ]]; then
    msg "Unable to view keyfile: '$CT_KEYFILE'"
    exit 1
  fi
  if [[ ! "${BID_TYPE,,}" == *"${CT_TYPE,,}"* ]]; then
    msg "Unable to decrypt format: $CT_TYPE"
    exit 1
  fi

  msg "Decrypting drive: $CT_LABEL (/dev/$DEVNAME)"
  cryptsetup luksOpen "/dev/$DEVNAME" "${CT_LABEL,,}" -d "$CT_KEYFILE"
  CS_EXIT="$?"
  case "$CS_EXIT" in
    0)  if test -e "/dev/mapper/${CT_LABEL,,}"; then
          msg "Drive decrypted: $CT_LABEL"
        else
          msg "Drive not found after decrypting: $CT_LABEL"
          exit 1
        fi;;
    5) msg "Device already exists: $CT_LABEL (Dmsetup stuck?)"; exit 1;;
    *) msg "Unable to decrypt drive: $CT_LABEL ($CS_EXIT)"; exit 1;;
  esac

  # Mount drive if specified in fstab (or LuCI > System > Mount Points)
  block mount
fi

Then in /etc/rc.local (Also editable via LuCI > System > Startup > Local Startup) for decrypting upon boot:

# Decrypt drives upon boot
for b in /dev/sd*; do
  /root/scripts/block-hotplug.sh "$b"
done

It should be able to read /etc/crypttab lines like the following: DEVICELABEL UUID=0000-0000-0000-0000-0000 /path/to/keyfile luks, but doesn’t support password input.

This may not work for you “as-is”, but can hopefully get anyone reading this started in the right direction.

2 Likes