nsenter.c 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // +build cgo
  2. //
  3. // formated with indent -linux nsenter.c
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <linux/limits.h>
  7. #include <linux/sched.h>
  8. #include <signal.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <sys/prctl.h>
  13. #include <sys/types.h>
  14. #include <unistd.h>
  15. #include <getopt.h>
  16. #ifndef PR_SET_CHILD_SUBREAPER
  17. #define PR_SET_CHILD_SUBREAPER 36
  18. #endif
  19. static const kBufSize = 256;
  20. static const char *kNsEnter = "nsenter";
  21. void get_args(int *argc, char ***argv)
  22. {
  23. // Read argv
  24. int fd = open("/proc/self/cmdline", O_RDONLY);
  25. // Read the whole commandline.
  26. ssize_t contents_size = 0;
  27. ssize_t contents_offset = 0;
  28. char *contents = NULL;
  29. ssize_t bytes_read = 0;
  30. do {
  31. contents_size += kBufSize;
  32. contents = (char *)realloc(contents, contents_size);
  33. bytes_read =
  34. read(fd, contents + contents_offset,
  35. contents_size - contents_offset);
  36. contents_offset += bytes_read;
  37. }
  38. while (bytes_read > 0);
  39. close(fd);
  40. // Parse the commandline into an argv. /proc/self/cmdline has \0 delimited args.
  41. ssize_t i;
  42. *argc = 0;
  43. for (i = 0; i < contents_offset; i++) {
  44. if (contents[i] == '\0') {
  45. (*argc)++;
  46. }
  47. }
  48. *argv = (char **)malloc(sizeof(char *) * ((*argc) + 1));
  49. int idx;
  50. for (idx = 0; idx < (*argc); idx++) {
  51. (*argv)[idx] = contents;
  52. contents += strlen(contents) + 1;
  53. }
  54. (*argv)[*argc] = NULL;
  55. }
  56. // Use raw setns syscall for versions of glibc that don't include it (namely glibc-2.12)
  57. #if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14
  58. #define _GNU_SOURCE
  59. #include <sched.h>
  60. #include "syscall.h"
  61. #ifdef SYS_setns
  62. int setns(int fd, int nstype)
  63. {
  64. return syscall(SYS_setns, fd, nstype);
  65. }
  66. #endif
  67. #endif
  68. void print_usage()
  69. {
  70. fprintf(stderr,
  71. "nsenter --nspid <pid> --console <console> -- cmd1 arg1 arg2...\n");
  72. }
  73. void nsenter()
  74. {
  75. int argc, c;
  76. char **argv;
  77. get_args(&argc, &argv);
  78. // check argv 0 to ensure that we are supposed to setns
  79. // we use strncmp to test for a value of "nsenter" but also allows alternate implmentations
  80. // after the setns code path to continue to use the argv 0 to determine actions to be run
  81. // resulting in the ability to specify "nsenter-mknod", "nsenter-exec", etc...
  82. if (strncmp(argv[0], kNsEnter, strlen(kNsEnter)) != 0) {
  83. return;
  84. }
  85. if (prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) == -1) {
  86. fprintf(stderr, "nsenter: failed to set child subreaper: %s",
  87. strerror(errno));
  88. exit(1);
  89. }
  90. static const struct option longopts[] = {
  91. {"nspid", required_argument, NULL, 'n'},
  92. {"console", required_argument, NULL, 't'},
  93. {NULL, 0, NULL, 0}
  94. };
  95. pid_t init_pid = -1;
  96. char *init_pid_str = NULL;
  97. char *console = NULL;
  98. while ((c = getopt_long_only(argc, argv, "n:c:", longopts, NULL)) != -1) {
  99. switch (c) {
  100. case 'n':
  101. init_pid_str = optarg;
  102. break;
  103. case 't':
  104. console = optarg;
  105. break;
  106. }
  107. }
  108. if (init_pid_str == NULL) {
  109. print_usage();
  110. exit(1);
  111. }
  112. init_pid = strtol(init_pid_str, NULL, 10);
  113. if ((init_pid == 0 && errno == EINVAL) || errno == ERANGE) {
  114. fprintf(stderr,
  115. "nsenter: Failed to parse PID from \"%s\" with output \"%d\" and error: \"%s\"\n",
  116. init_pid_str, init_pid, strerror(errno));
  117. print_usage();
  118. exit(1);
  119. }
  120. argc -= 3;
  121. argv += 3;
  122. if (setsid() == -1) {
  123. fprintf(stderr, "setsid failed. Error: %s\n", strerror(errno));
  124. exit(1);
  125. }
  126. // before we setns we need to dup the console
  127. int consolefd = -1;
  128. if (console != NULL) {
  129. consolefd = open(console, O_RDWR);
  130. if (consolefd < 0) {
  131. fprintf(stderr,
  132. "nsenter: failed to open console %s %s\n",
  133. console, strerror(errno));
  134. exit(1);
  135. }
  136. }
  137. // Setns on all supported namespaces.
  138. char ns_dir[PATH_MAX];
  139. memset(ns_dir, 0, PATH_MAX);
  140. snprintf(ns_dir, PATH_MAX - 1, "/proc/%d/ns/", init_pid);
  141. char *namespaces[] = { "ipc", "uts", "net", "pid", "mnt" };
  142. const int num = sizeof(namespaces) / sizeof(char *);
  143. int i;
  144. for (i = 0; i < num; i++) {
  145. char buf[PATH_MAX];
  146. memset(buf, 0, PATH_MAX);
  147. snprintf(buf, PATH_MAX - 1, "%s%s", ns_dir, namespaces[i]);
  148. int fd = open(buf, O_RDONLY);
  149. if (fd == -1) {
  150. // Ignore nonexistent namespaces.
  151. if (errno == ENOENT)
  152. continue;
  153. fprintf(stderr,
  154. "nsenter: Failed to open ns file \"%s\" for ns \"%s\" with error: \"%s\"\n",
  155. buf, namespaces[i], strerror(errno));
  156. exit(1);
  157. }
  158. // Set the namespace.
  159. if (setns(fd, 0) == -1) {
  160. fprintf(stderr,
  161. "nsenter: Failed to setns for \"%s\" with error: \"%s\"\n",
  162. namespaces[i], strerror(errno));
  163. exit(1);
  164. }
  165. close(fd);
  166. }
  167. // We must fork to actually enter the PID namespace.
  168. int child = fork();
  169. if (child == 0) {
  170. if (consolefd != -1) {
  171. if (dup2(consolefd, STDIN_FILENO) != 0) {
  172. fprintf(stderr, "nsenter: failed to dup 0 %s\n",
  173. strerror(errno));
  174. exit(1);
  175. }
  176. if (dup2(consolefd, STDOUT_FILENO) != STDOUT_FILENO) {
  177. fprintf(stderr, "nsenter: failed to dup 1 %s\n",
  178. strerror(errno));
  179. exit(1);
  180. }
  181. if (dup2(consolefd, STDERR_FILENO) != STDERR_FILENO) {
  182. fprintf(stderr, "nsenter: failed to dup 2 %s\n",
  183. strerror(errno));
  184. exit(1);
  185. }
  186. }
  187. // Finish executing, let the Go runtime take over.
  188. return;
  189. } else {
  190. // Parent, wait for the child.
  191. int status = 0;
  192. if (waitpid(child, &status, 0) == -1) {
  193. fprintf(stderr,
  194. "nsenter: Failed to waitpid with error: \"%s\"\n",
  195. strerror(errno));
  196. exit(1);
  197. }
  198. // Forward the child's exit code or re-send its death signal.
  199. if (WIFEXITED(status)) {
  200. exit(WEXITSTATUS(status));
  201. } else if (WIFSIGNALED(status)) {
  202. kill(getpid(), WTERMSIG(status));
  203. }
  204. exit(1);
  205. }
  206. return;
  207. }