Skip to content

Instantly share code, notes, and snippets.

@mmonaco
Created June 21, 2013 15:42
Show Gist options
  • Save mmonaco/5832095 to your computer and use it in GitHub Desktop.
Save mmonaco/5832095 to your computer and use it in GitHub Desktop.
#!/bin/bash
dev=/dev/disk/by-partlabel/$(hostname -s)-crypt-root
key=/boot/key
grubcfg=/boot/grub/grub.cfg
usage() {
local arg0=$(basename "$0")
cat <<-EOF
usage $arg0 add|rm [dev]
default dev: $dev
EOF
}
err() {
local fmt="$1"
shift
printf "$fmt\n" "$@" >&2
}
main() {
for a in "$@"; do
for b in -h --help -help --usage -usage -?; do
[[ $a = $b ]] && usage && exit 0
done
done
if (($# == 0 || $# > 2)); then
usage
exit 1
elif (($# == 2)); then
dev="$2"
fi
case "$1" in
add) main_add;;
rm) main_rm;;
*) usage; exit 1
esac
}
main_add() {
if [[ ! -b $dev ]]; then
err "not a block device; %s" "$dev"
exit 1
elif [[ -e $key ]]; then
err "key exists (and may still be in a keyslot!): %s" "$key"
exit 1
elif ! grep -q cryptkey "$grubcfg" &> /dev/null; then
err "cryptkey= not in %s" "$grubcfg"
exit 1
fi
if ! dd if=/dev/urandom of="$key" bs=1024 count=4; then
err "error creating key"
exit 1
fi
if ! cryptsetup luksAddKey "$dev" "$key"; then
err "err adding key, removing %s" "$key"
rm "$key"
exit 1
fi
}
main_rm() {
if [[ ! -e $key ]]; then
err "key does not exist: %s" "$key"
exit 1
fi
if ! cryptsetup luksRemoveKey "$dev" "$key"; then
err "error deleting key"
exit 1
fi
rm "$key"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment