I recently bumped into trouble after starting to use common environment variables in post-install scripts. When I use sudo to execute a bash script, the sudo commands within that script translate $HOME to /home/root instead of the currently/single/default/admin logged in user.
I understand this is not how Ubuntu normally behaves, it is how Debian behaves.
This behaviour even caused all my docker container volumes to appear in the root home folder, creating all sorts of access denied and fatal exception issues. It took me a while to figure this out as the cause.
I first created a new environment variable using sudo nano /etc/environment but then that variable is only available to sudo and not to commands run without sudo.
Then I found this information:
Sudo has many compile-time configuration options. You can list the settings in your version with
sudo -V. One of the differences between the configuration in Debian wheezy and in Ubuntu 12.04 is that theHOMEenvironment variable is preserved in Ubuntu but not in Debian; both distributions erase all environment variables except for a few that are explicitly marked as safe to preserve. Thussudo -spreservesHOMEon Ubuntu, while on DebianHOMEis erased andsudothen sets it to the home directory of the target user.You can override this behavior in the
sudoersfile. Runvisudoto edit thesudoersfile. There are several relevant options:
env_keepdetermines which environment variables are preserved. UseDefaults env_keep += "HOME"to retain the caller’sHOMEenvironment variable orDefaults env_keep -= "HOME"to erase it (and replace it by the home directory of the target user).env_resetdetermines whether environment variables are reset at all. Resetting environment variables is often necessary for rules that allow running a specific command, but does not have a direct security benefit for rules that allow running arbitrary commands anyway.always_set_home, if set, causesHOMEto be overridden even if it was preserved due toenv_resetbeing disabled orHOMEbeing in theenv_keeplist. This option has no effect ifHOMEisn’t preserved anyway.set_homeis likealways_set_home, but only applies tosudo -s, not when callingsudowith an explicit command.These options can be set for a given source user, a given target user or a given command; see the
sudoersmanual for details.You can always choose to override
HOMEfor a given call tosudoby passing the option-H.The shell will never override the value of
HOME. (It would setHOMEif it was unset, butsudoalways setsHOMEone way or another.)If you run
sudo -i,sudosimulates an initial login. This includes settingHOMEto the home directory of the target user and invoking a login shell.
Now I ran sudo visudo and added this line:
Defaults env_keep += "HOME"
Now, whether I use sudo or not, $HOME always points to /home/user instead of /home/root.
Should this not be the default behaviour for UB as friendly operating system?