Xorg/Running applications as another user

From Sidvind
Jump to: navigation, search

Sometimes it is desirable to run a GUI application as another user, for instance running your browser as a separate user (browsers such as Firefox and Chrome are complex and bound to have security issues). Out-of-the-box the X server will not allow the application to run:

$ sudo -u otheruser firefox
Error: cannot open display: :0.0

This happens because that user doesn't carry the authorization cookie required to connect to the current display. By default each user stores its authorization data in ~/.Xauthority and is modified using xauth. You list current available cookies by executing xauth list and add new using xauth [-f FILENAME] add :0.0 . KEY.

As your primary user run:

$ xauth list
myhost/unix:0  MIT-MAGIC-COOKIE-1  0123456789abcdef0123456789abcdef

The last part is the cookie as a hex key that can be imported for other users:

$ sudo -u otheruser xauth -f /home/otheruser/.Xauthority add :0.0 . 0123456789abcdef0123456789abcdef

Since sudo by default carries the env. variable XAUTHORITY (set to your current file) you either have to override/unset the variable or use -f FILENAME. Failing to do this will make the command hang while trying to acquire file lock (it will eventually timeout). If you get an error that the file does not exist you can just create an empty file with touch /home/otheruser/.Xauthority and retry.

You can verify that it was added correctly using xauth list

$ sudo -u otheruser xauth -f /home/otheruser/.Xauthority list
myhost/unix:0  MIT-MAGIC-COOKIE-1  0123456789abcdef0123456789abcdef

</nowiki>

If you see the same entry as before the authorization is setup correctly and you should now be able to run GUI applications as that user.

TL;DR[edit]

# Create user
$ useradd -m surf
 
# Once (or in your .xinitrc if Xorg changes it every time you restart)
$ sudo -u otheruser XAUTHORITY=/home/surf/.Xauthority xauth add ${DISPLAY} . $(xauth list | grep $(uname -n) | tr -s ' ' | cut -d ' ' -f3)
 
# Start application
$ sudo -u otheruser XAUTHORITY=/home/surf/.Xauthority firefox

Passwordless[edit]

To run without password run visudo and add a new entry as following:

user ALL=(otheruser) NOPASSWD: /usr/bin/firefox

Wrapper script[edit]

Wrapper script to make it a bit easier when running applications (assumes xauth and sudo is setup already)

Code: surf.sh (view, download)

  1. #!/bin/sh
  2.  
  3. if [ $# -eq 0 ]; then
  4.         echo "usage: $0 [COMMAND...]"
  5.         echo "runs COMMAND as the pseudo-Xorg-sandboxed used 'surf'"
  6.         exit 1
  7. fi
  8.  
  9. exec sudo -n -u otheruser XAUTHORITY=/home/otheruser/.Xauthority "$@"