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