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