Factor out isRootUser function

This commit is contained in:
John Ericson 2024-03-29 15:40:56 -04:00
parent eeecbb9c36
commit e4d9b207c2
11 changed files with 30 additions and 15 deletions

View file

@ -2,7 +2,6 @@
#include "current-process.hh"
#include "archive.hh"
#include "args.hh"
#include "users.hh"
#include "abstract-setting-to-json.hh"
#include "compute-levels.hh"
@ -57,7 +56,7 @@ Settings::Settings()
, nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(getEnvNonEmpty("NIX_DAEMON_SOCKET_PATH").value_or(nixStateDir + DEFAULT_SOCKET_PATH)))
{
buildUsersGroup = getuid() == 0 ? "nixbld" : "";
buildUsersGroup = isRootUser() ? "nixbld" : "";
allowSymlinkedStore = getEnv("NIX_IGNORE_SYMLINK_STORE") == "1";
auto sslOverride = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));

View file

@ -5,6 +5,7 @@
#include "config.hh"
#include "environment-variables.hh"
#include "experimental-features.hh"
#include "users.hh"
#include <map>
#include <limits>
@ -665,7 +666,7 @@ public:
Setting<bool> sandboxFallback{this, true, "sandbox-fallback",
"Whether to disable sandboxing when the kernel doesn't allow it."};
Setting<bool> requireDropSupplementaryGroups{this, getuid() == 0, "require-drop-supplementary-groups",
Setting<bool> requireDropSupplementaryGroups{this, isRootUser(), "require-drop-supplementary-groups",
R"(
Following the principle of least privilege,
Nix will attempt to drop supplementary groups when building with sandboxing.

View file

@ -16,6 +16,7 @@
#include "posix-fs-canonicalise.hh"
#include "posix-source-accessor.hh"
#include "keys.hh"
#include "users.hh"
#include <iostream>
#include <algorithm>
@ -223,7 +224,7 @@ LocalStore::LocalStore(const Params & params)
/* Optionally, create directories and set permissions for a
multi-user install. */
if (getuid() == 0 && settings.buildUsersGroup != "") {
if (isRootUser() && settings.buildUsersGroup != "") {
mode_t perm = 01775;
struct group * gr = getgrnam(settings.buildUsersGroup.get().c_str());
@ -573,7 +574,7 @@ void LocalStore::openDB(State & state, bool create)
void LocalStore::makeStoreWritable()
{
#if __linux__
if (getuid() != 0) return;
if (!isRootUser()) return;
/* Check if /nix/store is on a read-only mount. */
struct statvfs stat;
if (statvfs(realStoreDir.get().c_str(), &stat) != 0)
@ -1570,7 +1571,7 @@ static void makeMutable(const Path & path)
/* Upgrade from schema 6 (Nix 0.15) to schema 7 (Nix >= 1.3). */
void LocalStore::upgradeStore7()
{
if (getuid() != 0) return;
if (!isRootUser()) return;
printInfo("removing immutable bits from the Nix store (this may take a while)...");
makeMutable(realStoreDir);
}

View file

@ -2,6 +2,7 @@
#include "file-system.hh"
#include "globals.hh"
#include "pathlocks.hh"
#include "users.hh"
#include <pwd.h>
#include <grp.h>
@ -192,10 +193,10 @@ std::unique_ptr<UserLock> acquireUserLock(uid_t nrIds, bool useUserNamespace)
bool useBuildUsers()
{
#if __linux__
static bool b = (settings.buildUsersGroup != "" || settings.autoAllocateUids) && getuid() == 0;
static bool b = (settings.buildUsersGroup != "" || settings.autoAllocateUids) && isRootUser();
return b;
#elif __APPLE__
static bool b = settings.buildUsersGroup != "" && getuid() == 0;
static bool b = settings.buildUsersGroup != "" && isRootUser();
return b;
#else
return false;

View file

@ -308,7 +308,7 @@ std::string optimisticLockProfile(const Path & profile)
Path profilesDir()
{
auto profileRoot =
(getuid() == 0)
isRootUser()
? rootProfilesDir()
: createNixStateDir() + "/profiles";
createDirs(profileRoot);
@ -332,7 +332,7 @@ Path getDefaultProfile()
// Backwards compatibiliy measure: Make root's profile available as
// `.../default` as it's what NixOS and most of the init scripts expect
Path globalProfileLink = settings.nixStateDir + "/profiles/default";
if (getuid() == 0 && !pathExists(globalProfileLink)) {
if (isRootUser() && !pathExists(globalProfileLink)) {
replaceSymlink(profile, globalProfileLink);
}
return absPath(readLink(profileLink), dirOf(profileLink));

View file

@ -1307,7 +1307,7 @@ std::shared_ptr<Store> openFromNonUri(const std::string & uri, const Store::Para
#if __linux__
else if (!pathExists(stateDir)
&& params.empty()
&& getuid() != 0
&& !isRootUser()
&& !getEnv("NIX_STORE_DIR").has_value()
&& !getEnv("NIX_STATE_DIR").has_value())
{

View file

@ -113,4 +113,9 @@ std::string expandTilde(std::string_view path)
return std::string(path);
}
bool isRootUser() {
return getuid() == 0;
}
}

View file

@ -55,4 +55,10 @@ Path createNixStateDir();
*/
std::string expandTilde(std::string_view path);
/**
* Is the current user UID 0 on Unix?
*/
bool isRootUser();
}

View file

@ -24,6 +24,7 @@
#include "common-eval-args.hh"
#include "attr-path.hh"
#include "legacy.hh"
#include "users.hh"
using namespace nix;
using namespace std::string_literals;
@ -572,8 +573,9 @@ static void main_nix_build(int argc, char * * argv)
"BASH=%5%; "
"set +e; "
R"s([ -n "$PS1" -a -z "$NIX_SHELL_PRESERVE_PROMPT" ] && )s" +
(getuid() == 0 ? R"s(PS1='\n\[\033[1;31m\][nix-shell:\w]\$\[\033[0m\] '; )s"
: R"s(PS1='\n\[\033[1;32m\][nix-shell:\w]\$\[\033[0m\] '; )s") +
(isRootUser()
? R"s(PS1='\n\[\033[1;31m\][nix-shell:\w]\$\[\033[0m\] '; )s"
: R"s(PS1='\n\[\033[1;32m\][nix-shell:\w]\$\[\033[0m\] '; )s") +
"if [ \"$(type -t runHook)\" = function ]; then runHook shellHook; fi; "
"unset NIX_ENFORCE_PURITY; "
"shopt -u nullglob; "

View file

@ -1414,7 +1414,7 @@ static int main_nix_env(int argc, char * * argv)
replaceSymlink(
defaultChannelsDir(),
nixExprPath + "/channels");
if (getuid() != 0)
if (!isRootUser())
replaceSymlink(
rootChannelsDir(),
nixExprPath + "/channels_root");

View file

@ -348,7 +348,7 @@ void mainWrapped(int argc, char * * argv)
initGC();
#if __linux__
if (getuid() == 0) {
if (isRootUser()) {
try {
saveMountNamespace();
if (unshare(CLONE_NEWNS) == -1)