owner.c 2.0 KB

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