Drop root privileges earlier

We don't need the root privileges after we unshare and the first fork. Therefor
we can drop those for safety reasons.
This commit is contained in:
madmaurice 2021-01-12 19:50:07 +01:00
parent f3cd63c137
commit 1f5e1a9c1f

34
main.c
View file

@ -9,6 +9,22 @@
#include <sys/wait.h> #include <sys/wait.h>
#include <unistd.h> #include <unistd.h>
void drop_root(void) {
// Drop root privileges
if (seteuid(getuid()) == -1)
{
int err = errno;
printf("Failed to drop root privileges with seteuid (%d)\n", err);
exit(err);
}
if (setegid(getgid()) == -1)
{
int err = errno;
printf("Failed to drop root privileges with setegid (%d)\n", err);
exit(err);
}
}
char** argdup(int argc, const char** argv) char** argdup(int argc, const char** argv)
{ {
@ -46,6 +62,9 @@ int main(int argc, const char** argv)
return err; return err;
} }
// Drop root privileges, we only needed those for the unshare call and fork above.
drop_root();
if (pid != 0) if (pid != 0)
{ {
// parent waits for child then exits // parent waits for child then exits
@ -94,21 +113,6 @@ int main(int argc, const char** argv)
// First child of init process. do exec here // First child of init process. do exec here
// use cli arguments for subprocess. skip 0 as it's our programs name. // use cli arguments for subprocess. skip 0 as it's our programs name.
// Drop root privileges
if (seteuid(getuid()) == -1)
{
int err = errno;
printf("Failed to drop root privileges with seteuid (%d)\n", err);
return err;
}
if (setegid(getgid()) == -1)
{
int err = errno;
printf("Failed to drop root privileges with setegid (%d)\n", err);
return err;
}
char** newargs = argdup(argc-1, &argv[1]); char** newargs = argdup(argc-1, &argv[1]);
if (execvp(newargs[0], newargs) == -1) if (execvp(newargs[0], newargs) == -1)