So you have your nice shiny linux box, and you are properly not allowing remote root logins, but you still need to be able to run X11 apps as root through ssh. But when you try, you get the dreaded error like:
Gtk-WARNING **: 19:41:13.383: cannot open display: localhost:10.0
Well that is a pain. This is because X11 has an authorization token to prevent other users from hijacking your session. And annoying as the restriction can be, it is a good thing. Anyone old enough to have used X11 back before they implemented it will remember roaches or snow randomly appearing on their screens.
Just run this little snippet of code once you have used “sudo -i
” to get your root shell. It will figure out who you logged in as, and then extract the token(s) from your .Xauthority
file, and put it into root’s so you can now run X11 apps as root in your unprivileged X11 session.
if [ "$DISPLAY" ] && [ "$SUDO_USER" ] && [ "${USER}" == root ] && [ "${SUDO_USER}" != root ]
then
SUDO_HOME="$( getent passwd "${SUDO_USER}" | cut -d: -f 6 )"
# For some reason, "-q" still generates a file not found error
# if there is no .Xauthority. Create an empty file to keep things
# quiet.
XAUTHORITY="${HOME}/.Xauthority"
if [ ! -f "${XAUTHORITY}" ]
then
touch "${XAUTHORITY}"
fi
xauth -q add $( xauth -i -f "${SUDO_HOME}/.Xauthority" list "${DISPLAY}" )
fi
I add this code to /etc/profile.d/sudo-xauth.sh
and it runs for any user that elevates their privileges. Keep in mind, though, that by adding your auth token to root’s, anyone else that can elevate privileges will also be able to use it to send X11 windows to your screen. But anyone who has root access could do this anyway.