Skip to content

Commit

Permalink
Verify $HOME exists and is owned by current user in getHome()
Browse files Browse the repository at this point in the history
Useful because a default `sudo` on darwin doesn't clear `$HOME`, so things like `sudo nix-channel --list`
will surprisingly return the USER'S channels, rather than `root`'s.

Other counterintuitive outcomes can be seen in this PR description:
  NixOS#6622
  • Loading branch information
virusdave committed Jun 17, 2022
1 parent 65cd26e commit 73d175d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/libutil/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,20 @@ Path getHome()
static Path homeDir = []()
{
auto homeDir = getEnv("HOME");
if (homeDir) {
// Only use $HOME if doesn't exist or is owned by the current user.
struct stat st;
int result = stat(homeDir->c_str(), &st);
if (result != 0) {
if (errno != ENOENT) {
warn("Couldn't stat $HOME ('%s') for reason other than not existing ('%d'), falling back to the one defined in the 'passwd' file", *homeDir, errno);
homeDir.reset();
}
} else if (st.st_uid != geteuid()) {
warn("$HOME ('%s') is not owned by you, falling back to the one defined in the 'passwd' file", *homeDir);
homeDir.reset();
}
}
if (!homeDir) {
std::vector<char> buf(16384);
struct passwd pwbuf;
Expand Down
4 changes: 4 additions & 0 deletions tests/config.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ source common.sh
# Other tests (e.g. flake registry tests) could be writing to $HOME in parallel.
export HOME=$TEST_ROOT/userhome

# # If home didn't exist or wasn't owned by this user, nix would have reverted to
# # using the homedir entry from /etc/passwd instead.
# mkdir $HOME

# Test that using XDG_CONFIG_HOME works
# Assert the config folder didn't exist initially.
[ ! -e "$HOME/.config" ]
Expand Down
3 changes: 3 additions & 0 deletions tests/tarball.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ source common.sh
clearStore

rm -rf $TEST_HOME
# # If home didn't exist or wasn't owned by this user, nix would have reverted to
# # using the homedir entry from /etc/passwd instead.
# mkdir $TEST_HOME

tarroot=$TEST_ROOT/tarball
rm -rf $tarroot
Expand Down

0 comments on commit 73d175d

Please sign in to comment.