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