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
68 #include "lxcseccomp.h"
70 #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/current\0 = (5 + 21 + 7 + 1) */
92 #define __LSMATTRLEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
93 static int lsm_open(pid_t pid
, int on_exec
)
96 char path
[__LSMATTRLEN
];
102 if (strcmp(name
, "nop") == 0)
105 if (strcmp(name
, "none") == 0)
108 /* We don't support on-exec with AppArmor */
109 if (strcmp(name
, "AppArmor") == 0)
113 ret
= snprintf(path
, __LSMATTRLEN
, "/proc/%d/attr/exec", pid
);
115 ret
= snprintf(path
, __LSMATTRLEN
, "/proc/%d/attr/current", pid
);
116 if (ret
< 0 || ret
>= __LSMATTRLEN
)
119 labelfd
= open(path
, O_RDWR
);
121 SYSERROR("%s - Unable to open file descriptor to set LSM label",
129 static int lsm_set_label_at(int lsm_labelfd
, int on_exec
, char *lsm_label
)
133 char *command
= NULL
;
137 if (strcmp(name
, "nop") == 0)
140 if (strcmp(name
, "none") == 0)
143 /* We don't support on-exec with AppArmor */
144 if (strcmp(name
, "AppArmor") == 0)
147 if (strcmp(name
, "AppArmor") == 0) {
151 malloc(strlen(lsm_label
) + strlen("changeprofile ") + 1);
153 SYSERROR("Failed to write apparmor profile.");
157 size
= sprintf(command
, "changeprofile %s", lsm_label
);
159 SYSERROR("Failed to write apparmor profile.");
163 if (write(lsm_labelfd
, command
, size
+ 1) < 0) {
164 SYSERROR("Unable to set LSM label: %s.", command
);
167 INFO("Set LSM label to: %s.", command
);
168 } else if (strcmp(name
, "SELinux") == 0) {
169 if (write(lsm_labelfd
, lsm_label
, strlen(lsm_label
) + 1) < 0) {
170 SYSERROR("Unable to set LSM label: %s.", lsm_label
);
173 INFO("Set LSM label to: %s.", lsm_label
);
175 ERROR("Unable to restore label for unknown LSM: %s.", name
);
183 if (lsm_labelfd
!= -1)
189 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
190 #define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
191 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
196 char proc_fn
[__PROC_STATUS_LEN
];
197 size_t line_bufsz
= 0;
199 struct lxc_proc_context_info
*info
= NULL
;
201 /* Read capabilities. */
202 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
203 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
206 proc_file
= fopen(proc_fn
, "r");
208 SYSERROR("Could not open %s.", proc_fn
);
212 info
= calloc(1, sizeof(*info
));
214 SYSERROR("Could not allocate memory.");
220 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
221 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
222 if (ret
!= EOF
&& ret
== 1) {
232 SYSERROR("Could not read capability bounding set from %s.",
238 info
->lsm_label
= lsm_process_label_get(pid
);
239 info
->ns_inherited
= 0;
240 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
249 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
253 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
254 if (ctx
->ns_fd
[i
] < 0)
256 close(ctx
->ns_fd
[i
]);
257 ctx
->ns_fd
[i
] = -EBADF
;
261 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
263 free(ctx
->lsm_label
);
264 ctx
->lsm_label
= NULL
;
266 if (ctx
->container
) {
267 lxc_container_put(ctx
->container
);
268 ctx
->container
= NULL
;
271 lxc_proc_close_ns_fd(ctx
);
277 * in_same_namespace - Check whether two processes are in the same namespace.
278 * @pid1 - PID of the first process.
279 * @pid2 - PID of the second process.
280 * @ns - Name of the namespace to check. Must correspond to one of the names
281 * for the namespaces as shown in /proc/<pid/ns/
283 * If the two processes are not in the same namespace returns an fd to the
284 * namespace of the second process identified by @pid2. If the two processes are
285 * in the same namespace returns -EINVAL, -1 if an error occurred.
287 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
289 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
290 struct stat ns_st1
, ns_st2
;
292 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
294 /* The kernel does not support this namespace. This is not an
303 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
307 ret
= fstat(ns_fd1
, &ns_st1
);
311 ret
= fstat(ns_fd2
, &ns_st2
);
315 /* processes are in the same namespace */
317 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
320 /* processes are in different namespaces */
334 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
338 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
339 if (ctx
->ns_fd
[i
] < 0)
342 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
344 SYSERROR("Failed to attach to %s namespace of %d",
345 ns_info
[i
].proc_name
, pid
);
349 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
355 static int lxc_attach_remount_sys_proc(void)
359 ret
= unshare(CLONE_NEWNS
);
361 SYSERROR("Failed to unshare mount namespace.");
365 if (detect_shared_rootfs()) {
366 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
367 SYSERROR("Failed to make / rslave.");
368 ERROR("Continuing...");
372 /* Assume /proc is always mounted, so remount it. */
373 ret
= umount2("/proc", MNT_DETACH
);
375 SYSERROR("Failed to unmount /proc.");
379 ret
= mount("none", "/proc", "proc", 0, NULL
);
381 SYSERROR("Failed to remount /proc.");
385 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
386 * we ignore it because it may not have been mounted in the first place.
388 ret
= umount2("/sys", MNT_DETACH
);
389 if (ret
< 0 && errno
!= EINVAL
) {
390 SYSERROR("Failed to unmount /sys.");
392 } else if (ret
== 0) {
394 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
396 SYSERROR("Failed to remount /sys.");
404 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
408 last_cap
= lxc_caps_last_cap();
409 for (cap
= 0; cap
<= last_cap
; cap
++) {
410 if (ctx
->capability_mask
& (1LL << cap
))
413 if (prctl(PR_CAPBSET_DROP
, cap
, 0, 0, 0)) {
414 SYSERROR("Failed to drop capability %d", cap
);
417 TRACE("Dropped capability %d", cap
);
423 static int lxc_attach_set_environment(enum lxc_attach_env_policy_t policy
,
424 char **extra_env
, char **extra_keep
)
426 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
428 char **extra_keep_store
= NULL
;
433 for (count
= 0; extra_keep
[count
]; count
++);
435 extra_keep_store
= calloc(count
, sizeof(char *));
436 if (!extra_keep_store
) {
437 SYSERROR("Failed to allocate memory for storing current "
438 "environment variable values that will be kept.");
441 for (i
= 0; i
< count
; i
++) {
442 char *v
= getenv(extra_keep
[i
]);
444 extra_keep_store
[i
] = strdup(v
);
445 if (!extra_keep_store
[i
]) {
446 SYSERROR("Failed to allocate memory for storing current "
447 "environment variable values that will be kept.");
449 free(extra_keep_store
[--i
]);
450 free(extra_keep_store
);
453 if (strcmp(extra_keep
[i
], "PATH") == 0)
456 /* Calloc sets entire array to zero, so we don't
465 SYSERROR("Failed to clear environment.");
466 if (extra_keep_store
) {
467 for (p
= extra_keep_store
; *p
; p
++)
469 free(extra_keep_store
);
474 if (extra_keep_store
) {
477 for (i
= 0; extra_keep
[i
]; i
++) {
478 if (extra_keep_store
[i
]) {
479 if (setenv(extra_keep
[i
], extra_keep_store
[i
], 1) < 0)
480 SYSERROR("Unable to set environment variable.");
482 free(extra_keep_store
[i
]);
484 free(extra_keep_store
);
487 /* Always set a default path; shells and execlp tend to be fine
488 * without it, but there is a disturbing number of C programs
489 * out there that just assume that getenv("PATH") is never NULL
490 * and then die a painful segfault death.
493 setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
496 if (putenv("container=lxc")) {
497 SYSERROR("Failed to set environment variable.");
501 /* Set extra environment variables. */
503 for (; *extra_env
; extra_env
++) {
504 /* Duplicate the string, just to be on the safe side,
505 * because putenv does not do it for us.
507 char *p
= strdup(*extra_env
);
508 /* We just assume the user knows what they are doing, so
509 * we don't do any checks.
512 SYSERROR("Failed to allocate memory for additional environment "
523 static char *lxc_attach_getpwshell(uid_t uid
)
530 /* We need to fork off a process that runs the getent program, and we
531 * need to capture its output, so we use a pipe for that purpose.
548 size_t line_bufsz
= 0;
553 pipe_f
= fdopen(pipes
[0], "r");
554 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
558 char *endptr
= NULL
, *saveptr
= NULL
;
560 /* If we already found something, just continue to read
561 * until the pipe doesn't deliver any more data, but
562 * don't modify the existing data structure.
567 /* Trim line on the right hand side. */
568 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
571 /* Split into tokens: first: user name. */
572 token
= strtok_r(line
, ":", &saveptr
);
575 /* next: dummy password field */
576 token
= strtok_r(NULL
, ":", &saveptr
);
580 token
= strtok_r(NULL
, ":", &saveptr
);
581 value
= token
? strtol(token
, &endptr
, 10) : 0;
582 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
|| value
== LONG_MAX
)
584 /* dummy sanity check: user id matches */
585 if ((uid_t
) value
!= uid
)
587 /* skip fields: gid, gecos, dir, go to next field 'shell' */
588 for (i
= 0; i
< 4; i
++) {
589 token
= strtok_r(NULL
, ":", &saveptr
);
596 result
= strdup(token
);
598 /* Sanity check that there are no fields after that. */
599 token
= strtok_r(NULL
, ":", &saveptr
);
609 if (waitpid(pid
, &status
, 0) < 0) {
616 /* Some sanity checks. If anything even hinted at going wrong,
617 * we can't be sure we have a valid result, so we assume we
621 if (!WIFEXITED(status
)) {
626 if (WEXITSTATUS(status
) != 0) {
639 char *arguments
[] = {
648 /* We want to capture stdout. */
652 /* Get rid of stdin/stderr, so we try to associate it with
655 fd
= open("/dev/null", O_RDWR
);
665 /* Finish argument list. */
666 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long) uid
);
670 /* Try to run getent program. */
671 (void) execvp("getent", arguments
);
676 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
679 char proc_fn
[__PROC_STATUS_LEN
];
682 size_t line_bufsz
= 0;
684 uid_t uid
= (uid_t
)-1;
685 gid_t gid
= (gid_t
)-1;
687 /* Read capabilities. */
688 snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
690 proc_file
= fopen(proc_fn
, "r");
694 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
695 /* Format is: real, effective, saved set user, fs we only care
698 ret
= sscanf(line
, "Uid: %ld", &value
);
699 if (ret
!= EOF
&& ret
== 1) {
702 ret
= sscanf(line
, "Gid: %ld", &value
);
703 if (ret
!= EOF
&& ret
== 1)
706 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
713 /* Only override arguments if we found something. */
714 if (uid
!= (uid_t
)-1)
716 if (gid
!= (gid_t
)-1)
719 /* TODO: we should also parse supplementary groups and use
720 * setgroups() to set them.
724 /* Help the optimizer along if it doesn't know that exit always exits. */
732 /* Define default options if no options are supplied by the user. */
733 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
735 static bool fetch_seccomp(struct lxc_container
*c
,
736 lxc_attach_options_t
*options
)
740 if (!(options
->namespaces
& CLONE_NEWNS
) ||
741 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
742 free(c
->lxc_conf
->seccomp
);
743 c
->lxc_conf
->seccomp
= NULL
;
747 /* Remove current setting. */
748 if (!c
->set_config_item(c
, "lxc.seccomp", "") &&
749 !c
->set_config_item(c
, "lxc.seccomp.profile", "")) {
753 /* Fetch the current profile path over the cmd interface. */
754 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
756 INFO("Failed to get running config item for lxc.seccomp.profile");
757 path
= c
->get_running_config_item(c
, "lxc.seccomp");
760 INFO("Failed to get running config item for lxc.seccomp");
764 /* Copy the value into the new lxc_conf. */
765 if (!c
->set_config_item(c
, "lxc.seccomp.profile", path
)) {
771 /* Attempt to parse the resulting config. */
772 if (lxc_read_seccomp_config(c
->lxc_conf
) < 0) {
773 ERROR("Error reading seccomp policy.");
777 INFO("Retrieved seccomp policy.");
781 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
785 /* Remove current setting. */
786 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
789 /* Retrieve currently active setting. */
790 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
792 INFO("Failed to get running config item for lxc.no_new_privs.");
796 /* Set currently active setting. */
797 if (!c
->set_config_item(c
, "lxc.no_new_privs", val
)) {
806 static signed long get_personality(const char *name
, const char *lxcpath
)
811 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
815 ret
= lxc_config_parse_arch(p
);
821 struct attach_clone_payload
{
824 lxc_attach_options_t
*options
;
825 struct lxc_proc_context_info
*init_ctx
;
826 lxc_attach_exec_t exec_function
;
830 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
832 if (p
->ipc_socket
>= 0) {
833 shutdown(p
->ipc_socket
, SHUT_RDWR
);
834 close(p
->ipc_socket
);
835 p
->ipc_socket
= -EBADF
;
838 if (p
->pty_fd
>= 0) {
844 lxc_proc_put_context_info(p
->init_ctx
);
849 static int attach_child_main(struct attach_clone_payload
*payload
)
854 lxc_attach_options_t
* options
= payload
->options
;
855 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
856 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
857 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
860 /* A description of the purpose of this functionality is provided in the
861 * lxc-attach(1) manual page. We have to remount here and not in the
862 * parent process, otherwise /proc may not properly reflect the new pid
865 if (!(options
->namespaces
& CLONE_NEWNS
) &&
866 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
867 ret
= lxc_attach_remount_sys_proc();
870 TRACE("Remounted \"/proc\" and \"/sys\"");
873 /* Now perform additional attachments. */
874 #if HAVE_SYS_PERSONALITY_H
875 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
876 long new_personality
;
878 if (options
->personality
< 0)
879 new_personality
= init_ctx
->personality
;
881 new_personality
= options
->personality
;
882 ret
= personality(new_personality
);
885 TRACE("Set new personality");
889 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
890 ret
= lxc_attach_drop_privs(init_ctx
);
893 TRACE("Dropped capabilities");
896 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
897 * if you want this to be a no-op).
899 ret
= lxc_attach_set_environment(options
->env_policy
,
900 options
->extra_env_vars
,
901 options
->extra_keep_env
);
904 TRACE("Set up environment");
906 /* This remark only affects fully unprivileged containers:
907 * Receive fd for LSM security module before we set{g,u}id(). The reason
908 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
909 * we will change our effective uid. This means our effective uid will
910 * be different from the effective uid of the process that created us
911 * which means that this processs no longer has capabilities in our
912 * namespace including CAP_SYS_PTRACE. This means we will not be able to
913 * read and /proc/<pid> files for the process anymore when /proc is
914 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
918 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
921 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
924 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
925 ret
= lxc_make_controlling_pty(options
->stdin_fd
);
933 /* Ignore errors, we will fall back to root in that case (/proc was not
936 if (options
->namespaces
& CLONE_NEWUSER
)
937 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
939 if (options
->uid
!= (uid_t
)-1)
940 new_uid
= options
->uid
;
941 if (options
->gid
!= (gid_t
)-1)
942 new_gid
= options
->gid
;
944 /* Try to set the {u,g}id combination. */
945 if (new_uid
!= 0 || new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) {
946 ret
= lxc_switch_uid_gid(new_uid
, new_gid
);
950 ret
= lxc_setgroups(0, NULL
);
955 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
956 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
957 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
958 ret
= prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0);
961 TRACE("Set PR_SET_NO_NEW_PRIVS");
967 /* Change into our new LSM profile. */
968 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? 1 : 0;
969 ret
= lsm_set_label_at(lsm_fd
, on_exec
, init_ctx
->lsm_label
);
973 TRACE("Set LSM label");
976 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
977 init_ctx
->container
->lxc_conf
->seccomp
) {
978 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
981 TRACE("Loaded seccomp profile");
983 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
984 close(payload
->ipc_socket
);
985 payload
->ipc_socket
= -EBADF
;
986 lxc_proc_put_context_info(init_ctx
);
988 /* The following is done after the communication socket is shut down.
989 * That way, all errors that might (though unlikely) occur up until this
990 * point will have their messages printed to the original stderr (if
991 * logging is so configured) and not the fd the user supplied, if any.
994 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
995 * may want to make sure the fds are closed, for example.
997 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
998 dup2(options
->stdin_fd
, STDIN_FILENO
);
1000 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
1001 dup2(options
->stdout_fd
, STDOUT_FILENO
);
1003 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
1004 dup2(options
->stderr_fd
, STDERR_FILENO
);
1006 /* close the old fds */
1007 if (options
->stdin_fd
> STDERR_FILENO
)
1008 close(options
->stdin_fd
);
1010 if (options
->stdout_fd
> STDERR_FILENO
)
1011 close(options
->stdout_fd
);
1013 if (options
->stderr_fd
> STDERR_FILENO
)
1014 close(options
->stderr_fd
);
1016 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
1017 * here, ignore errors.
1019 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
1022 flags
= fcntl(fd
, F_GETFL
);
1026 if ((flags
& FD_CLOEXEC
) == 0)
1029 ret
= fcntl(fd
, F_SETFL
, flags
& ~FD_CLOEXEC
);
1031 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
1036 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1037 ret
= lxc_login_pty(payload
->pty_fd
);
1039 SYSERROR("Failed to prepare pty file descriptor %d", payload
->pty_fd
);
1042 TRACE("Prepared pty file descriptor %d", payload
->pty_fd
);
1045 /* We're done, so we can now do whatever the user intended us to do. */
1046 rexit(payload
->exec_function(payload
->exec_payload
));
1049 lxc_put_attach_clone_payload(payload
);
1050 rexit(EXIT_FAILURE
);
1053 static int lxc_attach_pty(struct lxc_conf
*conf
, struct lxc_console
*pty
)
1059 ret
= lxc_pty_create(pty
);
1061 SYSERROR("Failed to create pty");
1065 /* Shift ttys to container. */
1066 ret
= lxc_pty_map_ids(conf
, pty
);
1068 ERROR("Failed to shift pty");
1075 lxc_console_delete(pty
);
1076 lxc_pty_conf_free(pty
);
1080 static int lxc_attach_pty_mainloop_init(struct lxc_console
*pty
,
1081 struct lxc_epoll_descr
*descr
)
1085 ret
= lxc_mainloop_open(descr
);
1087 ERROR("Failed to create mainloop");
1091 ret
= lxc_console_mainloop_add(descr
, pty
);
1093 ERROR("Failed to add handlers to mainloop");
1094 lxc_mainloop_close(descr
);
1101 static inline void lxc_attach_pty_close_master(struct lxc_console
*pty
)
1103 if (pty
->master
< 0)
1107 pty
->master
= -EBADF
;
1110 static inline void lxc_attach_pty_close_slave(struct lxc_console
*pty
)
1116 pty
->slave
= -EBADF
;
1119 static inline void lxc_attach_pty_close_peer(struct lxc_console
*pty
)
1128 static inline void lxc_attach_pty_close_log(struct lxc_console
*pty
)
1130 if (pty
->log_fd
< 0)
1134 pty
->log_fd
= -EBADF
;
1137 int lxc_attach(const char *name
, const char *lxcpath
,
1138 lxc_attach_exec_t exec_function
, void *exec_payload
,
1139 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1143 char *cwd
, *new_cwd
;
1144 signed long personality
;
1145 pid_t attached_pid
, init_pid
, pid
;
1146 struct lxc_proc_context_info
*init_ctx
;
1147 struct lxc_console pty
;
1148 struct lxc_conf
*conf
;
1149 struct attach_clone_payload payload
= {0};
1151 ret
= access("/proc/self/ns", X_OK
);
1153 ERROR("Does this kernel version support namespaces?");
1158 options
= &attach_static_default_options
;
1160 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1162 ERROR("Failed to get init pid.");
1166 init_ctx
= lxc_proc_get_context_info(init_pid
);
1168 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1172 personality
= get_personality(name
, lxcpath
);
1173 if (init_ctx
->personality
< 0) {
1174 ERROR("Failed to get personality of the container");
1175 lxc_proc_put_context_info(init_ctx
);
1178 init_ctx
->personality
= personality
;
1180 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1181 if (!init_ctx
->container
) {
1182 lxc_proc_put_context_info(init_ctx
);
1186 if (!init_ctx
->container
->lxc_conf
) {
1187 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1188 if (!init_ctx
->container
->lxc_conf
) {
1189 lxc_proc_put_context_info(init_ctx
);
1193 conf
= init_ctx
->container
->lxc_conf
;
1195 if (!fetch_seccomp(init_ctx
->container
, options
))
1196 WARN("Failed to get seccomp policy.");
1198 if (!no_new_privs(init_ctx
->container
, options
))
1199 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set.");
1201 cwd
= getcwd(NULL
, 0);
1203 /* Determine which namespaces the container was created with
1204 * by asking lxc-start, if necessary.
1206 if (options
->namespaces
== -1) {
1207 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1209 if (options
->namespaces
== -1) {
1210 ERROR("Failed to automatically determine the "
1211 "namespaces which the container uses");
1213 lxc_proc_put_context_info(init_ctx
);
1217 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1218 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1219 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1223 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1226 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1230 pid
= lxc_raw_getpid();
1231 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1234 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1235 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1236 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1237 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1240 if (init_ctx
->ns_fd
[i
] >= 0)
1243 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1244 DEBUG("Inheriting %s namespace from %d",
1245 ns_info
[i
].proc_name
, pid
);
1246 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1250 /* We failed to preserve the namespace. */
1251 saved_errno
= errno
;
1252 /* Close all already opened file descriptors before we return an
1253 * error, so we don't leak them.
1255 for (j
= 0; j
< i
; j
++)
1256 close(init_ctx
->ns_fd
[j
]);
1258 errno
= saved_errno
;
1259 SYSERROR("Failed to attach to %s namespace of %d",
1260 ns_info
[i
].proc_name
, pid
);
1262 lxc_proc_put_context_info(init_ctx
);
1266 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1267 ret
= lxc_attach_pty(conf
, &pty
);
1269 ERROR("Failed to allocate pty");
1271 lxc_proc_put_context_info(init_ctx
);
1275 pty
.log_fd
= options
->log_fd
;
1280 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1281 * to make sure we don't irritate other threads that want to fork+exec
1284 * IMPORTANT: if the initial process is multithreaded and another call
1285 * just fork()s away without exec'ing directly after, the socket fd will
1286 * exist in the forked process from the other thread and any close() in
1287 * our own child process will not really cause the socket to close
1288 * properly, potentiall causing the parent to hang.
1290 * For this reason, while IPC is still active, we have to use shutdown()
1291 * if the child exits prematurely in order to signal that the socket is
1292 * closed and cannot assume that the child exiting will automatically do
1295 * IPC mechanism: (X is receiver)
1296 * initial process intermediate attached
1297 * X <--- send pid of
1300 * send 0 ------------------------------------> X
1301 * [do initialization]
1302 * X <------------------------------------ send 1
1303 * [add to cgroup, ...]
1304 * send 2 ------------------------------------> X
1305 * [set LXC_ATTACH_NO_NEW_PRIVS]
1306 * X <------------------------------------ send 3
1307 * [open LSM label fd]
1308 * send 4 ------------------------------------> X
1310 * close socket close socket
1313 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1315 SYSERROR("Could not set up required IPC mechanism for attaching.");
1317 lxc_proc_put_context_info(init_ctx
);
1321 /* Create intermediate subprocess, three reasons:
1322 * 1. Runs all pthread_atfork handlers and the child will no
1323 * longer be threaded (we can't properly setns() in a threaded
1325 * 2. We can't setns() in the child itself, since we want to make
1326 * sure we are properly attached to the pidns.
1327 * 3. Also, the initial thread has to put the attached process
1328 * into the cgroup, which we can only do if we didn't already
1329 * setns() (otherwise, user namespaces will hate us).
1333 SYSERROR("Failed to create first subprocess.");
1335 lxc_proc_put_context_info(init_ctx
);
1340 int ret_parent
= -1;
1341 pid_t to_cleanup_pid
= pid
;
1342 struct lxc_epoll_descr descr
= {0};
1344 /* close unneeded file descriptors */
1345 close(ipc_sockets
[1]);
1347 lxc_proc_close_ns_fd(init_ctx
);
1348 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
)
1349 lxc_attach_pty_close_slave(&pty
);
1351 /* Attach to cgroup, if requested. */
1352 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1353 if (!cgroup_attach(name
, lxcpath
, pid
))
1355 TRACE("Moved intermediate process %d into container's "
1359 /* Setup /proc limits */
1360 if (!lxc_list_empty(&conf
->procs
)) {
1361 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1366 /* Setup resource limits */
1367 if (!lxc_list_empty(&conf
->limits
)) {
1368 ret
= setup_resource_limits(&conf
->limits
, pid
);
1373 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1374 ret
= lxc_attach_pty_mainloop_init(&pty
, &descr
);
1377 TRACE("Initalized pty mainloop");
1380 /* Let the child process know to go ahead. */
1382 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1383 if (ret
!= sizeof(status
))
1384 goto close_mainloop
;
1385 TRACE("Told intermediate process to start initializing");
1387 /* Get pid of attached process from intermediate process. */
1388 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1389 if (ret
!= sizeof(attached_pid
))
1390 goto close_mainloop
;
1391 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1393 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1394 if (options
->stdin_fd
== 0) {
1395 signal(SIGINT
, SIG_IGN
);
1396 signal(SIGQUIT
, SIG_IGN
);
1399 /* Reap intermediate process. */
1400 ret
= wait_for_pid(pid
);
1402 goto close_mainloop
;
1403 TRACE("Intermediate process %d exited", pid
);
1405 /* We will always have to reap the attached process now. */
1406 to_cleanup_pid
= attached_pid
;
1408 /* Open LSM fd and send it to child. */
1409 if ((options
->namespaces
& CLONE_NEWNS
) &&
1410 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1411 init_ctx
->lsm_label
) {
1412 int labelfd
, on_exec
;
1415 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? 1 : 0;
1416 labelfd
= lsm_open(attached_pid
, on_exec
);
1418 goto close_mainloop
;
1419 TRACE("Opened LSM label file descriptor %d", labelfd
);
1421 /* Send child fd of the LSM security module to write to. */
1422 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1425 SYSERROR("%d", (int)ret
);
1426 goto close_mainloop
;
1428 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1431 /* We're done, the child process should now execute whatever it
1432 * is that the user requested. The parent can now track it with
1433 * waitpid() or similar.
1436 *attached_process
= attached_pid
;
1438 /* Now shut down communication with child, we're done. */
1439 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1440 close(ipc_sockets
[0]);
1441 ipc_sockets
[0] = -1;
1444 to_cleanup_pid
= -1;
1445 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1446 ret
= lxc_mainloop(&descr
, -1);
1449 to_cleanup_pid
= attached_pid
;
1454 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
)
1455 lxc_mainloop_close(&descr
);
1458 if (ipc_sockets
[0] >= 0) {
1459 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1460 close(ipc_sockets
[0]);
1463 if (to_cleanup_pid
> 0)
1464 (void)wait_for_pid(to_cleanup_pid
);
1466 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1467 lxc_console_delete(&pty
);
1468 lxc_pty_conf_free(&pty
);
1470 lxc_proc_put_context_info(init_ctx
);
1474 /* close unneeded file descriptors */
1475 close(ipc_sockets
[0]);
1476 ipc_sockets
[0] = -EBADF
;
1477 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
) {
1478 lxc_attach_pty_close_master(&pty
);
1479 lxc_attach_pty_close_peer(&pty
);
1480 lxc_attach_pty_close_log(&pty
);
1483 /* Wait for the parent to have setup cgroups. */
1484 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1485 if (ret
!= sizeof(status
)) {
1486 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1487 lxc_proc_put_context_info(init_ctx
);
1490 TRACE("Intermediate process starting to initialize");
1492 /* Attach now, create another subprocess later, since pid namespaces
1493 * only really affect the children of the current process.
1495 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1497 ERROR("Failed to enter namespaces");
1498 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1499 lxc_proc_put_context_info(init_ctx
);
1502 /* close namespace file descriptors */
1503 lxc_proc_close_ns_fd(init_ctx
);
1505 /* Attach succeeded, try to cwd. */
1506 if (options
->initial_cwd
)
1507 new_cwd
= options
->initial_cwd
;
1511 ret
= chdir(new_cwd
);
1513 WARN("Could not change directory to \"%s\"", new_cwd
);
1517 /* Create attached process. */
1518 payload
.ipc_socket
= ipc_sockets
[1];
1519 payload
.options
= options
;
1520 payload
.init_ctx
= init_ctx
;
1521 payload
.pty_fd
= pty
.slave
;
1522 payload
.exec_function
= exec_function
;
1523 payload
.exec_payload
= exec_payload
;
1525 pid
= lxc_raw_clone(CLONE_PARENT
);
1527 SYSERROR("Failed to clone attached process");
1528 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1529 lxc_proc_put_context_info(init_ctx
);
1534 ret
= attach_child_main(&payload
);
1536 ERROR("Failed to exec");
1537 _exit(EXIT_FAILURE
);
1539 if (options
->attach_flags
& LXC_ATTACH_ALLOCATE_PTY
)
1540 lxc_attach_pty_close_slave(&pty
);
1542 /* Tell grandparent the pid of the pid of the newly created child. */
1543 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1544 if (ret
!= sizeof(pid
)) {
1545 /* If this really happens here, this is very unfortunate, since
1546 * the parent will not know the pid of the attached process and
1547 * will not be able to wait for it (and we won't either due to
1548 * CLONE_PARENT) so the parent won't be able to reap it and the
1549 * attached process will remain a zombie.
1551 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1552 lxc_proc_put_context_info(init_ctx
);
1555 TRACE("Sending pid %d of attached process", pid
);
1557 /* The rest is in the hands of the initial and the attached process. */
1558 lxc_proc_put_context_info(init_ctx
);
1562 int lxc_attach_run_command(void* payload
)
1564 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1566 execvp(cmd
->program
, cmd
->argv
);
1567 SYSERROR("Failed to exec \"%s\".", cmd
->program
);
1571 int lxc_attach_run_shell(void* payload
)
1574 struct passwd
*passwd
;
1577 /* Ignore payload parameter. */
1581 passwd
= getpwuid(uid
);
1583 /* This probably happens because of incompatible nss implementations in
1584 * host and container (remember, this code is still using the host's
1585 * glibc but our mount namespace is in the container) we may try to get
1586 * the information by spawning a [getent passwd uid] process and parsing
1590 user_shell
= lxc_attach_getpwshell(uid
);
1592 user_shell
= passwd
->pw_shell
;
1594 execlp(user_shell
, user_shell
, (char *)NULL
);
1596 /* Executed if either no passwd entry or execvp fails, we will fall back
1597 * on /bin/sh as a default shell.
1599 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1600 SYSERROR("Failed to execute shell");