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