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