Skip to content

Instantly share code, notes, and snippets.

@xkr47
Last active April 24, 2018 04:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xkr47/d0a1706f960c59648218 to your computer and use it in GitHub Desktop.
Save xkr47/d0a1706f960c59648218 to your computer and use it in GitHub Desktop.
Forward X DISPLAY over "sudo su - <user>", for example after ssh:ing to server
username=<user> ; echo -n "xauth add `xauth list :${DISPLAY#*:}`" | sudo su - $username ; sudo su - $username ; echo -n "xauth remove :${DISPLAY#*:}" | sudo su - $username
@xkr47
Copy link
Author

xkr47 commented May 18, 2015

Replace <user> with the target user - leave empty or specify "root" for root user.

NOTE: Credentials are cleaned up when you log out. Since there is no "reference counting" so if you change to the same user on the server in multiple sessions with the same DISPLAY setting, then you "lose" DISPLAY forwarding when one of them logs out. If you log in to the server using multiple ssh sessions, then they will have different DISPLAY settings and no problem arises.

SECURITY NOTE: If multiple persons have access to the user account you are switching to then those persons can access your X DISPLAY while you are logged in to the user, which means malicious persons will be able to read your keyboard typing, mouse movements, pop up unappropriate windows on your display. This is not due to the specific solution used here but due to how X access is provided i.e. an user account either can or cannot access a DISPLAY, regardless of which person is doing it. The same problem exists if you ssh directly to the target user with X forwarding enabled.

@xkr47
Copy link
Author

xkr47 commented May 19, 2015

Current version doesn't work if your system is set up to randomize the XAUTHORITY environment variable when using su. In that case you can run echo xauth add xauth list :${DISPLAY#*:}`` before running su and copypaste the command it displays once user switching has ocured.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment