3

This question is a side-effect of Default owners/permissions of files in user home directory, and after a search which found this Q&A on Unix&Linux SE.

When you use

sudo command 

only a bunch of environment variable are preserved, for security reasons (although this point here is debated... but well). It is a matter of configuration defaults to decide if $HOME is preserved or not; in Ubuntu by default it is preserved and you need to use sudo -H to not preserve it (and setting it to the target user).

Check it (be careful with quoting, we don't want $HOME be resolved before calling sudo!):

[romano:~] % sudo bash -c 'echo $HOME'
/home/romano
[romano:~] % sudo -H bash -c 'echo $HOME'
/root

I can see that preserving $HOME has the possible negative effect that you can use sudo whatever and if the program writes or modify files in $HOME (configuration, whatever) you will end with a file owned by root and subsequently not modifiable by the normal user.

This can wreak havoc especially with new users... we have quite a bit of login loops due to a root-owned .Xauthority due to a (admittedly crazy) sudo startx in a terminal emulator under X, or unmodifiable configuration settings due to a misguided sudo dconf-editor, and so on.

On the other side, I see no positive effects. So I am now running with

Defaults        always_set_home

in my /etc/sudoers(1), checking it:

[romano:~] % sudo bash -c 'echo $HOME'
/root

The question: What are the positive effects of preserving $HOME by default, if any?


Footnotes

(1) Always, always, edit /etc/sudoers with visudo and with a terminal (better a VC) with a sudo -i shell running. You will be grateful when you make some mistake cutting yourself out of superuser powers.

Rmano
  • 32,167

1 Answers1

2

You are correct in pointing out potential problems with sudo and applications that write files in $HOME.

The reason for this behaviour would not really be a conscious developer choice, but more that it wasn't really necessary for the intended purposes for which sudo was first conceived: for use with simpler unix-style applications that just take some input and return some output in a predictable manner and then return. It wouldn't originally have been designed to contend with larger applications that run interactively and manage their own files.

As rightly pointed out, sudo -i <command> is good for any application that's interactive (think of the i as standing for interactive, even though that's not what it stands for). -i has further theoretical benefits over -H in that the target user's environment, eg .profile, is read too.

There's also gksudo <command> for graphical interactive applications, but sudo -i <command> works well enough for those too.

If you don't want to type sudo -i <command> all the time you could create a script/alias for it I guess.

thomasrutter
  • 37,804