This repository has been archived by the owner on Dec 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnschroot.c
86 lines (69 loc) · 2 KB
/
nschroot.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* nschroot - chroot into a fresh Linux namespace
* Copyright 2011, Albert P. Tobey <[email protected]>
* https://github.com/tobert/nslite
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the Artistic License 2.0. See the file LICENSE for details.
*/
#include "config.h"
#include <err.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "nsfork.h"
static void usage(char *program)
{
printf("%s: chroot into a new Linux namespace.\n\n", program);
printf("Usage:\n");
printf(" %s <chroot path> <executable> [executable args]\n", program);
exit(1);
}
int main(int argc, char *argv[])
{
struct stat sb;
pid_t child;
int i, status;
char *program, *newroot, *command;
char *newenv[] = { NULL };
char **newargv;
if (argc < 3)
usage(argv[0]);
program = argv[0];
newroot = argv[1];
command = argv[2];
if (stat(newroot, &sb) == -1)
err(1, "'%s'", newroot);
if (!S_ISDIR(sb.st_mode))
errx(1, "stat(): '%s' is not a directory\n", newroot);
newargv = malloc(sizeof(argv));
for (i=2; i<=argc; i++) {
newargv[i-2] = argv[i];
}
newargv[i] = "\0";
child = nsfork(0);
/* parent process - wait here for the child to exit */
if (child > 0) {
/* TODO: good enough for testing but needs to be checked */
waitpid(child, &status, 0);
}
/* child process */
else if (child == 0) {
if (chdir(newroot) == -1)
err(1, "chdir to directory '%s' failed", newroot);
if (chroot(".") == -1)
err(1, "chroot failed");
if (stat(command, &sb) == -1)
err(1, "'%s'", command);
if (execve(command, newargv, newenv) == -1)
err(1, "'%s'", command);
}
else {
errx(1, "error in nsfork(): probably lacking privileges or running on an old kernel\n");
}
free(newargv);
return(0);
}