passwd: Drop privileges after opening files for writing

Once we have /etc/passwd and /etc/shadow open for writing, there's no
need for passwd to continue running as root.

We can also drop a bunch of pledge promises, further tightening things.
This commit is contained in:
Andreas Kling 2021-01-09 17:46:30 +01:00
parent 9a688af4b1
commit 71d23bb262
Notes: sideshowbarker 2024-07-18 23:59:38 +09:00

View file

@ -39,7 +39,7 @@ int main(int argc, char** argv)
return 1;
}
if (pledge("stdio wpath rpath cpath tty", nullptr) < 0) {
if (pledge("stdio wpath rpath cpath tty id", nullptr) < 0) {
perror("pledge");
return 1;
}
@ -86,6 +86,27 @@ int main(int argc, char** argv)
return 1;
}
// Drop privileges after opening all the files through the Core::Account object.
auto gid = getgid();
if (setresgid(gid, gid, gid) < 0) {
perror("setresgid");
return 1;
}
auto uid = getuid();
if (setresuid(uid, uid, uid) < 0) {
perror("setresuid");
return 1;
}
// Make sure /etc/passwd is open and ready for reading, then we can drop a bunch of pledge promises.
setpwent();
if (pledge("stdio tty", nullptr) < 0) {
perror("pledge");
return 1;
}
// target_account is the account we are changing the password of.
auto target_account = account_or_error.value();