Skip to content

Instantly share code, notes, and snippets.

@hashbrowncipher
Last active August 29, 2015 14:10
Show Gist options
  • Save hashbrowncipher/a1928d0aed1b24105a7a to your computer and use it in GitHub Desktop.
Save hashbrowncipher/a1928d0aed1b24105a7a to your computer and use it in GitHub Desktop.
Wraps running a process under a PID namespace.
#include <errno.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char * argv[]) {
if (argc < 2) {
printf("Usage: %s <command> <arg1> ... <argn>\n", argv[0]);
return 252;
}
int ret;
ret = unshare(CLONE_NEWPID);
if (ret < 0) {
return 255;
}
/*
* unshare(2) requires root privileges, so the expectation is for this script
* to execute setuid root. Once we've done unshare(), we drop root privs
* like they're hot.
*/
ret = getuid();
ret = setuid(ret);
if (ret < 0) {
return 255;
}
ret = fork();
if (ret < 0) {
return 255;
} else if (ret == 0) {
execvp(argv[1], argv + 1);
/* If we get here, execvp has failed. Set the exit code in accordance
* with POSIX */
if(errno == ENOENT) {
return 127;
} else {
return 126;
}
}
int status;
ret = wait(&status);
if (ret < 0) {
return 255;
}
if (WIFSIGNALED(status)) {
return 128 + WTERMSIG(status);
}
return WEXITSTATUS(status);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment