2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
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.
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.
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
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>
42 #include <lxc/lxccontainer.h>
44 #ifndef HAVE_DECL_PR_CAPBSET_DROP
45 #define PR_CAPBSET_DROP 24
48 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
49 #define PR_SET_NO_NEW_PRIVS 38
52 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
53 #define PR_GET_NO_NEW_PRIVS 39
68 #include "lxcseccomp.h"
69 #include "namespace.h"
72 #if HAVE_SYS_PERSONALITY_H
73 #include <sys/personality.h>
77 #define SOCK_CLOEXEC 02000000
85 #define MS_SLAVE (1 << 19)
88 lxc_log_define(lxc_attach
, lxc
);
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
)
95 char path
[__LSMATTRLEN
];
101 if (strcmp(name
, "nop") == 0)
104 if (strcmp(name
, "none") == 0)
107 /* We don't support on-exec with AppArmor */
108 if (strcmp(name
, "AppArmor") == 0)
112 ret
= snprintf(path
, __LSMATTRLEN
, "/proc/%d/attr/exec", pid
);
114 ret
= snprintf(path
, __LSMATTRLEN
, "/proc/%d/attr/current", pid
);
115 if (ret
< 0 || ret
>= __LSMATTRLEN
)
118 labelfd
= open(path
, O_RDWR
);
120 SYSERROR("%s - Unable to open file descriptor to set LSM label",
128 static int lsm_set_label_at(int lsm_labelfd
, int on_exec
, char *lsm_label
)
132 char *command
= NULL
;
136 if (strcmp(name
, "nop") == 0)
139 if (strcmp(name
, "none") == 0)
142 /* We don't support on-exec with AppArmor */
143 if (strcmp(name
, "AppArmor") == 0)
146 if (strcmp(name
, "AppArmor") == 0) {
150 malloc(strlen(lsm_label
) + strlen("changeprofile ") + 1);
152 SYSERROR("Failed to write apparmor profile.");
156 size
= sprintf(command
, "changeprofile %s", lsm_label
);
158 SYSERROR("Failed to write apparmor profile.");
162 if (write(lsm_labelfd
, command
, size
+ 1) < 0) {
163 SYSERROR("Unable to set LSM label: %s.", command
);
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
);
172 INFO("Set LSM label to: %s.", lsm_label
);
174 ERROR("Unable to restore label for unknown LSM: %s.", name
);
182 if (lsm_labelfd
!= -1)
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
)
195 char proc_fn
[__PROC_STATUS_LEN
];
196 size_t line_bufsz
= 0;
198 struct lxc_proc_context_info
*info
= NULL
;
200 /* Read capabilities. */
201 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
202 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
205 proc_file
= fopen(proc_fn
, "r");
207 SYSERROR("Could not open %s.", proc_fn
);
211 info
= calloc(1, sizeof(*info
));
213 SYSERROR("Could not allocate memory.");
219 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
220 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
221 if (ret
!= EOF
&& ret
== 1) {
231 SYSERROR("Could not read capability bounding set from %s.",
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
);
248 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
252 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
253 if (ctx
->ns_fd
[i
] < 0)
255 close(ctx
->ns_fd
[i
]);
256 ctx
->ns_fd
[i
] = -EBADF
;
260 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
262 free(ctx
->lsm_label
);
263 ctx
->lsm_label
= NULL
;
265 if (ctx
->container
) {
266 lxc_container_put(ctx
->container
);
267 ctx
->container
= NULL
;
270 lxc_proc_close_ns_fd(ctx
);
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/
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.
286 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
288 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
289 struct stat ns_st1
, ns_st2
;
291 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
293 /* The kernel does not support this namespace. This is not an
302 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
306 ret
= fstat(ns_fd1
, &ns_st1
);
310 ret
= fstat(ns_fd2
, &ns_st2
);
314 /* processes are in the same namespace */
316 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
319 /* processes are in different namespaces */
333 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
337 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
338 if (ctx
->ns_fd
[i
] < 0)
341 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
343 SYSERROR("Failed to attach to %s namespace of %d",
344 ns_info
[i
].proc_name
, pid
);
348 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
354 static int lxc_attach_remount_sys_proc(void)
358 ret
= unshare(CLONE_NEWNS
);
360 SYSERROR("Failed to unshare mount namespace.");
364 if (detect_shared_rootfs()) {
365 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
366 SYSERROR("Failed to make / rslave.");
367 ERROR("Continuing...");
371 /* Assume /proc is always mounted, so remount it. */
372 ret
= umount2("/proc", MNT_DETACH
);
374 SYSERROR("Failed to unmount /proc.");
378 ret
= mount("none", "/proc", "proc", 0, NULL
);
380 SYSERROR("Failed to remount /proc.");
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.
387 ret
= umount2("/sys", MNT_DETACH
);
388 if (ret
< 0 && errno
!= EINVAL
) {
389 SYSERROR("Failed to unmount /sys.");
391 } else if (ret
== 0) {
393 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
395 SYSERROR("Failed to remount /sys.");
403 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
407 last_cap
= lxc_caps_last_cap();
408 for (cap
= 0; cap
<= last_cap
; cap
++) {
409 if (ctx
->capability_mask
& (1LL << cap
))
412 if (prctl(PR_CAPBSET_DROP
, cap
, 0, 0, 0)) {
413 SYSERROR("Failed to drop capability %d", cap
);
416 TRACE("Dropped capability %d", cap
);
422 static int lxc_attach_set_environment(enum lxc_attach_env_policy_t policy
,
423 char **extra_env
, char **extra_keep
)
425 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
427 char **extra_keep_store
= NULL
;
432 for (count
= 0; extra_keep
[count
]; count
++);
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.");
440 for (i
= 0; i
< count
; i
++) {
441 char *v
= getenv(extra_keep
[i
]);
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.");
448 free(extra_keep_store
[--i
]);
449 free(extra_keep_store
);
452 if (strcmp(extra_keep
[i
], "PATH") == 0)
455 /* Calloc sets entire array to zero, so we don't
464 SYSERROR("Failed to clear environment.");
465 if (extra_keep_store
) {
466 for (p
= extra_keep_store
; *p
; p
++)
468 free(extra_keep_store
);
473 if (extra_keep_store
) {
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.");
481 free(extra_keep_store
[i
]);
483 free(extra_keep_store
);
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.
492 setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
495 if (putenv("container=lxc")) {
496 SYSERROR("Failed to set environment variable.");
500 /* Set extra environment variables. */
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.
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.
511 SYSERROR("Failed to allocate memory for additional environment "
522 static char *lxc_attach_getpwshell(uid_t uid
)
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.
547 size_t line_bufsz
= 0;
552 pipe_f
= fdopen(pipes
[0], "r");
553 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
557 char *endptr
= NULL
, *saveptr
= NULL
;
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.
566 /* Trim line on the right hand side. */
567 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
570 /* Split into tokens: first: user name. */
571 token
= strtok_r(line
, ":", &saveptr
);
574 /* next: dummy password field */
575 token
= strtok_r(NULL
, ":", &saveptr
);
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
)
583 /* dummy sanity check: user id matches */
584 if ((uid_t
) value
!= uid
)
586 /* skip fields: gid, gecos, dir, go to next field 'shell' */
587 for (i
= 0; i
< 4; i
++) {
588 token
= strtok_r(NULL
, ":", &saveptr
);
595 result
= strdup(token
);
597 /* Sanity check that there are no fields after that. */
598 token
= strtok_r(NULL
, ":", &saveptr
);
608 if (waitpid(pid
, &status
, 0) < 0) {
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
620 if (!WIFEXITED(status
)) {
625 if (WEXITSTATUS(status
) != 0) {
638 char *arguments
[] = {
647 /* We want to capture stdout. */
651 /* Get rid of stdin/stderr, so we try to associate it with
654 fd
= open("/dev/null", O_RDWR
);
664 /* Finish argument list. */
665 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long) uid
);
669 /* Try to run getent program. */
670 (void) execvp("getent", arguments
);
675 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
678 char proc_fn
[__PROC_STATUS_LEN
];
681 size_t line_bufsz
= 0;
683 uid_t uid
= (uid_t
)-1;
684 gid_t gid
= (gid_t
)-1;
686 /* Read capabilities. */
687 snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
689 proc_file
= fopen(proc_fn
, "r");
693 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
694 /* Format is: real, effective, saved set user, fs we only care
697 ret
= sscanf(line
, "Uid: %ld", &value
);
698 if (ret
!= EOF
&& ret
== 1) {
701 ret
= sscanf(line
, "Gid: %ld", &value
);
702 if (ret
!= EOF
&& ret
== 1)
705 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
712 /* Only override arguments if we found something. */
713 if (uid
!= (uid_t
)-1)
715 if (gid
!= (gid_t
)-1)
718 /* TODO: we should also parse supplementary groups and use
719 * setgroups() to set them.
723 /* Help the optimizer along if it doesn't know that exit always exits. */
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
;
734 static bool fetch_seccomp(struct lxc_container
*c
,
735 lxc_attach_options_t
*options
)
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
;
746 /* Remove current setting. */
747 if (!c
->set_config_item(c
, "lxc.seccomp", "") &&
748 !c
->set_config_item(c
, "lxc.seccomp.profile", "")) {
752 /* Fetch the current profile path over the cmd interface. */
753 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
755 INFO("Failed to get running config item for lxc.seccomp.profile");
756 path
= c
->get_running_config_item(c
, "lxc.seccomp");
759 INFO("Failed to get running config item for lxc.seccomp");
763 /* Copy the value into the new lxc_conf. */
764 if (!c
->set_config_item(c
, "lxc.seccomp.profile", path
)) {
770 /* Attempt to parse the resulting config. */
771 if (lxc_read_seccomp_config(c
->lxc_conf
) < 0) {
772 ERROR("Error reading seccomp policy.");
776 INFO("Retrieved seccomp policy.");
780 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
784 /* Remove current setting. */
785 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
788 /* Retrieve currently active setting. */
789 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
791 INFO("Failed to get running config item for lxc.no_new_privs.");
795 /* Set currently active setting. */
796 if (!c
->set_config_item(c
, "lxc.no_new_privs", val
)) {
805 static signed long get_personality(const char *name
, const char *lxcpath
)
810 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
814 ret
= lxc_config_parse_arch(p
);
820 struct attach_clone_payload
{
822 lxc_attach_options_t
*options
;
823 struct lxc_proc_context_info
*init_ctx
;
824 lxc_attach_exec_t exec_function
;
828 static int attach_child_main(struct attach_clone_payload
*payload
)
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
) &&
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
844 if (!(options
->namespaces
& CLONE_NEWNS
) &&
845 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
846 ret
= lxc_attach_remount_sys_proc();
849 TRACE("Remounted \"/proc\" and \"/sys\"");
852 /* Now perform additional attachments. */
853 #if HAVE_SYS_PERSONALITY_H
854 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
855 long new_personality
;
857 if (options
->personality
< 0)
858 new_personality
= init_ctx
->personality
;
860 new_personality
= options
->personality
;
861 ret
= personality(new_personality
);
864 TRACE("Set new personality");
868 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
869 ret
= lxc_attach_drop_privs(init_ctx
);
872 TRACE("Dropped capabilities");
875 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
876 * if you want this to be a no-op).
878 ret
= lxc_attach_set_environment(options
->env_policy
,
879 options
->extra_env_vars
,
880 options
->extra_keep_env
);
883 TRACE("Set up environment");
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
897 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
900 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
903 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
904 ret
= lxc_make_controlling_pty(options
->stdin_fd
);
912 /* Ignore errors, we will fall back to root in that case (/proc was not
915 if (options
->namespaces
& CLONE_NEWUSER
)
916 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
918 if (options
->uid
!= (uid_t
)-1)
919 new_uid
= options
->uid
;
920 if (options
->gid
!= (gid_t
)-1)
921 new_gid
= options
->gid
;
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
);
929 ret
= lxc_setgroups(0, NULL
);
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);
940 TRACE("Set PR_SET_NO_NEW_PRIVS");
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
);
952 TRACE("Set LSM label");
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
);
960 TRACE("Loaded seccomp profile");
962 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
963 close(payload
->ipc_socket
);
964 payload
->ipc_socket
= -1;
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.
972 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
973 * may want to make sure the fds are closed, for example.
975 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
976 dup2(options
->stdin_fd
, STDIN_FILENO
);
978 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
979 dup2(options
->stdout_fd
, STDOUT_FILENO
);
981 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
982 dup2(options
->stderr_fd
, STDERR_FILENO
);
984 /* close the old fds */
985 if (options
->stdin_fd
> STDERR_FILENO
)
986 close(options
->stdin_fd
);
988 if (options
->stdout_fd
> STDERR_FILENO
)
989 close(options
->stdout_fd
);
991 if (options
->stderr_fd
> STDERR_FILENO
)
992 close(options
->stderr_fd
);
994 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
995 * here, ignore errors.
997 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
1000 flags
= fcntl(fd
, F_GETFL
);
1004 if ((flags
& FD_CLOEXEC
) == 0)
1007 ret
= fcntl(fd
, F_SETFL
, flags
& ~FD_CLOEXEC
);
1009 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
1014 /* We're done, so we can now do whatever the user intended us to do. */
1015 rexit(payload
->exec_function(payload
->exec_payload
));
1018 if (payload
->ipc_socket
>= 0) {
1019 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
1020 close(payload
->ipc_socket
);
1021 payload
->ipc_socket
= -1;
1023 lxc_proc_put_context_info(init_ctx
);
1024 rexit(EXIT_FAILURE
);
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
)
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};
1039 ret
= access("/proc/self/ns", X_OK
);
1041 ERROR("Does this kernel version support namespaces?");
1046 options
= &attach_static_default_options
;
1048 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1050 ERROR("Failed to get init pid.");
1054 init_ctx
= lxc_proc_get_context_info(init_pid
);
1056 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
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
);
1066 init_ctx
->personality
= personality
;
1068 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1069 if (!init_ctx
->container
) {
1070 lxc_proc_put_context_info(init_ctx
);
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
);
1082 if (!fetch_seccomp(init_ctx
->container
, options
))
1083 WARN("Failed to get seccomp policy.");
1085 if (!no_new_privs(init_ctx
->container
, options
))
1086 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set.");
1088 cwd
= getcwd(NULL
, 0);
1090 /* Determine which namespaces the container was created with
1091 * by asking lxc-start, if necessary.
1093 if (options
->namespaces
== -1) {
1094 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1096 if (options
->namespaces
== -1) {
1097 ERROR("Failed to automatically determine the "
1098 "namespaces which the container uses");
1100 lxc_proc_put_context_info(init_ctx
);
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
) ||
1110 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1113 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1117 pid
= lxc_raw_getpid();
1118 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
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
);
1127 if (init_ctx
->ns_fd
[i
] >= 0)
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
;
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.
1142 for (j
= 0; j
< i
; j
++)
1143 close(init_ctx
->ns_fd
[j
]);
1145 errno
= saved_errno
;
1146 SYSERROR("Failed to attach to %s namespace of %d",
1147 ns_info
[i
].proc_name
, pid
);
1149 lxc_proc_put_context_info(init_ctx
);
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
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.
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
1168 * IPC mechanism: (X is receiver)
1169 * initial process intermediate attached
1170 * X <--- send pid of
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
1183 * close socket close socket
1186 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1188 SYSERROR("Could not set up required IPC mechanism for attaching.");
1190 lxc_proc_put_context_info(init_ctx
);
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
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).
1206 SYSERROR("Failed to create first subprocess.");
1208 lxc_proc_put_context_info(init_ctx
);
1213 pid_t to_cleanup_pid
= pid
;
1215 /* Initial thread, we close the socket that is for the
1218 close(ipc_sockets
[1]);
1221 /* Attach to cgroup, if requested. */
1222 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1223 if (!cgroup_attach(name
, lxcpath
, pid
))
1225 TRACE("Moved intermediate process %d into container's "
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)
1234 /* Let the child process know to go ahead. */
1236 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1237 if (ret
!= sizeof(status
))
1239 TRACE("Told intermediate process to start initializing");
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
))
1245 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
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
);
1253 /* Reap intermediate process. */
1254 ret
= wait_for_pid(pid
);
1257 TRACE("Intermediate process %d exited", pid
);
1259 /* We will always have to reap the attached process now. */
1260 to_cleanup_pid
= attached_pid
;
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
;
1269 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? 1 : 0;
1270 labelfd
= lsm_open(attached_pid
, on_exec
);
1273 TRACE("Opened LSM label file descriptor %d", labelfd
);
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);
1279 SYSERROR("%d", (int)ret
);
1282 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
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
);
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.
1295 *attached_process
= attached_pid
;
1299 /* First shut down the socket, then wait for the pid, otherwise
1300 * the pid we're waiting for may never exit.
1302 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1303 close(ipc_sockets
[0]);
1305 (void)wait_for_pid(to_cleanup_pid
);
1306 lxc_proc_put_context_info(init_ctx
);
1310 /* First subprocess begins here, we close the socket that is for the
1313 close(ipc_sockets
[0]);
1315 /* Wait for the parent to have setup cgroups. */
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
);
1323 TRACE("Intermediate process starting to initialize");
1325 /* Attach now, create another subprocess later, since pid namespaces
1326 * only really affect the children of the current process.
1328 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1330 ERROR("Failed to enter namespaces");
1331 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1332 lxc_proc_put_context_info(init_ctx
);
1335 /* close namespace file descriptors */
1336 lxc_proc_close_ns_fd(init_ctx
);
1338 /* Attach succeeded, try to cwd. */
1339 if (options
->initial_cwd
)
1340 new_cwd
= options
->initial_cwd
;
1344 ret
= chdir(new_cwd
);
1346 WARN("Could not change directory to \"%s\"", new_cwd
);
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
;
1357 pid
= lxc_raw_clone(CLONE_PARENT
);
1359 SYSERROR("Failed to clone attached process");
1360 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1361 lxc_proc_put_context_info(init_ctx
);
1366 ret
= attach_child_main(&payload
);
1368 ERROR("Failed to exec");
1369 _exit(EXIT_FAILURE
);
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.
1381 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1382 lxc_proc_put_context_info(init_ctx
);
1385 TRACE("Sending pid %d of attached process", pid
);
1387 /* The rest is in the hands of the initial and the attached process. */
1388 lxc_proc_put_context_info(init_ctx
);
1392 int lxc_attach_run_command(void* payload
)
1394 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1396 execvp(cmd
->program
, cmd
->argv
);
1397 SYSERROR("Failed to exec \"%s\".", cmd
->program
);
1401 int lxc_attach_run_shell(void* payload
)
1404 struct passwd
*passwd
;
1407 /* Ignore payload parameter. */
1411 passwd
= getpwuid(uid
);
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
1420 user_shell
= lxc_attach_getpwshell(uid
);
1422 user_shell
= passwd
->pw_shell
;
1424 execlp(user_shell
, user_shell
, (char *)NULL
);
1426 /* Executed if either no passwd entry or execvp fails, we will fall back
1427 * on /bin/sh as a default shell.
1429 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1430 SYSERROR("Failed to execute shell");