Make the operation of wrap.c conditional on need

Don't create a user namespace if we are already root and don't chroot if
cwd is already root
This commit is contained in:
MaxHearnden 2023-11-27 22:28:31 +00:00
parent a135fc1eca
commit f13aa2964a

View file

@ -92,25 +92,44 @@ void deny_setgroups() {
} }
int main(int argc, char **argv, char **envp) { int main(int argc, char **argv, char **envp) {
int uid = geteuid(); char *cwd = get_current_dir_name();
int gid = getegid(); /* Do nothing if cwd is already root */
unshare(CLONE_NEWUSER | CLONE_NEWNS); if (strcmp(cwd, "/")) {
mkdir ("dev", 0755); int uid = geteuid();
touch ("dev/null"); int gid = getegid();
mount ("/dev/null", "dev/null", "", MS_BIND, NULL); /* Don't create a user and mount namespace if we are already root */
touch ("dev/zero"); if (uid != 0) {
mount ("/dev/zero", "dev/zero", "", MS_BIND, NULL); require(unshare(CLONE_NEWUSER | CLONE_NEWNS) == 0, "Failed to create user and mount namespaces");
touch ("dev/random"); /* Prevent the use of setgroups and make gid_map writeable */
mount ("/dev/random", "dev/random", "", MS_BIND, NULL); deny_setgroups();
touch ("dev/urandom"); /* Map the root user in the user namespace to our user id */
mount ("/dev/urandom", "dev/urandom", "", MS_BIND, NULL); set_map(uid, "/proc/self/uid_map");
touch ("dev/ptmx"); /* Map the root group in the user namespace to our group id */
mount ("/dev/ptmx", "dev/ptmx", "", MS_BIND, NULL); set_map(gid, "/proc/self/gid_map");
touch ("dev/tty"); }
mount ("/dev/tty", "dev/tty", "", MS_BIND, NULL); mkdir ("dev", 0755);
deny_setgroups(); touch ("dev/null");
set_map(uid, "/proc/self/uid_map"); mount ("/dev/null", "dev/null", "", MS_BIND, NULL);
set_map(gid, "/proc/self/gid_map"); touch ("dev/zero");
chroot ("."); mount ("/dev/zero", "dev/zero", "", MS_BIND, NULL);
execve (argv[1], argv + 4 , envp); touch ("dev/random");
mount ("/dev/random", "dev/random", "", MS_BIND, NULL);
touch ("dev/urandom");
mount ("/dev/urandom", "dev/urandom", "", MS_BIND, NULL);
touch ("dev/ptmx");
mount ("/dev/ptmx", "dev/ptmx", "", MS_BIND, NULL);
touch ("dev/tty");
mount ("/dev/tty", "dev/tty", "", MS_BIND, NULL);
mkdir ("dev/shm", 0755);
mount ("tmpfs", "dev/shm", "tmpfs", 0, NULL);
mkdir ("proc", 0755);
mount ("proc", "proc", "proc", 0, NULL);
mkdir ("sys", 0755);
mount ("/sys", "sys", "", MS_BIND, NULL);
mkdir ("tmp", 0755);
mkdir ("tmpfs", "tmp", "tmpfs", 0, NULL);
chroot (".");
}
free(cwd);
return execve (argv[1], argv + sizeof(char *) , envp);
} }