Sudo Command – Why Does sudo -i Not Set XDG_RUNTIME_DIR for Target User?

pamsshsudosystemd

XDG_RUNTIME_DIR is necessary for systemctl --user to work.

I have set up ubuntu server 16.04 to run systemd user sessions. Now, when trying to administer them, I find that when changin a user via sudo -u $user -i or even su - $user, the environment does not have XDG_RUNTIME_DIR set, preventing systemctl --user from working. However, when I ssh straight into that user, it is set correctly.

If I understand the documentation correctly, this should be set by libpam-systemd when creating the user session. The user slice is started correctly, as the directory to which XDG_RUNTIME_DIR should point(/run/users/$uid) exists. I'm hesitant to just hardcode it in, say, .bash_profile, because that seems hacky (albeit working), when pam should be taking care of it.

I can, of course, add XDG_RUNTIME_DIR to env_keep in sudoers, but that would just preserve the sudoing user's environment, which is not what I want. I want the target user's environment.

What I'm really wondering, though, is how come the session is set up correctly with ssh, but not with su or sudo -i?

Best Answer

I have replicated this issue on my Fedora 25 system.

I found a very suspicious condition in the source code. https://github.com/systemd/systemd/blob/f97b34a/src/login/pam_systemd.c#L439 It looks as if it was written with normal sudo in mind but not sudo -u non-root-user.

machinectl shell --uid=non-root-user worked as you requested.

systemd-run did not appear to work as desired, despite the reference to it in the machinectl documentation.

Some machinectl commands don't work if you have enabled SELinux at the moment, and these specific commands didn't work for me until I did setenforce 0. However I'm in the middle of trying workarounds to get machinectl working as I want it to w.r.t SELinux, so it's possible my fiddling is what causes e.g. machinectl shell to timeout.

EDIT: I think this code was introduced after this discussion. And apparently su - / sudo -i could be made to work, but no-one has implemented it (still).

Related Question