Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
Based on demo_userns.c by Michael Kerrisk
Copyright 2013, Michael Kerrisk
Licensed under GNU General Public License v2 or later
*/
#define _GNU_SOURCE
#include <sys/wait.h>
#include <sys/sysmacros.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
static int /* Startup function for cloned child */
childFunc(void *arg)
{
if (mount("minijail-devfs", "/dev", "tmpfs",
MS_NOEXEC | MS_NOSUID, "size=5M,mode=755") != 0)
errExit("mount");
if (mknod("/dev/null", S_IFCHR|0666, makedev(1, 3)) != 0)
errExit("mknod");
return 0;
}
#define STACK_SIZE (1024 * 1024)
static char child_stack[STACK_SIZE]; /* Space for child's stack */
int
main(int argc, char *argv[])
{
pid_t pid;
/* Create child; child commences execution in childFunc() */
pid = clone(childFunc, child_stack + STACK_SIZE, /* Assume stack
grows downward */
CLONE_NEWUSER | CLONE_NEWNS | SIGCHLD, argv[1]);
if (pid == -1)
errExit("clone");
/* Parent falls through to here. Wait for child. */
if (waitpid(pid, NULL, 0) == -1)
errExit("waitpid");
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment