From ca2be509b96a10a2035039a825fc2b292ec0ad4d Mon Sep 17 00:00:00 2001 From: Dave Nicponski Date: Wed, 15 Jun 2022 16:38:56 -0400 Subject: [PATCH] Verify `$HOME` is owned by current user in `getHome()`, if it exists. 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: https://github.com/NixOS/nix/pull/6622 --- src/libutil/util.cc | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 1c19938a8..a368ac844 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -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 buf(16384); struct passwd pwbuf;