#!/usr/bin/env bash set -euo pipefail export IFS=$'\n\t' # # A script that handles basic crypttab functionality to mount encrypted volumes # on execution. # TAB=/etc/crypttab # Iterrates through all entries in crypttab with the purpose to close the # decrypted block devices (typically at /dev/mapper/*). # # NOTE: If any of the listed encrypted devices are mounted, attempts to umount # them first, since not doing so will cause the luksClose to hang. destroy_entries() { local dev='' if [ ! -f "${TAB}" ]; then printf 'Could not access %s.\n' "${TAB}" exit 1 fi # For each entry in crypttab for entry in "$(grep -v -e '^#' -e '^ *$' ${TAB})"; do dev="${entry%% *}" mount="${entry##* }" mapper="${dev////_}" printf '%s mounted at %s. Unmounting\n' "${dev}" "${mount}" # Kill any running processes accessing mount point if lsof is available if type lsof 2>/dev/null 1>/dev/null; then for pid in $(lsof -t ${mntpoint}); do pidstr=$(ps -f ${pid} | tail -n 1) printf 'Halting %s %d\n' "${pid}" "${pidstr##* }" kill "${pid}" done fi umount -R "${mount}" || : printf 'Closing cryptdevice %s (%s)\n' "${dev}" "${mapper}" cryptsetup luksClose "${mapper}" done } # Checks each device listed in the crypttab file for its current status # (encrypted, or decrypted). stat_entries() { if [ ! -f "${TAB}" ]; then printf 'Could not access %s.\n' "${TAB}" exit 1 fi # For each entry in crypttab for entry in "$(grep -v -e '^#' -e '^ *$' ${TAB})"; do dev="${entry%% *}" mapper="${dev////_}" if [ -L "/dev/mapper/${mapper}" ]; then printf '%s decrypted at /dev/mapper/%s\n' "${dev}" "${mapper}" else printf '%s not decrypted\n' "${_dev}" fi done < "${TAB}" } # Decrypts each encrypted device listed in crypttab setup_entries() { if [ ! -f "${TAB}" ]; then printf 'Could not access %s.\n' "${TAB}" exit 1 fi for entry in "$(grep -v -e '^#' -e '^ *$' ${TAB})"; do dev="${entry%% *}" key=$(echo ${entry} | tr -s ' ' | cut -d ' ' -f 2) mount="${entry##* }" mapper="${dev////_}" printf 'Decrypting %s using key %s.\n' "${dev}" "${key}" cryptsetup luksOpen "${dev}" "${mapper}" --key-file "${key}" printf 'Plaintext device is at /dev/mapper/%s\n' "${mapper}" printf 'Mounting /dev/mapper/%s to %s\n' "${mapper}" "${mount}" mount "/dev/mapper/${mapper}" "${mount}" done } case "${1:-}" in start) setup_entries mount -a ;; stop) destroy_entries ;; status) stat_entries ;; restart) $0 stop $0 start ;; *) echo "usage: $0 [start|stop|restart|status]" ;; esac