]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/attach.c
attach: cleanup various helpers
[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 = LXC_INVALID_UID;
522 gid_t gid = LXC_INVALID_GID;
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 != LXC_INVALID_UID && gid != LXC_INVALID_GID)
546 break;
547 }
548
549 /* Only override arguments if we found something. */
550 if (uid != LXC_INVALID_UID)
551 *init_uid = uid;
552
553 if (gid != LXC_INVALID_GID)
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_disarm(c->lxc_conf->seccomp.seccomp);
570 return true;
571 }
572
573 /* Remove current setting. */
574 if (!c->set_config_item(c, "lxc.seccomp.profile", "") &&
575 !c->set_config_item(c, "lxc.seccomp", ""))
576 return false;
577
578 /* Fetch the current profile path over the cmd interface. */
579 path = c->get_running_config_item(c, "lxc.seccomp.profile");
580 if (!path) {
581 INFO("Failed to retrieve lxc.seccomp.profile");
582
583 path = c->get_running_config_item(c, "lxc.seccomp");
584 if (!path)
585 return log_info(true, "Failed to retrieve lxc.seccomp");
586 }
587
588 /* Copy the value into the new lxc_conf. */
589 bret = c->set_config_item(c, "lxc.seccomp.profile", path);
590 if (!bret)
591 return false;
592
593 /* Attempt to parse the resulting config. */
594 ret = lxc_read_seccomp_config(c->lxc_conf);
595 if (ret < 0)
596 return log_error(false, "Failed to retrieve seccomp policy");
597
598 return log_info(true, "Retrieved seccomp policy");
599 }
600
601 static bool no_new_privs(struct lxc_container *c, lxc_attach_options_t *options)
602 {
603 __do_free char *val = NULL;
604
605 /* Remove current setting. */
606 if (!c->set_config_item(c, "lxc.no_new_privs", ""))
607 return log_info(false, "Failed to unset lxc.no_new_privs");
608
609 /* Retrieve currently active setting. */
610 val = c->get_running_config_item(c, "lxc.no_new_privs");
611 if (!val)
612 return log_info(false, "Failed to retrieve lxc.no_new_privs");
613
614 /* Set currently active setting. */
615 return c->set_config_item(c, "lxc.no_new_privs", val);
616 }
617
618 static signed long get_personality(const char *name, const char *lxcpath)
619 {
620 __do_free char *p = NULL;
621
622 p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath);
623 if (!p)
624 return -1;
625
626 return lxc_config_parse_arch(p);
627 }
628
629 struct attach_clone_payload {
630 int ipc_socket;
631 int terminal_slave_fd;
632 lxc_attach_options_t *options;
633 struct lxc_proc_context_info *init_ctx;
634 lxc_attach_exec_t exec_function;
635 void *exec_payload;
636 };
637
638 static void lxc_put_attach_clone_payload(struct attach_clone_payload *p)
639 {
640 close_prot_errno_disarm(p->ipc_socket);
641 close_prot_errno_disarm(p->terminal_slave_fd);
642 if (p->init_ctx) {
643 lxc_proc_put_context_info(p->init_ctx);
644 p->init_ctx = NULL;
645 }
646 }
647
648 static int attach_child_main(struct attach_clone_payload *payload)
649 {
650 int lsm_fd, ret;
651 uid_t new_uid;
652 gid_t new_gid;
653 uid_t ns_root_uid = 0;
654 gid_t ns_root_gid = 0;
655 lxc_attach_options_t* options = payload->options;
656 struct lxc_proc_context_info* init_ctx = payload->init_ctx;
657 bool needs_lsm = (options->namespaces & CLONE_NEWNS) &&
658 (options->attach_flags & LXC_ATTACH_LSM) &&
659 init_ctx->lsm_label;
660
661 /* A description of the purpose of this functionality is provided in the
662 * lxc-attach(1) manual page. We have to remount here and not in the
663 * parent process, otherwise /proc may not properly reflect the new pid
664 * namespace.
665 */
666 if (!(options->namespaces & CLONE_NEWNS) &&
667 (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {
668 ret = lxc_attach_remount_sys_proc();
669 if (ret < 0)
670 goto on_error;
671
672 TRACE("Remounted \"/proc\" and \"/sys\"");
673 }
674
675 /* Now perform additional attachments. */
676 #if HAVE_SYS_PERSONALITY_H
677 if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
678 long new_personality;
679
680 if (options->personality < 0)
681 new_personality = init_ctx->personality;
682 else
683 new_personality = options->personality;
684
685 ret = personality(new_personality);
686 if (ret < 0)
687 goto on_error;
688
689 TRACE("Set new personality");
690 }
691 #endif
692
693 if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
694 ret = lxc_attach_drop_privs(init_ctx);
695 if (ret < 0)
696 goto on_error;
697
698 TRACE("Dropped capabilities");
699 }
700
701 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
702 * if you want this to be a no-op).
703 */
704 ret = lxc_attach_set_environment(init_ctx,
705 options->env_policy,
706 options->extra_env_vars,
707 options->extra_keep_env);
708 if (ret < 0)
709 goto on_error;
710
711 TRACE("Set up environment");
712
713 /* This remark only affects fully unprivileged containers:
714 * Receive fd for LSM security module before we set{g,u}id(). The reason
715 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
716 * we will change our effective uid. This means our effective uid will
717 * be different from the effective uid of the process that created us
718 * which means that this processs no longer has capabilities in our
719 * namespace including CAP_SYS_PTRACE. This means we will not be able to
720 * read and /proc/<pid> files for the process anymore when /proc is
721 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
722 * set{g,u}id().
723 */
724 if (needs_lsm) {
725 ret = lxc_abstract_unix_recv_fds(payload->ipc_socket, &lsm_fd, 1, NULL, 0);
726 if (ret <= 0) {
727 if (ret < 0)
728 SYSERROR("Failed to receive lsm label fd");
729
730 goto on_error;
731 }
732
733 TRACE("Received LSM label file descriptor %d from parent", lsm_fd);
734 }
735
736 if (options->stdin_fd > 0 && isatty(options->stdin_fd)) {
737 ret = lxc_make_controlling_terminal(options->stdin_fd);
738 if (ret < 0)
739 goto on_error;
740 }
741
742 if (!lxc_setgroups(0, NULL) && errno != EPERM)
743 goto on_error;
744
745 if (options->namespaces & CLONE_NEWUSER) {
746 /* Check whether nsuid 0 has a mapping. */
747 ns_root_uid = get_ns_uid(0);
748
749 /* Check whether nsgid 0 has a mapping. */
750 ns_root_gid = get_ns_gid(0);
751
752 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
753 * init was started with.
754 */
755 if (ns_root_uid == LXC_INVALID_UID)
756 lxc_attach_get_init_uidgid(&ns_root_uid, &ns_root_gid);
757
758 if (ns_root_uid == LXC_INVALID_UID)
759 goto on_error;
760
761 if (!lxc_switch_uid_gid(ns_root_uid, ns_root_gid))
762 goto on_error;
763 }
764
765 /* Set {u,g}id. */
766 if (options->uid != LXC_INVALID_UID)
767 new_uid = options->uid;
768 else
769 new_uid = ns_root_uid;
770
771 if (options->gid != LXC_INVALID_GID)
772 new_gid = options->gid;
773 else
774 new_gid = ns_root_gid;
775
776 if ((init_ctx->container && init_ctx->container->lxc_conf &&
777 init_ctx->container->lxc_conf->no_new_privs) ||
778 (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
779 ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
780 prctl_arg(0), prctl_arg(0));
781 if (ret < 0)
782 goto on_error;
783
784 TRACE("Set PR_SET_NO_NEW_PRIVS");
785 }
786
787 if (needs_lsm) {
788 bool on_exec;
789
790 /* Change into our new LSM profile. */
791 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
792
793 ret = lsm_process_label_set_at(lsm_fd, init_ctx->lsm_label, on_exec);
794 close(lsm_fd);
795 if (ret < 0)
796 goto on_error;
797
798 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx->lsm_label);
799 }
800
801 if (init_ctx->container && init_ctx->container->lxc_conf &&
802 init_ctx->container->lxc_conf->seccomp.seccomp) {
803 struct lxc_conf *conf = init_ctx->container->lxc_conf;
804
805 ret = lxc_seccomp_load(conf);
806 if (ret < 0)
807 goto on_error;
808
809 TRACE("Loaded seccomp profile");
810
811 ret = lxc_seccomp_send_notifier_fd(&conf->seccomp, payload->ipc_socket);
812 if (ret < 0)
813 goto on_error;
814 }
815
816 close(payload->ipc_socket);
817 payload->ipc_socket = -EBADF;
818 lxc_proc_put_context_info(init_ctx);
819 payload->init_ctx = NULL;
820
821 /* The following is done after the communication socket is shut down.
822 * That way, all errors that might (though unlikely) occur up until this
823 * point will have their messages printed to the original stderr (if
824 * logging is so configured) and not the fd the user supplied, if any.
825 */
826
827 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
828 * may want to make sure the fds are closed, for example.
829 */
830 if (options->stdin_fd >= 0 && options->stdin_fd != STDIN_FILENO)
831 (void)dup2(options->stdin_fd, STDIN_FILENO);
832
833 if (options->stdout_fd >= 0 && options->stdout_fd != STDOUT_FILENO)
834 (void)dup2(options->stdout_fd, STDOUT_FILENO);
835
836 if (options->stderr_fd >= 0 && options->stderr_fd != STDERR_FILENO)
837 (void)dup2(options->stderr_fd, STDERR_FILENO);
838
839 /* close the old fds */
840 if (options->stdin_fd > STDERR_FILENO)
841 close(options->stdin_fd);
842
843 if (options->stdout_fd > STDERR_FILENO)
844 close(options->stdout_fd);
845
846 if (options->stderr_fd > STDERR_FILENO)
847 close(options->stderr_fd);
848
849 /*
850 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
851 * here, ignore errors.
852 */
853 for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
854 ret = fd_cloexec(fd, false);
855 if (ret < 0) {
856 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd);
857 goto on_error;
858 }
859 }
860
861 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
862 ret = lxc_terminal_prepare_login(payload->terminal_slave_fd);
863 if (ret < 0) {
864 SYSERROR("Failed to prepare terminal file descriptor %d", payload->terminal_slave_fd);
865 goto on_error;
866 }
867
868 TRACE("Prepared terminal file descriptor %d", payload->terminal_slave_fd);
869 }
870
871 /* Avoid unnecessary syscalls. */
872 if (new_uid == ns_root_uid)
873 new_uid = LXC_INVALID_UID;
874
875 if (new_gid == ns_root_gid)
876 new_gid = LXC_INVALID_GID;
877
878 if (!lxc_switch_uid_gid(new_uid, new_gid))
879 goto on_error;
880
881 /* We're done, so we can now do whatever the user intended us to do. */
882 _exit(payload->exec_function(payload->exec_payload));
883
884 on_error:
885 lxc_put_attach_clone_payload(payload);
886 _exit(EXIT_FAILURE);
887 }
888
889 static int lxc_attach_terminal(struct lxc_conf *conf,
890 struct lxc_terminal *terminal)
891 {
892 int ret;
893
894 lxc_terminal_init(terminal);
895
896 ret = lxc_terminal_create(terminal);
897 if (ret < 0)
898 return log_error(-1, "Failed to create terminal");
899
900 /* Shift ttys to container. */
901 ret = lxc_terminal_map_ids(conf, terminal);
902 if (ret < 0) {
903 ERROR("Failed to chown terminal");
904 goto on_error;
905 }
906
907 return 0;
908
909 on_error:
910 lxc_terminal_delete(terminal);
911 lxc_terminal_conf_free(terminal);
912 return -1;
913 }
914
915 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal *terminal,
916 struct lxc_epoll_descr *descr)
917 {
918 int ret;
919
920 ret = lxc_mainloop_open(descr);
921 if (ret < 0)
922 return log_error(-1, "Failed to create mainloop");
923
924 ret = lxc_terminal_mainloop_add(descr, terminal);
925 if (ret < 0) {
926 lxc_mainloop_close(descr);
927 return log_error(-1, "Failed to add handlers to mainloop");
928 }
929
930 return 0;
931 }
932
933 static inline void lxc_attach_terminal_close_master(struct lxc_terminal *terminal)
934 {
935 close_prot_errno_disarm(terminal->master);
936 }
937
938 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal *terminal)
939 {
940 close_prot_errno_disarm(terminal->slave);
941 }
942
943 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal *terminal)
944 {
945 close_prot_errno_disarm(terminal->peer);
946 }
947
948 static inline void lxc_attach_terminal_close_log(struct lxc_terminal *terminal)
949 {
950 close_prot_errno_disarm(terminal->log_fd);
951 }
952
953 int lxc_attach(struct lxc_container *container, lxc_attach_exec_t exec_function,
954 void *exec_payload, lxc_attach_options_t *options,
955 pid_t *attached_process)
956 {
957 int i, ret, status;
958 int ipc_sockets[2];
959 char *cwd, *new_cwd;
960 signed long personality;
961 pid_t attached_pid, init_pid, pid;
962 struct lxc_proc_context_info *init_ctx;
963 struct lxc_terminal terminal;
964 struct lxc_conf *conf;
965 char *name, *lxcpath;
966 struct attach_clone_payload payload = {0};
967
968 ret = access("/proc/self/ns", X_OK);
969 if (ret)
970 return log_error_errno(-1, errno, "Does this kernel version support namespaces?");
971
972 if (!container)
973 return ret_set_errno(-1, EINVAL);
974
975 if (!lxc_container_get(container))
976 return ret_set_errno(-1, EINVAL);
977
978 name = container->name;
979 lxcpath = container->config_path;
980
981 if (!options)
982 options = &attach_static_default_options;
983
984 init_pid = lxc_cmd_get_init_pid(name, lxcpath);
985 if (init_pid < 0) {
986 lxc_container_put(container);
987 return log_error(-1, "Failed to get init pid");
988 }
989
990 init_ctx = lxc_proc_get_context_info(init_pid);
991 if (!init_ctx) {
992 ERROR("Failed to get context of init process: %ld", (long)init_pid);
993 lxc_container_put(container);
994 return -1;
995 }
996
997 init_ctx->container = container;
998
999 personality = get_personality(name, lxcpath);
1000 if (init_ctx->personality < 0) {
1001 ERROR("Failed to get personality of the container");
1002 lxc_proc_put_context_info(init_ctx);
1003 return -1;
1004 }
1005 init_ctx->personality = personality;
1006
1007 if (!init_ctx->container->lxc_conf) {
1008 init_ctx->container->lxc_conf = lxc_conf_init();
1009 if (!init_ctx->container->lxc_conf) {
1010 lxc_proc_put_context_info(init_ctx);
1011 return -1;
1012 }
1013 }
1014 conf = init_ctx->container->lxc_conf;
1015
1016 if (!fetch_seccomp(init_ctx->container, options))
1017 WARN("Failed to get seccomp policy");
1018
1019 if (!no_new_privs(init_ctx->container, options))
1020 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1021
1022 cwd = getcwd(NULL, 0);
1023
1024 /* Determine which namespaces the container was created with
1025 * by asking lxc-start, if necessary.
1026 */
1027 if (options->namespaces == -1) {
1028 options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);
1029 /* call failed */
1030 if (options->namespaces == -1) {
1031 ERROR("Failed to automatically determine the "
1032 "namespaces which the container uses");
1033 free(cwd);
1034 lxc_proc_put_context_info(init_ctx);
1035 return -1;
1036 }
1037
1038 for (i = 0; i < LXC_NS_MAX; i++) {
1039 if (ns_info[i].clone_flag & CLONE_NEWCGROUP)
1040 if (!(options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) ||
1041 !cgns_supported())
1042 continue;
1043
1044 if (ns_info[i].clone_flag & options->namespaces)
1045 continue;
1046
1047 init_ctx->ns_inherited |= ns_info[i].clone_flag;
1048 }
1049 }
1050
1051 pid = lxc_raw_getpid();
1052
1053 for (i = 0; i < LXC_NS_MAX; i++) {
1054 int j;
1055
1056 if (options->namespaces & ns_info[i].clone_flag)
1057 init_ctx->ns_fd[i] = lxc_preserve_ns(init_pid, ns_info[i].proc_name);
1058 else if (init_ctx->ns_inherited & ns_info[i].clone_flag)
1059 init_ctx->ns_fd[i] = in_same_namespace(pid, init_pid, ns_info[i].proc_name);
1060 else
1061 continue;
1062
1063 if (init_ctx->ns_fd[i] >= 0)
1064 continue;
1065
1066 if (init_ctx->ns_fd[i] == -EINVAL) {
1067 DEBUG("Inheriting %s namespace from %d",
1068 ns_info[i].proc_name, pid);
1069 init_ctx->ns_inherited &= ~ns_info[i].clone_flag;
1070 continue;
1071 }
1072
1073 /* We failed to preserve the namespace. */
1074 SYSERROR("Failed to attach to %s namespace of %d",
1075 ns_info[i].proc_name, pid);
1076
1077 /* Close all already opened file descriptors before we return an
1078 * error, so we don't leak them.
1079 */
1080 for (j = 0; j < i; j++)
1081 close(init_ctx->ns_fd[j]);
1082
1083 free(cwd);
1084 lxc_proc_put_context_info(init_ctx);
1085 return -1;
1086 }
1087
1088 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1089 ret = lxc_attach_terminal(conf, &terminal);
1090 if (ret < 0) {
1091 ERROR("Failed to setup new terminal");
1092 free(cwd);
1093 lxc_proc_put_context_info(init_ctx);
1094 return -1;
1095 }
1096
1097 terminal.log_fd = options->log_fd;
1098 } else {
1099 lxc_terminal_init(&terminal);
1100 }
1101
1102 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1103 * to make sure we don't irritate other threads that want to fork+exec
1104 * away
1105 *
1106 * IMPORTANT: if the initial process is multithreaded and another call
1107 * just fork()s away without exec'ing directly after, the socket fd will
1108 * exist in the forked process from the other thread and any close() in
1109 * our own child process will not really cause the socket to close
1110 * properly, potentially causing the parent to hang.
1111 *
1112 * For this reason, while IPC is still active, we have to use shutdown()
1113 * if the child exits prematurely in order to signal that the socket is
1114 * closed and cannot assume that the child exiting will automatically do
1115 * that.
1116 *
1117 * IPC mechanism: (X is receiver)
1118 * initial process intermediate attached
1119 * X <--- send pid of
1120 * attached proc,
1121 * then exit
1122 * send 0 ------------------------------------> X
1123 * [do initialization]
1124 * X <------------------------------------ send 1
1125 * [add to cgroup, ...]
1126 * send 2 ------------------------------------> X
1127 * [set LXC_ATTACH_NO_NEW_PRIVS]
1128 * X <------------------------------------ send 3
1129 * [open LSM label fd]
1130 * send 4 ------------------------------------> X
1131 * [set LSM label]
1132 * close socket close socket
1133 * run program
1134 */
1135 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
1136 if (ret < 0) {
1137 SYSERROR("Could not set up required IPC mechanism for attaching");
1138 free(cwd);
1139 lxc_proc_put_context_info(init_ctx);
1140 return -1;
1141 }
1142
1143 /* Create intermediate subprocess, two reasons:
1144 * 1. We can't setns() in the child itself, since we want to make
1145 * sure we are properly attached to the pidns.
1146 * 2. Also, the initial thread has to put the attached process
1147 * into the cgroup, which we can only do if we didn't already
1148 * setns() (otherwise, user namespaces will hate us).
1149 */
1150 pid = fork();
1151 if (pid < 0) {
1152 SYSERROR("Failed to create first subprocess");
1153 free(cwd);
1154 lxc_proc_put_context_info(init_ctx);
1155 return -1;
1156 }
1157
1158 if (pid) {
1159 int ret_parent = -1;
1160 pid_t to_cleanup_pid = pid;
1161 struct lxc_epoll_descr descr = {0};
1162
1163 /* close unneeded file descriptors */
1164 close(ipc_sockets[1]);
1165 free(cwd);
1166 lxc_proc_close_ns_fd(init_ctx);
1167 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1168 lxc_attach_terminal_close_slave(&terminal);
1169
1170 /* Attach to cgroup, if requested. */
1171 if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
1172 /*
1173 * If this is the unified hierarchy cgroup_attach() is
1174 * enough.
1175 */
1176 ret = cgroup_attach(name, lxcpath, pid);
1177 if (ret) {
1178 __do_cgroup_exit struct cgroup_ops *cgroup_ops = NULL;
1179
1180 cgroup_ops = cgroup_init(conf);
1181 if (!cgroup_ops)
1182 goto on_error;
1183
1184 if (!cgroup_ops->attach(cgroup_ops, name, lxcpath, pid))
1185 goto on_error;
1186 }
1187 TRACE("Moved intermediate process %d into container's cgroups", pid);
1188 }
1189
1190 /* Setup /proc limits */
1191 if (!lxc_list_empty(&conf->procs)) {
1192 ret = setup_proc_filesystem(&conf->procs, pid);
1193 if (ret < 0)
1194 goto on_error;
1195 }
1196
1197 /* Setup resource limits */
1198 if (!lxc_list_empty(&conf->limits)) {
1199 ret = setup_resource_limits(&conf->limits, pid);
1200 if (ret < 0)
1201 goto on_error;
1202 }
1203
1204 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1205 ret = lxc_attach_terminal_mainloop_init(&terminal, &descr);
1206 if (ret < 0)
1207 goto on_error;
1208
1209 TRACE("Initialized terminal mainloop");
1210 }
1211
1212 /* Let the child process know to go ahead. */
1213 status = 0;
1214 ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
1215 if (ret != sizeof(status))
1216 goto close_mainloop;
1217
1218 TRACE("Told intermediate process to start initializing");
1219
1220 /* Get pid of attached process from intermediate process. */
1221 ret = lxc_read_nointr(ipc_sockets[0], &attached_pid, sizeof(attached_pid));
1222 if (ret != sizeof(attached_pid))
1223 goto close_mainloop;
1224
1225 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
1226
1227 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1228 if (options->stdin_fd == 0) {
1229 signal(SIGINT, SIG_IGN);
1230 signal(SIGQUIT, SIG_IGN);
1231 }
1232
1233 /* Reap intermediate process. */
1234 ret = wait_for_pid(pid);
1235 if (ret < 0)
1236 goto close_mainloop;
1237
1238 TRACE("Intermediate process %d exited", pid);
1239
1240 /* We will always have to reap the attached process now. */
1241 to_cleanup_pid = attached_pid;
1242
1243 /* Open LSM fd and send it to child. */
1244 if ((options->namespaces & CLONE_NEWNS) &&
1245 (options->attach_flags & LXC_ATTACH_LSM) &&
1246 init_ctx->lsm_label) {
1247 int labelfd;
1248 bool on_exec;
1249
1250 ret = -1;
1251 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
1252 labelfd = lsm_process_label_fd_get(attached_pid, on_exec);
1253 if (labelfd < 0)
1254 goto close_mainloop;
1255
1256 TRACE("Opened LSM label file descriptor %d", labelfd);
1257
1258 /* Send child fd of the LSM security module to write to. */
1259 ret = lxc_abstract_unix_send_fds(ipc_sockets[0], &labelfd, 1, NULL, 0);
1260 if (ret <= 0) {
1261 if (ret < 0)
1262 SYSERROR("Failed to send lsm label fd");
1263
1264 close(labelfd);
1265 goto close_mainloop;
1266 }
1267
1268 close(labelfd);
1269 TRACE("Sent LSM label file descriptor %d to child", labelfd);
1270 }
1271
1272 if (conf && conf->seccomp.seccomp) {
1273 ret = lxc_seccomp_recv_notifier_fd(&conf->seccomp, ipc_sockets[0]);
1274 if (ret < 0)
1275 goto close_mainloop;
1276
1277 ret = lxc_seccomp_add_notifier(name, lxcpath, &conf->seccomp);
1278 if (ret < 0)
1279 goto close_mainloop;
1280 }
1281
1282 /* We're done, the child process should now execute whatever it
1283 * is that the user requested. The parent can now track it with
1284 * waitpid() or similar.
1285 */
1286
1287 *attached_process = attached_pid;
1288
1289 /* Now shut down communication with child, we're done. */
1290 shutdown(ipc_sockets[0], SHUT_RDWR);
1291 close(ipc_sockets[0]);
1292 ipc_sockets[0] = -1;
1293
1294 ret_parent = 0;
1295 to_cleanup_pid = -1;
1296
1297 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1298 ret = lxc_mainloop(&descr, -1);
1299 if (ret < 0) {
1300 ret_parent = -1;
1301 to_cleanup_pid = attached_pid;
1302 }
1303 }
1304
1305 close_mainloop:
1306 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1307 lxc_mainloop_close(&descr);
1308
1309 on_error:
1310 if (ipc_sockets[0] >= 0) {
1311 shutdown(ipc_sockets[0], SHUT_RDWR);
1312 close(ipc_sockets[0]);
1313 }
1314
1315 if (to_cleanup_pid > 0)
1316 (void)wait_for_pid(to_cleanup_pid);
1317
1318 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1319 lxc_terminal_delete(&terminal);
1320 lxc_terminal_conf_free(&terminal);
1321 }
1322
1323 lxc_proc_put_context_info(init_ctx);
1324 return ret_parent;
1325 }
1326
1327 /* close unneeded file descriptors */
1328 close(ipc_sockets[0]);
1329 ipc_sockets[0] = -EBADF;
1330
1331 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1332 lxc_attach_terminal_close_master(&terminal);
1333 lxc_attach_terminal_close_peer(&terminal);
1334 lxc_attach_terminal_close_log(&terminal);
1335 }
1336
1337 /* Wait for the parent to have setup cgroups. */
1338 ret = lxc_read_nointr(ipc_sockets[1], &status, sizeof(status));
1339 if (ret != sizeof(status)) {
1340 shutdown(ipc_sockets[1], SHUT_RDWR);
1341 lxc_proc_put_context_info(init_ctx);
1342 _exit(EXIT_FAILURE);
1343 }
1344
1345 TRACE("Intermediate process starting to initialize");
1346
1347 /* Attach now, create another subprocess later, since pid namespaces
1348 * only really affect the children of the current process.
1349 */
1350 ret = lxc_attach_to_ns(init_pid, init_ctx);
1351 if (ret < 0) {
1352 ERROR("Failed to enter namespaces");
1353 shutdown(ipc_sockets[1], SHUT_RDWR);
1354 lxc_proc_put_context_info(init_ctx);
1355 _exit(EXIT_FAILURE);
1356 }
1357
1358 /* close namespace file descriptors */
1359 lxc_proc_close_ns_fd(init_ctx);
1360
1361 /* Attach succeeded, try to cwd. */
1362 if (options->initial_cwd)
1363 new_cwd = options->initial_cwd;
1364 else
1365 new_cwd = cwd;
1366 if (new_cwd) {
1367 ret = chdir(new_cwd);
1368 if (ret < 0)
1369 WARN("Could not change directory to \"%s\"", new_cwd);
1370 }
1371 free(cwd);
1372
1373 /* Create attached process. */
1374 payload.ipc_socket = ipc_sockets[1];
1375 payload.options = options;
1376 payload.init_ctx = init_ctx;
1377 payload.terminal_slave_fd = terminal.slave;
1378 payload.exec_function = exec_function;
1379 payload.exec_payload = exec_payload;
1380
1381 pid = lxc_raw_clone(CLONE_PARENT, NULL);
1382 if (pid < 0) {
1383 SYSERROR("Failed to clone attached process");
1384 shutdown(ipc_sockets[1], SHUT_RDWR);
1385 lxc_proc_put_context_info(init_ctx);
1386 _exit(EXIT_FAILURE);
1387 }
1388
1389 if (pid == 0) {
1390 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1391 ret = pthread_sigmask(SIG_SETMASK,
1392 &terminal.tty_state->oldmask, NULL);
1393 if (ret < 0) {
1394 SYSERROR("Failed to reset signal mask");
1395 _exit(EXIT_FAILURE);
1396 }
1397 }
1398
1399 ret = attach_child_main(&payload);
1400 if (ret < 0)
1401 ERROR("Failed to exec");
1402
1403 _exit(EXIT_FAILURE);
1404 }
1405
1406 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1407 lxc_attach_terminal_close_slave(&terminal);
1408
1409 /* Tell grandparent the pid of the pid of the newly created child. */
1410 ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid));
1411 if (ret != sizeof(pid)) {
1412 /* If this really happens here, this is very unfortunate, since
1413 * the parent will not know the pid of the attached process and
1414 * will not be able to wait for it (and we won't either due to
1415 * CLONE_PARENT) so the parent won't be able to reap it and the
1416 * attached process will remain a zombie.
1417 */
1418 shutdown(ipc_sockets[1], SHUT_RDWR);
1419 lxc_proc_put_context_info(init_ctx);
1420 _exit(EXIT_FAILURE);
1421 }
1422
1423 TRACE("Sending pid %d of attached process", pid);
1424
1425 /* The rest is in the hands of the initial and the attached process. */
1426 lxc_proc_put_context_info(init_ctx);
1427 _exit(EXIT_SUCCESS);
1428 }
1429
1430 int lxc_attach_run_command(void *payload)
1431 {
1432 int ret = -1;
1433 lxc_attach_command_t *cmd = payload;
1434
1435 ret = execvp(cmd->program, cmd->argv);
1436 if (ret < 0) {
1437 switch (errno) {
1438 case ENOEXEC:
1439 ret = 126;
1440 break;
1441 case ENOENT:
1442 ret = 127;
1443 break;
1444 }
1445 }
1446
1447 return log_error_errno(ret, errno, "Failed to exec \"%s\"", cmd->program);
1448 }
1449
1450 int lxc_attach_run_shell(void* payload)
1451 {
1452 __do_free char *buf = NULL;
1453 uid_t uid;
1454 struct passwd pwent;
1455 struct passwd *pwentp = NULL;
1456 char *user_shell;
1457 size_t bufsize;
1458 int ret;
1459
1460 /* Ignore payload parameter. */
1461 (void)payload;
1462
1463 uid = getuid();
1464
1465 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1466 if (bufsize == -1)
1467 bufsize = 1024;
1468
1469 buf = malloc(bufsize);
1470 if (buf) {
1471 ret = getpwuid_r(uid, &pwent, buf, bufsize, &pwentp);
1472 if (!pwentp) {
1473 if (ret == 0)
1474 WARN("Could not find matched password record");
1475
1476 WARN("Failed to get password record - %u", uid);
1477 }
1478 }
1479
1480 /* This probably happens because of incompatible nss implementations in
1481 * host and container (remember, this code is still using the host's
1482 * glibc but our mount namespace is in the container) we may try to get
1483 * the information by spawning a [getent passwd uid] process and parsing
1484 * the result.
1485 */
1486 if (!pwentp)
1487 user_shell = lxc_attach_getpwshell(uid);
1488 else
1489 user_shell = pwent.pw_shell;
1490
1491 if (user_shell)
1492 execlp(user_shell, user_shell, (char *)NULL);
1493
1494 /* Executed if either no passwd entry or execvp fails, we will fall back
1495 * on /bin/sh as a default shell.
1496 */
1497 execlp("/bin/sh", "/bin/sh", (char *)NULL);
1498
1499 SYSERROR("Failed to execute shell");
1500 if (!pwentp)
1501 free(user_shell);
1502
1503 return -1;
1504 }