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
35 #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>
43 #include <lxc/lxccontainer.h>
45 #ifndef HAVE_DECL_PR_CAPBSET_DROP
46 #define PR_CAPBSET_DROP 24
49 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
50 #define PR_SET_NO_NEW_PRIVS 38
53 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
54 #define PR_GET_NO_NEW_PRIVS 39
68 #include "lxcseccomp.h"
70 #include "namespace.h"
74 #if HAVE_SYS_PERSONALITY_H
75 #include <sys/personality.h>
79 #define SOCK_CLOEXEC 02000000
87 #define MS_SLAVE (1 << 19)
90 lxc_log_define(attach
, lxc
);
92 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
93 #define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
94 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
99 char proc_fn
[__PROC_STATUS_LEN
];
100 size_t line_bufsz
= 0;
102 struct lxc_proc_context_info
*info
= NULL
;
104 /* Read capabilities. */
105 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
106 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
109 proc_file
= fopen(proc_fn
, "r");
111 SYSERROR("Could not open %s", proc_fn
);
115 info
= calloc(1, sizeof(*info
));
117 SYSERROR("Could not allocate memory");
124 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
125 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
126 if (ret
!= EOF
&& ret
== 1) {
136 ERROR("Could not read capability bounding set from %s",
141 info
->lsm_label
= lsm_process_label_get(pid
);
142 info
->ns_inherited
= 0;
143 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
152 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
156 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
157 if (ctx
->ns_fd
[i
] < 0)
160 close(ctx
->ns_fd
[i
]);
161 ctx
->ns_fd
[i
] = -EBADF
;
165 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
167 free(ctx
->lsm_label
);
168 ctx
->lsm_label
= NULL
;
170 if (ctx
->container
) {
171 lxc_container_put(ctx
->container
);
172 ctx
->container
= NULL
;
175 lxc_proc_close_ns_fd(ctx
);
180 * in_same_namespace - Check whether two processes are in the same namespace.
181 * @pid1 - PID of the first process.
182 * @pid2 - PID of the second process.
183 * @ns - Name of the namespace to check. Must correspond to one of the names
184 * for the namespaces as shown in /proc/<pid/ns/
186 * If the two processes are not in the same namespace returns an fd to the
187 * namespace of the second process identified by @pid2. If the two processes are
188 * in the same namespace returns -EINVAL, -1 if an error occurred.
190 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
192 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
194 struct stat ns_st1
, ns_st2
;
196 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
198 /* The kernel does not support this namespace. This is not an
207 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
211 ret
= fstat(ns_fd1
, &ns_st1
);
215 ret
= fstat(ns_fd2
, &ns_st2
);
219 /* processes are in the same namespace */
220 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
)) {
225 /* processes are in different namespaces */
242 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
246 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
247 if (ctx
->ns_fd
[i
] < 0)
250 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
252 SYSERROR("Failed to attach to %s namespace of %d",
253 ns_info
[i
].proc_name
, pid
);
257 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
263 static int lxc_attach_remount_sys_proc(void)
267 ret
= unshare(CLONE_NEWNS
);
269 SYSERROR("Failed to unshare mount namespace");
273 if (detect_shared_rootfs()) {
274 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
275 SYSERROR("Failed to make / rslave");
276 ERROR("Continuing...");
280 /* Assume /proc is always mounted, so remount it. */
281 ret
= umount2("/proc", MNT_DETACH
);
283 SYSERROR("Failed to unmount /proc");
287 ret
= mount("none", "/proc", "proc", 0, NULL
);
289 SYSERROR("Failed to remount /proc");
293 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
294 * we ignore it because it may not have been mounted in the first place.
296 ret
= umount2("/sys", MNT_DETACH
);
297 if (ret
< 0 && errno
!= EINVAL
) {
298 SYSERROR("Failed to unmount /sys");
300 } else if (ret
== 0) {
302 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
304 SYSERROR("Failed to remount /sys");
312 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
316 last_cap
= lxc_caps_last_cap();
317 for (cap
= 0; cap
<= last_cap
; cap
++) {
318 if (ctx
->capability_mask
& (1LL << cap
))
321 if (prctl(PR_CAPBSET_DROP
, cap
, 0, 0, 0)) {
322 SYSERROR("Failed to drop capability %d", cap
);
326 TRACE("Dropped capability %d", cap
);
332 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
333 enum lxc_attach_env_policy_t policy
,
334 char **extra_env
, char **extra_keep
)
337 struct lxc_list
*iterator
;
339 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
341 char **extra_keep_store
= NULL
;
346 for (count
= 0; extra_keep
[count
]; count
++)
349 extra_keep_store
= calloc(count
, sizeof(char *));
350 if (!extra_keep_store
)
353 for (i
= 0; i
< count
; i
++) {
354 char *v
= getenv(extra_keep
[i
]);
356 extra_keep_store
[i
] = strdup(v
);
357 if (!extra_keep_store
[i
]) {
359 free(extra_keep_store
[--i
]);
361 free(extra_keep_store
);
365 if (strcmp(extra_keep
[i
], "PATH") == 0)
372 if (extra_keep_store
) {
375 for (p
= extra_keep_store
; *p
; p
++)
378 free(extra_keep_store
);
381 ERROR("Failed to clear environment");
385 if (extra_keep_store
) {
388 for (i
= 0; extra_keep
[i
]; i
++) {
389 if (extra_keep_store
[i
]) {
390 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
392 SYSWARN("Failed to set environment variable");
395 free(extra_keep_store
[i
]);
398 free(extra_keep_store
);
401 /* Always set a default path; shells and execlp tend to be fine
402 * without it, but there is a disturbing number of C programs
403 * out there that just assume that getenv("PATH") is never NULL
404 * and then die a painful segfault death.
407 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
409 SYSWARN("Failed to set environment variable");
413 ret
= putenv("container=lxc");
415 SYSWARN("Failed to set environment variable");
419 /* Set container environment variables.*/
420 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
421 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
424 env_tmp
= strdup((char *)iterator
->elem
);
428 ret
= putenv(env_tmp
);
430 SYSERROR("Failed to set environment variable: %s", (char *)iterator
->elem
);
436 /* Set extra environment variables. */
438 for (; *extra_env
; extra_env
++) {
441 /* We just assume the user knows what they are doing, so
442 * we don't do any checks.
444 p
= strdup(*extra_env
);
450 SYSWARN("Failed to set environment variable");
457 static char *lxc_attach_getpwshell(uid_t uid
)
464 size_t line_bufsz
= 0;
465 char *line
= NULL
, *result
= NULL
;
467 /* We need to fork off a process that runs the getent program, and we
468 * need to capture its output, so we use a pipe for that purpose.
470 ret
= pipe2(pipes
, O_CLOEXEC
);
483 char *arguments
[] = {
492 /* We want to capture stdout. */
493 ret
= dup2(pipes
[1], STDOUT_FILENO
);
498 /* Get rid of stdin/stderr, so we try to associate it with
504 close(STDERR_FILENO
);
506 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
507 (void)dup3(fd
, STDOUT_FILENO
, O_CLOEXEC
);
511 /* Finish argument list. */
512 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
513 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
516 /* Try to run getent program. */
517 (void)execvp("getent", arguments
);
523 pipe_f
= fdopen(pipes
[0], "r");
524 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
528 char *endptr
= NULL
, *saveptr
= NULL
;
530 /* If we already found something, just continue to read
531 * until the pipe doesn't deliver any more data, but
532 * don't modify the existing data structure.
540 /* Trim line on the right hand side. */
541 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
544 /* Split into tokens: first: user name. */
545 token
= strtok_r(line
, ":", &saveptr
);
549 /* next: dummy password field */
550 token
= strtok_r(NULL
, ":", &saveptr
);
555 token
= strtok_r(NULL
, ":", &saveptr
);
556 value
= token
? strtol(token
, &endptr
, 10) : 0;
557 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
561 /* dummy sanity check: user id matches */
562 if ((uid_t
)value
!= uid
)
565 /* skip fields: gid, gecos, dir, go to next field 'shell' */
566 for (i
= 0; i
< 4; i
++) {
567 token
= strtok_r(NULL
, ":", &saveptr
);
576 result
= strdup(token
);
578 /* Sanity check that there are no fields after that. */
579 token
= strtok_r(NULL
, ":", &saveptr
);
589 ret
= wait_for_pid(pid
);
603 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
606 char proc_fn
[__PROC_STATUS_LEN
];
609 size_t line_bufsz
= 0;
611 uid_t uid
= (uid_t
)-1;
612 gid_t gid
= (gid_t
)-1;
614 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
615 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
618 proc_file
= fopen(proc_fn
, "r");
622 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
623 /* Format is: real, effective, saved set user, fs we only care
626 ret
= sscanf(line
, "Uid: %ld", &value
);
627 if (ret
!= EOF
&& ret
== 1) {
630 ret
= sscanf(line
, "Gid: %ld", &value
);
631 if (ret
!= EOF
&& ret
== 1)
635 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
642 /* Only override arguments if we found something. */
643 if (uid
!= (uid_t
)-1)
646 if (gid
!= (gid_t
)-1)
649 /* TODO: we should also parse supplementary groups and use
650 * setgroups() to set them.
654 /* Help the optimizer along if it doesn't know that exit always exits. */
662 /* Define default options if no options are supplied by the user. */
663 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
665 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
671 if (!(options
->namespaces
& CLONE_NEWNS
) ||
672 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
673 free(c
->lxc_conf
->seccomp
);
674 c
->lxc_conf
->seccomp
= NULL
;
678 /* Remove current setting. */
679 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
680 !c
->set_config_item(c
, "lxc.seccomp", ""))
683 /* Fetch the current profile path over the cmd interface. */
684 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
686 INFO("Failed to retrieve lxc.seccomp.profile");
688 path
= c
->get_running_config_item(c
, "lxc.seccomp");
690 INFO("Failed to retrieve lxc.seccomp");
695 /* Copy the value into the new lxc_conf. */
696 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
701 /* Attempt to parse the resulting config. */
702 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
704 ERROR("Failed to retrieve seccomp policy");
708 INFO("Retrieved seccomp policy");
712 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
717 /* Remove current setting. */
718 if (!c
->set_config_item(c
, "lxc.no_new_privs", "")) {
719 INFO("Failed to unset lxc.no_new_privs");
723 /* Retrieve currently active setting. */
724 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
726 INFO("Failed to retrieve lxc.no_new_privs");
730 /* Set currently active setting. */
731 bret
= c
->set_config_item(c
, "lxc.no_new_privs", val
);
736 static signed long get_personality(const char *name
, const char *lxcpath
)
741 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
745 ret
= lxc_config_parse_arch(p
);
751 struct attach_clone_payload
{
753 int terminal_slave_fd
;
754 lxc_attach_options_t
*options
;
755 struct lxc_proc_context_info
*init_ctx
;
756 lxc_attach_exec_t exec_function
;
760 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
762 if (p
->ipc_socket
>= 0) {
763 shutdown(p
->ipc_socket
, SHUT_RDWR
);
764 close(p
->ipc_socket
);
765 p
->ipc_socket
= -EBADF
;
768 if (p
->terminal_slave_fd
>= 0) {
769 close(p
->terminal_slave_fd
);
770 p
->terminal_slave_fd
= -EBADF
;
774 lxc_proc_put_context_info(p
->init_ctx
);
779 static int attach_child_main(struct attach_clone_payload
*payload
)
784 lxc_attach_options_t
* options
= payload
->options
;
785 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
786 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
787 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
790 /* A description of the purpose of this functionality is provided in the
791 * lxc-attach(1) manual page. We have to remount here and not in the
792 * parent process, otherwise /proc may not properly reflect the new pid
795 if (!(options
->namespaces
& CLONE_NEWNS
) &&
796 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
797 ret
= lxc_attach_remount_sys_proc();
801 TRACE("Remounted \"/proc\" and \"/sys\"");
804 /* Now perform additional attachments. */
805 #if HAVE_SYS_PERSONALITY_H
806 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
807 long new_personality
;
809 if (options
->personality
< 0)
810 new_personality
= init_ctx
->personality
;
812 new_personality
= options
->personality
;
814 ret
= personality(new_personality
);
818 TRACE("Set new personality");
822 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
823 ret
= lxc_attach_drop_privs(init_ctx
);
827 TRACE("Dropped capabilities");
830 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
831 * if you want this to be a no-op).
833 ret
= lxc_attach_set_environment(init_ctx
,
835 options
->extra_env_vars
,
836 options
->extra_keep_env
);
840 TRACE("Set up environment");
842 /* This remark only affects fully unprivileged containers:
843 * Receive fd for LSM security module before we set{g,u}id(). The reason
844 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
845 * we will change our effective uid. This means our effective uid will
846 * be different from the effective uid of the process that created us
847 * which means that this processs no longer has capabilities in our
848 * namespace including CAP_SYS_PTRACE. This means we will not be able to
849 * read and /proc/<pid> files for the process anymore when /proc is
850 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
854 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
857 SYSERROR("Failed to receive lsm label fd");
862 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
865 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
866 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
875 /* Ignore errors, we will fall back to root in that case (/proc was not
878 if (options
->namespaces
& CLONE_NEWUSER
)
879 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
881 if (options
->uid
!= (uid_t
)-1)
882 new_uid
= options
->uid
;
884 if (options
->gid
!= (gid_t
)-1)
885 new_gid
= options
->gid
;
887 /* Try to set the {u,g}id combination. */
888 if (new_uid
!= 0 || new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) {
889 ret
= lxc_switch_uid_gid(new_uid
, new_gid
);
894 ret
= lxc_setgroups(0, NULL
);
895 if (ret
< 0 && errno
!= EPERM
)
898 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
899 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
900 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
901 ret
= prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0);
905 TRACE("Set PR_SET_NO_NEW_PRIVS");
911 /* Change into our new LSM profile. */
912 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
914 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
919 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
922 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
923 init_ctx
->container
->lxc_conf
->seccomp
) {
924 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
928 TRACE("Loaded seccomp profile");
931 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
932 close(payload
->ipc_socket
);
933 payload
->ipc_socket
= -EBADF
;
934 lxc_proc_put_context_info(init_ctx
);
935 payload
->init_ctx
= NULL
;
937 /* The following is done after the communication socket is shut down.
938 * That way, all errors that might (though unlikely) occur up until this
939 * point will have their messages printed to the original stderr (if
940 * logging is so configured) and not the fd the user supplied, if any.
943 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
944 * may want to make sure the fds are closed, for example.
946 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
947 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
949 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
950 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
952 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
953 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
955 /* close the old fds */
956 if (options
->stdin_fd
> STDERR_FILENO
)
957 close(options
->stdin_fd
);
959 if (options
->stdout_fd
> STDERR_FILENO
)
960 close(options
->stdout_fd
);
962 if (options
->stderr_fd
> STDERR_FILENO
)
963 close(options
->stderr_fd
);
965 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
966 * here, ignore errors.
968 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
969 ret
= fd_cloexec(fd
, false);
971 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
976 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
977 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
979 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
983 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
986 /* We're done, so we can now do whatever the user intended us to do. */
987 rexit(payload
->exec_function(payload
->exec_payload
));
990 lxc_put_attach_clone_payload(payload
);
994 static int lxc_attach_terminal(struct lxc_conf
*conf
,
995 struct lxc_terminal
*terminal
)
999 lxc_terminal_init(terminal
);
1001 ret
= lxc_terminal_create(terminal
);
1003 ERROR("Failed to create terminal");
1007 /* Shift ttys to container. */
1008 ret
= lxc_terminal_map_ids(conf
, terminal
);
1010 ERROR("Failed to chown terminal");
1017 lxc_terminal_delete(terminal
);
1018 lxc_terminal_conf_free(terminal
);
1022 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
1023 struct lxc_epoll_descr
*descr
)
1027 ret
= lxc_mainloop_open(descr
);
1029 ERROR("Failed to create mainloop");
1033 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
1035 ERROR("Failed to add handlers to mainloop");
1036 lxc_mainloop_close(descr
);
1043 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
1045 if (terminal
->master
< 0)
1048 close(terminal
->master
);
1049 terminal
->master
= -EBADF
;
1052 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
1054 if (terminal
->slave
< 0)
1057 close(terminal
->slave
);
1058 terminal
->slave
= -EBADF
;
1061 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
1063 if (terminal
->peer
< 0)
1066 close(terminal
->peer
);
1067 terminal
->peer
= -EBADF
;
1070 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1072 if (terminal
->log_fd
< 0)
1075 close(terminal
->log_fd
);
1076 terminal
->log_fd
= -EBADF
;
1079 int lxc_attach(const char *name
, const char *lxcpath
,
1080 lxc_attach_exec_t exec_function
, void *exec_payload
,
1081 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1085 char *cwd
, *new_cwd
;
1086 signed long personality
;
1087 pid_t attached_pid
, init_pid
, pid
;
1088 struct lxc_proc_context_info
*init_ctx
;
1089 struct lxc_terminal terminal
;
1090 struct lxc_conf
*conf
;
1091 struct attach_clone_payload payload
= {0};
1093 ret
= access("/proc/self/ns", X_OK
);
1095 SYSERROR("Does this kernel version support namespaces?");
1100 options
= &attach_static_default_options
;
1102 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1104 ERROR("Failed to get init pid");
1108 init_ctx
= lxc_proc_get_context_info(init_pid
);
1110 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1114 personality
= get_personality(name
, lxcpath
);
1115 if (init_ctx
->personality
< 0) {
1116 ERROR("Failed to get personality of the container");
1117 lxc_proc_put_context_info(init_ctx
);
1120 init_ctx
->personality
= personality
;
1122 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1123 if (!init_ctx
->container
) {
1124 lxc_proc_put_context_info(init_ctx
);
1128 if (!init_ctx
->container
->lxc_conf
) {
1129 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1130 if (!init_ctx
->container
->lxc_conf
) {
1131 lxc_proc_put_context_info(init_ctx
);
1135 conf
= init_ctx
->container
->lxc_conf
;
1137 if (!fetch_seccomp(init_ctx
->container
, options
))
1138 WARN("Failed to get seccomp policy");
1140 if (!no_new_privs(init_ctx
->container
, options
))
1141 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1143 cwd
= getcwd(NULL
, 0);
1145 /* Determine which namespaces the container was created with
1146 * by asking lxc-start, if necessary.
1148 if (options
->namespaces
== -1) {
1149 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1151 if (options
->namespaces
== -1) {
1152 ERROR("Failed to automatically determine the "
1153 "namespaces which the container uses");
1155 lxc_proc_put_context_info(init_ctx
);
1159 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1160 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1161 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1165 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1168 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1172 pid
= lxc_raw_getpid();
1174 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1177 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1178 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1179 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1180 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1184 if (init_ctx
->ns_fd
[i
] >= 0)
1187 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1188 DEBUG("Inheriting %s namespace from %d",
1189 ns_info
[i
].proc_name
, pid
);
1190 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1194 /* We failed to preserve the namespace. */
1195 SYSERROR("Failed to attach to %s namespace of %d",
1196 ns_info
[i
].proc_name
, pid
);
1198 /* Close all already opened file descriptors before we return an
1199 * error, so we don't leak them.
1201 for (j
= 0; j
< i
; j
++)
1202 close(init_ctx
->ns_fd
[j
]);
1205 lxc_proc_put_context_info(init_ctx
);
1209 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1210 ret
= lxc_attach_terminal(conf
, &terminal
);
1212 ERROR("Failed to setup new terminal");
1214 lxc_proc_put_context_info(init_ctx
);
1218 terminal
.log_fd
= options
->log_fd
;
1220 lxc_terminal_init(&terminal
);
1223 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1224 * to make sure we don't irritate other threads that want to fork+exec
1227 * IMPORTANT: if the initial process is multithreaded and another call
1228 * just fork()s away without exec'ing directly after, the socket fd will
1229 * exist in the forked process from the other thread and any close() in
1230 * our own child process will not really cause the socket to close
1231 * properly, potentiall causing the parent to hang.
1233 * For this reason, while IPC is still active, we have to use shutdown()
1234 * if the child exits prematurely in order to signal that the socket is
1235 * closed and cannot assume that the child exiting will automatically do
1238 * IPC mechanism: (X is receiver)
1239 * initial process intermediate attached
1240 * X <--- send pid of
1243 * send 0 ------------------------------------> X
1244 * [do initialization]
1245 * X <------------------------------------ send 1
1246 * [add to cgroup, ...]
1247 * send 2 ------------------------------------> X
1248 * [set LXC_ATTACH_NO_NEW_PRIVS]
1249 * X <------------------------------------ send 3
1250 * [open LSM label fd]
1251 * send 4 ------------------------------------> X
1253 * close socket close socket
1256 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1258 SYSERROR("Could not set up required IPC mechanism for attaching");
1260 lxc_proc_put_context_info(init_ctx
);
1264 /* Create intermediate subprocess, two reasons:
1265 * 1. We can't setns() in the child itself, since we want to make
1266 * sure we are properly attached to the pidns.
1267 * 2. Also, the initial thread has to put the attached process
1268 * into the cgroup, which we can only do if we didn't already
1269 * setns() (otherwise, user namespaces will hate us).
1273 SYSERROR("Failed to create first subprocess");
1275 lxc_proc_put_context_info(init_ctx
);
1280 int ret_parent
= -1;
1281 pid_t to_cleanup_pid
= pid
;
1282 struct lxc_epoll_descr descr
= {0};
1284 /* close unneeded file descriptors */
1285 close(ipc_sockets
[1]);
1287 lxc_proc_close_ns_fd(init_ctx
);
1288 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1289 lxc_attach_terminal_close_slave(&terminal
);
1291 /* Attach to cgroup, if requested. */
1292 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1293 struct cgroup_ops
*cgroup_ops
;
1295 cgroup_ops
= cgroup_init(NULL
);
1299 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1302 cgroup_exit(cgroup_ops
);
1303 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1306 /* Setup /proc limits */
1307 if (!lxc_list_empty(&conf
->procs
)) {
1308 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1313 /* Setup resource limits */
1314 if (!lxc_list_empty(&conf
->limits
)) {
1315 ret
= setup_resource_limits(&conf
->limits
, pid
);
1320 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1321 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1325 TRACE("Initialized terminal mainloop");
1328 /* Let the child process know to go ahead. */
1330 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1331 if (ret
!= sizeof(status
))
1332 goto close_mainloop
;
1334 TRACE("Told intermediate process to start initializing");
1336 /* Get pid of attached process from intermediate process. */
1337 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1338 if (ret
!= sizeof(attached_pid
))
1339 goto close_mainloop
;
1341 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1343 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1344 if (options
->stdin_fd
== 0) {
1345 signal(SIGINT
, SIG_IGN
);
1346 signal(SIGQUIT
, SIG_IGN
);
1349 /* Reap intermediate process. */
1350 ret
= wait_for_pid(pid
);
1352 goto close_mainloop
;
1354 TRACE("Intermediate process %d exited", pid
);
1356 /* We will always have to reap the attached process now. */
1357 to_cleanup_pid
= attached_pid
;
1359 /* Open LSM fd and send it to child. */
1360 if ((options
->namespaces
& CLONE_NEWNS
) &&
1361 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1362 init_ctx
->lsm_label
) {
1367 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1368 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1370 goto close_mainloop
;
1372 TRACE("Opened LSM label file descriptor %d", labelfd
);
1374 /* Send child fd of the LSM security module to write to. */
1375 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1378 SYSERROR("Failed to send lsm label fd");
1381 goto close_mainloop
;
1385 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1388 /* We're done, the child process should now execute whatever it
1389 * is that the user requested. The parent can now track it with
1390 * waitpid() or similar.
1393 *attached_process
= attached_pid
;
1395 /* Now shut down communication with child, we're done. */
1396 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1397 close(ipc_sockets
[0]);
1398 ipc_sockets
[0] = -1;
1401 to_cleanup_pid
= -1;
1403 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1404 ret
= lxc_mainloop(&descr
, -1);
1407 to_cleanup_pid
= attached_pid
;
1412 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1413 lxc_mainloop_close(&descr
);
1416 if (ipc_sockets
[0] >= 0) {
1417 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1418 close(ipc_sockets
[0]);
1421 if (to_cleanup_pid
> 0)
1422 (void)wait_for_pid(to_cleanup_pid
);
1424 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1425 lxc_terminal_delete(&terminal
);
1426 lxc_terminal_conf_free(&terminal
);
1429 lxc_proc_put_context_info(init_ctx
);
1433 /* close unneeded file descriptors */
1434 close(ipc_sockets
[0]);
1435 ipc_sockets
[0] = -EBADF
;
1437 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1438 lxc_attach_terminal_close_master(&terminal
);
1439 lxc_attach_terminal_close_peer(&terminal
);
1440 lxc_attach_terminal_close_log(&terminal
);
1443 /* Wait for the parent to have setup cgroups. */
1444 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1445 if (ret
!= sizeof(status
)) {
1446 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1447 lxc_proc_put_context_info(init_ctx
);
1451 TRACE("Intermediate process starting to initialize");
1453 /* Attach now, create another subprocess later, since pid namespaces
1454 * only really affect the children of the current process.
1456 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1458 ERROR("Failed to enter namespaces");
1459 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1460 lxc_proc_put_context_info(init_ctx
);
1464 /* close namespace file descriptors */
1465 lxc_proc_close_ns_fd(init_ctx
);
1467 /* Attach succeeded, try to cwd. */
1468 if (options
->initial_cwd
)
1469 new_cwd
= options
->initial_cwd
;
1473 ret
= chdir(new_cwd
);
1475 WARN("Could not change directory to \"%s\"", new_cwd
);
1479 /* Create attached process. */
1480 payload
.ipc_socket
= ipc_sockets
[1];
1481 payload
.options
= options
;
1482 payload
.init_ctx
= init_ctx
;
1483 payload
.terminal_slave_fd
= terminal
.slave
;
1484 payload
.exec_function
= exec_function
;
1485 payload
.exec_payload
= exec_payload
;
1487 pid
= lxc_raw_clone(CLONE_PARENT
);
1489 SYSERROR("Failed to clone attached process");
1490 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1491 lxc_proc_put_context_info(init_ctx
);
1496 ret
= attach_child_main(&payload
);
1498 ERROR("Failed to exec");
1500 _exit(EXIT_FAILURE
);
1503 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1504 lxc_attach_terminal_close_slave(&terminal
);
1506 /* Tell grandparent the pid of the pid of the newly created child. */
1507 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1508 if (ret
!= sizeof(pid
)) {
1509 /* If this really happens here, this is very unfortunate, since
1510 * the parent will not know the pid of the attached process and
1511 * will not be able to wait for it (and we won't either due to
1512 * CLONE_PARENT) so the parent won't be able to reap it and the
1513 * attached process will remain a zombie.
1515 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1516 lxc_proc_put_context_info(init_ctx
);
1520 TRACE("Sending pid %d of attached process", pid
);
1522 /* The rest is in the hands of the initial and the attached process. */
1523 lxc_proc_put_context_info(init_ctx
);
1527 int lxc_attach_run_command(void* payload
)
1529 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1531 execvp(cmd
->program
, cmd
->argv
);
1533 SYSERROR("Failed to exec \"%s\"", cmd
->program
);
1537 int lxc_attach_run_shell(void* payload
)
1540 struct passwd pwent
;
1541 struct passwd
*pwentp
= NULL
;
1547 /* Ignore payload parameter. */
1552 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1556 buf
= malloc(bufsize
);
1558 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1561 WARN("Could not find matched password record");
1563 WARN("Failed to get password record - %u", uid
);
1567 /* This probably happens because of incompatible nss implementations in
1568 * host and container (remember, this code is still using the host's
1569 * glibc but our mount namespace is in the container) we may try to get
1570 * the information by spawning a [getent passwd uid] process and parsing
1574 user_shell
= lxc_attach_getpwshell(uid
);
1576 user_shell
= pwent
.pw_shell
;
1579 execlp(user_shell
, user_shell
, (char *)NULL
);
1581 /* Executed if either no passwd entry or execvp fails, we will fall back
1582 * on /bin/sh as a default shell.
1584 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1586 SYSERROR("Failed to execute shell");