-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserns_spawn.c
More file actions
70 lines (67 loc) · 1.63 KB
/
Copy pathuserns_spawn.c
File metadata and controls
70 lines (67 loc) · 1.63 KB
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
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <sched.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
static int write_file(const char *path, const char *s)
{
int fd = open(path, O_WRONLY);
if (fd < 0) return -1;
ssize_t n = write(fd, s, strlen(s));
close(fd);
return n == (ssize_t)strlen(s) ? 0 : -1;
}
static int child_fn(void *arg)
{
char buf[64];
snprintf(buf, sizeof buf, "0 %d 1", getuid());
if (write_file("/proc/self/uid_map", buf) < 0) {
perror("uid_map");
return 1;
}
if (write_file("/proc/self/setgroups", "deny") < 0) {
}
snprintf(buf, sizeof buf, "0 %d 1", getgid());
if (write_file("/proc/self/gid_map", buf) < 0) {
perror("gid_map");
return 1;
}
char **argv = arg;
execvp(argv[0], argv);
perror("execvp");
return 1;
}
int main(int argc, char **argv)
{
#if !defined(__linux__)
fprintf(stderr, "userns_spawn is Linux-only");
return 1;
#else
if (argc < 2) {
fprintf(stderr, "usage: %s command [args...]", argv[0]);
return 1;
}
size_t stack_size = 1024 * 1024;
void *stack = malloc(stack_size);
if (!stack) return 1;
void *stack_top = (char *)stack + stack_size;
int flags = CLONE_NEWUSER | SIGCHLD;
char **child_argv = &argv[1];
pid_t pid = clone(child_fn, stack_top, flags, child_argv);
if (pid < 0) {
perror("clone");
return 1;
}
int status;
waitpid(pid, &status, 0);
free(stack);
return 0;
#endif
}