]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/attach.c
fix non-root user cannot write /dev/stdout
[mirror_lxc.git] / src / lxc / attach.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #ifndef _GNU_SOURCE
4 #define _GNU_SOURCE 1
5 #endif
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <grp.h>
9 #include <linux/unistd.h>
10 #include <pwd.h>
11 #include <pthread.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/mount.h>
17 #include <sys/param.h>
18 #include <sys/prctl.h>
19 #include <sys/socket.h>
20 #include <sys/syscall.h>
21 #include <sys/wait.h>
22 #include <termios.h>
23 #include <unistd.h>
24
25 #include <lxc/lxccontainer.h>
26
27 #include "af_unix.h"
28 #include "attach.h"
29 #include "caps.h"
30 #include "cgroup.h"
31 #include "commands.h"
32 #include "conf.h"
33 #include "config.h"
34 #include "confile.h"
35 #include "log.h"
36 #include "lsm/lsm.h"
37 #include "lxclock.h"
38 #include "lxcseccomp.h"
39 #include "macro.h"
40 #include "mainloop.h"
41 #include "memory_utils.h"
42 #include "namespace.h"
43 #include "raw_syscalls.h"
44 #include "syscall_wrappers.h"
45 #include "terminal.h"
46 #include "utils.h"
47
48 #if HAVE_SYS_PERSONALITY_H
49 #include <sys/personality.h>
50 #endif
51
52 lxc_log_define(attach, lxc);
53
54 /* Define default options if no options are supplied by the user. */
55 static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
56
57 static struct lxc_proc_context_info *lxc_proc_get_context_info(pid_t pid)
58 {
59 __do_free char *line = NULL;
60 __do_fclose FILE *proc_file = NULL;
61 __do_free struct lxc_proc_context_info *info = NULL;
62 int ret;
63 bool found;
64 char proc_fn[LXC_PROC_STATUS_LEN];
65 size_t line_bufsz = 0;
66
67 /* Read capabilities. */
68 ret = snprintf(proc_fn, LXC_PROC_STATUS_LEN, "/proc/%d/status", pid);
69 if (ret < 0 || ret >= LXC_PROC_STATUS_LEN)
70 return NULL;
71
72 proc_file = fopen(proc_fn, "re");
73 if (!proc_file)
74 return log_error_errno(NULL, errno, "Failed to open %s", proc_fn);
75
76 info = calloc(1, sizeof(*info));
77 if (!info)
78 return NULL;
79
80 found = false;
81
82 while (getline(&line, &line_bufsz, proc_file) != -1) {
83 ret = sscanf(line, "CapBnd: %llx", &info->capability_mask);
84 if (ret != EOF && ret == 1) {
85 found = true;
86 break;
87 }
88 }
89
90 if (!found)
91 return log_error_errno(NULL, ENOENT, "Failed to read capability bounding set from %s", proc_fn);
92
93 info->lsm_label = lsm_process_label_get(pid);
94 info->ns_inherited = 0;
95 for (int i = 0; i < LXC_NS_MAX; i++)
96 info->ns_fd[i] = -EBADF;
97
98 return move_ptr(info);
99 }
100
101 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info *ctx)
102 {
103 for (int i = 0; i < LXC_NS_MAX; i++)
104 close_prot_errno_disarm(ctx->ns_fd[i]);
105 }
106
107 static void lxc_proc_put_context_info(struct lxc_proc_context_info *ctx)
108 {
109 free(ctx->lsm_label);
110 ctx->lsm_label = NULL;
111
112 if (ctx->container) {
113 lxc_container_put(ctx->container);
114 ctx->container = NULL;
115 }
116
117 lxc_proc_close_ns_fd(ctx);
118 free(ctx);
119 }
120
121 /**
122 * in_same_namespace - Check whether two processes are in the same namespace.
123 * @pid1 - PID of the first process.
124 * @pid2 - PID of the second process.
125 * @ns - Name of the namespace to check. Must correspond to one of the names
126 * for the namespaces as shown in /proc/<pid/ns/
127 *
128 * If the two processes are not in the same namespace returns an fd to the
129 * namespace of the second process identified by @pid2. If the two processes are
130 * in the same namespace returns -EINVAL, -1 if an error occurred.
131 */
132 static int in_same_namespace(pid_t pid1, pid_t pid2, const char *ns)
133 {
134 __do_close int ns_fd1 = -EBADF, ns_fd2 = -EBADF;
135 int ret = -1;
136 struct stat ns_st1, ns_st2;
137
138 ns_fd1 = lxc_preserve_ns(pid1, ns);
139 if (ns_fd1 < 0) {
140 /* The kernel does not support this namespace. This is not an
141 * error.
142 */
143 if (errno == ENOENT)
144 return -EINVAL;
145
146 return -1;
147 }
148
149 ns_fd2 = lxc_preserve_ns(pid2, ns);
150 if (ns_fd2 < 0)
151 return -1;
152
153 ret = fstat(ns_fd1, &ns_st1);
154 if (ret < 0)
155 return -1;
156
157 ret = fstat(ns_fd2, &ns_st2);
158 if (ret < 0)
159 return -1;
160
161 /* processes are in the same namespace */
162 if ((ns_st1.st_dev == ns_st2.st_dev) && (ns_st1.st_ino == ns_st2.st_ino))
163 return -EINVAL;
164
165 /* processes are in different namespaces */
166 return move_fd(ns_fd2);
167 }
168
169 static int lxc_attach_to_ns(pid_t pid, struct lxc_proc_context_info *ctx)
170 {
171 for (int i = 0; i < LXC_NS_MAX; i++) {
172 int ret;
173
174 if (ctx->ns_fd[i] < 0)
175 continue;
176
177 ret = setns(ctx->ns_fd[i], ns_info[i].clone_flag);
178 if (ret < 0)
179 return log_error_errno(-1,
180 errno, "Failed to attach to %s namespace of %d",
181 ns_info[i].proc_name, pid);
182
183 DEBUG("Attached to %s namespace of %d", ns_info[i].proc_name, pid);
184 }
185
186 return 0;
187 }
188
189 int lxc_attach_remount_sys_proc(void)
190 {
191 int ret;
192
193 ret = unshare(CLONE_NEWNS);
194 if (ret < 0)
195 return log_error_errno(-1, errno, "Failed to unshare mount namespace");
196
197 if (detect_shared_rootfs()) {
198 if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL)) {
199 SYSERROR("Failed to make / rslave");
200 ERROR("Continuing...");
201 }
202 }
203
204 /* Assume /proc is always mounted, so remount it. */
205 ret = umount2("/proc", MNT_DETACH);
206 if (ret < 0)
207 return log_error_errno(-1, errno, "Failed to unmount /proc");
208
209 ret = mount("none", "/proc", "proc", 0, NULL);
210 if (ret < 0)
211 return log_error_errno(-1, errno, "Failed to remount /proc");
212
213 /*
214 * Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
215 * we ignore it because it may not have been mounted in the first place.
216 */
217 ret = umount2("/sys", MNT_DETACH);
218 if (ret < 0 && errno != EINVAL)
219 return log_error_errno(-1, errno, "Failed to unmount /sys");
220
221 /* Remount it. */
222 if (ret == 0 && mount("none", "/sys", "sysfs", 0, NULL))
223 return log_error_errno(-1, errno, "Failed to remount /sys");
224
225 return 0;
226 }
227
228 static int lxc_attach_drop_privs(struct lxc_proc_context_info *ctx)
229 {
230 int last_cap;
231
232 last_cap = lxc_caps_last_cap();
233 for (int cap = 0; cap <= last_cap; cap++) {
234 if (ctx->capability_mask & (1LL << cap))
235 continue;
236
237 if (prctl(PR_CAPBSET_DROP, prctl_arg(cap), prctl_arg(0),
238 prctl_arg(0), prctl_arg(0)))
239 return log_error_errno(-1, errno, "Failed to drop capability %d", cap);
240
241 TRACE("Dropped capability %d", cap);
242 }
243
244 return 0;
245 }
246
247 static int lxc_attach_set_environment(struct lxc_proc_context_info *init_ctx,
248 enum lxc_attach_env_policy_t policy,
249 char **extra_env, char **extra_keep)
250 {
251 int ret;
252 struct lxc_list *iterator;
253
254 if (policy == LXC_ATTACH_CLEAR_ENV) {
255 int path_kept = 0;
256 char **extra_keep_store = NULL;
257
258 if (extra_keep) {
259 size_t count, i;
260
261 for (count = 0; extra_keep[count]; count++)
262 ;
263
264 extra_keep_store = calloc(count, sizeof(char *));
265 if (!extra_keep_store)
266 return -1;
267
268 for (i = 0; i < count; i++) {
269 char *v = getenv(extra_keep[i]);
270 if (v) {
271 extra_keep_store[i] = strdup(v);
272 if (!extra_keep_store[i]) {
273 while (i > 0)
274 free(extra_keep_store[--i]);
275
276 free(extra_keep_store);
277 return -1;
278 }
279
280 if (strcmp(extra_keep[i], "PATH") == 0)
281 path_kept = 1;
282 }
283 }
284 }
285
286 if (clearenv()) {
287 if (extra_keep_store) {
288 char **p;
289
290 for (p = extra_keep_store; *p; p++)
291 free(*p);
292
293 free(extra_keep_store);
294 }
295
296 return log_error(-1, "Failed to clear environment");
297 }
298
299 if (extra_keep_store) {
300 size_t i;
301
302 for (i = 0; extra_keep[i]; i++) {
303 if (extra_keep_store[i]) {
304 ret = setenv(extra_keep[i], extra_keep_store[i], 1);
305 if (ret < 0)
306 SYSWARN("Failed to set environment variable");
307 }
308
309 free(extra_keep_store[i]);
310 }
311
312 free(extra_keep_store);
313 }
314
315 /* Always set a default path; shells and execlp tend to be fine
316 * without it, but there is a disturbing number of C programs
317 * out there that just assume that getenv("PATH") is never NULL
318 * and then die a painful segfault death.
319 */
320 if (!path_kept) {
321 ret = setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
322 if (ret < 0)
323 SYSWARN("Failed to set environment variable");
324 }
325 }
326
327 ret = putenv("container=lxc");
328 if (ret < 0)
329 return log_warn(-1, "Failed to set environment variable");
330
331 /* Set container environment variables.*/
332 if (init_ctx && init_ctx->container && init_ctx->container->lxc_conf) {
333 lxc_list_for_each(iterator, &init_ctx->container->lxc_conf->environment) {
334 char *env_tmp;
335
336 env_tmp = strdup((char *)iterator->elem);
337 if (!env_tmp)
338 return -1;
339
340 ret = putenv(env_tmp);
341 if (ret < 0)
342 return log_error_errno(-1, errno, "Failed to set environment variable: %s", (char *)iterator->elem);
343 }
344 }
345
346 /* Set extra environment variables. */
347 if (extra_env) {
348 for (; *extra_env; extra_env++) {
349 char *p;
350
351 /* We just assume the user knows what they are doing, so
352 * we don't do any checks.
353 */
354 p = strdup(*extra_env);
355 if (!p)
356 return -1;
357
358 ret = putenv(p);
359 if (ret < 0)
360 SYSWARN("Failed to set environment variable");
361 }
362 }
363
364 return 0;
365 }
366
367 static char *lxc_attach_getpwshell(uid_t uid)
368 {
369 __do_free char *line = NULL, *result = NULL;
370 __do_fclose FILE *pipe_f = NULL;
371 int fd, ret;
372 pid_t pid;
373 int pipes[2];
374 bool found = false;
375 size_t line_bufsz = 0;
376
377 /* We need to fork off a process that runs the getent program, and we
378 * need to capture its output, so we use a pipe for that purpose.
379 */
380 ret = pipe2(pipes, O_CLOEXEC);
381 if (ret < 0)
382 return NULL;
383
384 pid = fork();
385 if (pid < 0) {
386 close(pipes[0]);
387 close(pipes[1]);
388 return NULL;
389 }
390
391 if (!pid) {
392 char uid_buf[32];
393 char *arguments[] = {
394 "getent",
395 "passwd",
396 uid_buf,
397 NULL
398 };
399
400 close(pipes[0]);
401
402 /* We want to capture stdout. */
403 ret = dup2(pipes[1], STDOUT_FILENO);
404 close(pipes[1]);
405 if (ret < 0)
406 _exit(EXIT_FAILURE);
407
408 /* Get rid of stdin/stderr, so we try to associate it with
409 * /dev/null.
410 */
411 fd = open_devnull();
412 if (fd < 0) {
413 close(STDIN_FILENO);
414 close(STDERR_FILENO);
415 } else {
416 (void)dup3(fd, STDIN_FILENO, O_CLOEXEC);
417 (void)dup3(fd, STDERR_FILENO, O_CLOEXEC);
418 close(fd);
419 }
420
421 /* Finish argument list. */
422 ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long)uid);
423 if (ret <= 0 || ret >= sizeof(uid_buf))
424 _exit(EXIT_FAILURE);
425
426 /* Try to run getent program. */
427 (void)execvp("getent", arguments);
428 _exit(EXIT_FAILURE);
429 }
430
431 close(pipes[1]);
432
433 pipe_f = fdopen(pipes[0], "re");
434 if (!pipe_f) {
435 close(pipes[0]);
436 goto reap_child;
437 }
438 /* Transfer ownership of pipes[0] to pipe_f. */
439 move_fd(pipes[0]);
440
441 while (getline(&line, &line_bufsz, pipe_f) != -1) {
442 int i;
443 long value;
444 char *token;
445 char *endptr = NULL, *saveptr = NULL;
446
447 /* If we already found something, just continue to read
448 * until the pipe doesn't deliver any more data, but
449 * don't modify the existing data structure.
450 */
451 if (found)
452 continue;
453
454 if (!line)
455 continue;
456
457 /* Trim line on the right hand side. */
458 for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i)
459 line[i - 1] = '\0';
460
461 /* Split into tokens: first: user name. */
462 token = strtok_r(line, ":", &saveptr);
463 if (!token)
464 continue;
465
466 /* next: dummy password field */
467 token = strtok_r(NULL, ":", &saveptr);
468 if (!token)
469 continue;
470
471 /* next: user id */
472 token = strtok_r(NULL, ":", &saveptr);
473 value = token ? strtol(token, &endptr, 10) : 0;
474 if (!token || !endptr || *endptr || value == LONG_MIN ||
475 value == LONG_MAX)
476 continue;
477
478 /* dummy sanity check: user id matches */
479 if ((uid_t)value != uid)
480 continue;
481
482 /* skip fields: gid, gecos, dir, go to next field 'shell' */
483 for (i = 0; i < 4; i++) {
484 token = strtok_r(NULL, ":", &saveptr);
485 if (!token)
486 continue;
487 }
488
489 if (!token)
490 continue;
491
492 free_disarm(result);
493 result = strdup(token);
494
495 /* Sanity check that there are no fields after that. */
496 token = strtok_r(NULL, ":", &saveptr);
497 if (token)
498 continue;
499
500 found = true;
501 }
502
503 reap_child:
504 ret = wait_for_pid(pid);
505 if (ret < 0)
506 return NULL;
507
508 if (!found)
509 return NULL;
510
511 return move_ptr(result);
512 }
513
514 static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
515 {
516 __do_free char *line = NULL;
517 __do_fclose FILE *proc_file = NULL;
518 char proc_fn[LXC_PROC_STATUS_LEN];
519 int ret;
520 size_t line_bufsz = 0;
521 long value = -1;
522 uid_t uid = LXC_INVALID_UID;
523 gid_t gid = LXC_INVALID_GID;
524
525 ret = snprintf(proc_fn, LXC_PROC_STATUS_LEN, "/proc/%d/status", 1);
526 if (ret < 0 || ret >= LXC_PROC_STATUS_LEN)
527 return;
528
529 proc_file = fopen(proc_fn, "re");
530 if (!proc_file)
531 return;
532
533 while (getline(&line, &line_bufsz, proc_file) != -1) {
534 /* Format is: real, effective, saved set user, fs we only care
535 * about real uid.
536 */
537 ret = sscanf(line, "Uid: %ld", &value);
538 if (ret != EOF && ret == 1) {
539 uid = (uid_t)value;
540 } else {
541 ret = sscanf(line, "Gid: %ld", &value);
542 if (ret != EOF && ret == 1)
543 gid = (gid_t)value;
544 }
545
546 if (uid != LXC_INVALID_UID && gid != LXC_INVALID_GID)
547 break;
548 }
549
550 /* Only override arguments if we found something. */
551 if (uid != LXC_INVALID_UID)
552 *init_uid = uid;
553
554 if (gid != LXC_INVALID_GID)
555 *init_gid = gid;
556
557 /* TODO: we should also parse supplementary groups and use
558 * setgroups() to set them.
559 */
560 }
561
562 static bool fetch_seccomp(struct lxc_container *c, lxc_attach_options_t *options)
563 {
564 __do_free char *path = NULL;
565 int ret;
566 bool bret;
567
568 if (!(options->namespaces & CLONE_NEWNS) ||
569 !(options->attach_flags & LXC_ATTACH_LSM)) {
570 free_disarm(c->lxc_conf->seccomp.seccomp);
571 return true;
572 }
573
574 /* Remove current setting. */
575 if (!c->set_config_item(c, "lxc.seccomp.profile", "") &&
576 !c->set_config_item(c, "lxc.seccomp", ""))
577 return false;
578
579 /* Fetch the current profile path over the cmd interface. */
580 path = c->get_running_config_item(c, "lxc.seccomp.profile");
581 if (!path) {
582 INFO("Failed to retrieve lxc.seccomp.profile");
583
584 path = c->get_running_config_item(c, "lxc.seccomp");
585 if (!path)
586 return log_info(true, "Failed to retrieve lxc.seccomp");
587 }
588
589 /* Copy the value into the new lxc_conf. */
590 bret = c->set_config_item(c, "lxc.seccomp.profile", path);
591 if (!bret)
592 return false;
593
594 /* Attempt to parse the resulting config. */
595 ret = lxc_read_seccomp_config(c->lxc_conf);
596 if (ret < 0)
597 return log_error(false, "Failed to retrieve seccomp policy");
598
599 return log_info(true, "Retrieved seccomp policy");
600 }
601
602 static bool no_new_privs(struct lxc_container *c, lxc_attach_options_t *options)
603 {
604 __do_free char *val = NULL;
605
606 /* Remove current setting. */
607 if (!c->set_config_item(c, "lxc.no_new_privs", ""))
608 return log_info(false, "Failed to unset lxc.no_new_privs");
609
610 /* Retrieve currently active setting. */
611 val = c->get_running_config_item(c, "lxc.no_new_privs");
612 if (!val)
613 return log_info(false, "Failed to retrieve lxc.no_new_privs");
614
615 /* Set currently active setting. */
616 return c->set_config_item(c, "lxc.no_new_privs", val);
617 }
618
619 static signed long get_personality(const char *name, const char *lxcpath)
620 {
621 __do_free char *p = NULL;
622
623 p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath);
624 if (!p)
625 return -1;
626
627 return lxc_config_parse_arch(p);
628 }
629
630 struct attach_clone_payload {
631 int ipc_socket;
632 int terminal_slave_fd;
633 lxc_attach_options_t *options;
634 struct lxc_proc_context_info *init_ctx;
635 lxc_attach_exec_t exec_function;
636 void *exec_payload;
637 };
638
639 static void lxc_put_attach_clone_payload(struct attach_clone_payload *p)
640 {
641 close_prot_errno_disarm(p->ipc_socket);
642 close_prot_errno_disarm(p->terminal_slave_fd);
643 if (p->init_ctx) {
644 lxc_proc_put_context_info(p->init_ctx);
645 p->init_ctx = NULL;
646 }
647 }
648
649 static int attach_child_main(struct attach_clone_payload *payload)
650 {
651 int lsm_fd, ret;
652 uid_t new_uid;
653 gid_t new_gid;
654 uid_t ns_root_uid = 0;
655 gid_t ns_root_gid = 0;
656 lxc_attach_options_t* options = payload->options;
657 struct lxc_proc_context_info* init_ctx = payload->init_ctx;
658 bool needs_lsm = (options->namespaces & CLONE_NEWNS) &&
659 (options->attach_flags & LXC_ATTACH_LSM) &&
660 init_ctx->lsm_label;
661
662 /* A description of the purpose of this functionality is provided in the
663 * lxc-attach(1) manual page. We have to remount here and not in the
664 * parent process, otherwise /proc may not properly reflect the new pid
665 * namespace.
666 */
667 if (!(options->namespaces & CLONE_NEWNS) &&
668 (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {
669 ret = lxc_attach_remount_sys_proc();
670 if (ret < 0)
671 goto on_error;
672
673 TRACE("Remounted \"/proc\" and \"/sys\"");
674 }
675
676 /* Now perform additional attachments. */
677 #if HAVE_SYS_PERSONALITY_H
678 if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
679 long new_personality;
680
681 if (options->personality < 0)
682 new_personality = init_ctx->personality;
683 else
684 new_personality = options->personality;
685
686 ret = personality(new_personality);
687 if (ret < 0)
688 goto on_error;
689
690 TRACE("Set new personality");
691 }
692 #endif
693
694 if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
695 ret = lxc_attach_drop_privs(init_ctx);
696 if (ret < 0)
697 goto on_error;
698
699 TRACE("Dropped capabilities");
700 }
701
702 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
703 * if you want this to be a no-op).
704 */
705 ret = lxc_attach_set_environment(init_ctx,
706 options->env_policy,
707 options->extra_env_vars,
708 options->extra_keep_env);
709 if (ret < 0)
710 goto on_error;
711
712 TRACE("Set up environment");
713
714 /* This remark only affects fully unprivileged containers:
715 * Receive fd for LSM security module before we set{g,u}id(). The reason
716 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
717 * we will change our effective uid. This means our effective uid will
718 * be different from the effective uid of the process that created us
719 * which means that this processs no longer has capabilities in our
720 * namespace including CAP_SYS_PTRACE. This means we will not be able to
721 * read and /proc/<pid> files for the process anymore when /proc is
722 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
723 * set{g,u}id().
724 */
725 if (needs_lsm) {
726 ret = lxc_abstract_unix_recv_fds(payload->ipc_socket, &lsm_fd, 1, NULL, 0);
727 if (ret <= 0) {
728 if (ret < 0)
729 SYSERROR("Failed to receive lsm label fd");
730
731 goto on_error;
732 }
733
734 TRACE("Received LSM label file descriptor %d from parent", lsm_fd);
735 }
736
737 if (options->stdin_fd > 0 && isatty(options->stdin_fd)) {
738 ret = lxc_make_controlling_terminal(options->stdin_fd);
739 if (ret < 0)
740 goto on_error;
741 }
742
743 if (!lxc_setgroups(0, NULL) && errno != EPERM)
744 goto on_error;
745
746 if (options->namespaces & CLONE_NEWUSER) {
747 /* Check whether nsuid 0 has a mapping. */
748 ns_root_uid = get_ns_uid(0);
749
750 /* Check whether nsgid 0 has a mapping. */
751 ns_root_gid = get_ns_gid(0);
752
753 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
754 * init was started with.
755 */
756 if (ns_root_uid == LXC_INVALID_UID)
757 lxc_attach_get_init_uidgid(&ns_root_uid, &ns_root_gid);
758
759 if (ns_root_uid == LXC_INVALID_UID)
760 goto on_error;
761
762 if (!lxc_switch_uid_gid(ns_root_uid, ns_root_gid))
763 goto on_error;
764 }
765
766 /* Set {u,g}id. */
767 if (options->uid != LXC_INVALID_UID)
768 new_uid = options->uid;
769 else
770 new_uid = ns_root_uid;
771
772 if (options->gid != LXC_INVALID_GID)
773 new_gid = options->gid;
774 else
775 new_gid = ns_root_gid;
776
777 if ((init_ctx->container && init_ctx->container->lxc_conf &&
778 init_ctx->container->lxc_conf->no_new_privs) ||
779 (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
780 ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
781 prctl_arg(0), prctl_arg(0));
782 if (ret < 0)
783 goto on_error;
784
785 TRACE("Set PR_SET_NO_NEW_PRIVS");
786 }
787
788 if (needs_lsm) {
789 bool on_exec;
790
791 /* Change into our new LSM profile. */
792 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
793
794 ret = lsm_process_label_set_at(lsm_fd, init_ctx->lsm_label, on_exec);
795 close(lsm_fd);
796 if (ret < 0)
797 goto on_error;
798
799 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx->lsm_label);
800 }
801
802 if (init_ctx->container && init_ctx->container->lxc_conf &&
803 init_ctx->container->lxc_conf->seccomp.seccomp) {
804 struct lxc_conf *conf = init_ctx->container->lxc_conf;
805
806 ret = lxc_seccomp_load(conf);
807 if (ret < 0)
808 goto on_error;
809
810 TRACE("Loaded seccomp profile");
811
812 ret = lxc_seccomp_send_notifier_fd(&conf->seccomp, payload->ipc_socket);
813 if (ret < 0)
814 goto on_error;
815 }
816
817 close(payload->ipc_socket);
818 payload->ipc_socket = -EBADF;
819 lxc_proc_put_context_info(init_ctx);
820 payload->init_ctx = NULL;
821
822 /* The following is done after the communication socket is shut down.
823 * That way, all errors that might (though unlikely) occur up until this
824 * point will have their messages printed to the original stderr (if
825 * logging is so configured) and not the fd the user supplied, if any.
826 */
827
828 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
829 * may want to make sure the fds are closed, for example.
830 */
831 if (options->stdin_fd >= 0 && options->stdin_fd != STDIN_FILENO)
832 (void)dup2(options->stdin_fd, STDIN_FILENO);
833
834 if (options->stdout_fd >= 0 && options->stdout_fd != STDOUT_FILENO)
835 (void)dup2(options->stdout_fd, STDOUT_FILENO);
836
837 if (options->stderr_fd >= 0 && options->stderr_fd != STDERR_FILENO)
838 (void)dup2(options->stderr_fd, STDERR_FILENO);
839
840 /* close the old fds */
841 if (options->stdin_fd > STDERR_FILENO)
842 close(options->stdin_fd);
843
844 if (options->stdout_fd > STDERR_FILENO)
845 close(options->stdout_fd);
846
847 if (options->stderr_fd > STDERR_FILENO)
848 close(options->stderr_fd);
849
850 /*
851 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
852 * here, ignore errors.
853 */
854 for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
855 ret = fd_cloexec(fd, false);
856 if (ret < 0) {
857 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd);
858 goto on_error;
859 }
860 }
861
862 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
863 ret = lxc_terminal_prepare_login(payload->terminal_slave_fd);
864 if (ret < 0) {
865 SYSERROR("Failed to prepare terminal file descriptor %d", payload->terminal_slave_fd);
866 goto on_error;
867 }
868
869 TRACE("Prepared terminal file descriptor %d", payload->terminal_slave_fd);
870 }
871
872 /* Avoid unnecessary syscalls. */
873 if (new_uid == ns_root_uid)
874 new_uid = LXC_INVALID_UID;
875
876 if (new_gid == ns_root_gid)
877 new_gid = LXC_INVALID_GID;
878
879 /* Make sure that the processes STDIO is correctly owned by the user that we are switching to */
880 fix_stdio_permissions(new_uid);
881
882 if (!lxc_switch_uid_gid(new_uid, new_gid))
883 goto on_error;
884
885 /* We're done, so we can now do whatever the user intended us to do. */
886 _exit(payload->exec_function(payload->exec_payload));
887
888 on_error:
889 lxc_put_attach_clone_payload(payload);
890 _exit(EXIT_FAILURE);
891 }
892
893 static int lxc_attach_terminal(struct lxc_conf *conf,
894 struct lxc_terminal *terminal)
895 {
896 int ret;
897
898 lxc_terminal_init(terminal);
899
900 ret = lxc_terminal_create(terminal);
901 if (ret < 0)
902 return log_error(-1, "Failed to create terminal");
903
904 /* Shift ttys to container. */
905 ret = lxc_terminal_map_ids(conf, terminal);
906 if (ret < 0) {
907 ERROR("Failed to chown terminal");
908 goto on_error;
909 }
910
911 return 0;
912
913 on_error:
914 lxc_terminal_delete(terminal);
915 lxc_terminal_conf_free(terminal);
916 return -1;
917 }
918
919 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal *terminal,
920 struct lxc_epoll_descr *descr)
921 {
922 int ret;
923
924 ret = lxc_mainloop_open(descr);
925 if (ret < 0)
926 return log_error(-1, "Failed to create mainloop");
927
928 ret = lxc_terminal_mainloop_add(descr, terminal);
929 if (ret < 0) {
930 lxc_mainloop_close(descr);
931 return log_error(-1, "Failed to add handlers to mainloop");
932 }
933
934 return 0;
935 }
936
937 static inline void lxc_attach_terminal_close_master(struct lxc_terminal *terminal)
938 {
939 close_prot_errno_disarm(terminal->master);
940 }
941
942 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal *terminal)
943 {
944 close_prot_errno_disarm(terminal->slave);
945 }
946
947 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal *terminal)
948 {
949 close_prot_errno_disarm(terminal->peer);
950 }
951
952 static inline void lxc_attach_terminal_close_log(struct lxc_terminal *terminal)
953 {
954 close_prot_errno_disarm(terminal->log_fd);
955 }
956
957 int lxc_attach(struct lxc_container *container, lxc_attach_exec_t exec_function,
958 void *exec_payload, lxc_attach_options_t *options,
959 pid_t *attached_process)
960 {
961 int i, ret, status;
962 int ipc_sockets[2];
963 char *cwd, *new_cwd;
964 signed long personality;
965 pid_t attached_pid, init_pid, pid;
966 struct lxc_proc_context_info *init_ctx;
967 struct lxc_terminal terminal;
968 struct lxc_conf *conf;
969 char *name, *lxcpath;
970 struct attach_clone_payload payload = {0};
971
972 ret = access("/proc/self/ns", X_OK);
973 if (ret)
974 return log_error_errno(-1, errno, "Does this kernel version support namespaces?");
975
976 if (!container)
977 return ret_set_errno(-1, EINVAL);
978
979 if (!lxc_container_get(container))
980 return ret_set_errno(-1, EINVAL);
981
982 name = container->name;
983 lxcpath = container->config_path;
984
985 if (!options)
986 options = &attach_static_default_options;
987
988 init_pid = lxc_cmd_get_init_pid(name, lxcpath);
989 if (init_pid < 0) {
990 lxc_container_put(container);
991 return log_error(-1, "Failed to get init pid");
992 }
993
994 init_ctx = lxc_proc_get_context_info(init_pid);
995 if (!init_ctx) {
996 ERROR("Failed to get context of init process: %ld", (long)init_pid);
997 lxc_container_put(container);
998 return -1;
999 }
1000
1001 init_ctx->container = container;
1002
1003 personality = get_personality(name, lxcpath);
1004 if (init_ctx->personality < 0) {
1005 ERROR("Failed to get personality of the container");
1006 lxc_proc_put_context_info(init_ctx);
1007 return -1;
1008 }
1009 init_ctx->personality = personality;
1010
1011 if (!init_ctx->container->lxc_conf) {
1012 init_ctx->container->lxc_conf = lxc_conf_init();
1013 if (!init_ctx->container->lxc_conf) {
1014 lxc_proc_put_context_info(init_ctx);
1015 return -1;
1016 }
1017 }
1018 conf = init_ctx->container->lxc_conf;
1019
1020 if (!fetch_seccomp(init_ctx->container, options))
1021 WARN("Failed to get seccomp policy");
1022
1023 if (!no_new_privs(init_ctx->container, options))
1024 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1025
1026 cwd = getcwd(NULL, 0);
1027
1028 /* Determine which namespaces the container was created with
1029 * by asking lxc-start, if necessary.
1030 */
1031 if (options->namespaces == -1) {
1032 options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);
1033 /* call failed */
1034 if (options->namespaces == -1) {
1035 ERROR("Failed to automatically determine the "
1036 "namespaces which the container uses");
1037 free(cwd);
1038 lxc_proc_put_context_info(init_ctx);
1039 return -1;
1040 }
1041
1042 for (i = 0; i < LXC_NS_MAX; i++) {
1043 if (ns_info[i].clone_flag & CLONE_NEWCGROUP)
1044 if (!(options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) ||
1045 !cgns_supported())
1046 continue;
1047
1048 if (ns_info[i].clone_flag & options->namespaces)
1049 continue;
1050
1051 init_ctx->ns_inherited |= ns_info[i].clone_flag;
1052 }
1053 }
1054
1055 pid = lxc_raw_getpid();
1056
1057 for (i = 0; i < LXC_NS_MAX; i++) {
1058 int j;
1059
1060 if (options->namespaces & ns_info[i].clone_flag)
1061 init_ctx->ns_fd[i] = lxc_preserve_ns(init_pid, ns_info[i].proc_name);
1062 else if (init_ctx->ns_inherited & ns_info[i].clone_flag)
1063 init_ctx->ns_fd[i] = in_same_namespace(pid, init_pid, ns_info[i].proc_name);
1064 else
1065 continue;
1066
1067 if (init_ctx->ns_fd[i] >= 0)
1068 continue;
1069
1070 if (init_ctx->ns_fd[i] == -EINVAL) {
1071 DEBUG("Inheriting %s namespace from %d",
1072 ns_info[i].proc_name, pid);
1073 init_ctx->ns_inherited &= ~ns_info[i].clone_flag;
1074 continue;
1075 }
1076
1077 /* We failed to preserve the namespace. */
1078 SYSERROR("Failed to attach to %s namespace of %d",
1079 ns_info[i].proc_name, pid);
1080
1081 /* Close all already opened file descriptors before we return an
1082 * error, so we don't leak them.
1083 */
1084 for (j = 0; j < i; j++)
1085 close(init_ctx->ns_fd[j]);
1086
1087 free(cwd);
1088 lxc_proc_put_context_info(init_ctx);
1089 return -1;
1090 }
1091
1092 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1093 ret = lxc_attach_terminal(conf, &terminal);
1094 if (ret < 0) {
1095 ERROR("Failed to setup new terminal");
1096 free(cwd);
1097 lxc_proc_put_context_info(init_ctx);
1098 return -1;
1099 }
1100
1101 terminal.log_fd = options->log_fd;
1102 } else {
1103 lxc_terminal_init(&terminal);
1104 }
1105
1106 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1107 * to make sure we don't irritate other threads that want to fork+exec
1108 * away
1109 *
1110 * IMPORTANT: if the initial process is multithreaded and another call
1111 * just fork()s away without exec'ing directly after, the socket fd will
1112 * exist in the forked process from the other thread and any close() in
1113 * our own child process will not really cause the socket to close
1114 * properly, potentially causing the parent to hang.
1115 *
1116 * For this reason, while IPC is still active, we have to use shutdown()
1117 * if the child exits prematurely in order to signal that the socket is
1118 * closed and cannot assume that the child exiting will automatically do
1119 * that.
1120 *
1121 * IPC mechanism: (X is receiver)
1122 * initial process intermediate attached
1123 * X <--- send pid of
1124 * attached proc,
1125 * then exit
1126 * send 0 ------------------------------------> X
1127 * [do initialization]
1128 * X <------------------------------------ send 1
1129 * [add to cgroup, ...]
1130 * send 2 ------------------------------------> X
1131 * [set LXC_ATTACH_NO_NEW_PRIVS]
1132 * X <------------------------------------ send 3
1133 * [open LSM label fd]
1134 * send 4 ------------------------------------> X
1135 * [set LSM label]
1136 * close socket close socket
1137 * run program
1138 */
1139 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
1140 if (ret < 0) {
1141 SYSERROR("Could not set up required IPC mechanism for attaching");
1142 free(cwd);
1143 lxc_proc_put_context_info(init_ctx);
1144 return -1;
1145 }
1146
1147 /* Create intermediate subprocess, two reasons:
1148 * 1. We can't setns() in the child itself, since we want to make
1149 * sure we are properly attached to the pidns.
1150 * 2. Also, the initial thread has to put the attached process
1151 * into the cgroup, which we can only do if we didn't already
1152 * setns() (otherwise, user namespaces will hate us).
1153 */
1154 pid = fork();
1155 if (pid < 0) {
1156 SYSERROR("Failed to create first subprocess");
1157 free(cwd);
1158 lxc_proc_put_context_info(init_ctx);
1159 return -1;
1160 }
1161
1162 if (pid) {
1163 int ret_parent = -1;
1164 pid_t to_cleanup_pid = pid;
1165 struct lxc_epoll_descr descr = {0};
1166
1167 /* close unneeded file descriptors */
1168 close(ipc_sockets[1]);
1169 free(cwd);
1170 lxc_proc_close_ns_fd(init_ctx);
1171 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1172 lxc_attach_terminal_close_slave(&terminal);
1173
1174 /* Attach to cgroup, if requested. */
1175 if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
1176 /*
1177 * If this is the unified hierarchy cgroup_attach() is
1178 * enough.
1179 */
1180 ret = cgroup_attach(conf, name, lxcpath, pid);
1181 if (ret) {
1182 call_cleaner(cgroup_exit) struct cgroup_ops *cgroup_ops = NULL;
1183
1184 cgroup_ops = cgroup_init(conf);
1185 if (!cgroup_ops)
1186 goto on_error;
1187
1188 if (!cgroup_ops->attach(cgroup_ops, conf, name, lxcpath, pid))
1189 goto on_error;
1190 }
1191 TRACE("Moved intermediate process %d into container's cgroups", pid);
1192 }
1193
1194 /* Setup /proc limits */
1195 if (!lxc_list_empty(&conf->procs)) {
1196 ret = setup_proc_filesystem(&conf->procs, pid);
1197 if (ret < 0)
1198 goto on_error;
1199 }
1200
1201 /* Setup resource limits */
1202 if (!lxc_list_empty(&conf->limits)) {
1203 ret = setup_resource_limits(&conf->limits, pid);
1204 if (ret < 0)
1205 goto on_error;
1206 }
1207
1208 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1209 ret = lxc_attach_terminal_mainloop_init(&terminal, &descr);
1210 if (ret < 0)
1211 goto on_error;
1212
1213 TRACE("Initialized terminal mainloop");
1214 }
1215
1216 /* Let the child process know to go ahead. */
1217 status = 0;
1218 ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
1219 if (ret != sizeof(status))
1220 goto close_mainloop;
1221
1222 TRACE("Told intermediate process to start initializing");
1223
1224 /* Get pid of attached process from intermediate process. */
1225 ret = lxc_read_nointr(ipc_sockets[0], &attached_pid, sizeof(attached_pid));
1226 if (ret != sizeof(attached_pid))
1227 goto close_mainloop;
1228
1229 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
1230
1231 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1232 if (options->stdin_fd == 0) {
1233 signal(SIGINT, SIG_IGN);
1234 signal(SIGQUIT, SIG_IGN);
1235 }
1236
1237 /* Reap intermediate process. */
1238 ret = wait_for_pid(pid);
1239 if (ret < 0)
1240 goto close_mainloop;
1241
1242 TRACE("Intermediate process %d exited", pid);
1243
1244 /* We will always have to reap the attached process now. */
1245 to_cleanup_pid = attached_pid;
1246
1247 /* Open LSM fd and send it to child. */
1248 if ((options->namespaces & CLONE_NEWNS) &&
1249 (options->attach_flags & LXC_ATTACH_LSM) &&
1250 init_ctx->lsm_label) {
1251 int labelfd;
1252 bool on_exec;
1253
1254 ret = -1;
1255 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
1256 labelfd = lsm_process_label_fd_get(attached_pid, on_exec);
1257 if (labelfd < 0)
1258 goto close_mainloop;
1259
1260 TRACE("Opened LSM label file descriptor %d", labelfd);
1261
1262 /* Send child fd of the LSM security module to write to. */
1263 ret = lxc_abstract_unix_send_fds(ipc_sockets[0], &labelfd, 1, NULL, 0);
1264 if (ret <= 0) {
1265 if (ret < 0)
1266 SYSERROR("Failed to send lsm label fd");
1267
1268 close(labelfd);
1269 goto close_mainloop;
1270 }
1271
1272 close(labelfd);
1273 TRACE("Sent LSM label file descriptor %d to child", labelfd);
1274 }
1275
1276 if (conf && conf->seccomp.seccomp) {
1277 ret = lxc_seccomp_recv_notifier_fd(&conf->seccomp, ipc_sockets[0]);
1278 if (ret < 0)
1279 goto close_mainloop;
1280
1281 ret = lxc_seccomp_add_notifier(name, lxcpath, &conf->seccomp);
1282 if (ret < 0)
1283 goto close_mainloop;
1284 }
1285
1286 /* We're done, the child process should now execute whatever it
1287 * is that the user requested. The parent can now track it with
1288 * waitpid() or similar.
1289 */
1290
1291 *attached_process = attached_pid;
1292
1293 /* Now shut down communication with child, we're done. */
1294 shutdown(ipc_sockets[0], SHUT_RDWR);
1295 close(ipc_sockets[0]);
1296 ipc_sockets[0] = -1;
1297
1298 ret_parent = 0;
1299 to_cleanup_pid = -1;
1300
1301 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1302 ret = lxc_mainloop(&descr, -1);
1303 if (ret < 0) {
1304 ret_parent = -1;
1305 to_cleanup_pid = attached_pid;
1306 }
1307 }
1308
1309 close_mainloop:
1310 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1311 lxc_mainloop_close(&descr);
1312
1313 on_error:
1314 if (ipc_sockets[0] >= 0) {
1315 shutdown(ipc_sockets[0], SHUT_RDWR);
1316 close(ipc_sockets[0]);
1317 }
1318
1319 if (to_cleanup_pid > 0)
1320 (void)wait_for_pid(to_cleanup_pid);
1321
1322 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1323 lxc_terminal_delete(&terminal);
1324 lxc_terminal_conf_free(&terminal);
1325 }
1326
1327 lxc_proc_put_context_info(init_ctx);
1328 return ret_parent;
1329 }
1330
1331 /* close unneeded file descriptors */
1332 close_prot_errno_disarm(ipc_sockets[0]);
1333
1334 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1335 lxc_attach_terminal_close_master(&terminal);
1336 lxc_attach_terminal_close_peer(&terminal);
1337 lxc_attach_terminal_close_log(&terminal);
1338 }
1339
1340 /* Wait for the parent to have setup cgroups. */
1341 ret = lxc_read_nointr(ipc_sockets[1], &status, sizeof(status));
1342 if (ret != sizeof(status)) {
1343 shutdown(ipc_sockets[1], SHUT_RDWR);
1344 lxc_proc_put_context_info(init_ctx);
1345 _exit(EXIT_FAILURE);
1346 }
1347
1348 TRACE("Intermediate process starting to initialize");
1349
1350 /* Attach now, create another subprocess later, since pid namespaces
1351 * only really affect the children of the current process.
1352 */
1353 ret = lxc_attach_to_ns(init_pid, init_ctx);
1354 if (ret < 0) {
1355 ERROR("Failed to enter namespaces");
1356 shutdown(ipc_sockets[1], SHUT_RDWR);
1357 lxc_proc_put_context_info(init_ctx);
1358 _exit(EXIT_FAILURE);
1359 }
1360
1361 /* close namespace file descriptors */
1362 lxc_proc_close_ns_fd(init_ctx);
1363
1364 /* Attach succeeded, try to cwd. */
1365 if (options->initial_cwd)
1366 new_cwd = options->initial_cwd;
1367 else
1368 new_cwd = cwd;
1369 if (new_cwd) {
1370 ret = chdir(new_cwd);
1371 if (ret < 0)
1372 WARN("Could not change directory to \"%s\"", new_cwd);
1373 }
1374 free(cwd);
1375
1376 /* Create attached process. */
1377 payload.ipc_socket = ipc_sockets[1];
1378 payload.options = options;
1379 payload.init_ctx = init_ctx;
1380 payload.terminal_slave_fd = terminal.slave;
1381 payload.exec_function = exec_function;
1382 payload.exec_payload = exec_payload;
1383
1384 pid = lxc_raw_clone(CLONE_PARENT, NULL);
1385 if (pid < 0) {
1386 SYSERROR("Failed to clone attached process");
1387 shutdown(ipc_sockets[1], SHUT_RDWR);
1388 lxc_proc_put_context_info(init_ctx);
1389 _exit(EXIT_FAILURE);
1390 }
1391
1392 if (pid == 0) {
1393 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1394 ret = pthread_sigmask(SIG_SETMASK,
1395 &terminal.tty_state->oldmask, NULL);
1396 if (ret < 0) {
1397 SYSERROR("Failed to reset signal mask");
1398 _exit(EXIT_FAILURE);
1399 }
1400 }
1401
1402 ret = attach_child_main(&payload);
1403 if (ret < 0)
1404 ERROR("Failed to exec");
1405
1406 _exit(EXIT_FAILURE);
1407 }
1408
1409 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1410 lxc_attach_terminal_close_slave(&terminal);
1411
1412 /* Tell grandparent the pid of the pid of the newly created child. */
1413 ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid));
1414 if (ret != sizeof(pid)) {
1415 /* If this really happens here, this is very unfortunate, since
1416 * the parent will not know the pid of the attached process and
1417 * will not be able to wait for it (and we won't either due to
1418 * CLONE_PARENT) so the parent won't be able to reap it and the
1419 * attached process will remain a zombie.
1420 */
1421 shutdown(ipc_sockets[1], SHUT_RDWR);
1422 lxc_proc_put_context_info(init_ctx);
1423 _exit(EXIT_FAILURE);
1424 }
1425
1426 TRACE("Sending pid %d of attached process", pid);
1427
1428 /* The rest is in the hands of the initial and the attached process. */
1429 lxc_proc_put_context_info(init_ctx);
1430 _exit(EXIT_SUCCESS);
1431 }
1432
1433 int lxc_attach_run_command(void *payload)
1434 {
1435 int ret = -1;
1436 lxc_attach_command_t *cmd = payload;
1437
1438 ret = execvp(cmd->program, cmd->argv);
1439 if (ret < 0) {
1440 switch (errno) {
1441 case ENOEXEC:
1442 ret = 126;
1443 break;
1444 case ENOENT:
1445 ret = 127;
1446 break;
1447 }
1448 }
1449
1450 return log_error_errno(ret, errno, "Failed to exec \"%s\"", cmd->program);
1451 }
1452
1453 int lxc_attach_run_shell(void* payload)
1454 {
1455 __do_free char *buf = NULL;
1456 uid_t uid;
1457 struct passwd pwent;
1458 struct passwd *pwentp = NULL;
1459 char *user_shell;
1460 size_t bufsize;
1461 int ret;
1462
1463 /* Ignore payload parameter. */
1464 (void)payload;
1465
1466 uid = getuid();
1467
1468 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1469 if (bufsize == -1)
1470 bufsize = 1024;
1471
1472 buf = malloc(bufsize);
1473 if (buf) {
1474 ret = getpwuid_r(uid, &pwent, buf, bufsize, &pwentp);
1475 if (!pwentp) {
1476 if (ret == 0)
1477 WARN("Could not find matched password record");
1478
1479 WARN("Failed to get password record - %u", uid);
1480 }
1481 }
1482
1483 /* This probably happens because of incompatible nss implementations in
1484 * host and container (remember, this code is still using the host's
1485 * glibc but our mount namespace is in the container) we may try to get
1486 * the information by spawning a [getent passwd uid] process and parsing
1487 * the result.
1488 */
1489 if (!pwentp)
1490 user_shell = lxc_attach_getpwshell(uid);
1491 else
1492 user_shell = pwent.pw_shell;
1493
1494 if (user_shell)
1495 execlp(user_shell, user_shell, (char *)NULL);
1496
1497 /* Executed if either no passwd entry or execvp fails, we will fall back
1498 * on /bin/sh as a default shell.
1499 */
1500 execlp("/bin/sh", "/bin/sh", (char *)NULL);
1501
1502 SYSERROR("Failed to execute shell");
1503 if (!pwentp)
1504 free(user_shell);
1505
1506 return -1;
1507 }