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
= 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;
163 struct stat ns_st1
, ns_st2
;
165 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
167 /* The kernel does not support this namespace. This is not an
176 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
180 ret
= fstat(ns_fd1
, &ns_st1
);
184 ret
= fstat(ns_fd2
, &ns_st2
);
188 /* processes are in the same namespace */
189 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
192 /* processes are in different namespaces */
193 return move_fd(ns_fd2
);
196 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
200 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
201 if (ctx
->ns_fd
[i
] < 0)
204 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
206 SYSERROR("Failed to attach to %s namespace of %d",
207 ns_info
[i
].proc_name
, pid
);
211 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
217 static int lxc_attach_remount_sys_proc(void)
221 ret
= unshare(CLONE_NEWNS
);
223 SYSERROR("Failed to unshare mount namespace");
227 if (detect_shared_rootfs()) {
228 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
229 SYSERROR("Failed to make / rslave");
230 ERROR("Continuing...");
234 /* Assume /proc is always mounted, so remount it. */
235 ret
= umount2("/proc", MNT_DETACH
);
237 SYSERROR("Failed to unmount /proc");
241 ret
= mount("none", "/proc", "proc", 0, NULL
);
243 SYSERROR("Failed to remount /proc");
247 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
248 * we ignore it because it may not have been mounted in the first place.
250 ret
= umount2("/sys", MNT_DETACH
);
251 if (ret
< 0 && errno
!= EINVAL
) {
252 SYSERROR("Failed to unmount /sys");
254 } else if (ret
== 0) {
256 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
258 SYSERROR("Failed to remount /sys");
266 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
270 last_cap
= lxc_caps_last_cap();
271 for (cap
= 0; cap
<= last_cap
; cap
++) {
272 if (ctx
->capability_mask
& (1LL << cap
))
275 if (prctl(PR_CAPBSET_DROP
, prctl_arg(cap
), prctl_arg(0),
276 prctl_arg(0), prctl_arg(0))) {
277 SYSERROR("Failed to drop capability %d", cap
);
281 TRACE("Dropped capability %d", cap
);
287 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
288 enum lxc_attach_env_policy_t policy
,
289 char **extra_env
, char **extra_keep
)
292 struct lxc_list
*iterator
;
294 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
296 char **extra_keep_store
= NULL
;
301 for (count
= 0; extra_keep
[count
]; count
++)
304 extra_keep_store
= calloc(count
, sizeof(char *));
305 if (!extra_keep_store
)
308 for (i
= 0; i
< count
; i
++) {
309 char *v
= getenv(extra_keep
[i
]);
311 extra_keep_store
[i
] = strdup(v
);
312 if (!extra_keep_store
[i
]) {
314 free(extra_keep_store
[--i
]);
316 free(extra_keep_store
);
320 if (strcmp(extra_keep
[i
], "PATH") == 0)
327 if (extra_keep_store
) {
330 for (p
= extra_keep_store
; *p
; p
++)
333 free(extra_keep_store
);
336 ERROR("Failed to clear environment");
340 if (extra_keep_store
) {
343 for (i
= 0; extra_keep
[i
]; i
++) {
344 if (extra_keep_store
[i
]) {
345 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
347 SYSWARN("Failed to set environment variable");
350 free(extra_keep_store
[i
]);
353 free(extra_keep_store
);
356 /* Always set a default path; shells and execlp tend to be fine
357 * without it, but there is a disturbing number of C programs
358 * out there that just assume that getenv("PATH") is never NULL
359 * and then die a painful segfault death.
362 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
364 SYSWARN("Failed to set environment variable");
368 ret
= putenv("container=lxc");
370 SYSWARN("Failed to set environment variable");
374 /* Set container environment variables.*/
375 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
376 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
379 env_tmp
= strdup((char *)iterator
->elem
);
383 ret
= putenv(env_tmp
);
385 SYSERROR("Failed to set environment variable: %s", (char *)iterator
->elem
);
391 /* Set extra environment variables. */
393 for (; *extra_env
; extra_env
++) {
396 /* We just assume the user knows what they are doing, so
397 * we don't do any checks.
399 p
= strdup(*extra_env
);
405 SYSWARN("Failed to set environment variable");
412 static char *lxc_attach_getpwshell(uid_t uid
)
414 __do_free
char *line
= NULL
;
415 __do_fclose
FILE *pipe_f
= NULL
;
420 size_t line_bufsz
= 0;
423 /* We need to fork off a process that runs the getent program, and we
424 * need to capture its output, so we use a pipe for that purpose.
426 ret
= pipe2(pipes
, O_CLOEXEC
);
439 char *arguments
[] = {
448 /* We want to capture stdout. */
449 ret
= dup2(pipes
[1], STDOUT_FILENO
);
454 /* Get rid of stdin/stderr, so we try to associate it with
460 close(STDERR_FILENO
);
462 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
463 (void)dup3(fd
, STDOUT_FILENO
, O_CLOEXEC
);
467 /* Finish argument list. */
468 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
469 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
472 /* Try to run getent program. */
473 (void)execvp("getent", arguments
);
479 pipe_f
= fdopen(pipes
[0], "r");
480 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
484 char *endptr
= NULL
, *saveptr
= NULL
;
486 /* If we already found something, just continue to read
487 * until the pipe doesn't deliver any more data, but
488 * don't modify the existing data structure.
496 /* Trim line on the right hand side. */
497 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
500 /* Split into tokens: first: user name. */
501 token
= strtok_r(line
, ":", &saveptr
);
505 /* next: dummy password field */
506 token
= strtok_r(NULL
, ":", &saveptr
);
511 token
= strtok_r(NULL
, ":", &saveptr
);
512 value
= token
? strtol(token
, &endptr
, 10) : 0;
513 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
517 /* dummy sanity check: user id matches */
518 if ((uid_t
)value
!= uid
)
521 /* skip fields: gid, gecos, dir, go to next field 'shell' */
522 for (i
= 0; i
< 4; i
++) {
523 token
= strtok_r(NULL
, ":", &saveptr
);
532 result
= strdup(token
);
534 /* Sanity check that there are no fields after that. */
535 token
= strtok_r(NULL
, ":", &saveptr
);
542 ret
= wait_for_pid(pid
);
556 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
558 __do_free
char *line
= NULL
;
559 __do_fclose
FILE *proc_file
= NULL
;
560 char proc_fn
[LXC_PROC_STATUS_LEN
];
562 size_t line_bufsz
= 0;
564 uid_t uid
= (uid_t
)-1;
565 gid_t gid
= (gid_t
)-1;
567 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", 1);
568 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
571 proc_file
= fopen(proc_fn
, "r");
575 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
576 /* Format is: real, effective, saved set user, fs we only care
579 ret
= sscanf(line
, "Uid: %ld", &value
);
580 if (ret
!= EOF
&& ret
== 1) {
583 ret
= sscanf(line
, "Gid: %ld", &value
);
584 if (ret
!= EOF
&& ret
== 1)
588 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
592 /* Only override arguments if we found something. */
593 if (uid
!= (uid_t
)-1)
596 if (gid
!= (gid_t
)-1)
599 /* TODO: we should also parse supplementary groups and use
600 * setgroups() to set them.
604 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
606 __do_free
char *path
= NULL
;
610 if (!(options
->namespaces
& CLONE_NEWNS
) ||
611 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
612 free(c
->lxc_conf
->seccomp
);
613 c
->lxc_conf
->seccomp
= NULL
;
617 /* Remove current setting. */
618 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
619 !c
->set_config_item(c
, "lxc.seccomp", ""))
622 /* Fetch the current profile path over the cmd interface. */
623 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
625 INFO("Failed to retrieve lxc.seccomp.profile");
627 path
= c
->get_running_config_item(c
, "lxc.seccomp");
629 INFO("Failed to retrieve lxc.seccomp");
634 /* Copy the value into the new lxc_conf. */
635 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
639 /* Attempt to parse the resulting config. */
640 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
642 ERROR("Failed to retrieve seccomp policy");
646 INFO("Retrieved seccomp policy");
650 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
652 __do_free
char *val
= NULL
;
654 /* Remove current setting. */
655 if (!c
->set_config_item(c
, "lxc.no_new_privs", "")) {
656 INFO("Failed to unset lxc.no_new_privs");
660 /* Retrieve currently active setting. */
661 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
663 INFO("Failed to retrieve lxc.no_new_privs");
667 /* Set currently active setting. */
668 return c
->set_config_item(c
, "lxc.no_new_privs", val
);
671 static signed long get_personality(const char *name
, const char *lxcpath
)
675 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
679 return lxc_config_parse_arch(p
);
682 struct attach_clone_payload
{
684 int terminal_slave_fd
;
685 lxc_attach_options_t
*options
;
686 struct lxc_proc_context_info
*init_ctx
;
687 lxc_attach_exec_t exec_function
;
691 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
693 __do_close_prot_errno
int ipc_socket
= p
->ipc_socket
;
694 __do_close_prot_errno
int terminal_slave_fd
= p
->terminal_slave_fd
;
697 lxc_proc_put_context_info(p
->init_ctx
);
702 static int attach_child_main(struct attach_clone_payload
*payload
)
707 uid_t ns_root_uid
= 0;
708 gid_t ns_root_gid
= 0;
709 lxc_attach_options_t
* options
= payload
->options
;
710 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
711 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
712 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
715 /* A description of the purpose of this functionality is provided in the
716 * lxc-attach(1) manual page. We have to remount here and not in the
717 * parent process, otherwise /proc may not properly reflect the new pid
720 if (!(options
->namespaces
& CLONE_NEWNS
) &&
721 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
722 ret
= lxc_attach_remount_sys_proc();
726 TRACE("Remounted \"/proc\" and \"/sys\"");
729 /* Now perform additional attachments. */
730 #if HAVE_SYS_PERSONALITY_H
731 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
732 long new_personality
;
734 if (options
->personality
< 0)
735 new_personality
= init_ctx
->personality
;
737 new_personality
= options
->personality
;
739 ret
= personality(new_personality
);
743 TRACE("Set new personality");
747 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
748 ret
= lxc_attach_drop_privs(init_ctx
);
752 TRACE("Dropped capabilities");
755 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
756 * if you want this to be a no-op).
758 ret
= lxc_attach_set_environment(init_ctx
,
760 options
->extra_env_vars
,
761 options
->extra_keep_env
);
765 TRACE("Set up environment");
767 /* This remark only affects fully unprivileged containers:
768 * Receive fd for LSM security module before we set{g,u}id(). The reason
769 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
770 * we will change our effective uid. This means our effective uid will
771 * be different from the effective uid of the process that created us
772 * which means that this processs no longer has capabilities in our
773 * namespace including CAP_SYS_PTRACE. This means we will not be able to
774 * read and /proc/<pid> files for the process anymore when /proc is
775 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
779 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
782 SYSERROR("Failed to receive lsm label fd");
787 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
790 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
791 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
796 if (options
->namespaces
& CLONE_NEWUSER
) {
797 /* Check whether nsuid 0 has a mapping. */
798 ns_root_uid
= get_ns_uid(0);
800 /* Check whether nsgid 0 has a mapping. */
801 ns_root_gid
= get_ns_gid(0);
803 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
804 * init was started with.
806 if (ns_root_uid
== LXC_INVALID_UID
)
807 lxc_attach_get_init_uidgid(&ns_root_uid
, &ns_root_gid
);
809 if (ns_root_uid
== LXC_INVALID_UID
)
812 if (!lxc_switch_uid_gid(ns_root_uid
, ns_root_gid
))
816 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
820 if (options
->uid
!= LXC_INVALID_UID
)
821 new_uid
= options
->uid
;
823 new_uid
= ns_root_uid
;
825 if (options
->gid
!= LXC_INVALID_GID
)
826 new_gid
= options
->gid
;
828 new_gid
= ns_root_gid
;
830 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
831 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
832 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
833 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
834 prctl_arg(0), prctl_arg(0));
838 TRACE("Set PR_SET_NO_NEW_PRIVS");
844 /* Change into our new LSM profile. */
845 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
847 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
852 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
855 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
856 init_ctx
->container
->lxc_conf
->seccomp
) {
857 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
861 TRACE("Loaded seccomp profile");
864 close(payload
->ipc_socket
);
865 payload
->ipc_socket
= -EBADF
;
866 lxc_proc_put_context_info(init_ctx
);
867 payload
->init_ctx
= NULL
;
869 /* The following is done after the communication socket is shut down.
870 * That way, all errors that might (though unlikely) occur up until this
871 * point will have their messages printed to the original stderr (if
872 * logging is so configured) and not the fd the user supplied, if any.
875 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
876 * may want to make sure the fds are closed, for example.
878 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
879 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
881 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
882 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
884 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
885 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
887 /* close the old fds */
888 if (options
->stdin_fd
> STDERR_FILENO
)
889 close(options
->stdin_fd
);
891 if (options
->stdout_fd
> STDERR_FILENO
)
892 close(options
->stdout_fd
);
894 if (options
->stderr_fd
> STDERR_FILENO
)
895 close(options
->stderr_fd
);
897 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
898 * here, ignore errors.
900 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
901 ret
= fd_cloexec(fd
, false);
903 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
908 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
909 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
911 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
915 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
918 /* Avoid unnecessary syscalls. */
919 if (new_uid
== ns_root_uid
)
920 new_uid
= LXC_INVALID_UID
;
922 if (new_gid
== ns_root_gid
)
923 new_gid
= LXC_INVALID_GID
;
925 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
928 /* We're done, so we can now do whatever the user intended us to do. */
929 _exit(payload
->exec_function(payload
->exec_payload
));
932 lxc_put_attach_clone_payload(payload
);
936 static int lxc_attach_terminal(struct lxc_conf
*conf
,
937 struct lxc_terminal
*terminal
)
941 lxc_terminal_init(terminal
);
943 ret
= lxc_terminal_create(terminal
);
945 ERROR("Failed to create terminal");
949 /* Shift ttys to container. */
950 ret
= lxc_terminal_map_ids(conf
, terminal
);
952 ERROR("Failed to chown terminal");
959 lxc_terminal_delete(terminal
);
960 lxc_terminal_conf_free(terminal
);
964 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
965 struct lxc_epoll_descr
*descr
)
969 ret
= lxc_mainloop_open(descr
);
971 ERROR("Failed to create mainloop");
975 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
977 ERROR("Failed to add handlers to mainloop");
978 lxc_mainloop_close(descr
);
985 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
987 close_prot_errno_disarm(terminal
->master
);
990 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
992 close_prot_errno_disarm(terminal
->slave
);
995 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
997 close_prot_errno_disarm(terminal
->peer
);
1000 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1002 close_prot_errno_disarm(terminal
->log_fd
);
1005 int lxc_attach(const char *name
, const char *lxcpath
,
1006 lxc_attach_exec_t exec_function
, void *exec_payload
,
1007 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1011 char *cwd
, *new_cwd
;
1012 signed long personality
;
1013 pid_t attached_pid
, init_pid
, pid
;
1014 struct lxc_proc_context_info
*init_ctx
;
1015 struct lxc_terminal terminal
;
1016 struct lxc_conf
*conf
;
1017 struct attach_clone_payload payload
= {0};
1019 ret
= access("/proc/self/ns", X_OK
);
1021 SYSERROR("Does this kernel version support namespaces?");
1026 options
= &attach_static_default_options
;
1028 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1030 ERROR("Failed to get init pid");
1034 init_ctx
= lxc_proc_get_context_info(init_pid
);
1036 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1040 personality
= get_personality(name
, lxcpath
);
1041 if (init_ctx
->personality
< 0) {
1042 ERROR("Failed to get personality of the container");
1043 lxc_proc_put_context_info(init_ctx
);
1046 init_ctx
->personality
= personality
;
1048 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1049 if (!init_ctx
->container
) {
1050 lxc_proc_put_context_info(init_ctx
);
1054 if (!init_ctx
->container
->lxc_conf
) {
1055 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1056 if (!init_ctx
->container
->lxc_conf
) {
1057 lxc_proc_put_context_info(init_ctx
);
1061 conf
= init_ctx
->container
->lxc_conf
;
1063 if (!fetch_seccomp(init_ctx
->container
, options
))
1064 WARN("Failed to get seccomp policy");
1066 if (!no_new_privs(init_ctx
->container
, options
))
1067 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1069 cwd
= getcwd(NULL
, 0);
1071 /* Determine which namespaces the container was created with
1072 * by asking lxc-start, if necessary.
1074 if (options
->namespaces
== -1) {
1075 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1077 if (options
->namespaces
== -1) {
1078 ERROR("Failed to automatically determine the "
1079 "namespaces which the container uses");
1081 lxc_proc_put_context_info(init_ctx
);
1085 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1086 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1087 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1091 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1094 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1098 pid
= lxc_raw_getpid();
1100 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1103 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1104 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1105 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1106 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1110 if (init_ctx
->ns_fd
[i
] >= 0)
1113 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1114 DEBUG("Inheriting %s namespace from %d",
1115 ns_info
[i
].proc_name
, pid
);
1116 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1120 /* We failed to preserve the namespace. */
1121 SYSERROR("Failed to attach to %s namespace of %d",
1122 ns_info
[i
].proc_name
, pid
);
1124 /* Close all already opened file descriptors before we return an
1125 * error, so we don't leak them.
1127 for (j
= 0; j
< i
; j
++)
1128 close(init_ctx
->ns_fd
[j
]);
1131 lxc_proc_put_context_info(init_ctx
);
1135 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1136 ret
= lxc_attach_terminal(conf
, &terminal
);
1138 ERROR("Failed to setup new terminal");
1140 lxc_proc_put_context_info(init_ctx
);
1144 terminal
.log_fd
= options
->log_fd
;
1146 lxc_terminal_init(&terminal
);
1149 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1150 * to make sure we don't irritate other threads that want to fork+exec
1153 * IMPORTANT: if the initial process is multithreaded and another call
1154 * just fork()s away without exec'ing directly after, the socket fd will
1155 * exist in the forked process from the other thread and any close() in
1156 * our own child process will not really cause the socket to close
1157 * properly, potentially causing the parent to hang.
1159 * For this reason, while IPC is still active, we have to use shutdown()
1160 * if the child exits prematurely in order to signal that the socket is
1161 * closed and cannot assume that the child exiting will automatically do
1164 * IPC mechanism: (X is receiver)
1165 * initial process intermediate attached
1166 * X <--- send pid of
1169 * send 0 ------------------------------------> X
1170 * [do initialization]
1171 * X <------------------------------------ send 1
1172 * [add to cgroup, ...]
1173 * send 2 ------------------------------------> X
1174 * [set LXC_ATTACH_NO_NEW_PRIVS]
1175 * X <------------------------------------ send 3
1176 * [open LSM label fd]
1177 * send 4 ------------------------------------> X
1179 * close socket close socket
1182 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1184 SYSERROR("Could not set up required IPC mechanism for attaching");
1186 lxc_proc_put_context_info(init_ctx
);
1190 /* Create intermediate subprocess, two reasons:
1191 * 1. We can't setns() in the child itself, since we want to make
1192 * sure we are properly attached to the pidns.
1193 * 2. Also, the initial thread has to put the attached process
1194 * into the cgroup, which we can only do if we didn't already
1195 * setns() (otherwise, user namespaces will hate us).
1199 SYSERROR("Failed to create first subprocess");
1201 lxc_proc_put_context_info(init_ctx
);
1206 int ret_parent
= -1;
1207 pid_t to_cleanup_pid
= pid
;
1208 struct lxc_epoll_descr descr
= {0};
1210 /* close unneeded file descriptors */
1211 close(ipc_sockets
[1]);
1213 lxc_proc_close_ns_fd(init_ctx
);
1214 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1215 lxc_attach_terminal_close_slave(&terminal
);
1217 /* Attach to cgroup, if requested. */
1218 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1219 struct cgroup_ops
*cgroup_ops
;
1221 cgroup_ops
= cgroup_init(conf
);
1225 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1228 cgroup_exit(cgroup_ops
);
1229 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1232 /* Setup /proc limits */
1233 if (!lxc_list_empty(&conf
->procs
)) {
1234 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1239 /* Setup resource limits */
1240 if (!lxc_list_empty(&conf
->limits
)) {
1241 ret
= setup_resource_limits(&conf
->limits
, pid
);
1246 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1247 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1251 TRACE("Initialized terminal mainloop");
1254 /* Let the child process know to go ahead. */
1256 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1257 if (ret
!= sizeof(status
))
1258 goto close_mainloop
;
1260 TRACE("Told intermediate process to start initializing");
1262 /* Get pid of attached process from intermediate process. */
1263 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1264 if (ret
!= sizeof(attached_pid
))
1265 goto close_mainloop
;
1267 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1269 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1270 if (options
->stdin_fd
== 0) {
1271 signal(SIGINT
, SIG_IGN
);
1272 signal(SIGQUIT
, SIG_IGN
);
1275 /* Reap intermediate process. */
1276 ret
= wait_for_pid(pid
);
1278 goto close_mainloop
;
1280 TRACE("Intermediate process %d exited", pid
);
1282 /* We will always have to reap the attached process now. */
1283 to_cleanup_pid
= attached_pid
;
1285 /* Open LSM fd and send it to child. */
1286 if ((options
->namespaces
& CLONE_NEWNS
) &&
1287 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1288 init_ctx
->lsm_label
) {
1293 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1294 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1296 goto close_mainloop
;
1298 TRACE("Opened LSM label file descriptor %d", labelfd
);
1300 /* Send child fd of the LSM security module to write to. */
1301 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1304 SYSERROR("Failed to send lsm label fd");
1307 goto close_mainloop
;
1311 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1314 /* We're done, the child process should now execute whatever it
1315 * is that the user requested. The parent can now track it with
1316 * waitpid() or similar.
1319 *attached_process
= attached_pid
;
1321 /* Now shut down communication with child, we're done. */
1322 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1323 close(ipc_sockets
[0]);
1324 ipc_sockets
[0] = -1;
1327 to_cleanup_pid
= -1;
1329 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1330 ret
= lxc_mainloop(&descr
, -1);
1333 to_cleanup_pid
= attached_pid
;
1338 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1339 lxc_mainloop_close(&descr
);
1342 if (ipc_sockets
[0] >= 0) {
1343 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1344 close(ipc_sockets
[0]);
1347 if (to_cleanup_pid
> 0)
1348 (void)wait_for_pid(to_cleanup_pid
);
1350 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1351 lxc_terminal_delete(&terminal
);
1352 lxc_terminal_conf_free(&terminal
);
1355 lxc_proc_put_context_info(init_ctx
);
1359 /* close unneeded file descriptors */
1360 close(ipc_sockets
[0]);
1361 ipc_sockets
[0] = -EBADF
;
1363 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1364 lxc_attach_terminal_close_master(&terminal
);
1365 lxc_attach_terminal_close_peer(&terminal
);
1366 lxc_attach_terminal_close_log(&terminal
);
1369 /* Wait for the parent to have setup cgroups. */
1370 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1371 if (ret
!= sizeof(status
)) {
1372 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1373 lxc_proc_put_context_info(init_ctx
);
1374 _exit(EXIT_FAILURE
);
1377 TRACE("Intermediate process starting to initialize");
1379 /* Attach now, create another subprocess later, since pid namespaces
1380 * only really affect the children of the current process.
1382 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1384 ERROR("Failed to enter namespaces");
1385 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1386 lxc_proc_put_context_info(init_ctx
);
1387 _exit(EXIT_FAILURE
);
1390 /* close namespace file descriptors */
1391 lxc_proc_close_ns_fd(init_ctx
);
1393 /* Attach succeeded, try to cwd. */
1394 if (options
->initial_cwd
)
1395 new_cwd
= options
->initial_cwd
;
1399 ret
= chdir(new_cwd
);
1401 WARN("Could not change directory to \"%s\"", new_cwd
);
1405 /* Create attached process. */
1406 payload
.ipc_socket
= ipc_sockets
[1];
1407 payload
.options
= options
;
1408 payload
.init_ctx
= init_ctx
;
1409 payload
.terminal_slave_fd
= terminal
.slave
;
1410 payload
.exec_function
= exec_function
;
1411 payload
.exec_payload
= exec_payload
;
1413 pid
= lxc_raw_clone(CLONE_PARENT
);
1415 SYSERROR("Failed to clone attached process");
1416 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1417 lxc_proc_put_context_info(init_ctx
);
1418 _exit(EXIT_FAILURE
);
1422 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1423 ret
= pthread_sigmask(SIG_SETMASK
,
1424 &terminal
.tty_state
->oldmask
, NULL
);
1426 SYSERROR("Failed to reset signal mask");
1427 _exit(EXIT_FAILURE
);
1431 ret
= attach_child_main(&payload
);
1433 ERROR("Failed to exec");
1435 _exit(EXIT_FAILURE
);
1438 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1439 lxc_attach_terminal_close_slave(&terminal
);
1441 /* Tell grandparent the pid of the pid of the newly created child. */
1442 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1443 if (ret
!= sizeof(pid
)) {
1444 /* If this really happens here, this is very unfortunate, since
1445 * the parent will not know the pid of the attached process and
1446 * will not be able to wait for it (and we won't either due to
1447 * CLONE_PARENT) so the parent won't be able to reap it and the
1448 * attached process will remain a zombie.
1450 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1451 lxc_proc_put_context_info(init_ctx
);
1452 _exit(EXIT_FAILURE
);
1455 TRACE("Sending pid %d of attached process", pid
);
1457 /* The rest is in the hands of the initial and the attached process. */
1458 lxc_proc_put_context_info(init_ctx
);
1459 _exit(EXIT_SUCCESS
);
1462 int lxc_attach_run_command(void *payload
)
1465 lxc_attach_command_t
*cmd
= payload
;
1467 ret
= execvp(cmd
->program
, cmd
->argv
);
1479 SYSERROR("Failed to exec \"%s\"", cmd
->program
);
1483 int lxc_attach_run_shell(void* payload
)
1485 __do_free
char *buf
= NULL
;
1487 struct passwd pwent
;
1488 struct passwd
*pwentp
= NULL
;
1493 /* Ignore payload parameter. */
1498 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1502 buf
= malloc(bufsize
);
1504 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1507 WARN("Could not find matched password record");
1509 WARN("Failed to get password record - %u", uid
);
1513 /* This probably happens because of incompatible nss implementations in
1514 * host and container (remember, this code is still using the host's
1515 * glibc but our mount namespace is in the container) we may try to get
1516 * the information by spawning a [getent passwd uid] process and parsing
1520 user_shell
= lxc_attach_getpwshell(uid
);
1522 user_shell
= pwent
.pw_shell
;
1525 execlp(user_shell
, user_shell
, (char *)NULL
);
1527 /* Executed if either no passwd entry or execvp fails, we will fall back
1528 * on /bin/sh as a default shell.
1530 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1532 SYSERROR("Failed to execute shell");