2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <linux/unistd.h>
35 #include <sys/mount.h>
36 #include <sys/param.h>
37 #include <sys/prctl.h>
38 #include <sys/socket.h>
39 #include <sys/syscall.h>
42 #include <lxc/lxccontainer.h>
44 #ifndef HAVE_DECL_PR_CAPBSET_DROP
45 #define PR_CAPBSET_DROP 24
48 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
49 #define PR_SET_NO_NEW_PRIVS 38
52 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
53 #define PR_GET_NO_NEW_PRIVS 39
67 #include "lxcseccomp.h"
69 #include "namespace.h"
73 #if HAVE_SYS_PERSONALITY_H
74 #include <sys/personality.h>
78 #define SOCK_CLOEXEC 02000000
86 #define MS_SLAVE (1 << 19)
89 lxc_log_define(lxc_attach
, lxc
);
91 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
92 #define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
93 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
98 char proc_fn
[__PROC_STATUS_LEN
];
99 size_t line_bufsz
= 0;
101 struct lxc_proc_context_info
*info
= NULL
;
103 /* Read capabilities. */
104 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
105 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
108 proc_file
= fopen(proc_fn
, "r");
110 SYSERROR("Could not open %s.", proc_fn
);
114 info
= calloc(1, sizeof(*info
));
116 SYSERROR("Could not allocate memory.");
122 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
123 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
124 if (ret
!= EOF
&& ret
== 1) {
134 SYSERROR("Could not read capability bounding set from %s.",
140 info
->lsm_label
= lsm_process_label_get(pid
);
141 info
->ns_inherited
= 0;
142 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
151 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
155 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
156 if (ctx
->ns_fd
[i
] < 0)
158 close(ctx
->ns_fd
[i
]);
159 ctx
->ns_fd
[i
] = -EBADF
;
163 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
165 free(ctx
->lsm_label
);
166 ctx
->lsm_label
= NULL
;
168 if (ctx
->container
) {
169 lxc_container_put(ctx
->container
);
170 ctx
->container
= NULL
;
173 lxc_proc_close_ns_fd(ctx
);
179 * in_same_namespace - Check whether two processes are in the same namespace.
180 * @pid1 - PID of the first process.
181 * @pid2 - PID of the second process.
182 * @ns - Name of the namespace to check. Must correspond to one of the names
183 * for the namespaces as shown in /proc/<pid/ns/
185 * If the two processes are not in the same namespace returns an fd to the
186 * namespace of the second process identified by @pid2. If the two processes are
187 * in the same namespace returns -EINVAL, -1 if an error occurred.
189 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
191 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
192 struct stat ns_st1
, ns_st2
;
194 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
196 /* The kernel does not support this namespace. This is not an
205 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
209 ret
= fstat(ns_fd1
, &ns_st1
);
213 ret
= fstat(ns_fd2
, &ns_st2
);
217 /* processes are in the same namespace */
219 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
222 /* processes are in different namespaces */
236 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
240 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
241 if (ctx
->ns_fd
[i
] < 0)
244 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
246 SYSERROR("Failed to attach to %s namespace of %d",
247 ns_info
[i
].proc_name
, pid
);
251 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
257 static int lxc_attach_remount_sys_proc(void)
261 ret
= unshare(CLONE_NEWNS
);
263 SYSERROR("Failed to unshare mount namespace.");
267 if (detect_shared_rootfs()) {
268 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
269 SYSERROR("Failed to make / rslave.");
270 ERROR("Continuing...");
274 /* Assume /proc is always mounted, so remount it. */
275 ret
= umount2("/proc", MNT_DETACH
);
277 SYSERROR("Failed to unmount /proc.");
281 ret
= mount("none", "/proc", "proc", 0, NULL
);
283 SYSERROR("Failed to remount /proc.");
287 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
288 * we ignore it because it may not have been mounted in the first place.
290 ret
= umount2("/sys", MNT_DETACH
);
291 if (ret
< 0 && errno
!= EINVAL
) {
292 SYSERROR("Failed to unmount /sys.");
294 } else if (ret
== 0) {
296 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
298 SYSERROR("Failed to remount /sys.");
306 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
310 last_cap
= lxc_caps_last_cap();
311 for (cap
= 0; cap
<= last_cap
; cap
++) {
312 if (ctx
->capability_mask
& (1LL << cap
))
315 if (prctl(PR_CAPBSET_DROP
, cap
, 0, 0, 0)) {
316 SYSERROR("Failed to drop capability %d", cap
);
319 TRACE("Dropped capability %d", cap
);
325 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
326 enum lxc_attach_env_policy_t policy
,
327 char **extra_env
, char **extra_keep
)
330 struct lxc_list
*iterator
;
332 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
334 char **extra_keep_store
= NULL
;
339 for (count
= 0; extra_keep
[count
]; count
++)
342 extra_keep_store
= calloc(count
, sizeof(char *));
343 if (!extra_keep_store
)
346 for (i
= 0; i
< count
; i
++) {
347 char *v
= getenv(extra_keep
[i
]);
349 extra_keep_store
[i
] = strdup(v
);
350 if (!extra_keep_store
[i
]) {
352 free(extra_keep_store
[--i
]);
353 free(extra_keep_store
);
357 if (strcmp(extra_keep
[i
], "PATH") == 0)
364 if (extra_keep_store
) {
367 for (p
= extra_keep_store
; *p
; p
++)
370 free(extra_keep_store
);
373 SYSERROR("Failed to clear environment");
377 if (extra_keep_store
) {
380 for (i
= 0; extra_keep
[i
]; i
++) {
381 if (extra_keep_store
[i
]) {
382 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
384 WARN("%s - Failed to set environment variable", strerror(errno
));
386 free(extra_keep_store
[i
]);
388 free(extra_keep_store
);
391 /* Always set a default path; shells and execlp tend to be fine
392 * without it, but there is a disturbing number of C programs
393 * out there that just assume that getenv("PATH") is never NULL
394 * and then die a painful segfault death.
397 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
399 WARN("%s - Failed to set environment variable", strerror(errno
));
403 ret
= putenv("container=lxc");
405 WARN("%s - Failed to set environment variable", strerror(errno
));
409 /* Set container environment variables.*/
410 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
411 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
414 env_tmp
= strdup((char *)iterator
->elem
);
418 ret
= putenv(env_tmp
);
420 SYSERROR("Failed to set environment variable: %s", (char *)iterator
->elem
);
426 /* Set extra environment variables. */
428 for (; *extra_env
; extra_env
++) {
430 /* We just assume the user knows what they are doing, so
431 * we don't do any checks.
433 p
= strdup(*extra_env
);
439 WARN("%s - Failed to set environment variable", strerror(errno
));
446 static char *lxc_attach_getpwshell(uid_t uid
)
453 /* We need to fork off a process that runs the getent program, and we
454 * need to capture its output, so we use a pipe for that purpose.
471 size_t line_bufsz
= 0;
476 pipe_f
= fdopen(pipes
[0], "r");
477 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
481 char *endptr
= NULL
, *saveptr
= NULL
;
483 /* If we already found something, just continue to read
484 * until the pipe doesn't deliver any more data, but
485 * don't modify the existing data structure.
490 /* Trim line on the right hand side. */
491 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
494 /* Split into tokens: first: user name. */
495 token
= strtok_r(line
, ":", &saveptr
);
498 /* next: dummy password field */
499 token
= strtok_r(NULL
, ":", &saveptr
);
503 token
= strtok_r(NULL
, ":", &saveptr
);
504 value
= token
? strtol(token
, &endptr
, 10) : 0;
505 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
|| value
== LONG_MAX
)
507 /* dummy sanity check: user id matches */
508 if ((uid_t
) value
!= uid
)
510 /* skip fields: gid, gecos, dir, go to next field 'shell' */
511 for (i
= 0; i
< 4; i
++) {
512 token
= strtok_r(NULL
, ":", &saveptr
);
519 result
= strdup(token
);
521 /* Sanity check that there are no fields after that. */
522 token
= strtok_r(NULL
, ":", &saveptr
);
532 if (waitpid(pid
, &status
, 0) < 0) {
539 /* Some sanity checks. If anything even hinted at going wrong,
540 * we can't be sure we have a valid result, so we assume we
544 if (!WIFEXITED(status
)) {
549 if (WEXITSTATUS(status
) != 0) {
562 char *arguments
[] = {
571 /* We want to capture stdout. */
575 /* Get rid of stdin/stderr, so we try to associate it with
578 fd
= open("/dev/null", O_RDWR
);
588 /* Finish argument list. */
589 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long) uid
);
593 /* Try to run getent program. */
594 (void) execvp("getent", arguments
);
599 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
602 char proc_fn
[__PROC_STATUS_LEN
];
605 size_t line_bufsz
= 0;
607 uid_t uid
= (uid_t
)-1;
608 gid_t gid
= (gid_t
)-1;
610 /* Read capabilities. */
611 snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
613 proc_file
= fopen(proc_fn
, "r");
617 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
618 /* Format is: real, effective, saved set user, fs we only care
621 ret
= sscanf(line
, "Uid: %ld", &value
);
622 if (ret
!= EOF
&& ret
== 1) {
625 ret
= sscanf(line
, "Gid: %ld", &value
);
626 if (ret
!= EOF
&& ret
== 1)
629 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
636 /* Only override arguments if we found something. */
637 if (uid
!= (uid_t
)-1)
639 if (gid
!= (gid_t
)-1)
642 /* TODO: we should also parse supplementary groups and use
643 * setgroups() to set them.
647 /* Help the optimizer along if it doesn't know that exit always exits. */
655 /* Define default options if no options are supplied by the user. */
656 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
658 static bool fetch_seccomp(struct lxc_container
*c
,
659 lxc_attach_options_t
*options
)
663 if (!(options
->namespaces
& CLONE_NEWNS
) ||
664 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
665 free(c
->lxc_conf
->seccomp
);
666 c
->lxc_conf
->seccomp
= NULL
;
670 /* Remove current setting. */
671 if (!c
->set_config_item(c
, "lxc.seccomp", "") &&
672 !c
->set_config_item(c
, "lxc.seccomp.profile", "")) {
676 /* Fetch the current profile path over the cmd interface. */
677 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
679 INFO("Failed to get running config item for lxc.seccomp.profile");
680 path
= c
->get_running_config_item(c
, "lxc.seccomp");
683 INFO("Failed to get running config item for lxc.seccomp");
687 /* Copy the value into the new lxc_conf. */
688 if (!c
->set_config_item(c
, "lxc.seccomp.profile", path
)) {
694 /* Attempt to parse the resulting config. */
695 if (lxc_read_seccomp_config(c
->lxc_conf
) < 0) {
696 ERROR("Error reading seccomp policy.");
700 INFO("Retrieved seccomp policy.");
704 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
708 /* Remove current setting. */
709 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
712 /* Retrieve currently active setting. */
713 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
715 INFO("Failed to get running config item for lxc.no_new_privs.");
719 /* Set currently active setting. */
720 if (!c
->set_config_item(c
, "lxc.no_new_privs", val
)) {
729 static signed long get_personality(const char *name
, const char *lxcpath
)
734 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
738 ret
= lxc_config_parse_arch(p
);
744 struct attach_clone_payload
{
746 int terminal_slave_fd
;
747 lxc_attach_options_t
*options
;
748 struct lxc_proc_context_info
*init_ctx
;
749 lxc_attach_exec_t exec_function
;
753 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
755 if (p
->ipc_socket
>= 0) {
756 shutdown(p
->ipc_socket
, SHUT_RDWR
);
757 close(p
->ipc_socket
);
758 p
->ipc_socket
= -EBADF
;
761 if (p
->terminal_slave_fd
>= 0) {
762 close(p
->terminal_slave_fd
);
763 p
->terminal_slave_fd
= -EBADF
;
767 lxc_proc_put_context_info(p
->init_ctx
);
772 static int attach_child_main(struct attach_clone_payload
*payload
)
777 lxc_attach_options_t
* options
= payload
->options
;
778 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
779 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
780 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
783 /* A description of the purpose of this functionality is provided in the
784 * lxc-attach(1) manual page. We have to remount here and not in the
785 * parent process, otherwise /proc may not properly reflect the new pid
788 if (!(options
->namespaces
& CLONE_NEWNS
) &&
789 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
790 ret
= lxc_attach_remount_sys_proc();
793 TRACE("Remounted \"/proc\" and \"/sys\"");
796 /* Now perform additional attachments. */
797 #if HAVE_SYS_PERSONALITY_H
798 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
799 long new_personality
;
801 if (options
->personality
< 0)
802 new_personality
= init_ctx
->personality
;
804 new_personality
= options
->personality
;
805 ret
= personality(new_personality
);
808 TRACE("Set new personality");
812 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
813 ret
= lxc_attach_drop_privs(init_ctx
);
816 TRACE("Dropped capabilities");
819 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
820 * if you want this to be a no-op).
822 ret
= lxc_attach_set_environment(init_ctx
,
824 options
->extra_env_vars
,
825 options
->extra_keep_env
);
828 TRACE("Set up environment");
830 /* This remark only affects fully unprivileged containers:
831 * Receive fd for LSM security module before we set{g,u}id(). The reason
832 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
833 * we will change our effective uid. This means our effective uid will
834 * be different from the effective uid of the process that created us
835 * which means that this processs no longer has capabilities in our
836 * namespace including CAP_SYS_PTRACE. This means we will not be able to
837 * read and /proc/<pid> files for the process anymore when /proc is
838 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
842 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
845 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
848 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
849 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
857 /* Ignore errors, we will fall back to root in that case (/proc was not
860 if (options
->namespaces
& CLONE_NEWUSER
)
861 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
863 if (options
->uid
!= (uid_t
)-1)
864 new_uid
= options
->uid
;
865 if (options
->gid
!= (gid_t
)-1)
866 new_gid
= options
->gid
;
868 /* Try to set the {u,g}id combination. */
869 if (new_uid
!= 0 || new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) {
870 ret
= lxc_switch_uid_gid(new_uid
, new_gid
);
875 ret
= lxc_setgroups(0, NULL
);
876 if (ret
< 0 && errno
!= EPERM
)
879 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
880 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
881 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
882 ret
= prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0);
885 TRACE("Set PR_SET_NO_NEW_PRIVS");
891 /* Change into our new LSM profile. */
892 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
);
897 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
900 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
901 init_ctx
->container
->lxc_conf
->seccomp
) {
902 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
905 TRACE("Loaded seccomp profile");
907 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
908 close(payload
->ipc_socket
);
909 payload
->ipc_socket
= -EBADF
;
910 lxc_proc_put_context_info(init_ctx
);
912 /* The following is done after the communication socket is shut down.
913 * That way, all errors that might (though unlikely) occur up until this
914 * point will have their messages printed to the original stderr (if
915 * logging is so configured) and not the fd the user supplied, if any.
918 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
919 * may want to make sure the fds are closed, for example.
921 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
922 dup2(options
->stdin_fd
, STDIN_FILENO
);
924 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
925 dup2(options
->stdout_fd
, STDOUT_FILENO
);
927 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
928 dup2(options
->stderr_fd
, STDERR_FILENO
);
930 /* close the old fds */
931 if (options
->stdin_fd
> STDERR_FILENO
)
932 close(options
->stdin_fd
);
934 if (options
->stdout_fd
> STDERR_FILENO
)
935 close(options
->stdout_fd
);
937 if (options
->stderr_fd
> STDERR_FILENO
)
938 close(options
->stderr_fd
);
940 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
941 * here, ignore errors.
943 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
946 flags
= fcntl(fd
, F_GETFL
);
950 if ((flags
& FD_CLOEXEC
) == 0)
953 ret
= fcntl(fd
, F_SETFL
, flags
& ~FD_CLOEXEC
);
955 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
960 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
961 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
963 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
966 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
969 /* We're done, so we can now do whatever the user intended us to do. */
970 rexit(payload
->exec_function(payload
->exec_payload
));
973 lxc_put_attach_clone_payload(payload
);
977 static int lxc_attach_terminal(struct lxc_conf
*conf
,
978 struct lxc_terminal
*terminal
)
982 lxc_terminal_init(terminal
);
984 ret
= lxc_terminal_create(terminal
);
986 SYSERROR("Failed to create terminal");
990 /* Shift ttys to container. */
991 ret
= lxc_terminal_map_ids(conf
, terminal
);
993 ERROR("Failed to chown terminal");
1000 lxc_terminal_delete(terminal
);
1001 lxc_terminal_conf_free(terminal
);
1005 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
1006 struct lxc_epoll_descr
*descr
)
1010 ret
= lxc_mainloop_open(descr
);
1012 ERROR("Failed to create mainloop");
1016 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
1018 ERROR("Failed to add handlers to mainloop");
1019 lxc_mainloop_close(descr
);
1026 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
1028 if (terminal
->master
< 0)
1031 close(terminal
->master
);
1032 terminal
->master
= -EBADF
;
1035 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
1037 if (terminal
->slave
< 0)
1040 close(terminal
->slave
);
1041 terminal
->slave
= -EBADF
;
1044 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
1046 if (terminal
->peer
< 0)
1049 close(terminal
->peer
);
1050 terminal
->peer
= -EBADF
;
1053 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1055 if (terminal
->log_fd
< 0)
1058 close(terminal
->log_fd
);
1059 terminal
->log_fd
= -EBADF
;
1062 int lxc_attach(const char *name
, const char *lxcpath
,
1063 lxc_attach_exec_t exec_function
, void *exec_payload
,
1064 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1068 char *cwd
, *new_cwd
;
1069 signed long personality
;
1070 pid_t attached_pid
, init_pid
, pid
;
1071 struct lxc_proc_context_info
*init_ctx
;
1072 struct lxc_terminal terminal
;
1073 struct lxc_conf
*conf
;
1074 struct attach_clone_payload payload
= {0};
1076 ret
= access("/proc/self/ns", X_OK
);
1078 ERROR("Does this kernel version support namespaces?");
1083 options
= &attach_static_default_options
;
1085 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1087 ERROR("Failed to get init pid.");
1091 init_ctx
= lxc_proc_get_context_info(init_pid
);
1093 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1097 personality
= get_personality(name
, lxcpath
);
1098 if (init_ctx
->personality
< 0) {
1099 ERROR("Failed to get personality of the container");
1100 lxc_proc_put_context_info(init_ctx
);
1103 init_ctx
->personality
= personality
;
1105 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1106 if (!init_ctx
->container
) {
1107 lxc_proc_put_context_info(init_ctx
);
1111 if (!init_ctx
->container
->lxc_conf
) {
1112 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1113 if (!init_ctx
->container
->lxc_conf
) {
1114 lxc_proc_put_context_info(init_ctx
);
1118 conf
= init_ctx
->container
->lxc_conf
;
1120 if (!fetch_seccomp(init_ctx
->container
, options
))
1121 WARN("Failed to get seccomp policy.");
1123 if (!no_new_privs(init_ctx
->container
, options
))
1124 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set.");
1126 cwd
= getcwd(NULL
, 0);
1128 /* Determine which namespaces the container was created with
1129 * by asking lxc-start, if necessary.
1131 if (options
->namespaces
== -1) {
1132 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1134 if (options
->namespaces
== -1) {
1135 ERROR("Failed to automatically determine the "
1136 "namespaces which the container uses");
1138 lxc_proc_put_context_info(init_ctx
);
1142 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1143 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1144 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1148 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1151 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1155 pid
= lxc_raw_getpid();
1156 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1159 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1160 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1161 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1162 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1165 if (init_ctx
->ns_fd
[i
] >= 0)
1168 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1169 DEBUG("Inheriting %s namespace from %d",
1170 ns_info
[i
].proc_name
, pid
);
1171 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1175 /* We failed to preserve the namespace. */
1176 saved_errno
= errno
;
1177 /* Close all already opened file descriptors before we return an
1178 * error, so we don't leak them.
1180 for (j
= 0; j
< i
; j
++)
1181 close(init_ctx
->ns_fd
[j
]);
1183 errno
= saved_errno
;
1184 SYSERROR("Failed to attach to %s namespace of %d",
1185 ns_info
[i
].proc_name
, pid
);
1187 lxc_proc_put_context_info(init_ctx
);
1191 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1192 ret
= lxc_attach_terminal(conf
, &terminal
);
1194 ERROR("Failed to setup new terminal");
1196 lxc_proc_put_context_info(init_ctx
);
1200 terminal
.log_fd
= options
->log_fd
;
1202 lxc_terminal_init(&terminal
);
1205 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1206 * to make sure we don't irritate other threads that want to fork+exec
1209 * IMPORTANT: if the initial process is multithreaded and another call
1210 * just fork()s away without exec'ing directly after, the socket fd will
1211 * exist in the forked process from the other thread and any close() in
1212 * our own child process will not really cause the socket to close
1213 * properly, potentiall causing the parent to hang.
1215 * For this reason, while IPC is still active, we have to use shutdown()
1216 * if the child exits prematurely in order to signal that the socket is
1217 * closed and cannot assume that the child exiting will automatically do
1220 * IPC mechanism: (X is receiver)
1221 * initial process intermediate attached
1222 * X <--- send pid of
1225 * send 0 ------------------------------------> X
1226 * [do initialization]
1227 * X <------------------------------------ send 1
1228 * [add to cgroup, ...]
1229 * send 2 ------------------------------------> X
1230 * [set LXC_ATTACH_NO_NEW_PRIVS]
1231 * X <------------------------------------ send 3
1232 * [open LSM label fd]
1233 * send 4 ------------------------------------> X
1235 * close socket close socket
1238 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1240 SYSERROR("Could not set up required IPC mechanism for attaching.");
1242 lxc_proc_put_context_info(init_ctx
);
1246 /* Create intermediate subprocess, two reasons:
1247 * 1. We can't setns() in the child itself, since we want to make
1248 * sure we are properly attached to the pidns.
1249 * 2. Also, the initial thread has to put the attached process
1250 * into the cgroup, which we can only do if we didn't already
1251 * setns() (otherwise, user namespaces will hate us).
1255 SYSERROR("Failed to create first subprocess.");
1257 lxc_proc_put_context_info(init_ctx
);
1262 int ret_parent
= -1;
1263 pid_t to_cleanup_pid
= pid
;
1264 struct lxc_epoll_descr descr
= {0};
1266 /* close unneeded file descriptors */
1267 close(ipc_sockets
[1]);
1269 lxc_proc_close_ns_fd(init_ctx
);
1270 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1271 lxc_attach_terminal_close_slave(&terminal
);
1273 /* Attach to cgroup, if requested. */
1274 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1275 struct cgroup_ops
*cgroup_ops
;
1277 cgroup_ops
= cgroup_init(NULL
);
1281 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1284 cgroup_exit(cgroup_ops
);
1285 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1288 /* Setup /proc limits */
1289 if (!lxc_list_empty(&conf
->procs
)) {
1290 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1295 /* Setup resource limits */
1296 if (!lxc_list_empty(&conf
->limits
)) {
1297 ret
= setup_resource_limits(&conf
->limits
, pid
);
1302 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1303 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1306 TRACE("Initialized terminal mainloop");
1309 /* Let the child process know to go ahead. */
1311 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1312 if (ret
!= sizeof(status
))
1313 goto close_mainloop
;
1314 TRACE("Told intermediate process to start initializing");
1316 /* Get pid of attached process from intermediate process. */
1317 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1318 if (ret
!= sizeof(attached_pid
))
1319 goto close_mainloop
;
1320 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1322 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1323 if (options
->stdin_fd
== 0) {
1324 signal(SIGINT
, SIG_IGN
);
1325 signal(SIGQUIT
, SIG_IGN
);
1328 /* Reap intermediate process. */
1329 ret
= wait_for_pid(pid
);
1331 goto close_mainloop
;
1332 TRACE("Intermediate process %d exited", pid
);
1334 /* We will always have to reap the attached process now. */
1335 to_cleanup_pid
= attached_pid
;
1337 /* Open LSM fd and send it to child. */
1338 if ((options
->namespaces
& CLONE_NEWNS
) &&
1339 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1340 init_ctx
->lsm_label
) {
1345 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1346 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1348 goto close_mainloop
;
1349 TRACE("Opened LSM label file descriptor %d", labelfd
);
1351 /* Send child fd of the LSM security module to write to. */
1352 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1355 SYSERROR("%d", (int)ret
);
1356 goto close_mainloop
;
1358 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1361 /* We're done, the child process should now execute whatever it
1362 * is that the user requested. The parent can now track it with
1363 * waitpid() or similar.
1366 *attached_process
= attached_pid
;
1368 /* Now shut down communication with child, we're done. */
1369 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1370 close(ipc_sockets
[0]);
1371 ipc_sockets
[0] = -1;
1374 to_cleanup_pid
= -1;
1375 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1376 ret
= lxc_mainloop(&descr
, -1);
1379 to_cleanup_pid
= attached_pid
;
1384 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1385 lxc_mainloop_close(&descr
);
1388 if (ipc_sockets
[0] >= 0) {
1389 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1390 close(ipc_sockets
[0]);
1393 if (to_cleanup_pid
> 0)
1394 (void)wait_for_pid(to_cleanup_pid
);
1396 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1397 lxc_terminal_delete(&terminal
);
1398 lxc_terminal_conf_free(&terminal
);
1400 lxc_proc_put_context_info(init_ctx
);
1404 /* close unneeded file descriptors */
1405 close(ipc_sockets
[0]);
1406 ipc_sockets
[0] = -EBADF
;
1407 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1408 lxc_attach_terminal_close_master(&terminal
);
1409 lxc_attach_terminal_close_peer(&terminal
);
1410 lxc_attach_terminal_close_log(&terminal
);
1413 /* Wait for the parent to have setup cgroups. */
1414 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1415 if (ret
!= sizeof(status
)) {
1416 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1417 lxc_proc_put_context_info(init_ctx
);
1420 TRACE("Intermediate process starting to initialize");
1422 /* Attach now, create another subprocess later, since pid namespaces
1423 * only really affect the children of the current process.
1425 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1427 ERROR("Failed to enter namespaces");
1428 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1429 lxc_proc_put_context_info(init_ctx
);
1432 /* close namespace file descriptors */
1433 lxc_proc_close_ns_fd(init_ctx
);
1435 /* Attach succeeded, try to cwd. */
1436 if (options
->initial_cwd
)
1437 new_cwd
= options
->initial_cwd
;
1441 ret
= chdir(new_cwd
);
1443 WARN("Could not change directory to \"%s\"", new_cwd
);
1447 /* Create attached process. */
1448 payload
.ipc_socket
= ipc_sockets
[1];
1449 payload
.options
= options
;
1450 payload
.init_ctx
= init_ctx
;
1451 payload
.terminal_slave_fd
= terminal
.slave
;
1452 payload
.exec_function
= exec_function
;
1453 payload
.exec_payload
= exec_payload
;
1455 pid
= lxc_raw_clone(CLONE_PARENT
);
1457 SYSERROR("Failed to clone attached process");
1458 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1459 lxc_proc_put_context_info(init_ctx
);
1464 ret
= attach_child_main(&payload
);
1466 ERROR("Failed to exec");
1467 _exit(EXIT_FAILURE
);
1469 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1470 lxc_attach_terminal_close_slave(&terminal
);
1472 /* Tell grandparent the pid of the pid of the newly created child. */
1473 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1474 if (ret
!= sizeof(pid
)) {
1475 /* If this really happens here, this is very unfortunate, since
1476 * the parent will not know the pid of the attached process and
1477 * will not be able to wait for it (and we won't either due to
1478 * CLONE_PARENT) so the parent won't be able to reap it and the
1479 * attached process will remain a zombie.
1481 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1482 lxc_proc_put_context_info(init_ctx
);
1485 TRACE("Sending pid %d of attached process", pid
);
1487 /* The rest is in the hands of the initial and the attached process. */
1488 lxc_proc_put_context_info(init_ctx
);
1492 int lxc_attach_run_command(void* payload
)
1494 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1496 execvp(cmd
->program
, cmd
->argv
);
1497 SYSERROR("Failed to exec \"%s\".", cmd
->program
);
1501 int lxc_attach_run_shell(void* payload
)
1504 struct passwd
*passwd
;
1507 /* Ignore payload parameter. */
1511 passwd
= getpwuid(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
= passwd
->pw_shell
;
1524 execlp(user_shell
, user_shell
, (char *)NULL
);
1526 /* Executed if either no passwd entry or execvp fails, we will fall back
1527 * on /bin/sh as a default shell.
1529 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1530 SYSERROR("Failed to execute shell");