Skip to content

Instantly share code, notes, and snippets.

@gronke
Last active January 12, 2018 05:59
Show Gist options
  • Save gronke/4496b01d82de462c47c9e2d798906d12 to your computer and use it in GitHub Desktop.
Save gronke/4496b01d82de462c47c9e2d798906d12 to your computer and use it in GitHub Desktop.
Encrypt Disk on FreeBSD or Linux

Encrypt a disk on FreeBSD or Linux using the device serial as identifier for a random generated key.

  • Keys are stored in /root/encryption/$hostname/$serial
  • Encryption Algorithm AES-XTS 256

Usage

# Encrypt sda and ask for confirmation
./encryption sda

# Don't ask for confirmation
./encrypt-disk.sh ada0 -f
#!/bin/sh
# Caution: This script will delete all data on /dev/XYZ
export DEVICE=/dev/$1
export KEY_DIR=/root/encryption
export CONFIRM_ACTION=$2
# Lookup device serial number with smart to name the keyfile after it
export DEVICE_SERIAL=$(smartctl -i $DEVICE | grep "^Serial Number" | cut -d " " -f6)
export KEY_FILE="$KEY_DIR/$DEVICE_SERIAL.key"
# Create keyfile
if [ ! -f "$KEY_FILE" ]; then
mkdir -p "$KEY_DIR"
dd if=/dev/random of="$KEY_FILE" bs=512 count=1
chown -R root: "$KEY_DIR"
chmod -R 700 "$KEY_DIR"
fi
if [ "$CONFIRM_ACTION" != "-f" ]; then
echo -n "The disk $DISK will be deleted. Please enter uppercase YES to continue: "
read user_confirmed
if [ "$user_confirmed" != "YES" ]; then
echo "aborted. exiting"
exit 0;
fi
fi
case "$(uname)" in
FreeBSD)
geli init -P -K "$KEY_FILE" -e AES-XTS -l 256 -s 4096 "$DEVICE"
geli attach -p -k "$KEY_FILE" "$DEVICE"
echo "Created and mounted: /dev/$1.eli"
;;
Linux)
cryptsetup luksFormat \
--cipher aes-xts-plain64 \
--hash sha512 \
--key-file "$KEY_FILE" \
--use-random \
$DEVICE <<EOF
YES
EOF
cryptsetup luksOpen \
--key-file "$KEY_FILE" \
$DEVICE \
"$1.luks"
echo "Created and mounted: /dev/mapper/$1.luks"
;;
esac
@pennybuster
Copy link

Hi there! I'm new to Linux. Is there a way to automatically decrypt LUKS volume containing the root partition (excluding boot and tmp partitions) at boot time using the device serial id and "obfuscate" the process for non-technical users?
Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment