I'm trying to automatically mount an EncFS volume by using login/logout hook scripts on Mac OS X. The scripts are run as root and automatically run user defined hooks as the user logging in or out. The main scripts are in /usr/local/sbin
and are called loginhook
and logouthook
. Here is the login script:
#!/bin/bash
LOCAL_HOOK="/Users/$1/.loginhook"
if [ -e "$LOCAL_HOOK" ]
then
su - $1 -c "bash $LOCAL_HOOK"
fi
The script is registered to execute on login with:
sudo defaults write com.apple.loginwindow LoginHook /usr/local/sbin/loginhook
User defined .loginhook
:
ENCFS=/path/to/encfs
PWD=$(security find-generic-password -ga EncFS 2>&1 >/dev/null | cut -d'"' -f2)
echo $PWD | $ENCFS -S $HOME/.encrypted/Vault $HOME/Documents/Vault
The redirection for the security
command is necessary since normal output goes to stdout but the password goes to stderr and looks like password: "mypass"
.
If I execute .localhook
from my user account the script works fine, but if the script gets executed from the "parent" script (which runs as root) by using su
I get a blank password.
Debugging with bash -x
shows that everything runs as it should, but the env
command reveals that the environment is not the same as when I log in despite using su -
in the script. I suspect this is where the problem lies but I'm stumped as to what it is.
What am I doing wrong here?
Edit: LaunchAgent solution based on information from Gordon Davisson.
encfsd.sh
:
#!/bin/bash
ENCFS="/path/to/encfs"
ENCDIR="$HOME/.encrypted/Vault"
DECDIR="$HOME/Documents/Vault"
function cleanup {
# Kill sleep command ($! is PID of last command launched in background)
kill $!
umount "$DECDIR"
exit
}
trap cleanup 1 2 3 6 15
security find-generic-password -ga EncFS 2>&1 >/dev/null | cut -d'"' -f2 | "$ENCFS" -S "$ENCDIR" "$DECDIR"
# Wait for exit
while true; do
# Sleeping ignores normal signals so start it in a subprocess and wait for it
sleep 3600 &
wait
done
~/Library/LaunchAgents/localhost.encfsd.plist
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>localhost.encfsd</string>
<key>LimitLoadToSessionType</key>
<string>Background</string>
<key>Program</key>
<string>/Users/asdf/bin/encfsd.sh</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>