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