Skip to content

Instantly share code, notes, and snippets.

@stek29
Created April 13, 2024 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stek29/b682c81315c220db0248ed1b5700df2a to your computer and use it in GitHub Desktop.
Save stek29/b682c81315c220db0248ed1b5700df2a to your computer and use it in GitHub Desktop.
example on how to use pivot_root, and demonstration of fd's still being valid after pivot
#define _GNU_SOURCE
#include <sys/syscall.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sched.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char* const argv[], char* const envp[]) {
int fd1 = open("/etc/passwd", O_RDONLY);
unshare(CLONE_NEWNS);
mount(NULL, "/", NULL, MS_PRIVATE | MS_REC, NULL);
char cwd[1024];
getcwd(cwd, sizeof(cwd));
char put_old[1024];
snprintf(put_old, sizeof(put_old) - 1, "%s/oldroot", cwd);
mkdir(put_old, 0777);
mount(cwd, cwd, NULL, MS_BIND, NULL);
syscall(SYS_pivot_root, cwd, put_old);
chdir("/");
umount2("/oldroot", MNT_DETACH);
rmdir("/oldroot");
/*
mkdir("/sys", 0777);
mount(NULL, "/sys", "sysfs", 0, NULL);
mkdir("/proc", 0777);
mount(NULL, "/proc", "proc", 0, NULL);
*/
char buf[1024];
while (1) {
ssize_t rd = read(fd1, buf, sizeof(buf));
if (rd <= 0) {
break;
}
write(1, buf, rd);
}
close(fd1);
execve("/busybox", &argv[1], envp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment