owner.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #define _GNU_SOURCE
  2. #include <sched.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <signal.h>
  7. #include <errno.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <sys/ioctl.h>
  12. #include <sys/prctl.h>
  13. #include <sys/wait.h>
  14. #define NSIO 0xb7
  15. #define NS_GET_USERNS _IO(NSIO, 0x1)
  16. #define pr_err(fmt, ...) \
  17. ({ \
  18. fprintf(stderr, "%s:%d:" fmt ": %m\n", \
  19. __func__, __LINE__, ##__VA_ARGS__); \
  20. 1; \
  21. })
  22. int main(int argc, char *argvp[])
  23. {
  24. int pfd[2], ns, uns, init_uns;
  25. struct stat st1, st2;
  26. char path[128];
  27. pid_t pid;
  28. char c;
  29. if (pipe(pfd))
  30. return 1;
  31. pid = fork();
  32. if (pid < 0)
  33. return pr_err("fork");
  34. if (pid == 0) {
  35. prctl(PR_SET_PDEATHSIG, SIGKILL);
  36. if (unshare(CLONE_NEWUTS | CLONE_NEWUSER))
  37. return pr_err("unshare");
  38. close(pfd[0]);
  39. close(pfd[1]);
  40. while (1)
  41. sleep(1);
  42. return 0;
  43. }
  44. close(pfd[1]);
  45. if (read(pfd[0], &c, 1) != 0)
  46. return pr_err("Unable to read from pipe");
  47. close(pfd[0]);
  48. snprintf(path, sizeof(path), "/proc/%d/ns/uts", pid);
  49. ns = open(path, O_RDONLY);
  50. if (ns < 0)
  51. return pr_err("Unable to open %s", path);
  52. uns = ioctl(ns, NS_GET_USERNS);
  53. if (uns < 0)
  54. return pr_err("Unable to get an owning user namespace");
  55. if (fstat(uns, &st1))
  56. return pr_err("fstat");
  57. snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);
  58. if (stat(path, &st2))
  59. return pr_err("stat");
  60. if (st1.st_ino != st2.st_ino)
  61. return pr_err("NS_GET_USERNS returned a wrong namespace");
  62. init_uns = ioctl(uns, NS_GET_USERNS);
  63. if (uns < 0)
  64. return pr_err("Unable to get an owning user namespace");
  65. if (ioctl(init_uns, NS_GET_USERNS) >= 0 || errno != EPERM)
  66. return pr_err("Don't get EPERM");
  67. if (unshare(CLONE_NEWUSER))
  68. return pr_err("unshare");
  69. if (ioctl(ns, NS_GET_USERNS) >= 0 || errno != EPERM)
  70. return pr_err("Don't get EPERM");
  71. if (ioctl(init_uns, NS_GET_USERNS) >= 0 || errno != EPERM)
  72. return pr_err("Don't get EPERM");
  73. kill(pid, SIGKILL);
  74. wait(NULL);
  75. return 0;
  76. }