From 8798317ddc1bfbbdb3af56466a90a4fa61fb5309 Mon Sep 17 00:00:00 2001 From: Jake Hillion Date: Mon, 23 May 2022 00:28:16 +0100 Subject: [PATCH] wip: more examples --- examples/dir_descriptor.c | 23 ++++++++++++++++++ examples/unshare_mount_passwd.c | 42 +++++++++++++++++++++++++++++++++ examples/unshare_user.c | 20 ++++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 examples/dir_descriptor.c create mode 100644 examples/unshare_mount_passwd.c create mode 100644 examples/unshare_user.c diff --git a/examples/dir_descriptor.c b/examples/dir_descriptor.c new file mode 100644 index 0000000..18eaf2b --- /dev/null +++ b/examples/dir_descriptor.c @@ -0,0 +1,23 @@ +#include +#include +#include +#include +#include + +int main() { + int dirfd; + + if ((dirfd = open("/tmp", __O_DIRECTORY)) < 0) + perror("opendir"); + if (openat(dirfd, "filethatdoesexist", O_RDONLY) < 0) + perror("openat0"); + if (chroot("/tmp")) + perror("chroot"); + if (open("/etc/passwd", O_RDONLY) < 0) + perror("open"); + if (openat(dirfd, "../etc/passwd", O_RDONLY) < 0) + perror("openat1"); + if (openat(dirfd, "filethatdoesexist", O_RDONLY) < 0) + perror("openat2"); +} + diff --git a/examples/unshare_mount_passwd.c b/examples/unshare_mount_passwd.c new file mode 100644 index 0000000..957fc84 --- /dev/null +++ b/examples/unshare_mount_passwd.c @@ -0,0 +1,42 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define BUF_SIZE 1024 + +void print_file(int fd); + +int main() { + int fd; + + if ((fd = open("/etc/passwd", O_RDONLY)) < 0) + perror("open"); + print_file(fd); + if (close(fd)) + perror("close"); + + if (unshare(CLONE_NEWNS)) + perror("unshare"); + printf("----- unshared -----\n"); + + if ((fd = open("/etc/passwd", O_RDONLY)) < 0) + perror("open"); + print_file(fd); + if (close(fd)) + perror("close"); +} + +void print_file(int fd) { + char buf[BUF_SIZE]; + int bytes_read; + + while ((bytes_read = read(fd, buf, BUF_SIZE)) > 0) + if (write(1, buf, bytes_read) < 0) + perror("write"); + + if (bytes_read == -1) + perror("read"); +} + diff --git a/examples/unshare_user.c b/examples/unshare_user.c new file mode 100644 index 0000000..f3254da --- /dev/null +++ b/examples/unshare_user.c @@ -0,0 +1,20 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +int main() { + + int fd; + + if (unshare(CLONE_NEWUSER)) + perror("unshare"); + if ((fd = open("/proc/self/uid_map", O_WRONLY)) == -1) + perror("open"); + if (write(fd, "0 0 4294967295\n", 15) == -1) + perror("write"); + if (execl("/bin/bash", "/bin/bash", NULL)) + perror("execl"); +} +