Automatically unlock SSH keys at login with kwallet, kwallet-pam and ksshaskpass

 Since I hate typing passwords all the time, I looked for a way to automatically unlock my SSH keys at login. This guide focuses on KDE Plasma 5 and SDDM, but it should be easy to implement it for KDE Plasma 4 and other display managers as well.

1. Start ssh-agent during login. This can be done in /etc/plasma/startup/agent-startup.sh.

2. Install and enable the kwallet PAM module to automatically unlock your KDE wallet during login.

For this to work, you KDE wallet password should be the same as your account password. To enable it for SDDM, /etc/pam.d/sddm should look like this:

auth            include         system-login
auth            optional        pam_kwallet5.so
account         include         system-login
password        include         system-login
session         include         system-login
session         optional        pam_kwallet5.so

3. Install and enable ksshaskpass.

This is done by pointing the SSH_ASKPASS environment variable to the path of the ksshaskpass binary. In Gentoo this is done automatically in /etc/plasma/startup/ksshaskpass.sh

4. Run ssh-add from your autostart scripts.

For this, I wrote a small shell script that loops over all files in my .ssh directory, tests if they're a private key, and then adds them with ssh-add.
My .config/autostart-scripts/ssh-add.sh looks like this:

#!/bin/sh

try=0

while [ ! -S "${PAM_KWALLET5_LOGIN}" ]; do
        [ $try -ge 10 ] && exit
        sleep 1
        try=$(($try+1))
done

DOTSSHDIR="${HOME}/.ssh"

for FILE in $(ls "${DOTSSHDIR}"); do
        FPATH=$(readlink -f "${DOTSSHDIR}/${FILE}")
        file "${FPATH}" | egrep -q 'private key$' && ssh-add "${FPATH}" </dev/null
done

If all components are correctly configured, you should now get a popup window for each of your private keys in your .ssh directory. If you enable the Remember password checkbox, the passphrase will be saved in your KDE wallet, and the next time you login your keys should be automatically added to the SSH authentication agent.

If you only use standard paths for your keys (see man 1 ssh ) this script could be as simple as this:

#!/bin/sh
ssh-add </dev/null

For me this won't work, as I have more keys than there are standard paths. This could also be solved by passing the paths to all keys to the ssh-add command, but I decided to use this loop for two reasons:

  • whenever I add a new key, I don't need to edit the script
  • every key will be added in kwallet with its full path, even if some of them have the same passphrase

Tags: 

Topics: