marvin.im

Lock your Mac when unplugging your YubiKey automatically

Especially at work you should lock your screen when you leave your workspace.

To make this easier when you’re a YubiKey user, I’ve created the following script to automatically lock your screen when you unplug your YubiKey.

After that it waits until a YubiKey is inserted again and from then on it will lock the screen again if you remove it.

Even when it would be much nicer to install the script as a launchd daemon I don’t recommend it. (Would be bad if you get totally locked when there is a problem)

I’d recommend to create a Application using Apples Automator which runs the script after waiting 20 seconds (in case you need time to disable it) as a shell script and which will be loaded after login.

Test it before making it permanent

I use it on a macOS High Sierra

drawbacks

  • it will only lock if there is no device with the name yubikey plugged in

benefits

  • useable without YubiKey (in case you forgot it at home)

usage

by setting the environment variable DEBUG to any value, log output will be printed to stdout. It is really useful for testing this script.

DEBUG=true ./script

the script

#!/bin/bash

function prntdbg {
  if [ ! -z "$DEBUG" ]; then
    echo "$@"
  fi
}

function lock_screen {
  pmset displaysleepnow
}

function wait_for_plugin {
  while true; do
    if system_profiler SPUSBDataType | grep 'Yubikey' 2>/dev/null >/dev/null; then
      prntdbg yubikey plugged in
      break
    else
      prntdbg yubikey removed
    fi
    sleep 2
  done
}

function wait_for_unplug {
  while true; do
    if system_profiler SPUSBDataType | grep 'Yubikey' 2>/dev/null >/dev/null; then
      prntdbg yubikey plugged in
    else
      prntdbg yubikey removed
      lock_screen
      break
    fi
    sleep 2
  done
}

while true; do
  wait_for_plugin
  wait_for_unplug
done

licence

Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.