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