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(lxc_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.");
123 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
124 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
125 if (ret
!= EOF
&& ret
== 1) {
135 SYSERROR("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)
159 close(ctx
->ns_fd
[i
]);
160 ctx
->ns_fd
[i
] = -EBADF
;
164 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
166 free(ctx
->lsm_label
);
167 ctx
->lsm_label
= NULL
;
169 if (ctx
->container
) {
170 lxc_container_put(ctx
->container
);
171 ctx
->container
= NULL
;
174 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 SYSWARN("Failed to set environment variable");
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 SYSWARN("Failed to set environment variable");
403 ret
= putenv("container=lxc");
405 SYSWARN("Failed to set environment variable");
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 SYSWARN("Failed to set environment variable");
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 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
611 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
614 proc_file
= fopen(proc_fn
, "r");
618 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
619 /* Format is: real, effective, saved set user, fs we only care
622 ret
= sscanf(line
, "Uid: %ld", &value
);
623 if (ret
!= EOF
&& ret
== 1) {
626 ret
= sscanf(line
, "Gid: %ld", &value
);
627 if (ret
!= EOF
&& ret
== 1)
630 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
637 /* Only override arguments if we found something. */
638 if (uid
!= (uid_t
)-1)
640 if (gid
!= (gid_t
)-1)
643 /* TODO: we should also parse supplementary groups and use
644 * setgroups() to set them.
648 /* Help the optimizer along if it doesn't know that exit always exits. */
656 /* Define default options if no options are supplied by the user. */
657 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
659 static bool fetch_seccomp(struct lxc_container
*c
,
660 lxc_attach_options_t
*options
)
664 if (!(options
->namespaces
& CLONE_NEWNS
) ||
665 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
666 free(c
->lxc_conf
->seccomp
);
667 c
->lxc_conf
->seccomp
= NULL
;
671 /* Remove current setting. */
672 if (!c
->set_config_item(c
, "lxc.seccomp", "") &&
673 !c
->set_config_item(c
, "lxc.seccomp.profile", "")) {
677 /* Fetch the current profile path over the cmd interface. */
678 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
680 INFO("Failed to get running config item for lxc.seccomp.profile");
681 path
= c
->get_running_config_item(c
, "lxc.seccomp");
684 INFO("Failed to get running config item for lxc.seccomp");
688 /* Copy the value into the new lxc_conf. */
689 if (!c
->set_config_item(c
, "lxc.seccomp.profile", path
)) {
695 /* Attempt to parse the resulting config. */
696 if (lxc_read_seccomp_config(c
->lxc_conf
) < 0) {
697 ERROR("Error reading seccomp policy.");
701 INFO("Retrieved seccomp policy.");
705 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
709 /* Remove current setting. */
710 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
713 /* Retrieve currently active setting. */
714 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
716 INFO("Failed to get running config item for lxc.no_new_privs.");
720 /* Set currently active setting. */
721 if (!c
->set_config_item(c
, "lxc.no_new_privs", val
)) {
730 static signed long get_personality(const char *name
, const char *lxcpath
)
735 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
739 ret
= lxc_config_parse_arch(p
);
745 struct attach_clone_payload
{
747 int terminal_slave_fd
;
748 lxc_attach_options_t
*options
;
749 struct lxc_proc_context_info
*init_ctx
;
750 lxc_attach_exec_t exec_function
;
754 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
756 if (p
->ipc_socket
>= 0) {
757 shutdown(p
->ipc_socket
, SHUT_RDWR
);
758 close(p
->ipc_socket
);
759 p
->ipc_socket
= -EBADF
;
762 if (p
->terminal_slave_fd
>= 0) {
763 close(p
->terminal_slave_fd
);
764 p
->terminal_slave_fd
= -EBADF
;
768 lxc_proc_put_context_info(p
->init_ctx
);
773 static int attach_child_main(struct attach_clone_payload
*payload
)
778 lxc_attach_options_t
* options
= payload
->options
;
779 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
780 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
781 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
784 /* A description of the purpose of this functionality is provided in the
785 * lxc-attach(1) manual page. We have to remount here and not in the
786 * parent process, otherwise /proc may not properly reflect the new pid
789 if (!(options
->namespaces
& CLONE_NEWNS
) &&
790 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
791 ret
= lxc_attach_remount_sys_proc();
794 TRACE("Remounted \"/proc\" and \"/sys\"");
797 /* Now perform additional attachments. */
798 #if HAVE_SYS_PERSONALITY_H
799 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
800 long new_personality
;
802 if (options
->personality
< 0)
803 new_personality
= init_ctx
->personality
;
805 new_personality
= options
->personality
;
806 ret
= personality(new_personality
);
809 TRACE("Set new personality");
813 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
814 ret
= lxc_attach_drop_privs(init_ctx
);
817 TRACE("Dropped capabilities");
820 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
821 * if you want this to be a no-op).
823 ret
= lxc_attach_set_environment(init_ctx
,
825 options
->extra_env_vars
,
826 options
->extra_keep_env
);
829 TRACE("Set up environment");
831 /* This remark only affects fully unprivileged containers:
832 * Receive fd for LSM security module before we set{g,u}id(). The reason
833 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
834 * we will change our effective uid. This means our effective uid will
835 * be different from the effective uid of the process that created us
836 * which means that this processs no longer has capabilities in our
837 * namespace including CAP_SYS_PTRACE. This means we will not be able to
838 * read and /proc/<pid> files for the process anymore when /proc is
839 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
843 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
846 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
849 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
850 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
858 /* Ignore errors, we will fall back to root in that case (/proc was not
861 if (options
->namespaces
& CLONE_NEWUSER
)
862 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
864 if (options
->uid
!= (uid_t
)-1)
865 new_uid
= options
->uid
;
866 if (options
->gid
!= (gid_t
)-1)
867 new_gid
= options
->gid
;
869 /* Try to set the {u,g}id combination. */
870 if (new_uid
!= 0 || new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) {
871 ret
= lxc_switch_uid_gid(new_uid
, new_gid
);
876 ret
= lxc_setgroups(0, NULL
);
877 if (ret
< 0 && errno
!= EPERM
)
880 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
881 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
882 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
883 ret
= prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0);
886 TRACE("Set PR_SET_NO_NEW_PRIVS");
892 /* Change into our new LSM profile. */
893 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
894 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
898 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
901 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
902 init_ctx
->container
->lxc_conf
->seccomp
) {
903 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
906 TRACE("Loaded seccomp profile");
908 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
909 close(payload
->ipc_socket
);
910 payload
->ipc_socket
= -EBADF
;
911 lxc_proc_put_context_info(init_ctx
);
912 payload
->init_ctx
= NULL
;
914 /* The following is done after the communication socket is shut down.
915 * That way, all errors that might (though unlikely) occur up until this
916 * point will have their messages printed to the original stderr (if
917 * logging is so configured) and not the fd the user supplied, if any.
920 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
921 * may want to make sure the fds are closed, for example.
923 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
924 dup2(options
->stdin_fd
, STDIN_FILENO
);
926 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
927 dup2(options
->stdout_fd
, STDOUT_FILENO
);
929 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
930 dup2(options
->stderr_fd
, STDERR_FILENO
);
932 /* close the old fds */
933 if (options
->stdin_fd
> STDERR_FILENO
)
934 close(options
->stdin_fd
);
936 if (options
->stdout_fd
> STDERR_FILENO
)
937 close(options
->stdout_fd
);
939 if (options
->stderr_fd
> STDERR_FILENO
)
940 close(options
->stderr_fd
);
942 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
943 * here, ignore errors.
945 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
948 flags
= fcntl(fd
, F_GETFL
);
952 if ((flags
& FD_CLOEXEC
) == 0)
955 ret
= fcntl(fd
, F_SETFL
, flags
& ~FD_CLOEXEC
);
957 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
962 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
963 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
965 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
968 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
971 /* We're done, so we can now do whatever the user intended us to do. */
972 rexit(payload
->exec_function(payload
->exec_payload
));
975 lxc_put_attach_clone_payload(payload
);
979 static int lxc_attach_terminal(struct lxc_conf
*conf
,
980 struct lxc_terminal
*terminal
)
984 lxc_terminal_init(terminal
);
986 ret
= lxc_terminal_create(terminal
);
988 SYSERROR("Failed to create terminal");
992 /* Shift ttys to container. */
993 ret
= lxc_terminal_map_ids(conf
, terminal
);
995 ERROR("Failed to chown terminal");
1002 lxc_terminal_delete(terminal
);
1003 lxc_terminal_conf_free(terminal
);
1007 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
1008 struct lxc_epoll_descr
*descr
)
1012 ret
= lxc_mainloop_open(descr
);
1014 ERROR("Failed to create mainloop");
1018 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
1020 ERROR("Failed to add handlers to mainloop");
1021 lxc_mainloop_close(descr
);
1028 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
1030 if (terminal
->master
< 0)
1033 close(terminal
->master
);
1034 terminal
->master
= -EBADF
;
1037 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
1039 if (terminal
->slave
< 0)
1042 close(terminal
->slave
);
1043 terminal
->slave
= -EBADF
;
1046 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
1048 if (terminal
->peer
< 0)
1051 close(terminal
->peer
);
1052 terminal
->peer
= -EBADF
;
1055 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1057 if (terminal
->log_fd
< 0)
1060 close(terminal
->log_fd
);
1061 terminal
->log_fd
= -EBADF
;
1064 int lxc_attach(const char *name
, const char *lxcpath
,
1065 lxc_attach_exec_t exec_function
, void *exec_payload
,
1066 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1070 char *cwd
, *new_cwd
;
1071 signed long personality
;
1072 pid_t attached_pid
, init_pid
, pid
;
1073 struct lxc_proc_context_info
*init_ctx
;
1074 struct lxc_terminal terminal
;
1075 struct lxc_conf
*conf
;
1076 struct attach_clone_payload payload
= {0};
1078 ret
= access("/proc/self/ns", X_OK
);
1080 ERROR("Does this kernel version support namespaces?");
1085 options
= &attach_static_default_options
;
1087 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1089 ERROR("Failed to get init pid.");
1093 init_ctx
= lxc_proc_get_context_info(init_pid
);
1095 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1099 personality
= get_personality(name
, lxcpath
);
1100 if (init_ctx
->personality
< 0) {
1101 ERROR("Failed to get personality of the container");
1102 lxc_proc_put_context_info(init_ctx
);
1105 init_ctx
->personality
= personality
;
1107 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1108 if (!init_ctx
->container
) {
1109 lxc_proc_put_context_info(init_ctx
);
1113 if (!init_ctx
->container
->lxc_conf
) {
1114 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1115 if (!init_ctx
->container
->lxc_conf
) {
1116 lxc_proc_put_context_info(init_ctx
);
1120 conf
= init_ctx
->container
->lxc_conf
;
1122 if (!fetch_seccomp(init_ctx
->container
, options
))
1123 WARN("Failed to get seccomp policy.");
1125 if (!no_new_privs(init_ctx
->container
, options
))
1126 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set.");
1128 cwd
= getcwd(NULL
, 0);
1130 /* Determine which namespaces the container was created with
1131 * by asking lxc-start, if necessary.
1133 if (options
->namespaces
== -1) {
1134 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1136 if (options
->namespaces
== -1) {
1137 ERROR("Failed to automatically determine the "
1138 "namespaces which the container uses");
1140 lxc_proc_put_context_info(init_ctx
);
1144 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1145 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1146 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1150 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1153 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1157 pid
= lxc_raw_getpid();
1158 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1161 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1162 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1163 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1164 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1167 if (init_ctx
->ns_fd
[i
] >= 0)
1170 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1171 DEBUG("Inheriting %s namespace from %d",
1172 ns_info
[i
].proc_name
, pid
);
1173 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1177 /* We failed to preserve the namespace. */
1178 saved_errno
= errno
;
1179 /* Close all already opened file descriptors before we return an
1180 * error, so we don't leak them.
1182 for (j
= 0; j
< i
; j
++)
1183 close(init_ctx
->ns_fd
[j
]);
1185 errno
= saved_errno
;
1186 SYSERROR("Failed to attach to %s namespace of %d",
1187 ns_info
[i
].proc_name
, pid
);
1189 lxc_proc_put_context_info(init_ctx
);
1193 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1194 ret
= lxc_attach_terminal(conf
, &terminal
);
1196 ERROR("Failed to setup new terminal");
1198 lxc_proc_put_context_info(init_ctx
);
1202 terminal
.log_fd
= options
->log_fd
;
1204 lxc_terminal_init(&terminal
);
1207 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1208 * to make sure we don't irritate other threads that want to fork+exec
1211 * IMPORTANT: if the initial process is multithreaded and another call
1212 * just fork()s away without exec'ing directly after, the socket fd will
1213 * exist in the forked process from the other thread and any close() in
1214 * our own child process will not really cause the socket to close
1215 * properly, potentiall causing the parent to hang.
1217 * For this reason, while IPC is still active, we have to use shutdown()
1218 * if the child exits prematurely in order to signal that the socket is
1219 * closed and cannot assume that the child exiting will automatically do
1222 * IPC mechanism: (X is receiver)
1223 * initial process intermediate attached
1224 * X <--- send pid of
1227 * send 0 ------------------------------------> X
1228 * [do initialization]
1229 * X <------------------------------------ send 1
1230 * [add to cgroup, ...]
1231 * send 2 ------------------------------------> X
1232 * [set LXC_ATTACH_NO_NEW_PRIVS]
1233 * X <------------------------------------ send 3
1234 * [open LSM label fd]
1235 * send 4 ------------------------------------> X
1237 * close socket close socket
1240 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1242 SYSERROR("Could not set up required IPC mechanism for attaching.");
1244 lxc_proc_put_context_info(init_ctx
);
1248 /* Create intermediate subprocess, two reasons:
1249 * 1. We can't setns() in the child itself, since we want to make
1250 * sure we are properly attached to the pidns.
1251 * 2. Also, the initial thread has to put the attached process
1252 * into the cgroup, which we can only do if we didn't already
1253 * setns() (otherwise, user namespaces will hate us).
1257 SYSERROR("Failed to create first subprocess.");
1259 lxc_proc_put_context_info(init_ctx
);
1264 int ret_parent
= -1;
1265 pid_t to_cleanup_pid
= pid
;
1266 struct lxc_epoll_descr descr
= {0};
1268 /* close unneeded file descriptors */
1269 close(ipc_sockets
[1]);
1271 lxc_proc_close_ns_fd(init_ctx
);
1272 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1273 lxc_attach_terminal_close_slave(&terminal
);
1275 /* Attach to cgroup, if requested. */
1276 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1277 struct cgroup_ops
*cgroup_ops
;
1279 cgroup_ops
= cgroup_init(NULL
);
1283 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1286 cgroup_exit(cgroup_ops
);
1287 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1290 /* Setup /proc limits */
1291 if (!lxc_list_empty(&conf
->procs
)) {
1292 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1297 /* Setup resource limits */
1298 if (!lxc_list_empty(&conf
->limits
)) {
1299 ret
= setup_resource_limits(&conf
->limits
, pid
);
1304 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1305 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1308 TRACE("Initialized terminal mainloop");
1311 /* Let the child process know to go ahead. */
1313 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1314 if (ret
!= sizeof(status
))
1315 goto close_mainloop
;
1316 TRACE("Told intermediate process to start initializing");
1318 /* Get pid of attached process from intermediate process. */
1319 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1320 if (ret
!= sizeof(attached_pid
))
1321 goto close_mainloop
;
1322 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1324 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1325 if (options
->stdin_fd
== 0) {
1326 signal(SIGINT
, SIG_IGN
);
1327 signal(SIGQUIT
, SIG_IGN
);
1330 /* Reap intermediate process. */
1331 ret
= wait_for_pid(pid
);
1333 goto close_mainloop
;
1334 TRACE("Intermediate process %d exited", pid
);
1336 /* We will always have to reap the attached process now. */
1337 to_cleanup_pid
= attached_pid
;
1339 /* Open LSM fd and send it to child. */
1340 if ((options
->namespaces
& CLONE_NEWNS
) &&
1341 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1342 init_ctx
->lsm_label
) {
1347 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1348 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1350 goto close_mainloop
;
1351 TRACE("Opened LSM label file descriptor %d", labelfd
);
1353 /* Send child fd of the LSM security module to write to. */
1354 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1357 SYSERROR("%d", (int)ret
);
1358 goto close_mainloop
;
1360 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1363 /* We're done, the child process should now execute whatever it
1364 * is that the user requested. The parent can now track it with
1365 * waitpid() or similar.
1368 *attached_process
= attached_pid
;
1370 /* Now shut down communication with child, we're done. */
1371 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1372 close(ipc_sockets
[0]);
1373 ipc_sockets
[0] = -1;
1376 to_cleanup_pid
= -1;
1377 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1378 ret
= lxc_mainloop(&descr
, -1);
1381 to_cleanup_pid
= attached_pid
;
1386 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1387 lxc_mainloop_close(&descr
);
1390 if (ipc_sockets
[0] >= 0) {
1391 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1392 close(ipc_sockets
[0]);
1395 if (to_cleanup_pid
> 0)
1396 (void)wait_for_pid(to_cleanup_pid
);
1398 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1399 lxc_terminal_delete(&terminal
);
1400 lxc_terminal_conf_free(&terminal
);
1402 lxc_proc_put_context_info(init_ctx
);
1406 /* close unneeded file descriptors */
1407 close(ipc_sockets
[0]);
1408 ipc_sockets
[0] = -EBADF
;
1409 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1410 lxc_attach_terminal_close_master(&terminal
);
1411 lxc_attach_terminal_close_peer(&terminal
);
1412 lxc_attach_terminal_close_log(&terminal
);
1415 /* Wait for the parent to have setup cgroups. */
1416 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1417 if (ret
!= sizeof(status
)) {
1418 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1419 lxc_proc_put_context_info(init_ctx
);
1422 TRACE("Intermediate process starting to initialize");
1424 /* Attach now, create another subprocess later, since pid namespaces
1425 * only really affect the children of the current process.
1427 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1429 ERROR("Failed to enter namespaces");
1430 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1431 lxc_proc_put_context_info(init_ctx
);
1434 /* close namespace file descriptors */
1435 lxc_proc_close_ns_fd(init_ctx
);
1437 /* Attach succeeded, try to cwd. */
1438 if (options
->initial_cwd
)
1439 new_cwd
= options
->initial_cwd
;
1443 ret
= chdir(new_cwd
);
1445 WARN("Could not change directory to \"%s\"", new_cwd
);
1449 /* Create attached process. */
1450 payload
.ipc_socket
= ipc_sockets
[1];
1451 payload
.options
= options
;
1452 payload
.init_ctx
= init_ctx
;
1453 payload
.terminal_slave_fd
= terminal
.slave
;
1454 payload
.exec_function
= exec_function
;
1455 payload
.exec_payload
= exec_payload
;
1457 pid
= lxc_raw_clone(CLONE_PARENT
);
1459 SYSERROR("Failed to clone attached process");
1460 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1461 lxc_proc_put_context_info(init_ctx
);
1466 ret
= attach_child_main(&payload
);
1468 ERROR("Failed to exec");
1469 _exit(EXIT_FAILURE
);
1471 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1472 lxc_attach_terminal_close_slave(&terminal
);
1474 /* Tell grandparent the pid of the pid of the newly created child. */
1475 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1476 if (ret
!= sizeof(pid
)) {
1477 /* If this really happens here, this is very unfortunate, since
1478 * the parent will not know the pid of the attached process and
1479 * will not be able to wait for it (and we won't either due to
1480 * CLONE_PARENT) so the parent won't be able to reap it and the
1481 * attached process will remain a zombie.
1483 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1484 lxc_proc_put_context_info(init_ctx
);
1487 TRACE("Sending pid %d of attached process", pid
);
1489 /* The rest is in the hands of the initial and the attached process. */
1490 lxc_proc_put_context_info(init_ctx
);
1494 int lxc_attach_run_command(void* payload
)
1496 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1498 execvp(cmd
->program
, cmd
->argv
);
1499 SYSERROR("Failed to exec \"%s\".", cmd
->program
);
1503 int lxc_attach_run_shell(void* payload
)
1506 struct passwd pwent
;
1507 struct passwd
*pwentp
= NULL
;
1513 /* Ignore payload parameter. */
1518 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1522 buf
= malloc(bufsize
);
1524 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1527 WARN("Could not find matched password record.");
1529 WARN("Failed to get password record - %u", uid
);
1533 /* This probably happens because of incompatible nss implementations in
1534 * host and container (remember, this code is still using the host's
1535 * glibc but our mount namespace is in the container) we may try to get
1536 * the information by spawning a [getent passwd uid] process and parsing
1540 user_shell
= lxc_attach_getpwshell(uid
);
1542 user_shell
= pwent
.pw_shell
;
1544 execlp(user_shell
, user_shell
, (char *)NULL
);
1546 /* Executed if either no passwd entry or execvp fails, we will fall back
1547 * on /bin/sh as a default shell.
1549 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1550 SYSERROR("Failed to execute shell");