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