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