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