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