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"
70 #include "namespace.h"
73 #if HAVE_SYS_PERSONALITY_H
74 #include <sys/personality.h>
78 #define SOCK_CLOEXEC 02000000
86 #define MS_SLAVE (1 << 19)
89 lxc_log_define(lxc_attach
, lxc
);
91 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
92 #define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
93 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
98 char proc_fn
[__PROC_STATUS_LEN
];
99 size_t line_bufsz
= 0;
101 struct lxc_proc_context_info
*info
= NULL
;
103 /* Read capabilities. */
104 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
105 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
108 proc_file
= fopen(proc_fn
, "r");
110 SYSERROR("Could not open %s.", proc_fn
);
114 info
= calloc(1, sizeof(*info
));
116 SYSERROR("Could not allocate memory.");
122 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
123 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
124 if (ret
!= EOF
&& ret
== 1) {
134 SYSERROR("Could not read capability bounding set from %s.",
140 info
->lsm_label
= lsm_process_label_get(pid
);
141 info
->ns_inherited
= 0;
142 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
151 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
155 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
156 if (ctx
->ns_fd
[i
] < 0)
158 close(ctx
->ns_fd
[i
]);
159 ctx
->ns_fd
[i
] = -EBADF
;
163 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
165 free(ctx
->lsm_label
);
166 ctx
->lsm_label
= NULL
;
168 if (ctx
->container
) {
169 lxc_container_put(ctx
->container
);
170 ctx
->container
= NULL
;
173 lxc_proc_close_ns_fd(ctx
);
179 * in_same_namespace - Check whether two processes are in the same namespace.
180 * @pid1 - PID of the first process.
181 * @pid2 - PID of the second process.
182 * @ns - Name of the namespace to check. Must correspond to one of the names
183 * for the namespaces as shown in /proc/<pid/ns/
185 * If the two processes are not in the same namespace returns an fd to the
186 * namespace of the second process identified by @pid2. If the two processes are
187 * in the same namespace returns -EINVAL, -1 if an error occurred.
189 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
191 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
192 struct stat ns_st1
, ns_st2
;
194 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
196 /* The kernel does not support this namespace. This is not an
205 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
209 ret
= fstat(ns_fd1
, &ns_st1
);
213 ret
= fstat(ns_fd2
, &ns_st2
);
217 /* processes are in the same namespace */
219 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
222 /* processes are in different namespaces */
236 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
240 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
241 if (ctx
->ns_fd
[i
] < 0)
244 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
246 SYSERROR("Failed to attach to %s namespace of %d",
247 ns_info
[i
].proc_name
, pid
);
251 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
257 static int lxc_attach_remount_sys_proc(void)
261 ret
= unshare(CLONE_NEWNS
);
263 SYSERROR("Failed to unshare mount namespace.");
267 if (detect_shared_rootfs()) {
268 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
269 SYSERROR("Failed to make / rslave.");
270 ERROR("Continuing...");
274 /* Assume /proc is always mounted, so remount it. */
275 ret
= umount2("/proc", MNT_DETACH
);
277 SYSERROR("Failed to unmount /proc.");
281 ret
= mount("none", "/proc", "proc", 0, NULL
);
283 SYSERROR("Failed to remount /proc.");
287 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
288 * we ignore it because it may not have been mounted in the first place.
290 ret
= umount2("/sys", MNT_DETACH
);
291 if (ret
< 0 && errno
!= EINVAL
) {
292 SYSERROR("Failed to unmount /sys.");
294 } else if (ret
== 0) {
296 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
298 SYSERROR("Failed to remount /sys.");
306 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
310 last_cap
= lxc_caps_last_cap();
311 for (cap
= 0; cap
<= last_cap
; cap
++) {
312 if (ctx
->capability_mask
& (1LL << cap
))
315 if (prctl(PR_CAPBSET_DROP
, cap
, 0, 0, 0)) {
316 SYSERROR("Failed to drop capability %d", cap
);
319 TRACE("Dropped capability %d", cap
);
325 static int lxc_attach_set_environment(enum lxc_attach_env_policy_t policy
,
326 char **extra_env
, char **extra_keep
)
328 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
330 char **extra_keep_store
= NULL
;
335 for (count
= 0; extra_keep
[count
]; count
++);
337 extra_keep_store
= calloc(count
, sizeof(char *));
338 if (!extra_keep_store
) {
339 SYSERROR("Failed to allocate memory for storing current "
340 "environment variable values that will be kept.");
343 for (i
= 0; i
< count
; i
++) {
344 char *v
= getenv(extra_keep
[i
]);
346 extra_keep_store
[i
] = strdup(v
);
347 if (!extra_keep_store
[i
]) {
348 SYSERROR("Failed to allocate memory for storing current "
349 "environment variable values that will be kept.");
351 free(extra_keep_store
[--i
]);
352 free(extra_keep_store
);
355 if (strcmp(extra_keep
[i
], "PATH") == 0)
358 /* Calloc sets entire array to zero, so we don't
367 SYSERROR("Failed to clear environment.");
368 if (extra_keep_store
) {
369 for (p
= extra_keep_store
; *p
; p
++)
371 free(extra_keep_store
);
376 if (extra_keep_store
) {
379 for (i
= 0; extra_keep
[i
]; i
++) {
380 if (extra_keep_store
[i
]) {
381 if (setenv(extra_keep
[i
], extra_keep_store
[i
], 1) < 0)
382 SYSERROR("Unable to set environment variable.");
384 free(extra_keep_store
[i
]);
386 free(extra_keep_store
);
389 /* Always set a default path; shells and execlp tend to be fine
390 * without it, but there is a disturbing number of C programs
391 * out there that just assume that getenv("PATH") is never NULL
392 * and then die a painful segfault death.
395 setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
398 if (putenv("container=lxc")) {
399 SYSERROR("Failed to set environment variable.");
403 /* Set extra environment variables. */
405 for (; *extra_env
; extra_env
++) {
406 /* Duplicate the string, just to be on the safe side,
407 * because putenv does not do it for us.
409 char *p
= strdup(*extra_env
);
410 /* We just assume the user knows what they are doing, so
411 * we don't do any checks.
414 SYSERROR("Failed to allocate memory for additional environment "
425 static char *lxc_attach_getpwshell(uid_t uid
)
432 /* We need to fork off a process that runs the getent program, and we
433 * need to capture its output, so we use a pipe for that purpose.
450 size_t line_bufsz
= 0;
455 pipe_f
= fdopen(pipes
[0], "r");
456 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
460 char *endptr
= NULL
, *saveptr
= NULL
;
462 /* If we already found something, just continue to read
463 * until the pipe doesn't deliver any more data, but
464 * don't modify the existing data structure.
469 /* Trim line on the right hand side. */
470 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
473 /* Split into tokens: first: user name. */
474 token
= strtok_r(line
, ":", &saveptr
);
477 /* next: dummy password field */
478 token
= strtok_r(NULL
, ":", &saveptr
);
482 token
= strtok_r(NULL
, ":", &saveptr
);
483 value
= token
? strtol(token
, &endptr
, 10) : 0;
484 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
|| value
== LONG_MAX
)
486 /* dummy sanity check: user id matches */
487 if ((uid_t
) value
!= uid
)
489 /* skip fields: gid, gecos, dir, go to next field 'shell' */
490 for (i
= 0; i
< 4; i
++) {
491 token
= strtok_r(NULL
, ":", &saveptr
);
498 result
= strdup(token
);
500 /* Sanity check that there are no fields after that. */
501 token
= strtok_r(NULL
, ":", &saveptr
);
511 if (waitpid(pid
, &status
, 0) < 0) {
518 /* Some sanity checks. If anything even hinted at going wrong,
519 * we can't be sure we have a valid result, so we assume we
523 if (!WIFEXITED(status
)) {
528 if (WEXITSTATUS(status
) != 0) {
541 char *arguments
[] = {
550 /* We want to capture stdout. */
554 /* Get rid of stdin/stderr, so we try to associate it with
557 fd
= open("/dev/null", O_RDWR
);
567 /* Finish argument list. */
568 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long) uid
);
572 /* Try to run getent program. */
573 (void) execvp("getent", arguments
);
578 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
581 char proc_fn
[__PROC_STATUS_LEN
];
584 size_t line_bufsz
= 0;
586 uid_t uid
= (uid_t
)-1;
587 gid_t gid
= (gid_t
)-1;
589 /* Read capabilities. */
590 snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
592 proc_file
= fopen(proc_fn
, "r");
596 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
597 /* Format is: real, effective, saved set user, fs we only care
600 ret
= sscanf(line
, "Uid: %ld", &value
);
601 if (ret
!= EOF
&& ret
== 1) {
604 ret
= sscanf(line
, "Gid: %ld", &value
);
605 if (ret
!= EOF
&& ret
== 1)
608 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
615 /* Only override arguments if we found something. */
616 if (uid
!= (uid_t
)-1)
618 if (gid
!= (gid_t
)-1)
621 /* TODO: we should also parse supplementary groups and use
622 * setgroups() to set them.
626 /* Help the optimizer along if it doesn't know that exit always exits. */
634 /* Define default options if no options are supplied by the user. */
635 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
637 static bool fetch_seccomp(struct lxc_container
*c
,
638 lxc_attach_options_t
*options
)
642 if (!(options
->namespaces
& CLONE_NEWNS
) ||
643 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
644 free(c
->lxc_conf
->seccomp
);
645 c
->lxc_conf
->seccomp
= NULL
;
649 /* Remove current setting. */
650 if (!c
->set_config_item(c
, "lxc.seccomp", "") &&
651 !c
->set_config_item(c
, "lxc.seccomp.profile", "")) {
655 /* Fetch the current profile path over the cmd interface. */
656 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
658 INFO("Failed to get running config item for lxc.seccomp.profile");
659 path
= c
->get_running_config_item(c
, "lxc.seccomp");
662 INFO("Failed to get running config item for lxc.seccomp");
666 /* Copy the value into the new lxc_conf. */
667 if (!c
->set_config_item(c
, "lxc.seccomp.profile", path
)) {
673 /* Attempt to parse the resulting config. */
674 if (lxc_read_seccomp_config(c
->lxc_conf
) < 0) {
675 ERROR("Error reading seccomp policy.");
679 INFO("Retrieved seccomp policy.");
683 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
687 /* Remove current setting. */
688 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
691 /* Retrieve currently active setting. */
692 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
694 INFO("Failed to get running config item for lxc.no_new_privs.");
698 /* Set currently active setting. */
699 if (!c
->set_config_item(c
, "lxc.no_new_privs", val
)) {
708 static signed long get_personality(const char *name
, const char *lxcpath
)
713 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
717 ret
= lxc_config_parse_arch(p
);
723 struct attach_clone_payload
{
726 lxc_attach_options_t
*options
;
727 struct lxc_proc_context_info
*init_ctx
;
728 lxc_attach_exec_t exec_function
;
732 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
734 if (p
->ipc_socket
>= 0) {
735 shutdown(p
->ipc_socket
, SHUT_RDWR
);
736 close(p
->ipc_socket
);
737 p
->ipc_socket
= -EBADF
;
740 if (p
->pty_fd
>= 0) {
746 lxc_proc_put_context_info(p
->init_ctx
);
749 static int attach_child_main(struct attach_clone_payload
*payload
)
754 lxc_attach_options_t
* options
= payload
->options
;
755 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
756 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
757 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
760 /* A description of the purpose of this functionality is provided in the
761 * lxc-attach(1) manual page. We have to remount here and not in the
762 * parent process, otherwise /proc may not properly reflect the new pid
765 if (!(options
->namespaces
& CLONE_NEWNS
) &&
766 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
767 ret
= lxc_attach_remount_sys_proc();
770 TRACE("Remounted \"/proc\" and \"/sys\"");
773 /* Now perform additional attachments. */
774 #if HAVE_SYS_PERSONALITY_H
775 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
776 long new_personality
;
778 if (options
->personality
< 0)
779 new_personality
= init_ctx
->personality
;
781 new_personality
= options
->personality
;
782 ret
= personality(new_personality
);
785 TRACE("Set new personality");
789 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
790 ret
= lxc_attach_drop_privs(init_ctx
);
793 TRACE("Dropped capabilities");
796 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
797 * if you want this to be a no-op).
799 ret
= lxc_attach_set_environment(options
->env_policy
,
800 options
->extra_env_vars
,
801 options
->extra_keep_env
);
804 TRACE("Set up environment");
806 /* This remark only affects fully unprivileged containers:
807 * Receive fd for LSM security module before we set{g,u}id(). The reason
808 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
809 * we will change our effective uid. This means our effective uid will
810 * be different from the effective uid of the process that created us
811 * which means that this processs no longer has capabilities in our
812 * namespace including CAP_SYS_PTRACE. This means we will not be able to
813 * read and /proc/<pid> files for the process anymore when /proc is
814 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
818 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
821 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
824 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
825 ret
= lxc_make_controlling_pty(options
->stdin_fd
);
833 /* Ignore errors, we will fall back to root in that case (/proc was not
836 if (options
->namespaces
& CLONE_NEWUSER
)
837 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
839 if (options
->uid
!= (uid_t
)-1)
840 new_uid
= options
->uid
;
841 if (options
->gid
!= (gid_t
)-1)
842 new_gid
= options
->gid
;
844 /* Try to set the {u,g}id combination. */
845 if (new_uid
!= 0 || new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) {
846 ret
= lxc_switch_uid_gid(new_uid
, new_gid
);
850 ret
= lxc_setgroups(0, NULL
);
855 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
856 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
857 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
858 ret
= prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0);
861 TRACE("Set PR_SET_NO_NEW_PRIVS");
867 /* Change into our new LSM profile. */
868 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
869 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
873 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
876 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
877 init_ctx
->container
->lxc_conf
->seccomp
) {
878 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
881 TRACE("Loaded seccomp profile");
883 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
884 close(payload
->ipc_socket
);
885 payload
->ipc_socket
= -EBADF
;
886 lxc_proc_put_context_info(init_ctx
);
888 /* The following is done after the communication socket is shut down.
889 * That way, all errors that might (though unlikely) occur up until this
890 * point will have their messages printed to the original stderr (if
891 * logging is so configured) and not the fd the user supplied, if any.
894 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
895 * may want to make sure the fds are closed, for example.
897 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
898 dup2(options
->stdin_fd
, STDIN_FILENO
);
900 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
901 dup2(options
->stdout_fd
, STDOUT_FILENO
);
903 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
904 dup2(options
->stderr_fd
, STDERR_FILENO
);
906 /* close the old fds */
907 if (options
->stdin_fd
> STDERR_FILENO
)
908 close(options
->stdin_fd
);
910 if (options
->stdout_fd
> STDERR_FILENO
)
911 close(options
->stdout_fd
);
913 if (options
->stderr_fd
> STDERR_FILENO
)
914 close(options
->stderr_fd
);
916 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
917 * here, ignore errors.
919 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
922 flags
= fcntl(fd
, F_GETFL
);
926 if ((flags
& FD_CLOEXEC
) == 0)
929 ret
= fcntl(fd
, F_SETFL
, flags
& ~FD_CLOEXEC
);
931 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
936 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
937 ret
= lxc_login_pty(payload
->pty_fd
);
939 SYSERROR("Failed to prepare pty file descriptor %d", payload
->pty_fd
);
942 TRACE("Prepared pty file descriptor %d", payload
->pty_fd
);
945 /* We're done, so we can now do whatever the user intended us to do. */
946 rexit(payload
->exec_function(payload
->exec_payload
));
949 lxc_put_attach_clone_payload(payload
);
953 static int lxc_attach_pty(struct lxc_conf
*conf
, struct lxc_console
*pty
)
959 ret
= lxc_pty_create(pty
);
961 SYSERROR("Failed to create pty");
965 /* Shift ttys to container. */
966 ret
= lxc_pty_map_ids(conf
, pty
);
968 ERROR("Failed to shift pty");
975 lxc_console_delete(pty
);
976 lxc_pty_conf_free(pty
);
980 static int lxc_attach_pty_mainloop_init(struct lxc_console
*pty
,
981 struct lxc_epoll_descr
*descr
)
985 ret
= lxc_mainloop_open(descr
);
987 ERROR("Failed to create mainloop");
991 ret
= lxc_console_mainloop_add(descr
, pty
);
993 ERROR("Failed to add handlers to mainloop");
994 lxc_mainloop_close(descr
);
1001 static inline void lxc_attach_pty_close_master(struct lxc_console
*pty
)
1003 if (pty
->master
< 0)
1007 pty
->master
= -EBADF
;
1010 static inline void lxc_attach_pty_close_slave(struct lxc_console
*pty
)
1016 pty
->slave
= -EBADF
;
1019 static inline void lxc_attach_pty_close_peer(struct lxc_console
*pty
)
1028 static inline void lxc_attach_pty_close_log(struct lxc_console
*pty
)
1030 if (pty
->log_fd
< 0)
1034 pty
->log_fd
= -EBADF
;
1037 int lxc_attach(const char *name
, const char *lxcpath
,
1038 lxc_attach_exec_t exec_function
, void *exec_payload
,
1039 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1043 char *cwd
, *new_cwd
;
1044 signed long personality
;
1045 pid_t attached_pid
, init_pid
, pid
;
1046 struct lxc_proc_context_info
*init_ctx
;
1047 struct lxc_console pty
;
1048 struct attach_clone_payload payload
= {0};
1050 ret
= access("/proc/self/ns", X_OK
);
1052 ERROR("Does this kernel version support namespaces?");
1057 options
= &attach_static_default_options
;
1059 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1061 ERROR("Failed to get init pid.");
1065 init_ctx
= lxc_proc_get_context_info(init_pid
);
1067 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1071 personality
= get_personality(name
, lxcpath
);
1072 if (init_ctx
->personality
< 0) {
1073 ERROR("Failed to get personality of the container");
1074 lxc_proc_put_context_info(init_ctx
);
1077 init_ctx
->personality
= personality
;
1079 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1080 if (!init_ctx
->container
) {
1081 lxc_proc_put_context_info(init_ctx
);
1085 if (!init_ctx
->container
->lxc_conf
) {
1086 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1087 if (!init_ctx
->container
->lxc_conf
) {
1088 lxc_proc_put_context_info(init_ctx
);
1093 if (!fetch_seccomp(init_ctx
->container
, options
))
1094 WARN("Failed to get seccomp policy.");
1096 if (!no_new_privs(init_ctx
->container
, options
))
1097 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set.");
1099 cwd
= getcwd(NULL
, 0);
1101 /* Determine which namespaces the container was created with
1102 * by asking lxc-start, if necessary.
1104 if (options
->namespaces
== -1) {
1105 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1107 if (options
->namespaces
== -1) {
1108 ERROR("Failed to automatically determine the "
1109 "namespaces which the container uses");
1111 lxc_proc_put_context_info(init_ctx
);
1115 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1116 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1117 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1121 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1124 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1128 pid
= lxc_raw_getpid();
1129 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1132 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1133 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1134 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1135 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1138 if (init_ctx
->ns_fd
[i
] >= 0)
1141 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1142 DEBUG("Inheriting %s namespace from %d",
1143 ns_info
[i
].proc_name
, pid
);
1144 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1148 /* We failed to preserve the namespace. */
1149 saved_errno
= errno
;
1150 /* Close all already opened file descriptors before we return an
1151 * error, so we don't leak them.
1153 for (j
= 0; j
< i
; j
++)
1154 close(init_ctx
->ns_fd
[j
]);
1156 errno
= saved_errno
;
1157 SYSERROR("Failed to attach to %s namespace of %d",
1158 ns_info
[i
].proc_name
, pid
);
1160 lxc_proc_put_context_info(init_ctx
);
1164 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1165 ret
= lxc_attach_pty(init_ctx
->container
->lxc_conf
, &pty
);
1167 ERROR("Failed to allocate pty");
1169 lxc_proc_put_context_info(init_ctx
);
1173 pty
.log_fd
= options
->log_fd
;
1176 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1177 * to make sure we don't irritate other threads that want to fork+exec
1180 * IMPORTANT: if the initial process is multithreaded and another call
1181 * just fork()s away without exec'ing directly after, the socket fd will
1182 * exist in the forked process from the other thread and any close() in
1183 * our own child process will not really cause the socket to close
1184 * properly, potentiall causing the parent to hang.
1186 * For this reason, while IPC is still active, we have to use shutdown()
1187 * if the child exits prematurely in order to signal that the socket is
1188 * closed and cannot assume that the child exiting will automatically do
1191 * IPC mechanism: (X is receiver)
1192 * initial process intermediate attached
1193 * X <--- send pid of
1196 * send 0 ------------------------------------> X
1197 * [do initialization]
1198 * X <------------------------------------ send 1
1199 * [add to cgroup, ...]
1200 * send 2 ------------------------------------> X
1201 * [set LXC_ATTACH_NO_NEW_PRIVS]
1202 * X <------------------------------------ send 3
1203 * [open LSM label fd]
1204 * send 4 ------------------------------------> X
1206 * close socket close socket
1209 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1211 SYSERROR("Could not set up required IPC mechanism for attaching.");
1213 lxc_proc_put_context_info(init_ctx
);
1217 /* Create intermediate subprocess, three reasons:
1218 * 1. Runs all pthread_atfork handlers and the child will no
1219 * longer be threaded (we can't properly setns() in a threaded
1221 * 2. We can't setns() in the child itself, since we want to make
1222 * sure we are properly attached to the pidns.
1223 * 3. Also, the initial thread has to put the attached process
1224 * into the cgroup, which we can only do if we didn't already
1225 * setns() (otherwise, user namespaces will hate us).
1229 SYSERROR("Failed to create first subprocess.");
1231 lxc_proc_put_context_info(init_ctx
);
1236 int ret_parent
= -1;
1237 pid_t to_cleanup_pid
= pid
;
1238 struct lxc_epoll_descr descr
= {0};
1240 /* close unneeded file descriptors */
1241 close(ipc_sockets
[1]);
1243 lxc_proc_close_ns_fd(init_ctx
);
1244 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
)
1245 lxc_attach_pty_close_slave(&pty
);
1247 /* Attach to cgroup, if requested. */
1248 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1249 if (!cgroup_attach(name
, lxcpath
, pid
))
1251 TRACE("Moved intermediate process %d into container's "
1255 /* Setup resource limits */
1256 if (!lxc_list_empty(&init_ctx
->container
->lxc_conf
->limits
)) {
1257 ret
= setup_resource_limits(&init_ctx
->container
->lxc_conf
->limits
, pid
);
1262 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1263 ret
= lxc_attach_pty_mainloop_init(&pty
, &descr
);
1266 TRACE("Initalized pty mainloop");
1269 /* Let the child process know to go ahead. */
1271 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1272 if (ret
!= sizeof(status
))
1273 goto close_mainloop
;
1274 TRACE("Told intermediate process to start initializing");
1276 /* Get pid of attached process from intermediate process. */
1277 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1278 if (ret
!= sizeof(attached_pid
))
1279 goto close_mainloop
;
1280 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1282 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1283 if (options
->stdin_fd
== 0) {
1284 signal(SIGINT
, SIG_IGN
);
1285 signal(SIGQUIT
, SIG_IGN
);
1288 /* Reap intermediate process. */
1289 ret
= wait_for_pid(pid
);
1291 goto close_mainloop
;
1292 TRACE("Intermediate process %d exited", pid
);
1294 /* We will always have to reap the attached process now. */
1295 to_cleanup_pid
= attached_pid
;
1297 /* Open LSM fd and send it to child. */
1298 if ((options
->namespaces
& CLONE_NEWNS
) &&
1299 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1300 init_ctx
->lsm_label
) {
1305 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1306 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1308 goto close_mainloop
;
1309 TRACE("Opened LSM label file descriptor %d", labelfd
);
1311 /* Send child fd of the LSM security module to write to. */
1312 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1315 SYSERROR("%d", (int)ret
);
1316 goto close_mainloop
;
1318 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1321 /* We're done, the child process should now execute whatever it
1322 * is that the user requested. The parent can now track it with
1323 * waitpid() or similar.
1326 *attached_process
= attached_pid
;
1328 /* Now shut down communication with child, we're done. */
1329 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1330 close(ipc_sockets
[0]);
1331 ipc_sockets
[0] = -1;
1334 to_cleanup_pid
= -1;
1335 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1336 ret
= lxc_mainloop(&descr
, -1);
1339 to_cleanup_pid
= attached_pid
;
1344 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
)
1345 lxc_mainloop_close(&descr
);
1348 if (ipc_sockets
[0] >= 0) {
1349 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1350 close(ipc_sockets
[0]);
1353 if (to_cleanup_pid
> 0)
1354 (void)wait_for_pid(to_cleanup_pid
);
1356 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1357 lxc_console_delete(&pty
);
1358 lxc_pty_conf_free(&pty
);
1360 lxc_proc_put_context_info(init_ctx
);
1364 /* close unneeded file descriptors */
1365 close(ipc_sockets
[0]);
1366 ipc_sockets
[0] = -EBADF
;
1367 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1368 lxc_attach_pty_close_master(&pty
);
1369 lxc_attach_pty_close_peer(&pty
);
1370 lxc_attach_pty_close_log(&pty
);
1373 /* Wait for the parent to have setup cgroups. */
1374 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1375 if (ret
!= sizeof(status
)) {
1376 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1377 lxc_proc_put_context_info(init_ctx
);
1380 TRACE("Intermediate process starting to initialize");
1382 /* Attach now, create another subprocess later, since pid namespaces
1383 * only really affect the children of the current process.
1385 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1387 ERROR("Failed to enter namespaces");
1388 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1389 lxc_proc_put_context_info(init_ctx
);
1392 /* close namespace file descriptors */
1393 lxc_proc_close_ns_fd(init_ctx
);
1395 /* Attach succeeded, try to cwd. */
1396 if (options
->initial_cwd
)
1397 new_cwd
= options
->initial_cwd
;
1401 ret
= chdir(new_cwd
);
1403 WARN("Could not change directory to \"%s\"", new_cwd
);
1407 /* Create attached process. */
1408 payload
.ipc_socket
= ipc_sockets
[1];
1409 payload
.options
= options
;
1410 payload
.init_ctx
= init_ctx
;
1411 payload
.pty_fd
= pty
.slave
;
1412 payload
.exec_function
= exec_function
;
1413 payload
.exec_payload
= exec_payload
;
1415 pid
= lxc_raw_clone(CLONE_PARENT
);
1417 SYSERROR("Failed to clone attached process");
1418 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1419 lxc_proc_put_context_info(init_ctx
);
1424 ret
= attach_child_main(&payload
);
1426 ERROR("Failed to exec");
1427 _exit(EXIT_FAILURE
);
1429 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
)
1430 lxc_attach_pty_close_slave(&pty
);
1432 /* Tell grandparent the pid of the pid of the newly created child. */
1433 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1434 if (ret
!= sizeof(pid
)) {
1435 /* If this really happens here, this is very unfortunate, since
1436 * the parent will not know the pid of the attached process and
1437 * will not be able to wait for it (and we won't either due to
1438 * CLONE_PARENT) so the parent won't be able to reap it and the
1439 * attached process will remain a zombie.
1441 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1442 lxc_proc_put_context_info(init_ctx
);
1445 TRACE("Sending pid %d of attached process", pid
);
1447 /* The rest is in the hands of the initial and the attached process. */
1448 lxc_proc_put_context_info(init_ctx
);
1452 int lxc_attach_run_command(void* payload
)
1454 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1456 execvp(cmd
->program
, cmd
->argv
);
1457 SYSERROR("Failed to exec \"%s\".", cmd
->program
);
1461 int lxc_attach_run_shell(void* payload
)
1464 struct passwd
*passwd
;
1467 /* Ignore payload parameter. */
1471 passwd
= getpwuid(uid
);
1473 /* This probably happens because of incompatible nss implementations in
1474 * host and container (remember, this code is still using the host's
1475 * glibc but our mount namespace is in the container) we may try to get
1476 * the information by spawning a [getent passwd uid] process and parsing
1480 user_shell
= lxc_attach_getpwshell(uid
);
1482 user_shell
= passwd
->pw_shell
;
1484 execlp(user_shell
, user_shell
, (char *)NULL
);
1486 /* Executed if either no passwd entry or execvp fails, we will fall back
1487 * on /bin/sh as a default shell.
1489 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1490 SYSERROR("Failed to execute shell");