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>
36 #include <sys/mount.h>
37 #include <sys/param.h>
38 #include <sys/prctl.h>
39 #include <sys/socket.h>
40 #include <sys/syscall.h>
45 #include <lxc/lxccontainer.h>
58 #include "lxcseccomp.h"
61 #include "namespace.h"
65 #if HAVE_SYS_PERSONALITY_H
66 #include <sys/personality.h>
69 lxc_log_define(attach
, lxc
);
71 /* Define default options if no options are supplied by the user. */
72 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
74 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
79 char proc_fn
[LXC_PROC_STATUS_LEN
];
80 size_t line_bufsz
= 0;
82 struct lxc_proc_context_info
*info
= NULL
;
84 /* Read capabilities. */
85 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", pid
);
86 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
89 proc_file
= fopen(proc_fn
, "r");
91 SYSERROR("Could not open %s", proc_fn
);
95 info
= calloc(1, sizeof(*info
));
97 SYSERROR("Could not allocate memory");
104 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
105 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
106 if (ret
!= EOF
&& ret
== 1) {
116 ERROR("Could not read capability bounding set from %s",
121 info
->lsm_label
= lsm_process_label_get(pid
);
122 info
->ns_inherited
= 0;
123 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
132 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
136 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
137 if (ctx
->ns_fd
[i
] < 0)
140 close(ctx
->ns_fd
[i
]);
141 ctx
->ns_fd
[i
] = -EBADF
;
145 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
147 free(ctx
->lsm_label
);
148 ctx
->lsm_label
= NULL
;
150 if (ctx
->container
) {
151 lxc_container_put(ctx
->container
);
152 ctx
->container
= NULL
;
155 lxc_proc_close_ns_fd(ctx
);
160 * in_same_namespace - Check whether two processes are in the same namespace.
161 * @pid1 - PID of the first process.
162 * @pid2 - PID of the second process.
163 * @ns - Name of the namespace to check. Must correspond to one of the names
164 * for the namespaces as shown in /proc/<pid/ns/
166 * If the two processes are not in the same namespace returns an fd to the
167 * namespace of the second process identified by @pid2. If the two processes are
168 * in the same namespace returns -EINVAL, -1 if an error occurred.
170 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
172 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
174 struct stat ns_st1
, ns_st2
;
176 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
178 /* The kernel does not support this namespace. This is not an
187 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
191 ret
= fstat(ns_fd1
, &ns_st1
);
195 ret
= fstat(ns_fd2
, &ns_st2
);
199 /* processes are in the same namespace */
200 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
)) {
205 /* processes are in different namespaces */
222 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
226 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
227 if (ctx
->ns_fd
[i
] < 0)
230 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
232 SYSERROR("Failed to attach to %s namespace of %d",
233 ns_info
[i
].proc_name
, pid
);
237 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
243 static int lxc_attach_remount_sys_proc(void)
247 ret
= unshare(CLONE_NEWNS
);
249 SYSERROR("Failed to unshare mount namespace");
253 if (detect_shared_rootfs()) {
254 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
255 SYSERROR("Failed to make / rslave");
256 ERROR("Continuing...");
260 /* Assume /proc is always mounted, so remount it. */
261 ret
= umount2("/proc", MNT_DETACH
);
263 SYSERROR("Failed to unmount /proc");
267 ret
= mount("none", "/proc", "proc", 0, NULL
);
269 SYSERROR("Failed to remount /proc");
273 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
274 * we ignore it because it may not have been mounted in the first place.
276 ret
= umount2("/sys", MNT_DETACH
);
277 if (ret
< 0 && errno
!= EINVAL
) {
278 SYSERROR("Failed to unmount /sys");
280 } else if (ret
== 0) {
282 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
284 SYSERROR("Failed to remount /sys");
292 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
296 last_cap
= lxc_caps_last_cap();
297 for (cap
= 0; cap
<= last_cap
; cap
++) {
298 if (ctx
->capability_mask
& (1LL << cap
))
301 if (prctl(PR_CAPBSET_DROP
, prctl_arg(cap
), prctl_arg(0),
302 prctl_arg(0), prctl_arg(0))) {
303 SYSERROR("Failed to drop capability %d", cap
);
307 TRACE("Dropped capability %d", cap
);
313 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
314 enum lxc_attach_env_policy_t policy
,
315 char **extra_env
, char **extra_keep
)
318 struct lxc_list
*iterator
;
320 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
322 char **extra_keep_store
= NULL
;
327 for (count
= 0; extra_keep
[count
]; count
++)
330 extra_keep_store
= calloc(count
, sizeof(char *));
331 if (!extra_keep_store
)
334 for (i
= 0; i
< count
; i
++) {
335 char *v
= getenv(extra_keep
[i
]);
337 extra_keep_store
[i
] = strdup(v
);
338 if (!extra_keep_store
[i
]) {
340 free(extra_keep_store
[--i
]);
342 free(extra_keep_store
);
346 if (strcmp(extra_keep
[i
], "PATH") == 0)
353 if (extra_keep_store
) {
356 for (p
= extra_keep_store
; *p
; p
++)
359 free(extra_keep_store
);
362 ERROR("Failed to clear environment");
366 if (extra_keep_store
) {
369 for (i
= 0; extra_keep
[i
]; i
++) {
370 if (extra_keep_store
[i
]) {
371 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
373 SYSWARN("Failed to set environment variable");
376 free(extra_keep_store
[i
]);
379 free(extra_keep_store
);
382 /* Always set a default path; shells and execlp tend to be fine
383 * without it, but there is a disturbing number of C programs
384 * out there that just assume that getenv("PATH") is never NULL
385 * and then die a painful segfault death.
388 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
390 SYSWARN("Failed to set environment variable");
394 ret
= putenv("container=lxc");
396 SYSWARN("Failed to set environment variable");
400 /* Set container environment variables.*/
401 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
402 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
405 env_tmp
= strdup((char *)iterator
->elem
);
409 ret
= putenv(env_tmp
);
411 SYSERROR("Failed to set environment variable: %s", (char *)iterator
->elem
);
417 /* Set extra environment variables. */
419 for (; *extra_env
; extra_env
++) {
422 /* We just assume the user knows what they are doing, so
423 * we don't do any checks.
425 p
= strdup(*extra_env
);
431 SYSWARN("Failed to set environment variable");
438 static char *lxc_attach_getpwshell(uid_t uid
)
445 size_t line_bufsz
= 0;
446 char *line
= NULL
, *result
= NULL
;
448 /* We need to fork off a process that runs the getent program, and we
449 * need to capture its output, so we use a pipe for that purpose.
451 ret
= pipe2(pipes
, O_CLOEXEC
);
464 char *arguments
[] = {
473 /* We want to capture stdout. */
474 ret
= dup2(pipes
[1], STDOUT_FILENO
);
479 /* Get rid of stdin/stderr, so we try to associate it with
485 close(STDERR_FILENO
);
487 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
488 (void)dup3(fd
, STDOUT_FILENO
, O_CLOEXEC
);
492 /* Finish argument list. */
493 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
494 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
497 /* Try to run getent program. */
498 (void)execvp("getent", arguments
);
504 pipe_f
= fdopen(pipes
[0], "r");
505 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
509 char *endptr
= NULL
, *saveptr
= NULL
;
511 /* If we already found something, just continue to read
512 * until the pipe doesn't deliver any more data, but
513 * don't modify the existing data structure.
521 /* Trim line on the right hand side. */
522 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
525 /* Split into tokens: first: user name. */
526 token
= strtok_r(line
, ":", &saveptr
);
530 /* next: dummy password field */
531 token
= strtok_r(NULL
, ":", &saveptr
);
536 token
= strtok_r(NULL
, ":", &saveptr
);
537 value
= token
? strtol(token
, &endptr
, 10) : 0;
538 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
542 /* dummy sanity check: user id matches */
543 if ((uid_t
)value
!= uid
)
546 /* skip fields: gid, gecos, dir, go to next field 'shell' */
547 for (i
= 0; i
< 4; i
++) {
548 token
= strtok_r(NULL
, ":", &saveptr
);
557 result
= strdup(token
);
559 /* Sanity check that there are no fields after that. */
560 token
= strtok_r(NULL
, ":", &saveptr
);
570 ret
= wait_for_pid(pid
);
584 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
587 char proc_fn
[LXC_PROC_STATUS_LEN
];
590 size_t line_bufsz
= 0;
592 uid_t uid
= (uid_t
)-1;
593 gid_t gid
= (gid_t
)-1;
595 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", 1);
596 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
599 proc_file
= fopen(proc_fn
, "r");
603 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
604 /* Format is: real, effective, saved set user, fs we only care
607 ret
= sscanf(line
, "Uid: %ld", &value
);
608 if (ret
!= EOF
&& ret
== 1) {
611 ret
= sscanf(line
, "Gid: %ld", &value
);
612 if (ret
!= EOF
&& ret
== 1)
616 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
623 /* Only override arguments if we found something. */
624 if (uid
!= (uid_t
)-1)
627 if (gid
!= (gid_t
)-1)
630 /* TODO: we should also parse supplementary groups and use
631 * setgroups() to set them.
635 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
641 if (!(options
->namespaces
& CLONE_NEWNS
) ||
642 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
643 free(c
->lxc_conf
->seccomp
);
644 c
->lxc_conf
->seccomp
= NULL
;
648 /* Remove current setting. */
649 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
650 !c
->set_config_item(c
, "lxc.seccomp", ""))
653 /* Fetch the current profile path over the cmd interface. */
654 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
656 INFO("Failed to retrieve lxc.seccomp.profile");
658 path
= c
->get_running_config_item(c
, "lxc.seccomp");
660 INFO("Failed to retrieve lxc.seccomp");
665 /* Copy the value into the new lxc_conf. */
666 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
671 /* Attempt to parse the resulting config. */
672 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
674 ERROR("Failed to retrieve seccomp policy");
678 INFO("Retrieved seccomp policy");
682 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", "")) {
689 INFO("Failed to unset lxc.no_new_privs");
693 /* Retrieve currently active setting. */
694 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
696 INFO("Failed to retrieve lxc.no_new_privs");
700 /* Set currently active setting. */
701 bret
= c
->set_config_item(c
, "lxc.no_new_privs", val
);
706 static signed long get_personality(const char *name
, const char *lxcpath
)
711 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
715 ret
= lxc_config_parse_arch(p
);
721 struct attach_clone_payload
{
723 int terminal_slave_fd
;
724 lxc_attach_options_t
*options
;
725 struct lxc_proc_context_info
*init_ctx
;
726 lxc_attach_exec_t exec_function
;
730 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
732 if (p
->ipc_socket
>= 0) {
733 close(p
->ipc_socket
);
734 p
->ipc_socket
= -EBADF
;
737 if (p
->terminal_slave_fd
>= 0) {
738 close(p
->terminal_slave_fd
);
739 p
->terminal_slave_fd
= -EBADF
;
743 lxc_proc_put_context_info(p
->init_ctx
);
748 static int attach_child_main(struct attach_clone_payload
*payload
)
753 uid_t ns_root_uid
= 0;
754 gid_t ns_root_gid
= 0;
755 lxc_attach_options_t
* options
= payload
->options
;
756 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
757 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
758 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
761 /* A description of the purpose of this functionality is provided in the
762 * lxc-attach(1) manual page. We have to remount here and not in the
763 * parent process, otherwise /proc may not properly reflect the new pid
766 if (!(options
->namespaces
& CLONE_NEWNS
) &&
767 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
768 ret
= lxc_attach_remount_sys_proc();
772 TRACE("Remounted \"/proc\" and \"/sys\"");
775 /* Now perform additional attachments. */
776 #if HAVE_SYS_PERSONALITY_H
777 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
778 long new_personality
;
780 if (options
->personality
< 0)
781 new_personality
= init_ctx
->personality
;
783 new_personality
= options
->personality
;
785 ret
= personality(new_personality
);
789 TRACE("Set new personality");
793 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
794 ret
= lxc_attach_drop_privs(init_ctx
);
798 TRACE("Dropped capabilities");
801 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
802 * if you want this to be a no-op).
804 ret
= lxc_attach_set_environment(init_ctx
,
806 options
->extra_env_vars
,
807 options
->extra_keep_env
);
811 TRACE("Set up environment");
813 /* This remark only affects fully unprivileged containers:
814 * Receive fd for LSM security module before we set{g,u}id(). The reason
815 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
816 * we will change our effective uid. This means our effective uid will
817 * be different from the effective uid of the process that created us
818 * which means that this processs no longer has capabilities in our
819 * namespace including CAP_SYS_PTRACE. This means we will not be able to
820 * read and /proc/<pid> files for the process anymore when /proc is
821 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
825 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
828 SYSERROR("Failed to receive lsm label fd");
833 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
836 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
837 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
842 if (options
->namespaces
& CLONE_NEWUSER
) {
843 /* Check whether nsuid 0 has a mapping. */
844 ns_root_uid
= get_ns_uid(0);
846 /* Check whether nsgid 0 has a mapping. */
847 ns_root_gid
= get_ns_gid(0);
849 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
850 * init was started with.
852 if (ns_root_uid
== LXC_INVALID_UID
)
853 lxc_attach_get_init_uidgid(&ns_root_uid
, &ns_root_gid
);
855 if (ns_root_uid
== LXC_INVALID_UID
)
858 if (!lxc_switch_uid_gid(ns_root_uid
, ns_root_gid
))
862 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
866 if (options
->uid
!= LXC_INVALID_UID
)
867 new_uid
= options
->uid
;
869 new_uid
= ns_root_uid
;
871 if (options
->gid
!= LXC_INVALID_GID
)
872 new_gid
= options
->gid
;
874 new_gid
= ns_root_gid
;
876 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
877 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
878 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
879 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
880 prctl_arg(0), prctl_arg(0));
884 TRACE("Set PR_SET_NO_NEW_PRIVS");
890 /* Change into our new LSM profile. */
891 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
893 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
898 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
901 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
902 init_ctx
->container
->lxc_conf
->seccomp
) {
903 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
907 TRACE("Loaded seccomp profile");
910 close(payload
->ipc_socket
);
911 payload
->ipc_socket
= -EBADF
;
912 lxc_proc_put_context_info(init_ctx
);
913 payload
->init_ctx
= NULL
;
915 /* The following is done after the communication socket is shut down.
916 * That way, all errors that might (though unlikely) occur up until this
917 * point will have their messages printed to the original stderr (if
918 * logging is so configured) and not the fd the user supplied, if any.
921 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
922 * may want to make sure the fds are closed, for example.
924 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
925 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
927 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
928 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
930 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
931 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
933 /* close the old fds */
934 if (options
->stdin_fd
> STDERR_FILENO
)
935 close(options
->stdin_fd
);
937 if (options
->stdout_fd
> STDERR_FILENO
)
938 close(options
->stdout_fd
);
940 if (options
->stderr_fd
> STDERR_FILENO
)
941 close(options
->stderr_fd
);
943 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
944 * here, ignore errors.
946 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
947 ret
= fd_cloexec(fd
, false);
949 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
954 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
955 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
957 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
961 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
964 /* Avoid unnecessary syscalls. */
965 if (new_uid
== ns_root_uid
)
966 new_uid
= LXC_INVALID_UID
;
968 if (new_gid
== ns_root_gid
)
969 new_gid
= LXC_INVALID_GID
;
971 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
974 /* We're done, so we can now do whatever the user intended us to do. */
975 _exit(payload
->exec_function(payload
->exec_payload
));
978 lxc_put_attach_clone_payload(payload
);
982 static int lxc_attach_terminal(struct lxc_conf
*conf
,
983 struct lxc_terminal
*terminal
)
987 lxc_terminal_init(terminal
);
989 ret
= lxc_terminal_create(terminal
);
991 ERROR("Failed to create terminal");
995 /* Shift ttys to container. */
996 ret
= lxc_terminal_map_ids(conf
, terminal
);
998 ERROR("Failed to chown terminal");
1005 lxc_terminal_delete(terminal
);
1006 lxc_terminal_conf_free(terminal
);
1010 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
1011 struct lxc_epoll_descr
*descr
)
1015 ret
= lxc_mainloop_open(descr
);
1017 ERROR("Failed to create mainloop");
1021 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
1023 ERROR("Failed to add handlers to mainloop");
1024 lxc_mainloop_close(descr
);
1031 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
1033 if (terminal
->master
< 0)
1036 close(terminal
->master
);
1037 terminal
->master
= -EBADF
;
1040 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
1042 if (terminal
->slave
< 0)
1045 close(terminal
->slave
);
1046 terminal
->slave
= -EBADF
;
1049 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
1051 if (terminal
->peer
< 0)
1054 close(terminal
->peer
);
1055 terminal
->peer
= -EBADF
;
1058 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1060 if (terminal
->log_fd
< 0)
1063 close(terminal
->log_fd
);
1064 terminal
->log_fd
= -EBADF
;
1067 int lxc_attach(const char *name
, const char *lxcpath
,
1068 lxc_attach_exec_t exec_function
, void *exec_payload
,
1069 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1073 char *cwd
, *new_cwd
;
1074 signed long personality
;
1075 pid_t attached_pid
, init_pid
, pid
;
1076 struct lxc_proc_context_info
*init_ctx
;
1077 struct lxc_terminal terminal
;
1078 struct lxc_conf
*conf
;
1079 struct attach_clone_payload payload
= {0};
1081 ret
= access("/proc/self/ns", X_OK
);
1083 SYSERROR("Does this kernel version support namespaces?");
1088 options
= &attach_static_default_options
;
1090 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1092 ERROR("Failed to get init pid");
1096 init_ctx
= lxc_proc_get_context_info(init_pid
);
1098 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1102 personality
= get_personality(name
, lxcpath
);
1103 if (init_ctx
->personality
< 0) {
1104 ERROR("Failed to get personality of the container");
1105 lxc_proc_put_context_info(init_ctx
);
1108 init_ctx
->personality
= personality
;
1110 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1111 if (!init_ctx
->container
) {
1112 lxc_proc_put_context_info(init_ctx
);
1116 if (!init_ctx
->container
->lxc_conf
) {
1117 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1118 if (!init_ctx
->container
->lxc_conf
) {
1119 lxc_proc_put_context_info(init_ctx
);
1123 conf
= init_ctx
->container
->lxc_conf
;
1125 if (!fetch_seccomp(init_ctx
->container
, options
))
1126 WARN("Failed to get seccomp policy");
1128 if (!no_new_privs(init_ctx
->container
, options
))
1129 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1131 cwd
= getcwd(NULL
, 0);
1133 /* Determine which namespaces the container was created with
1134 * by asking lxc-start, if necessary.
1136 if (options
->namespaces
== -1) {
1137 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1139 if (options
->namespaces
== -1) {
1140 ERROR("Failed to automatically determine the "
1141 "namespaces which the container uses");
1143 lxc_proc_put_context_info(init_ctx
);
1147 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1148 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1149 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1153 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1156 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1160 pid
= lxc_raw_getpid();
1162 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1165 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1166 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1167 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1168 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1172 if (init_ctx
->ns_fd
[i
] >= 0)
1175 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1176 DEBUG("Inheriting %s namespace from %d",
1177 ns_info
[i
].proc_name
, pid
);
1178 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1182 /* We failed to preserve the namespace. */
1183 SYSERROR("Failed to attach to %s namespace of %d",
1184 ns_info
[i
].proc_name
, pid
);
1186 /* Close all already opened file descriptors before we return an
1187 * error, so we don't leak them.
1189 for (j
= 0; j
< i
; j
++)
1190 close(init_ctx
->ns_fd
[j
]);
1193 lxc_proc_put_context_info(init_ctx
);
1197 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1198 ret
= lxc_attach_terminal(conf
, &terminal
);
1200 ERROR("Failed to setup new terminal");
1202 lxc_proc_put_context_info(init_ctx
);
1206 terminal
.log_fd
= options
->log_fd
;
1208 lxc_terminal_init(&terminal
);
1211 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1212 * to make sure we don't irritate other threads that want to fork+exec
1215 * IMPORTANT: if the initial process is multithreaded and another call
1216 * just fork()s away without exec'ing directly after, the socket fd will
1217 * exist in the forked process from the other thread and any close() in
1218 * our own child process will not really cause the socket to close
1219 * properly, potentiall causing the parent to hang.
1221 * For this reason, while IPC is still active, we have to use shutdown()
1222 * if the child exits prematurely in order to signal that the socket is
1223 * closed and cannot assume that the child exiting will automatically do
1226 * IPC mechanism: (X is receiver)
1227 * initial process intermediate attached
1228 * X <--- send pid of
1231 * send 0 ------------------------------------> X
1232 * [do initialization]
1233 * X <------------------------------------ send 1
1234 * [add to cgroup, ...]
1235 * send 2 ------------------------------------> X
1236 * [set LXC_ATTACH_NO_NEW_PRIVS]
1237 * X <------------------------------------ send 3
1238 * [open LSM label fd]
1239 * send 4 ------------------------------------> X
1241 * close socket close socket
1244 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1246 SYSERROR("Could not set up required IPC mechanism for attaching");
1248 lxc_proc_put_context_info(init_ctx
);
1252 /* Create intermediate subprocess, two reasons:
1253 * 1. We can't setns() in the child itself, since we want to make
1254 * sure we are properly attached to the pidns.
1255 * 2. Also, the initial thread has to put the attached process
1256 * into the cgroup, which we can only do if we didn't already
1257 * setns() (otherwise, user namespaces will hate us).
1261 SYSERROR("Failed to create first subprocess");
1263 lxc_proc_put_context_info(init_ctx
);
1268 int ret_parent
= -1;
1269 pid_t to_cleanup_pid
= pid
;
1270 struct lxc_epoll_descr descr
= {0};
1272 /* close unneeded file descriptors */
1273 close(ipc_sockets
[1]);
1275 lxc_proc_close_ns_fd(init_ctx
);
1276 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1277 lxc_attach_terminal_close_slave(&terminal
);
1279 /* Attach to cgroup, if requested. */
1280 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1281 struct cgroup_ops
*cgroup_ops
;
1283 cgroup_ops
= cgroup_init(conf
);
1287 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1290 cgroup_exit(cgroup_ops
);
1291 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1294 /* Setup /proc limits */
1295 if (!lxc_list_empty(&conf
->procs
)) {
1296 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1301 /* Setup resource limits */
1302 if (!lxc_list_empty(&conf
->limits
)) {
1303 ret
= setup_resource_limits(&conf
->limits
, pid
);
1308 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1309 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1313 TRACE("Initialized terminal mainloop");
1316 /* Let the child process know to go ahead. */
1318 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1319 if (ret
!= sizeof(status
))
1320 goto close_mainloop
;
1322 TRACE("Told intermediate process to start initializing");
1324 /* Get pid of attached process from intermediate process. */
1325 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1326 if (ret
!= sizeof(attached_pid
))
1327 goto close_mainloop
;
1329 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1331 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1332 if (options
->stdin_fd
== 0) {
1333 signal(SIGINT
, SIG_IGN
);
1334 signal(SIGQUIT
, SIG_IGN
);
1337 /* Reap intermediate process. */
1338 ret
= wait_for_pid(pid
);
1340 goto close_mainloop
;
1342 TRACE("Intermediate process %d exited", pid
);
1344 /* We will always have to reap the attached process now. */
1345 to_cleanup_pid
= attached_pid
;
1347 /* Open LSM fd and send it to child. */
1348 if ((options
->namespaces
& CLONE_NEWNS
) &&
1349 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1350 init_ctx
->lsm_label
) {
1355 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1356 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1358 goto close_mainloop
;
1360 TRACE("Opened LSM label file descriptor %d", labelfd
);
1362 /* Send child fd of the LSM security module to write to. */
1363 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1366 SYSERROR("Failed to send lsm label fd");
1369 goto close_mainloop
;
1373 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1376 /* We're done, the child process should now execute whatever it
1377 * is that the user requested. The parent can now track it with
1378 * waitpid() or similar.
1381 *attached_process
= attached_pid
;
1383 /* Now shut down communication with child, we're done. */
1384 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1385 close(ipc_sockets
[0]);
1386 ipc_sockets
[0] = -1;
1389 to_cleanup_pid
= -1;
1391 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1392 ret
= lxc_mainloop(&descr
, -1);
1395 to_cleanup_pid
= attached_pid
;
1400 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1401 lxc_mainloop_close(&descr
);
1404 if (ipc_sockets
[0] >= 0) {
1405 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1406 close(ipc_sockets
[0]);
1409 if (to_cleanup_pid
> 0)
1410 (void)wait_for_pid(to_cleanup_pid
);
1412 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1413 lxc_terminal_delete(&terminal
);
1414 lxc_terminal_conf_free(&terminal
);
1417 lxc_proc_put_context_info(init_ctx
);
1421 /* close unneeded file descriptors */
1422 close(ipc_sockets
[0]);
1423 ipc_sockets
[0] = -EBADF
;
1425 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1426 lxc_attach_terminal_close_master(&terminal
);
1427 lxc_attach_terminal_close_peer(&terminal
);
1428 lxc_attach_terminal_close_log(&terminal
);
1431 /* Wait for the parent to have setup cgroups. */
1432 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1433 if (ret
!= sizeof(status
)) {
1434 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1435 lxc_proc_put_context_info(init_ctx
);
1436 _exit(EXIT_FAILURE
);
1439 TRACE("Intermediate process starting to initialize");
1441 /* Attach now, create another subprocess later, since pid namespaces
1442 * only really affect the children of the current process.
1444 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1446 ERROR("Failed to enter namespaces");
1447 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1448 lxc_proc_put_context_info(init_ctx
);
1449 _exit(EXIT_FAILURE
);
1452 /* close namespace file descriptors */
1453 lxc_proc_close_ns_fd(init_ctx
);
1455 /* Attach succeeded, try to cwd. */
1456 if (options
->initial_cwd
)
1457 new_cwd
= options
->initial_cwd
;
1461 ret
= chdir(new_cwd
);
1463 WARN("Could not change directory to \"%s\"", new_cwd
);
1467 /* Create attached process. */
1468 payload
.ipc_socket
= ipc_sockets
[1];
1469 payload
.options
= options
;
1470 payload
.init_ctx
= init_ctx
;
1471 payload
.terminal_slave_fd
= terminal
.slave
;
1472 payload
.exec_function
= exec_function
;
1473 payload
.exec_payload
= exec_payload
;
1475 pid
= lxc_raw_clone(CLONE_PARENT
);
1477 SYSERROR("Failed to clone attached process");
1478 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1479 lxc_proc_put_context_info(init_ctx
);
1480 _exit(EXIT_FAILURE
);
1484 ret
= attach_child_main(&payload
);
1486 ERROR("Failed to exec");
1488 _exit(EXIT_FAILURE
);
1491 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1492 lxc_attach_terminal_close_slave(&terminal
);
1494 /* Tell grandparent the pid of the pid of the newly created child. */
1495 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1496 if (ret
!= sizeof(pid
)) {
1497 /* If this really happens here, this is very unfortunate, since
1498 * the parent will not know the pid of the attached process and
1499 * will not be able to wait for it (and we won't either due to
1500 * CLONE_PARENT) so the parent won't be able to reap it and the
1501 * attached process will remain a zombie.
1503 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1504 lxc_proc_put_context_info(init_ctx
);
1505 _exit(EXIT_FAILURE
);
1508 TRACE("Sending pid %d of attached process", pid
);
1510 /* The rest is in the hands of the initial and the attached process. */
1511 lxc_proc_put_context_info(init_ctx
);
1515 int lxc_attach_run_command(void *payload
)
1518 lxc_attach_command_t
*cmd
= payload
;
1520 ret
= execvp(cmd
->program
, cmd
->argv
);
1532 SYSERROR("Failed to exec \"%s\"", cmd
->program
);
1536 int lxc_attach_run_shell(void* payload
)
1539 struct passwd pwent
;
1540 struct passwd
*pwentp
= NULL
;
1546 /* Ignore payload parameter. */
1551 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1555 buf
= malloc(bufsize
);
1557 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1560 WARN("Could not find matched password record");
1562 WARN("Failed to get password record - %u", uid
);
1566 /* This probably happens because of incompatible nss implementations in
1567 * host and container (remember, this code is still using the host's
1568 * glibc but our mount namespace is in the container) we may try to get
1569 * the information by spawning a [getent passwd uid] process and parsing
1573 user_shell
= lxc_attach_getpwshell(uid
);
1575 user_shell
= pwent
.pw_shell
;
1578 execlp(user_shell
, user_shell
, (char *)NULL
);
1580 /* Executed if either no passwd entry or execvp fails, we will fall back
1581 * on /bin/sh as a default shell.
1583 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1585 SYSERROR("Failed to execute shell");