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