[HowTo] Use kwallet as a login keychain for storing SSH key passphrases on KDE

Hi,

I’ve followed this guide to automate borg backups using kwallet, ksshaskpass, ssh-askpass, ssh-agent, ssh-add and systemd units (services). The procedure is well described here and the instructions helped me a lot - thank you!

I’ve successfully automated periodic backups of my home directory to one repository (using a systemd user service) but have some trouble automating periodic backups of my system files to another repository (using a systemd system service). The problem is probably not so much borg-, but rather systemd- and kwallet-related and I assume that user privileges and environment variables/ settings play a role. Hope you don’t mind me seeking assistance here.

The part I’m struggling with is the following:

In the script executed from the systemd user service to backup /home/<user> I use

BORG_PASSCOMMAND="kwalletcli -f 'borg' -e 'passphrase'"

to retrieve the passphrase of the borg keyfile from kwallet. Works like a charm.

In the script executed from the systemd system service (i. e. as root) to backup system files I use

BORG_PASSCOMMAND="sudo -E -u <user> kwalletcli -f \'borg\' -e \'passphrase\'"

to retrieve the passphrase as described on StackExchange Unix & Linux (post 611188 in “kwallet get password as root user” - first and only answer as of 2023-10-19T22:00:00Z)

If I execute the corresponding script directly as root, everything works perfectly fine. The passphrase is read from kwallet and the backup is created as expected. But if the script is being executed from the systemd system service, borg fails with the error message “cannot open wallet”.

I declare/ export some (environment) variables in that script to access kwallet and the ssh-agent of my usual (login) user, namely USER, LOGNAME, HOME, SSH_ASKPASS, SSH_ASKPASS_REQUIRE and SSH_AUTH_SOCK. As mentioned, this works fine if the script is being executed directly as root, but not in the systemd system service. SSH connection works including reading the passphrase of the private key from kwallet.

Any ideas which puzzle piece I am missing to get this running also inside the systemd system service?

EDIT 2023-10-23:

I managed to set it up properly so it is working now.

I had to set/ export a few more environment variables in the script executed by the systemd system service, namely DBUS_SESSION_BUS_ADDRESS, DESKTOP_SESSION, DISPLAY=":0", KDE_APPLICATIONS_AS_SCOPE, KDE_FULL_SESSION="true", KDE_SESSION_UID and XDG_RUNTIME_DIR. I used printenv to compare the environments when executing the script directly as root and from the systemd system unit.

I then encountered the issue desribed on StackExchange Unix & Linux in post “‘Invalid MIT-MAGIC-COOKIE-1 key’ when trying to run program remotely”, it was solved by the first (as of 2023-10-22T22:00:00Z) answer to that subject (post 496877).