In my previous post I showed an automount script for mounting a LUKS encrypted disk image as a loop device. The script was designed to always mount the same loop device, e.g. /dev/loop0. This prevented it from being able to mount multiple disk images, so with some tweaks I refined the script to use any available loop device and thus support multiple disk images.

The updated script looks like:

#!/bin/bash
# 
# Automount script to mount LUKS-encrypted disk image file.
# 
# This script must be executable to work (chmod 755).
# 
# Requires losetup and cryptsetup to be available in 
# one of /bin, /sbin, /usr/bin, or /usr/sbin.
#
# The LUKS key must exist as a file at /etc/<key>.key

key="$1"
los=""
cry=""
img="/cifs/lacie-2big/backup/$key.sparseimage"
mountopts="-fstype=ext3,defaults,noatime,nodiratime"

if [ ! -e "/etc/$key.key" ]; then
	exit 0
fi

if [ ! -e "$img" ]; then
	exit 0
fi

# search for losetup and cryptsetup
for P in /bin /sbin /usr/bin /usr/sbin
do
	if [ -z "$los" -a -x $P/losetup ]; then
		los=$P/losetup
	fi
	if [ -z "$cry" -a -x $P/cryptsetup ]; then
		cry=$P/cryptsetup
	fi
	if [ -n "$los" -a -n "$cry" ]; then
		break
	fi
done

# check if a loop device already attached to this image
dev=`$los -a |grep $img |cut -d: -f1`
if [ -z "$dev" ]; then
	# select any available loop device
	dev=`$los -f`
	if [ -z "$dev" ]; then
		echo "No loop device available for mounting $img" >&2
		exit 1
	fi
	
	# attach loop device
	$los $dev $img
	
	# open with LUKS
	$cry isLuks $dev 2>/dev/null
	if [ "$?" -eq "0" ]; then
		$cry --key-file /etc/$key.key luksOpen $dev luks-`$cry luksUUID $dev` >/dev/null 2>&1
	fi
fi

# print out mapping for automount
echo $mountopts / :/dev/mapper/luks-`$cry luksUUID $dev`

This script first checks if the disk image is already attached to a loop device, and if so will not attach it again. When attaching to a loop device, it uses losetup -f to find any unused loop device and attaches the disk image to that one.

These scripts can be viewed online or obtained via anonymous SVN:

svn co http://msqr.us/svn/pub/twobig/trunk twobig