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