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