X11 Forwarding and su/sudo

From Brandonhutchinson.com

Jump to: navigation, search

From my system with an Xorg X server, I login to host via ssh with X11 forwarding and execute an X client.

$ ssh hutch@host
(host) $ echo $DISPLAY
(host) $ /usr/openwin/bin/xclock

This works. What if I want to run an X client as the root user?

(host) $ /bin/su -
# echo $DISPLAY

# DISPLAY=localhost:10.0 /usr/openwin/bin/xclock
X11 connection rejected because of wrong authentication.
X connection to localhost:10.0 broken (explicit kill or server shutdown).

This doesn't work because the X client is looking for the authority file in ~root/.Xauthority, while the needed credentials (i.e., the "magic cookie") created by ssh are in ~hutch/.Xauthority.

From SSH(1):

    ssh will also automatically set up Xauthority data on the server machine.
    For this purpose, it will generate a random authorization cookie, store
    it in Xauthority on the server, and verify that any forwarded connections
    carry this cookie and replace it by the real cookie when the connection
    is opened.  The real authentication cookie is never sent to the server
    machine (and no cookies are sent in the plain).

To make this work, set XAUTHORITY=~hutch/.Xauthority and execute the X client.

# DISPLAY=localhost:10.0 XAUTHORITY=/home/hutch/.Xauthority /usr/openwin/bin/xclock

This won't work if the root user cannot read /home/hutch/.Xauthority, which would happen if the /home file system is on an NFS share and the root user is "squashed," or mapped to the nobody user.

If this is the case, use xauth in a pipeline to copy the user's credentials into the root user's authority file.

su example:

$ uname -n
$ echo $DISPLAY
$ /usr/openwin/bin/xauth extract - host/unix:10 | su - root -c "/usr/openwin/bin/xauth merge - ; DISPLAY=localhost:10.0 /usr/openwin/bin/xclock"

sudo example:

$ uname -n
$ echo $DISPLAY
$ /usr/openwin/bin/xauth extract - host/unix:10 | sudo su - root -c "/usr/openwin/bin/xauth merge - ; DISPLAY=localhost:10.0 /usr/openwin/bin/xclock"

If you unable to use xauth in a pipeline (perhaps you are using sudo to become another user, but additional command line arguments are not allowed), run xauth list on the account you are sudo'ing from, sudo to the account, and add the appropriate key via xauth add before starting your X client.


Personal tools