Split getting ans setting the cookie, and unset XAUTHORITY
[xudo.git] / xudo.sh
1 #!/bin/sh
2 #
3 # Execute a command as another user, with access to the X display
4 #
5 # Copyright (C) 2013  Antonio Ospite <ospite@studenti.unina.it>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21 # This is the equivalent of sux[1] but simpler and using sudo.
22 # [1] http://fgouget.free.fr/sux/
23
24 set -e
25
26 usage() {
27   echo "usage: $(basename $0) [OPTION]... <sudo_options>"
28   echo "Execute a command as another user, with access to the X display"
29   echo
30   echo "List of OPTIONs:"
31   echo
32   echo "  -u user     Execute the program as the specified user (default is root)"
33   echo "  -d display  Set the X display"
34   echo "  -h|--help   Show this help text"
35   echo
36   sudo -h | grep -v "^[ ]\+-u user"
37 }
38
39 USERNAME=root
40
41 while true;
42 do
43   case "$1" in
44     -u)
45       [ "x$2" != "x" ] || { usage 1>&2; exit 1; }
46       USERNAME="$2"
47       shift 2
48       ;;
49
50     -d)
51       [ "x$2" != "x" ] || { usage 1>&2; exit 1; }
52       DISPLAY="$2"
53       shift 2
54       ;;
55
56     -h | --help)
57       usage
58       exit 0
59       ;;
60
61     *)
62       break
63       ;;
64   esac
65 done
66
67 id $USERNAME > /dev/null || { echo "Invalid user." 1>&2; exit 1; }
68
69 [ -n "$DISPLAY" ] || { echo "Cannot get the DISPLAY env variable." 1>&2; exit 1; }
70
71 [ "x$@" != "x" ] || { usage 1>&2; exit 1; }
72
73
74 # Get the authorization cookie from the current user.
75 COOKIE="$(xauth nextract - $DISPLAY)"
76
77 # XAUTHORITY needs to be unset now, so that the default $HOME/.Xauthority will
78 # be used for the target user and not some locked auth file from the current
79 # user.
80 unset XAUTHORITY
81
82 # Authorize the user.
83 # Use "sudo -H" to cover the case when env_keep+="HOME" is set in /etc/sudoers
84 echo "$COOKIE" | sudo -H -u "$USERNAME" xauth nmerge -
85
86 # Execute the command.
87 # NOTE: -i or -s can be passed in order to open a shell
88 sudo DISPLAY="$DISPLAY" -u "$USERNAME" "$@"