Skip to content

Instantly share code, notes, and snippets.

@Exchizz
Created November 4, 2019 21:02
Show Gist options
  • Save Exchizz/3f548563cd490f8f51871f14d903b484 to your computer and use it in GitHub Desktop.
Save Exchizz/3f548563cd490f8f51871f14d903b484 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mount.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
int spawn_bash(void);
int child(void *args)
{
printf("pid as seen in the child: %lu\n", (unsigned long)getpid());
if (chroot("/path/to/container/filesystem/") < 0) {
errExit("chroot");
}
if (mount("/", "/", "none", MS_PRIVATE, NULL) == -1){
errExit("mount-root");
}
mount("proc", "/proc", "proc", 0, NULL);
printf("Mounting root at %s\n", "/");
if (setgid(1000) != 0)
errExit("Set group");
if (setuid(1000) != 0)
errExit("Set user");
spawn_bash();
}
int spawn_bash(void)
{
chdir("/home/someuser/");
char *newargv[] = { "/bin/bash", NULL };
execv("/bin/bash", newargv);
perror("exec_bash");
exit(EXIT_FAILURE);
}
int main()
{
// see "man clone", to see what the following options does.
int namespaces = CLONE_NEWUTS|CLONE_NEWPID|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWNET|CLONE_NEWCGROUP;
// This is where the magic happens!!!
pid_t p = clone(child, malloc(4096) + 4096, SIGCHLD|namespaces, NULL);
if (p == -1) {
perror("clone");
exit(1);
}
printf("child pid: %lu\n", p);
waitpid(p, NULL, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment