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