sudo
From the relevant man page:
The real and effective uid and gid are set to match those of the target user as specified in the passwd file.
Also, in the description for the -P
(preserve group vector) option to sudo:
The real and effective group IDs, however, are still set to match the target user.
Basically, whatever commands that are run using sudo will be run with the effective user and group IDs of the target user.
To answer the question, “Is there a safer way to do it”, when running sudo as a non-privileged user, I prefer to use the -H
(HOME) option to “set the HOME environment variable to the homedir of the target user”. Some time in the past I was caught out by some unexpected behaviour (can’t remember the details) which I was able to prevent by adding the -H
option to shell scripts that used sudo.
You should probably also make sure that the secure_path
and env_reset
options are set correctly in your /etc/sudoers
. Running sudo -V
shows which environment variables will be passed on to commands launched by sudo and which won’t along with other interesting / useful information.
su
Alternatively, you can use su $(id -un 1000) -c 'dbus-launch chromium'
to run Chromium with the effective user id and group id of user #1000.
If you use su
to accomplish the same task, you should be aware that (by
default) su
only sets the HOME
and SHELL
environment variables to those of
the target user. In this case (where the target user is non-priveleged, i.e., not
a super-user) the USER
and LOGNAME
are also set to those of the target user.
The remaining environment variables (such as PATH
) are preserved.
To avoid leaking any environment data to the non-privileged processes being run,
su
should be run with the --login
or -l
option for a login shell, e.g.
su $(id -un 1000) -lc 'dbus-launch chromium'
The --login
unsets all environment variables except TERM
and then resets
HOME
,SHELL
, USER
and LOGNAME
as listed above. In addition the PATH
is
set to a pre-compiled default value and the current working directory is set to
the target user’s home directory before running the target user’s login script.
I generally prefer sudo over su because of its logging capability and its
“ticketing system” which obviates the need to re-type your password within 5
minutes of the previously successful sudo.
sudo
for this, you can usesu username -c "command"
.sudo
.su
for this. In factsu
has some serious deficiencies thatsudo
can handle.