xauth and sudo

The below incantation will transfer X authority cookies from one user to another when using sudo. Maybe there is a better way?

There definately is a security risk between “xauth nextract” and “rm” where the security cookie is written to disk.

export PORT=`echo $DISPLAY | sed -e 's|.*:||' -e 's|\.[0-9]||'`
rm -f /tmp/${LOGNAME}:${PORT}_xauth
touch /tmp/${LOGNAME}:${PORT}_xauth
chmod 0666 /tmp/${LOGNAME}:${PORT}_xauth
/usr/openwin/bin/xauth nextract /tmp/${LOGNAME}:${PORT}_xauth `/usr/openwin/bin/xauth list | awk /\`hostname\`.*:$PORT/'{print $1}'`
sudo -s -u oracle
export XAUTHORITY=`getent passwd oracle | awk -F: '{print $6}'`/.Xauthority
/usr/openwin/bin/xauth nmerge /tmp/${SUDO_USER}:${PORT}_xauth
rm -f /tmp/${SUDO_USER}:${PORT}_xauth
xclock # or whatever X program
/usr/openwin/bin/xauth remove `/usr/openwin/bin/xauth list | awk /\`hostname\`.*:$PORT/'{print $1}'`
exit


Explanation

Get the display number:

export PORT=`echo $DISPLAY | sed -e 's|.*:||' -e 's|\.[0-9]||'`

Clear any existing temp file and create it with the given permissions:

rm -f /tmp/${LOGNAME}:${PORT}_xauth
touch /tmp/${LOGNAME}:${PORT}_xauth
chmod 0666 /tmp/${LOGNAME}:${PORT}_xauth

Get the xauth cookie for the current connection and save it to a file so we can use it as the target user:

/usr/openwin/bin/xauth nextract /tmp/${LOGNAME}:${PORT}_xauth `/usr/openwin/bin/xauth list | awk /\`hostname\`.*:$PORT/'{print $1}'`

Become the target user. Note that this required sudo incantation is similar to using su without the minus “-“;

sudo -s -u oracle

Change the .Xauthority file to something the target user can write to:

export XAUTHORITY=`getent passwd oracle | awk -F: '{print $6}'`/.Xauthority

Import the xauth cookie from the previous user for the current connection:

/usr/openwin/bin/xauth nmerge /tmp/${SUDO_USER}:${PORT}_xauth

Delete the temporary file so that others cannot steal the cookie:

rm -f /tmp/${SUDO_USER}:${PORT}_xauth

Run your X program (for example, xclock). The program should show up on your display:

xclock

When you are finished, remove the xauth cookie and exit the target user’s shell:

/usr/openwin/bin/xauth remove `/usr/openwin/bin/xauth list | awk /\`hostname\`.*:$PORT/'{print $1}'`
exit

Advertisements

About Michael Arnold
This is where I write about all of my unix hacking experiences so that you may be able to learn from my troubles.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: