Monday, May 2, 2011

HOWTO mount a remote luks encrypted volume on demand

I wanted to create a cron'd backup to a luks volume on a remote machine. My preference was to not have the volume mounted automatically so if my friend rebooted the box it wouldn't block the boot process waiting for the password. It would also be nice if it just mounted itself when necessary and was locked for the rest of the time.

First authorise my user to mount and unlock the volume using specific sudo commands (in /etc/sudoers):

Cmnd_Alias CRYPTOPEN=/sbin/cryptsetup luksOpen /dev/disk/by-uuid/41885992-3f80-4aaa-bc60-9c5854017ca9 crypt-backup --key-file /tmp/keyfile
Cmnd_Alias MOUNT=/bin/mount /dev/mapper/crypt-backup /mnt/backup
Cmnd_Alias UMOUNT=/bin/umount /mnt/backup
Cmnd_Alias CRYPTCLOSE=/sbin/cryptsetup luksClose crypt-backup

myuser ALL=(root) NOPASSWD: CRYPTOPEN,MOUNT,UMOUNT,CRYPTCLOSE

Then, a script on my side:

#!/bin/sh

scp /data/backup/scripts/backup/hdd_keyfile.luks home:/tmp/keyfile && \
ssh home "chmod 600 /tmp/keyfile && sudo /sbin/cryptsetup luksOpen /dev/disk/by-uuid/41885992-3f80-4aaa-bc60-9c5854017ca9 crypt-backup --key-file /tmp/keyfile"
if [ $? -ne 0 ]; then
    echo "cryptsetup failed."
    ssh home "shred -u /tmp/keyfile"
    exit 1
fi

ssh home "sudo /bin/mount /dev/mapper/crypt-backup /mnt/backup"
if [ $? -ne 0 ]; then
    echo "mount failed."
    exit 1
fi

rsync -rtv --compress-level=4 /data/ home:/mnt/backup/data/
rsync -rtv --compress-level=4 /mp3/ home:/mnt/backup/mp3/

ssh home "sudo /bin/umount /mnt/backup && sudo /sbin/cryptsetup luksClose crypt-backup"
if [ $? -ne 0 ]; then
    echo "umount failed."
    exit 1
fi

Chuck it in a cron. Done.

No comments: