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