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