Mac OS X: auto unmount disk images

Last time I wrote a small article about using encrypted disk images in Mac OS X to protect sensitive data in case your laptop gets stolen. I now use these images a couple of weeks and I’m very satisfied except one little thing (it’s always the little things). I want the volume to be unmounted when I close the lid of the laptop (sleep mode). When the laptop is stolen in sleep mode only my system password has to be compromized in order to get to the sensitive data. There’s no standard functionality to do this so we need to get creative…

update: better script added (thanks Karel!)

I found a great utility on the internet called SleepWatcher written by Bernhard Bähr. This little daemon will launch /etc/rc.sleep when the system goes to sleep and /etc/rc.wakeup when the system awakes. The default implementation of these two scripts hunt down the home directory of the current user and executes any ~/.sleep and ~/.awake scripts. Be careful the file permissions on the scripts need to be set.

Using this great tool I can umount and mount the required images. To do that I created the following .sleep file

#!/bin/sh

function umount_volume
{
    [ -d "$1" ] || exit 0
    pids=`lsof "$1" | awk '{ if (NR > 1) print $2 }'|sort -u`
    if [ -n "$pids" ]; then
        kill -HUP $pids
        kill -INT $pids
        kill -QUIT $pids
        kill -TERM $pids
    fi
    hdiutil detach "$1"    > /dev/null 2>&1
}

umount_volume /Volumes/secret_data

When the system wakes up I want to remount the volume automatically using this .wakeup script:

#!/bin/sh

hdiutil mount ~/Projects/secret_data.sparseimage

That’s it. We’re done. We do kill processes that keep the Volume mounted. Good editors keep track of changes themselves so no data will be lost. You can change it if you like.

One Response to “Mac OS X: auto unmount disk images”

  1. Karel Says:

    Brilliant!! Just what I was looking for, great tip Ed!

Leave a Reply