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
30 #include <linux/unistd.h>
37 #include <sys/mount.h>
38 #include <sys/param.h>
39 #include <sys/prctl.h>
40 #include <sys/socket.h>
41 #include <sys/syscall.h>
46 #include <lxc/lxccontainer.h>
59 #include "lxcseccomp.h"
62 #include "memory_utils.h"
63 #include "namespace.h"
64 #include "raw_syscalls.h"
65 #include "syscall_wrappers.h"
69 #if HAVE_SYS_PERSONALITY_H
70 #include <sys/personality.h>
73 lxc_log_define(attach
, lxc
);
75 /* Define default options if no options are supplied by the user. */
76 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
78 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
80 __do_free
char *line
= NULL
;
81 __do_fclose
FILE *proc_file
= NULL
;
84 char proc_fn
[LXC_PROC_STATUS_LEN
];
85 struct lxc_proc_context_info
*info
;
86 size_t line_bufsz
= 0;
88 /* Read capabilities. */
89 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", pid
);
90 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
93 proc_file
= fopen(proc_fn
, "r");
95 SYSERROR("Failed to open %s", proc_fn
);
99 info
= calloc(1, sizeof(*info
));
105 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
106 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
107 if (ret
!= EOF
&& ret
== 1) {
114 ERROR("Could not read capability bounding set from %s", proc_fn
);
119 info
->lsm_label
= lsm_process_label_get(pid
);
120 info
->ns_inherited
= 0;
121 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
126 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
128 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
129 __do_close_prot_errno
int fd ATTR_UNUSED
= move_fd(ctx
->ns_fd
[i
]);
133 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
135 free(ctx
->lsm_label
);
136 ctx
->lsm_label
= NULL
;
138 if (ctx
->container
) {
139 lxc_container_put(ctx
->container
);
140 ctx
->container
= NULL
;
143 lxc_proc_close_ns_fd(ctx
);
148 * in_same_namespace - Check whether two processes are in the same namespace.
149 * @pid1 - PID of the first process.
150 * @pid2 - PID of the second process.
151 * @ns - Name of the namespace to check. Must correspond to one of the names
152 * for the namespaces as shown in /proc/<pid/ns/
154 * If the two processes are not in the same namespace returns an fd to the
155 * namespace of the second process identified by @pid2. If the two processes are
156 * in the same namespace returns -EINVAL, -1 if an error occurred.
158 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
160 __do_close_prot_errno
int ns_fd1
= -1, ns_fd2
= -1;
162 struct stat ns_st1
, ns_st2
;
164 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
166 /* The kernel does not support this namespace. This is not an
175 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
179 ret
= fstat(ns_fd1
, &ns_st1
);
183 ret
= fstat(ns_fd2
, &ns_st2
);
187 /* processes are in the same namespace */
188 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
191 /* processes are in different namespaces */
192 return move_fd(ns_fd2
);
195 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
199 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
200 if (ctx
->ns_fd
[i
] < 0)
203 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
205 SYSERROR("Failed to attach to %s namespace of %d",
206 ns_info
[i
].proc_name
, pid
);
210 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
216 int lxc_attach_remount_sys_proc(void)
220 ret
= unshare(CLONE_NEWNS
);
222 SYSERROR("Failed to unshare mount namespace");
226 if (detect_shared_rootfs()) {
227 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
228 SYSERROR("Failed to make / rslave");
229 ERROR("Continuing...");
233 /* Assume /proc is always mounted, so remount it. */
234 ret
= umount2("/proc", MNT_DETACH
);
236 SYSERROR("Failed to unmount /proc");
240 ret
= mount("none", "/proc", "proc", 0, NULL
);
242 SYSERROR("Failed to remount /proc");
246 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
247 * we ignore it because it may not have been mounted in the first place.
249 ret
= umount2("/sys", MNT_DETACH
);
250 if (ret
< 0 && errno
!= EINVAL
) {
251 SYSERROR("Failed to unmount /sys");
253 } else if (ret
== 0) {
255 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
257 SYSERROR("Failed to remount /sys");
265 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
269 last_cap
= lxc_caps_last_cap();
270 for (cap
= 0; cap
<= last_cap
; cap
++) {
271 if (ctx
->capability_mask
& (1LL << cap
))
274 if (prctl(PR_CAPBSET_DROP
, prctl_arg(cap
), prctl_arg(0),
275 prctl_arg(0), prctl_arg(0))) {
276 SYSERROR("Failed to drop capability %d", cap
);
280 TRACE("Dropped capability %d", cap
);
286 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
287 enum lxc_attach_env_policy_t policy
,
288 char **extra_env
, char **extra_keep
)
291 struct lxc_list
*iterator
;
293 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
295 char **extra_keep_store
= NULL
;
300 for (count
= 0; extra_keep
[count
]; count
++)
303 extra_keep_store
= calloc(count
, sizeof(char *));
304 if (!extra_keep_store
)
307 for (i
= 0; i
< count
; i
++) {
308 char *v
= getenv(extra_keep
[i
]);
310 extra_keep_store
[i
] = strdup(v
);
311 if (!extra_keep_store
[i
]) {
313 free(extra_keep_store
[--i
]);
315 free(extra_keep_store
);
319 if (strcmp(extra_keep
[i
], "PATH") == 0)
326 if (extra_keep_store
) {
329 for (p
= extra_keep_store
; *p
; p
++)
332 free(extra_keep_store
);
335 ERROR("Failed to clear environment");
339 if (extra_keep_store
) {
342 for (i
= 0; extra_keep
[i
]; i
++) {
343 if (extra_keep_store
[i
]) {
344 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
346 SYSWARN("Failed to set environment variable");
349 free(extra_keep_store
[i
]);
352 free(extra_keep_store
);
355 /* Always set a default path; shells and execlp tend to be fine
356 * without it, but there is a disturbing number of C programs
357 * out there that just assume that getenv("PATH") is never NULL
358 * and then die a painful segfault death.
361 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
363 SYSWARN("Failed to set environment variable");
367 ret
= putenv("container=lxc");
369 SYSWARN("Failed to set environment variable");
373 /* Set container environment variables.*/
374 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
375 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
378 env_tmp
= strdup((char *)iterator
->elem
);
382 ret
= putenv(env_tmp
);
384 SYSERROR("Failed to set environment variable: %s", (char *)iterator
->elem
);
390 /* Set extra environment variables. */
392 for (; *extra_env
; extra_env
++) {
395 /* We just assume the user knows what they are doing, so
396 * we don't do any checks.
398 p
= strdup(*extra_env
);
404 SYSWARN("Failed to set environment variable");
411 static char *lxc_attach_getpwshell(uid_t uid
)
413 __do_free
char *line
= NULL
;
414 __do_fclose
FILE *pipe_f
= NULL
;
419 size_t line_bufsz
= 0;
422 /* We need to fork off a process that runs the getent program, and we
423 * need to capture its output, so we use a pipe for that purpose.
425 ret
= pipe2(pipes
, O_CLOEXEC
);
438 char *arguments
[] = {
447 /* We want to capture stdout. */
448 ret
= dup2(pipes
[1], STDOUT_FILENO
);
453 /* Get rid of stdin/stderr, so we try to associate it with
459 close(STDERR_FILENO
);
461 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
462 (void)dup3(fd
, STDERR_FILENO
, O_CLOEXEC
);
466 /* Finish argument list. */
467 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
468 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
471 /* Try to run getent program. */
472 (void)execvp("getent", arguments
);
478 pipe_f
= fdopen(pipes
[0], "r");
479 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
483 char *endptr
= NULL
, *saveptr
= NULL
;
485 /* If we already found something, just continue to read
486 * until the pipe doesn't deliver any more data, but
487 * don't modify the existing data structure.
495 /* Trim line on the right hand side. */
496 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
499 /* Split into tokens: first: user name. */
500 token
= strtok_r(line
, ":", &saveptr
);
504 /* next: dummy password field */
505 token
= strtok_r(NULL
, ":", &saveptr
);
510 token
= strtok_r(NULL
, ":", &saveptr
);
511 value
= token
? strtol(token
, &endptr
, 10) : 0;
512 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
516 /* dummy sanity check: user id matches */
517 if ((uid_t
)value
!= uid
)
520 /* skip fields: gid, gecos, dir, go to next field 'shell' */
521 for (i
= 0; i
< 4; i
++) {
522 token
= strtok_r(NULL
, ":", &saveptr
);
531 result
= strdup(token
);
533 /* Sanity check that there are no fields after that. */
534 token
= strtok_r(NULL
, ":", &saveptr
);
541 ret
= wait_for_pid(pid
);
555 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
557 __do_free
char *line
= NULL
;
558 __do_fclose
FILE *proc_file
= NULL
;
559 char proc_fn
[LXC_PROC_STATUS_LEN
];
561 size_t line_bufsz
= 0;
563 uid_t uid
= (uid_t
)-1;
564 gid_t gid
= (gid_t
)-1;
566 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", 1);
567 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
570 proc_file
= fopen(proc_fn
, "r");
574 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
575 /* Format is: real, effective, saved set user, fs we only care
578 ret
= sscanf(line
, "Uid: %ld", &value
);
579 if (ret
!= EOF
&& ret
== 1) {
582 ret
= sscanf(line
, "Gid: %ld", &value
);
583 if (ret
!= EOF
&& ret
== 1)
587 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
591 /* Only override arguments if we found something. */
592 if (uid
!= (uid_t
)-1)
595 if (gid
!= (gid_t
)-1)
598 /* TODO: we should also parse supplementary groups and use
599 * setgroups() to set them.
603 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
605 __do_free
char *path
= NULL
;
609 if (!(options
->namespaces
& CLONE_NEWNS
) ||
610 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
611 free(c
->lxc_conf
->seccomp
.seccomp
);
612 c
->lxc_conf
->seccomp
.seccomp
= NULL
;
616 /* Remove current setting. */
617 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
618 !c
->set_config_item(c
, "lxc.seccomp", ""))
621 /* Fetch the current profile path over the cmd interface. */
622 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
624 INFO("Failed to retrieve lxc.seccomp.profile");
626 path
= c
->get_running_config_item(c
, "lxc.seccomp");
628 INFO("Failed to retrieve lxc.seccomp");
633 /* Copy the value into the new lxc_conf. */
634 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
638 /* Attempt to parse the resulting config. */
639 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
641 ERROR("Failed to retrieve seccomp policy");
645 INFO("Retrieved seccomp policy");
649 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
651 __do_free
char *val
= NULL
;
653 /* Remove current setting. */
654 if (!c
->set_config_item(c
, "lxc.no_new_privs", "")) {
655 INFO("Failed to unset lxc.no_new_privs");
659 /* Retrieve currently active setting. */
660 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
662 INFO("Failed to retrieve lxc.no_new_privs");
666 /* Set currently active setting. */
667 return c
->set_config_item(c
, "lxc.no_new_privs", val
);
670 static signed long get_personality(const char *name
, const char *lxcpath
)
672 __do_free
char *p
= NULL
;
674 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
678 return lxc_config_parse_arch(p
);
681 struct attach_clone_payload
{
683 int terminal_slave_fd
;
684 lxc_attach_options_t
*options
;
685 struct lxc_proc_context_info
*init_ctx
;
686 lxc_attach_exec_t exec_function
;
690 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
692 __do_close_prot_errno
int ipc_socket ATTR_UNUSED
= p
->ipc_socket
;
693 __do_close_prot_errno
int terminal_slave_fd ATTR_UNUSED
= p
->terminal_slave_fd
;
696 lxc_proc_put_context_info(p
->init_ctx
);
701 static int attach_child_main(struct attach_clone_payload
*payload
)
706 uid_t ns_root_uid
= 0;
707 gid_t ns_root_gid
= 0;
708 lxc_attach_options_t
* options
= payload
->options
;
709 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
710 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
711 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
714 /* A description of the purpose of this functionality is provided in the
715 * lxc-attach(1) manual page. We have to remount here and not in the
716 * parent process, otherwise /proc may not properly reflect the new pid
719 if (!(options
->namespaces
& CLONE_NEWNS
) &&
720 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
721 ret
= lxc_attach_remount_sys_proc();
725 TRACE("Remounted \"/proc\" and \"/sys\"");
728 /* Now perform additional attachments. */
729 #if HAVE_SYS_PERSONALITY_H
730 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
731 long new_personality
;
733 if (options
->personality
< 0)
734 new_personality
= init_ctx
->personality
;
736 new_personality
= options
->personality
;
738 ret
= personality(new_personality
);
742 TRACE("Set new personality");
746 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
747 ret
= lxc_attach_drop_privs(init_ctx
);
751 TRACE("Dropped capabilities");
754 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
755 * if you want this to be a no-op).
757 ret
= lxc_attach_set_environment(init_ctx
,
759 options
->extra_env_vars
,
760 options
->extra_keep_env
);
764 TRACE("Set up environment");
766 /* This remark only affects fully unprivileged containers:
767 * Receive fd for LSM security module before we set{g,u}id(). The reason
768 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
769 * we will change our effective uid. This means our effective uid will
770 * be different from the effective uid of the process that created us
771 * which means that this processs no longer has capabilities in our
772 * namespace including CAP_SYS_PTRACE. This means we will not be able to
773 * read and /proc/<pid> files for the process anymore when /proc is
774 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
778 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
781 SYSERROR("Failed to receive lsm label fd");
786 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
789 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
790 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
795 if (options
->namespaces
& CLONE_NEWUSER
) {
796 /* Check whether nsuid 0 has a mapping. */
797 ns_root_uid
= get_ns_uid(0);
799 /* Check whether nsgid 0 has a mapping. */
800 ns_root_gid
= get_ns_gid(0);
802 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
803 * init was started with.
805 if (ns_root_uid
== LXC_INVALID_UID
)
806 lxc_attach_get_init_uidgid(&ns_root_uid
, &ns_root_gid
);
808 if (ns_root_uid
== LXC_INVALID_UID
)
811 if (!lxc_switch_uid_gid(ns_root_uid
, ns_root_gid
))
815 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
819 if (options
->uid
!= LXC_INVALID_UID
)
820 new_uid
= options
->uid
;
822 new_uid
= ns_root_uid
;
824 if (options
->gid
!= LXC_INVALID_GID
)
825 new_gid
= options
->gid
;
827 new_gid
= ns_root_gid
;
829 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
830 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
831 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
832 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
833 prctl_arg(0), prctl_arg(0));
837 TRACE("Set PR_SET_NO_NEW_PRIVS");
843 /* Change into our new LSM profile. */
844 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
846 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
851 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
854 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
855 init_ctx
->container
->lxc_conf
->seccomp
.seccomp
) {
856 struct lxc_conf
*conf
= init_ctx
->container
->lxc_conf
;
858 ret
= lxc_seccomp_load(conf
);
862 TRACE("Loaded seccomp profile");
864 ret
= lxc_seccomp_send_notifier_fd(&conf
->seccomp
, payload
->ipc_socket
);
869 close(payload
->ipc_socket
);
870 payload
->ipc_socket
= -EBADF
;
871 lxc_proc_put_context_info(init_ctx
);
872 payload
->init_ctx
= NULL
;
874 /* The following is done after the communication socket is shut down.
875 * That way, all errors that might (though unlikely) occur up until this
876 * point will have their messages printed to the original stderr (if
877 * logging is so configured) and not the fd the user supplied, if any.
880 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
881 * may want to make sure the fds are closed, for example.
883 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
884 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
886 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
887 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
889 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
890 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
892 /* close the old fds */
893 if (options
->stdin_fd
> STDERR_FILENO
)
894 close(options
->stdin_fd
);
896 if (options
->stdout_fd
> STDERR_FILENO
)
897 close(options
->stdout_fd
);
899 if (options
->stderr_fd
> STDERR_FILENO
)
900 close(options
->stderr_fd
);
903 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
904 * here, ignore errors.
906 for (int fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
907 ret
= fd_cloexec(fd
, false);
909 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
914 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
915 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
917 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
921 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
924 /* Avoid unnecessary syscalls. */
925 if (new_uid
== ns_root_uid
)
926 new_uid
= LXC_INVALID_UID
;
928 if (new_gid
== ns_root_gid
)
929 new_gid
= LXC_INVALID_GID
;
931 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
934 /* We're done, so we can now do whatever the user intended us to do. */
935 _exit(payload
->exec_function(payload
->exec_payload
));
938 lxc_put_attach_clone_payload(payload
);
942 static int lxc_attach_terminal(struct lxc_conf
*conf
,
943 struct lxc_terminal
*terminal
)
947 lxc_terminal_init(terminal
);
949 ret
= lxc_terminal_create(terminal
);
951 ERROR("Failed to create terminal");
955 /* Shift ttys to container. */
956 ret
= lxc_terminal_map_ids(conf
, terminal
);
958 ERROR("Failed to chown terminal");
965 lxc_terminal_delete(terminal
);
966 lxc_terminal_conf_free(terminal
);
970 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
971 struct lxc_epoll_descr
*descr
)
975 ret
= lxc_mainloop_open(descr
);
977 ERROR("Failed to create mainloop");
981 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
983 ERROR("Failed to add handlers to mainloop");
984 lxc_mainloop_close(descr
);
991 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
993 close_prot_errno_disarm(terminal
->master
);
996 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
998 close_prot_errno_disarm(terminal
->slave
);
1001 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
1003 close_prot_errno_disarm(terminal
->peer
);
1006 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1008 close_prot_errno_disarm(terminal
->log_fd
);
1011 int lxc_attach(struct lxc_container
*container
, lxc_attach_exec_t exec_function
,
1012 void *exec_payload
, lxc_attach_options_t
*options
,
1013 pid_t
*attached_process
)
1017 char *cwd
, *new_cwd
;
1018 signed long personality
;
1019 pid_t attached_pid
, init_pid
, pid
;
1020 struct lxc_proc_context_info
*init_ctx
;
1021 struct lxc_terminal terminal
;
1022 struct lxc_conf
*conf
;
1023 char *name
, *lxcpath
;
1024 struct attach_clone_payload payload
= {0};
1026 ret
= access("/proc/self/ns", X_OK
);
1028 SYSERROR("Does this kernel version support namespaces?");
1033 return minus_one_set_errno(EINVAL
);
1035 if (!lxc_container_get(container
))
1036 return minus_one_set_errno(EINVAL
);
1038 name
= container
->name
;
1039 lxcpath
= container
->config_path
;
1042 options
= &attach_static_default_options
;
1044 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1046 ERROR("Failed to get init pid");
1047 lxc_container_put(container
);
1051 init_ctx
= lxc_proc_get_context_info(init_pid
);
1053 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1054 lxc_container_put(container
);
1058 init_ctx
->container
= container
;
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 if (!init_ctx
->container
->lxc_conf
) {
1069 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1070 if (!init_ctx
->container
->lxc_conf
) {
1071 lxc_proc_put_context_info(init_ctx
);
1075 conf
= init_ctx
->container
->lxc_conf
;
1077 if (!fetch_seccomp(init_ctx
->container
, options
))
1078 WARN("Failed to get seccomp policy");
1080 if (!no_new_privs(init_ctx
->container
, options
))
1081 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1083 cwd
= getcwd(NULL
, 0);
1085 /* Determine which namespaces the container was created with
1086 * by asking lxc-start, if necessary.
1088 if (options
->namespaces
== -1) {
1089 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1091 if (options
->namespaces
== -1) {
1092 ERROR("Failed to automatically determine the "
1093 "namespaces which the container uses");
1095 lxc_proc_put_context_info(init_ctx
);
1099 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1100 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1101 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1105 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1108 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1112 pid
= lxc_raw_getpid();
1114 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1117 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1118 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1119 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1120 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1124 if (init_ctx
->ns_fd
[i
] >= 0)
1127 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1128 DEBUG("Inheriting %s namespace from %d",
1129 ns_info
[i
].proc_name
, pid
);
1130 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1134 /* We failed to preserve the namespace. */
1135 SYSERROR("Failed to attach to %s namespace of %d",
1136 ns_info
[i
].proc_name
, pid
);
1138 /* Close all already opened file descriptors before we return an
1139 * error, so we don't leak them.
1141 for (j
= 0; j
< i
; j
++)
1142 close(init_ctx
->ns_fd
[j
]);
1145 lxc_proc_put_context_info(init_ctx
);
1149 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1150 ret
= lxc_attach_terminal(conf
, &terminal
);
1152 ERROR("Failed to setup new terminal");
1154 lxc_proc_put_context_info(init_ctx
);
1158 terminal
.log_fd
= options
->log_fd
;
1160 lxc_terminal_init(&terminal
);
1163 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1164 * to make sure we don't irritate other threads that want to fork+exec
1167 * IMPORTANT: if the initial process is multithreaded and another call
1168 * just fork()s away without exec'ing directly after, the socket fd will
1169 * exist in the forked process from the other thread and any close() in
1170 * our own child process will not really cause the socket to close
1171 * properly, potentially causing the parent to hang.
1173 * For this reason, while IPC is still active, we have to use shutdown()
1174 * if the child exits prematurely in order to signal that the socket is
1175 * closed and cannot assume that the child exiting will automatically do
1178 * IPC mechanism: (X is receiver)
1179 * initial process intermediate attached
1180 * X <--- send pid of
1183 * send 0 ------------------------------------> X
1184 * [do initialization]
1185 * X <------------------------------------ send 1
1186 * [add to cgroup, ...]
1187 * send 2 ------------------------------------> X
1188 * [set LXC_ATTACH_NO_NEW_PRIVS]
1189 * X <------------------------------------ send 3
1190 * [open LSM label fd]
1191 * send 4 ------------------------------------> X
1193 * close socket close socket
1196 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1198 SYSERROR("Could not set up required IPC mechanism for attaching");
1200 lxc_proc_put_context_info(init_ctx
);
1204 /* Create intermediate subprocess, two reasons:
1205 * 1. We can't setns() in the child itself, since we want to make
1206 * sure we are properly attached to the pidns.
1207 * 2. Also, the initial thread has to put the attached process
1208 * into the cgroup, which we can only do if we didn't already
1209 * setns() (otherwise, user namespaces will hate us).
1213 SYSERROR("Failed to create first subprocess");
1215 lxc_proc_put_context_info(init_ctx
);
1220 int ret_parent
= -1;
1221 pid_t to_cleanup_pid
= pid
;
1222 struct lxc_epoll_descr descr
= {0};
1224 /* close unneeded file descriptors */
1225 close(ipc_sockets
[1]);
1227 lxc_proc_close_ns_fd(init_ctx
);
1228 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1229 lxc_attach_terminal_close_slave(&terminal
);
1231 /* Attach to cgroup, if requested. */
1232 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1234 * If this is the unified hierarchy cgroup_attach() is
1237 ret
= cgroup_attach(name
, lxcpath
, pid
);
1239 __do_cgroup_exit
struct cgroup_ops
*cgroup_ops
= NULL
;
1241 cgroup_ops
= cgroup_init(conf
);
1245 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1248 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1251 /* Setup /proc limits */
1252 if (!lxc_list_empty(&conf
->procs
)) {
1253 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1258 /* Setup resource limits */
1259 if (!lxc_list_empty(&conf
->limits
)) {
1260 ret
= setup_resource_limits(&conf
->limits
, pid
);
1265 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1266 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1270 TRACE("Initialized terminal mainloop");
1273 /* Let the child process know to go ahead. */
1275 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1276 if (ret
!= sizeof(status
))
1277 goto close_mainloop
;
1279 TRACE("Told intermediate process to start initializing");
1281 /* Get pid of attached process from intermediate process. */
1282 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1283 if (ret
!= sizeof(attached_pid
))
1284 goto close_mainloop
;
1286 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1288 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1289 if (options
->stdin_fd
== 0) {
1290 signal(SIGINT
, SIG_IGN
);
1291 signal(SIGQUIT
, SIG_IGN
);
1294 /* Reap intermediate process. */
1295 ret
= wait_for_pid(pid
);
1297 goto close_mainloop
;
1299 TRACE("Intermediate process %d exited", pid
);
1301 /* We will always have to reap the attached process now. */
1302 to_cleanup_pid
= attached_pid
;
1304 /* Open LSM fd and send it to child. */
1305 if ((options
->namespaces
& CLONE_NEWNS
) &&
1306 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1307 init_ctx
->lsm_label
) {
1312 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1313 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1315 goto close_mainloop
;
1317 TRACE("Opened LSM label file descriptor %d", labelfd
);
1319 /* Send child fd of the LSM security module to write to. */
1320 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1323 SYSERROR("Failed to send lsm label fd");
1326 goto close_mainloop
;
1330 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1333 if (conf
&& conf
->seccomp
.seccomp
) {
1334 ret
= lxc_seccomp_recv_notifier_fd(&conf
->seccomp
, ipc_sockets
[0]);
1336 goto close_mainloop
;
1338 ret
= lxc_seccomp_add_notifier(name
, lxcpath
, &conf
->seccomp
);
1340 goto close_mainloop
;
1343 /* We're done, the child process should now execute whatever it
1344 * is that the user requested. The parent can now track it with
1345 * waitpid() or similar.
1348 *attached_process
= attached_pid
;
1350 /* Now shut down communication with child, we're done. */
1351 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1352 close(ipc_sockets
[0]);
1353 ipc_sockets
[0] = -1;
1356 to_cleanup_pid
= -1;
1358 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1359 ret
= lxc_mainloop(&descr
, -1);
1362 to_cleanup_pid
= attached_pid
;
1367 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1368 lxc_mainloop_close(&descr
);
1371 if (ipc_sockets
[0] >= 0) {
1372 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1373 close(ipc_sockets
[0]);
1376 if (to_cleanup_pid
> 0)
1377 (void)wait_for_pid(to_cleanup_pid
);
1379 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1380 lxc_terminal_delete(&terminal
);
1381 lxc_terminal_conf_free(&terminal
);
1384 lxc_proc_put_context_info(init_ctx
);
1388 /* close unneeded file descriptors */
1389 close(ipc_sockets
[0]);
1390 ipc_sockets
[0] = -EBADF
;
1392 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1393 lxc_attach_terminal_close_master(&terminal
);
1394 lxc_attach_terminal_close_peer(&terminal
);
1395 lxc_attach_terminal_close_log(&terminal
);
1398 /* Wait for the parent to have setup cgroups. */
1399 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1400 if (ret
!= sizeof(status
)) {
1401 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1402 lxc_proc_put_context_info(init_ctx
);
1403 _exit(EXIT_FAILURE
);
1406 TRACE("Intermediate process starting to initialize");
1408 /* Attach now, create another subprocess later, since pid namespaces
1409 * only really affect the children of the current process.
1411 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1413 ERROR("Failed to enter namespaces");
1414 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1415 lxc_proc_put_context_info(init_ctx
);
1416 _exit(EXIT_FAILURE
);
1419 /* close namespace file descriptors */
1420 lxc_proc_close_ns_fd(init_ctx
);
1422 /* Attach succeeded, try to cwd. */
1423 if (options
->initial_cwd
)
1424 new_cwd
= options
->initial_cwd
;
1428 ret
= chdir(new_cwd
);
1430 WARN("Could not change directory to \"%s\"", new_cwd
);
1434 /* Create attached process. */
1435 payload
.ipc_socket
= ipc_sockets
[1];
1436 payload
.options
= options
;
1437 payload
.init_ctx
= init_ctx
;
1438 payload
.terminal_slave_fd
= terminal
.slave
;
1439 payload
.exec_function
= exec_function
;
1440 payload
.exec_payload
= exec_payload
;
1442 pid
= lxc_raw_clone(CLONE_PARENT
, NULL
);
1444 SYSERROR("Failed to clone attached process");
1445 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1446 lxc_proc_put_context_info(init_ctx
);
1447 _exit(EXIT_FAILURE
);
1451 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1452 ret
= pthread_sigmask(SIG_SETMASK
,
1453 &terminal
.tty_state
->oldmask
, NULL
);
1455 SYSERROR("Failed to reset signal mask");
1456 _exit(EXIT_FAILURE
);
1460 ret
= attach_child_main(&payload
);
1462 ERROR("Failed to exec");
1464 _exit(EXIT_FAILURE
);
1467 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1468 lxc_attach_terminal_close_slave(&terminal
);
1470 /* Tell grandparent the pid of the pid of the newly created child. */
1471 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1472 if (ret
!= sizeof(pid
)) {
1473 /* If this really happens here, this is very unfortunate, since
1474 * the parent will not know the pid of the attached process and
1475 * will not be able to wait for it (and we won't either due to
1476 * CLONE_PARENT) so the parent won't be able to reap it and the
1477 * attached process will remain a zombie.
1479 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1480 lxc_proc_put_context_info(init_ctx
);
1481 _exit(EXIT_FAILURE
);
1484 TRACE("Sending pid %d of attached process", pid
);
1486 /* The rest is in the hands of the initial and the attached process. */
1487 lxc_proc_put_context_info(init_ctx
);
1488 _exit(EXIT_SUCCESS
);
1491 int lxc_attach_run_command(void *payload
)
1494 lxc_attach_command_t
*cmd
= payload
;
1496 ret
= execvp(cmd
->program
, cmd
->argv
);
1508 SYSERROR("Failed to exec \"%s\"", cmd
->program
);
1512 int lxc_attach_run_shell(void* payload
)
1514 __do_free
char *buf
= NULL
;
1516 struct passwd pwent
;
1517 struct passwd
*pwentp
= NULL
;
1522 /* Ignore payload parameter. */
1527 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1531 buf
= malloc(bufsize
);
1533 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1536 WARN("Could not find matched password record");
1538 WARN("Failed to get password record - %u", uid
);
1542 /* This probably happens because of incompatible nss implementations in
1543 * host and container (remember, this code is still using the host's
1544 * glibc but our mount namespace is in the container) we may try to get
1545 * the information by spawning a [getent passwd uid] process and parsing
1549 user_shell
= lxc_attach_getpwshell(uid
);
1551 user_shell
= pwent
.pw_shell
;
1554 execlp(user_shell
, user_shell
, (char *)NULL
);
1556 /* Executed if either no passwd entry or execvp fails, we will fall back
1557 * on /bin/sh as a default shell.
1559 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1561 SYSERROR("Failed to execute shell");