-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnamespace.c
More file actions
59 lines (50 loc) · 1.51 KB
/
namespace.c
File metadata and controls
59 lines (50 loc) · 1.51 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
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
void setup_mount_namespace() {
if (mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL) == -1) {
perror("Error in making mounts private");
exit(EXIT_FAILURE);
}
if (mount("proc", "/proc", "proc", MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL) == -1) {
perror("Error while mounting /proc");
exit(EXIT_FAILURE);
}
if (mount("tmpfs", "/tmp", "tmpfs", MS_NOSUID|MS_NODEV|MS_NOEXEC, "size=256m,mode=1777") == -1) {
perror("Error in mounting private /tmp");
exit(EXIT_FAILURE);
}
}
int main() {
if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET | CLONE_NEWUTS) == -1) {
perror("unshare");
exit(EXIT_FAILURE);
}
printf("Namespaces created successfully.\n");
pid_t child = fork();
if (child == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child == 0) {
printf("Namespace isolated. PID: %d\n", getpid());
printf(" Parent PID in isolated namespace: %d\n", getppid());
sethostname("container", 10);
setup_mount_namespace();
printf("Starting shell inside isolated namespace...\n");
execlp("/bin/bash", "/bin/bash", NULL);
perror("execlp");
exit(EXIT_FAILURE);
}
waitpid(child, NULL, 0);
return 0;
}