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.");
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 size_t line_bufsz
= 0;
454 char *line
= NULL
, *result
= NULL
;
456 /* We need to fork off a process that runs the getent program, and we
457 * need to capture its output, so we use a pipe for that purpose.
459 ret
= pipe2(pipes
, O_CLOEXEC
);
472 char *arguments
[] = {
481 /* We want to capture stdout. */
482 ret
= dup2(pipes
[1], STDOUT_FILENO
);
487 /* Get rid of stdin/stderr, so we try to associate it with
493 close(STDERR_FILENO
);
495 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
496 (void)dup3(fd
, STDOUT_FILENO
, O_CLOEXEC
);
500 /* Finish argument list. */
501 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
502 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
505 /* Try to run getent program. */
506 (void)execvp("getent", arguments
);
512 pipe_f
= fdopen(pipes
[0], "r");
513 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
517 char *endptr
= NULL
, *saveptr
= NULL
;
519 /* If we already found something, just continue to read
520 * until the pipe doesn't deliver any more data, but
521 * don't modify the existing data structure.
526 /* Trim line on the right hand side. */
527 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
530 /* Split into tokens: first: user name. */
531 token
= strtok_r(line
, ":", &saveptr
);
535 /* next: dummy password field */
536 token
= strtok_r(NULL
, ":", &saveptr
);
541 token
= strtok_r(NULL
, ":", &saveptr
);
542 value
= token
? strtol(token
, &endptr
, 10) : 0;
543 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
547 /* dummy sanity check: user id matches */
548 if ((uid_t
)value
!= uid
)
551 /* skip fields: gid, gecos, dir, go to next field 'shell' */
552 for (i
= 0; i
< 4; i
++) {
553 token
= strtok_r(NULL
, ":", &saveptr
);
560 result
= strdup(token
);
562 /* Sanity check that there are no fields after that. */
563 token
= strtok_r(NULL
, ":", &saveptr
);
572 ret
= wait_for_pid(pid
);
586 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
589 char proc_fn
[__PROC_STATUS_LEN
];
592 size_t line_bufsz
= 0;
594 uid_t uid
= (uid_t
)-1;
595 gid_t gid
= (gid_t
)-1;
597 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
598 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
601 proc_file
= fopen(proc_fn
, "r");
605 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
606 /* Format is: real, effective, saved set user, fs we only care
609 ret
= sscanf(line
, "Uid: %ld", &value
);
610 if (ret
!= EOF
&& ret
== 1) {
613 ret
= sscanf(line
, "Gid: %ld", &value
);
614 if (ret
!= EOF
&& ret
== 1)
617 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
624 /* Only override arguments if we found something. */
625 if (uid
!= (uid_t
)-1)
627 if (gid
!= (gid_t
)-1)
630 /* TODO: we should also parse supplementary groups and use
631 * setgroups() to set them.
635 /* Help the optimizer along if it doesn't know that exit always exits. */
643 /* Define default options if no options are supplied by the user. */
644 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
646 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
652 if (!(options
->namespaces
& CLONE_NEWNS
) ||
653 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
654 free(c
->lxc_conf
->seccomp
);
655 c
->lxc_conf
->seccomp
= NULL
;
659 /* Remove current setting. */
660 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
661 !c
->set_config_item(c
, "lxc.seccomp", "")) {
665 /* Fetch the current profile path over the cmd interface. */
666 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
668 INFO("Failed to retrieve lxc.seccomp.profile");
669 path
= c
->get_running_config_item(c
, "lxc.seccomp");
671 INFO("Failed to retrieve lxc.seccomp");
676 /* Copy the value into the new lxc_conf. */
677 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
682 /* Attempt to parse the resulting config. */
683 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
685 ERROR("Failed to retrieve seccomp policy");
689 INFO("Retrieved seccomp policy");
693 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
698 /* Remove current setting. */
699 if (!c
->set_config_item(c
, "lxc.no_new_privs", "")) {
700 INFO("Failed to unset lxc.no_new_privs");
704 /* Retrieve currently active setting. */
705 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
707 INFO("Failed to retrieve lxc.no_new_privs");
711 /* Set currently active setting. */
712 bret
= c
->set_config_item(c
, "lxc.no_new_privs", val
);
717 static signed long get_personality(const char *name
, const char *lxcpath
)
722 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
726 ret
= lxc_config_parse_arch(p
);
732 struct attach_clone_payload
{
734 int terminal_slave_fd
;
735 lxc_attach_options_t
*options
;
736 struct lxc_proc_context_info
*init_ctx
;
737 lxc_attach_exec_t exec_function
;
741 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
743 if (p
->ipc_socket
>= 0) {
744 shutdown(p
->ipc_socket
, SHUT_RDWR
);
745 close(p
->ipc_socket
);
746 p
->ipc_socket
= -EBADF
;
749 if (p
->terminal_slave_fd
>= 0) {
750 close(p
->terminal_slave_fd
);
751 p
->terminal_slave_fd
= -EBADF
;
755 lxc_proc_put_context_info(p
->init_ctx
);
760 static int attach_child_main(struct attach_clone_payload
*payload
)
765 lxc_attach_options_t
* options
= payload
->options
;
766 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
767 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
768 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
771 /* A description of the purpose of this functionality is provided in the
772 * lxc-attach(1) manual page. We have to remount here and not in the
773 * parent process, otherwise /proc may not properly reflect the new pid
776 if (!(options
->namespaces
& CLONE_NEWNS
) &&
777 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
778 ret
= lxc_attach_remount_sys_proc();
781 TRACE("Remounted \"/proc\" and \"/sys\"");
784 /* Now perform additional attachments. */
785 #if HAVE_SYS_PERSONALITY_H
786 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
787 long new_personality
;
789 if (options
->personality
< 0)
790 new_personality
= init_ctx
->personality
;
792 new_personality
= options
->personality
;
793 ret
= personality(new_personality
);
796 TRACE("Set new personality");
800 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
801 ret
= lxc_attach_drop_privs(init_ctx
);
804 TRACE("Dropped capabilities");
807 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
808 * if you want this to be a no-op).
810 ret
= lxc_attach_set_environment(init_ctx
,
812 options
->extra_env_vars
,
813 options
->extra_keep_env
);
816 TRACE("Set up environment");
818 /* This remark only affects fully unprivileged containers:
819 * Receive fd for LSM security module before we set{g,u}id(). The reason
820 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
821 * we will change our effective uid. This means our effective uid will
822 * be different from the effective uid of the process that created us
823 * which means that this processs no longer has capabilities in our
824 * namespace including CAP_SYS_PTRACE. This means we will not be able to
825 * read and /proc/<pid> files for the process anymore when /proc is
826 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
830 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
833 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
836 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
837 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
845 /* Ignore errors, we will fall back to root in that case (/proc was not
848 if (options
->namespaces
& CLONE_NEWUSER
)
849 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
851 if (options
->uid
!= (uid_t
)-1)
852 new_uid
= options
->uid
;
853 if (options
->gid
!= (gid_t
)-1)
854 new_gid
= options
->gid
;
856 /* Try to set the {u,g}id combination. */
857 if (new_uid
!= 0 || new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) {
858 ret
= lxc_switch_uid_gid(new_uid
, new_gid
);
863 ret
= lxc_setgroups(0, NULL
);
864 if (ret
< 0 && errno
!= EPERM
)
867 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
868 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
869 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
870 ret
= prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0);
873 TRACE("Set PR_SET_NO_NEW_PRIVS");
879 /* Change into our new LSM profile. */
880 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
881 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
885 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
888 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
889 init_ctx
->container
->lxc_conf
->seccomp
) {
890 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
893 TRACE("Loaded seccomp profile");
895 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
896 close(payload
->ipc_socket
);
897 payload
->ipc_socket
= -EBADF
;
898 lxc_proc_put_context_info(init_ctx
);
899 payload
->init_ctx
= NULL
;
901 /* The following is done after the communication socket is shut down.
902 * That way, all errors that might (though unlikely) occur up until this
903 * point will have their messages printed to the original stderr (if
904 * logging is so configured) and not the fd the user supplied, if any.
907 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
908 * may want to make sure the fds are closed, for example.
910 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
911 dup2(options
->stdin_fd
, STDIN_FILENO
);
913 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
914 dup2(options
->stdout_fd
, STDOUT_FILENO
);
916 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
917 dup2(options
->stderr_fd
, STDERR_FILENO
);
919 /* close the old fds */
920 if (options
->stdin_fd
> STDERR_FILENO
)
921 close(options
->stdin_fd
);
923 if (options
->stdout_fd
> STDERR_FILENO
)
924 close(options
->stdout_fd
);
926 if (options
->stderr_fd
> STDERR_FILENO
)
927 close(options
->stderr_fd
);
929 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
930 * here, ignore errors.
932 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
933 ret
= fd_cloexec(fd
, false);
935 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
940 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
941 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
943 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
946 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
949 /* We're done, so we can now do whatever the user intended us to do. */
950 rexit(payload
->exec_function(payload
->exec_payload
));
953 lxc_put_attach_clone_payload(payload
);
957 static int lxc_attach_terminal(struct lxc_conf
*conf
,
958 struct lxc_terminal
*terminal
)
962 lxc_terminal_init(terminal
);
964 ret
= lxc_terminal_create(terminal
);
966 SYSERROR("Failed to create terminal");
970 /* Shift ttys to container. */
971 ret
= lxc_terminal_map_ids(conf
, terminal
);
973 ERROR("Failed to chown terminal");
980 lxc_terminal_delete(terminal
);
981 lxc_terminal_conf_free(terminal
);
985 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
986 struct lxc_epoll_descr
*descr
)
990 ret
= lxc_mainloop_open(descr
);
992 ERROR("Failed to create mainloop");
996 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
998 ERROR("Failed to add handlers to mainloop");
999 lxc_mainloop_close(descr
);
1006 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
1008 if (terminal
->master
< 0)
1011 close(terminal
->master
);
1012 terminal
->master
= -EBADF
;
1015 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
1017 if (terminal
->slave
< 0)
1020 close(terminal
->slave
);
1021 terminal
->slave
= -EBADF
;
1024 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
1026 if (terminal
->peer
< 0)
1029 close(terminal
->peer
);
1030 terminal
->peer
= -EBADF
;
1033 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1035 if (terminal
->log_fd
< 0)
1038 close(terminal
->log_fd
);
1039 terminal
->log_fd
= -EBADF
;
1042 int lxc_attach(const char *name
, const char *lxcpath
,
1043 lxc_attach_exec_t exec_function
, void *exec_payload
,
1044 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1048 char *cwd
, *new_cwd
;
1049 signed long personality
;
1050 pid_t attached_pid
, init_pid
, pid
;
1051 struct lxc_proc_context_info
*init_ctx
;
1052 struct lxc_terminal terminal
;
1053 struct lxc_conf
*conf
;
1054 struct attach_clone_payload payload
= {0};
1056 ret
= access("/proc/self/ns", X_OK
);
1058 ERROR("Does this kernel version support namespaces?");
1063 options
= &attach_static_default_options
;
1065 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1067 ERROR("Failed to get init pid");
1071 init_ctx
= lxc_proc_get_context_info(init_pid
);
1073 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1077 personality
= get_personality(name
, lxcpath
);
1078 if (init_ctx
->personality
< 0) {
1079 ERROR("Failed to get personality of the container");
1080 lxc_proc_put_context_info(init_ctx
);
1083 init_ctx
->personality
= personality
;
1085 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1086 if (!init_ctx
->container
) {
1087 lxc_proc_put_context_info(init_ctx
);
1091 if (!init_ctx
->container
->lxc_conf
) {
1092 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1093 if (!init_ctx
->container
->lxc_conf
) {
1094 lxc_proc_put_context_info(init_ctx
);
1098 conf
= init_ctx
->container
->lxc_conf
;
1100 if (!fetch_seccomp(init_ctx
->container
, options
))
1101 WARN("Failed to get seccomp policy");
1103 if (!no_new_privs(init_ctx
->container
, options
))
1104 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1106 cwd
= getcwd(NULL
, 0);
1108 /* Determine which namespaces the container was created with
1109 * by asking lxc-start, if necessary.
1111 if (options
->namespaces
== -1) {
1112 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1114 if (options
->namespaces
== -1) {
1115 ERROR("Failed to automatically determine the "
1116 "namespaces which the container uses");
1118 lxc_proc_put_context_info(init_ctx
);
1122 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1123 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1124 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1128 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1131 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1135 pid
= lxc_raw_getpid();
1136 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1139 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1140 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1141 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1142 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1145 if (init_ctx
->ns_fd
[i
] >= 0)
1148 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1149 DEBUG("Inheriting %s namespace from %d",
1150 ns_info
[i
].proc_name
, pid
);
1151 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1155 /* We failed to preserve the namespace. */
1156 saved_errno
= errno
;
1157 /* Close all already opened file descriptors before we return an
1158 * error, so we don't leak them.
1160 for (j
= 0; j
< i
; j
++)
1161 close(init_ctx
->ns_fd
[j
]);
1163 errno
= saved_errno
;
1164 SYSERROR("Failed to attach to %s namespace of %d",
1165 ns_info
[i
].proc_name
, pid
);
1167 lxc_proc_put_context_info(init_ctx
);
1171 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1172 ret
= lxc_attach_terminal(conf
, &terminal
);
1174 ERROR("Failed to setup new terminal");
1176 lxc_proc_put_context_info(init_ctx
);
1180 terminal
.log_fd
= options
->log_fd
;
1182 lxc_terminal_init(&terminal
);
1185 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1186 * to make sure we don't irritate other threads that want to fork+exec
1189 * IMPORTANT: if the initial process is multithreaded and another call
1190 * just fork()s away without exec'ing directly after, the socket fd will
1191 * exist in the forked process from the other thread and any close() in
1192 * our own child process will not really cause the socket to close
1193 * properly, potentiall causing the parent to hang.
1195 * For this reason, while IPC is still active, we have to use shutdown()
1196 * if the child exits prematurely in order to signal that the socket is
1197 * closed and cannot assume that the child exiting will automatically do
1200 * IPC mechanism: (X is receiver)
1201 * initial process intermediate attached
1202 * X <--- send pid of
1205 * send 0 ------------------------------------> X
1206 * [do initialization]
1207 * X <------------------------------------ send 1
1208 * [add to cgroup, ...]
1209 * send 2 ------------------------------------> X
1210 * [set LXC_ATTACH_NO_NEW_PRIVS]
1211 * X <------------------------------------ send 3
1212 * [open LSM label fd]
1213 * send 4 ------------------------------------> X
1215 * close socket close socket
1218 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1220 SYSERROR("Could not set up required IPC mechanism for attaching");
1222 lxc_proc_put_context_info(init_ctx
);
1226 /* Create intermediate subprocess, two reasons:
1227 * 1. We can't setns() in the child itself, since we want to make
1228 * sure we are properly attached to the pidns.
1229 * 2. Also, the initial thread has to put the attached process
1230 * into the cgroup, which we can only do if we didn't already
1231 * setns() (otherwise, user namespaces will hate us).
1235 SYSERROR("Failed to create first subprocess");
1237 lxc_proc_put_context_info(init_ctx
);
1242 int ret_parent
= -1;
1243 pid_t to_cleanup_pid
= pid
;
1244 struct lxc_epoll_descr descr
= {0};
1246 /* close unneeded file descriptors */
1247 close(ipc_sockets
[1]);
1249 lxc_proc_close_ns_fd(init_ctx
);
1250 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1251 lxc_attach_terminal_close_slave(&terminal
);
1253 /* Attach to cgroup, if requested. */
1254 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1255 struct cgroup_ops
*cgroup_ops
;
1257 cgroup_ops
= cgroup_init(NULL
);
1261 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1264 cgroup_exit(cgroup_ops
);
1265 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1268 /* Setup /proc limits */
1269 if (!lxc_list_empty(&conf
->procs
)) {
1270 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1275 /* Setup resource limits */
1276 if (!lxc_list_empty(&conf
->limits
)) {
1277 ret
= setup_resource_limits(&conf
->limits
, pid
);
1282 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1283 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1286 TRACE("Initialized terminal mainloop");
1289 /* Let the child process know to go ahead. */
1291 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1292 if (ret
!= sizeof(status
))
1293 goto close_mainloop
;
1294 TRACE("Told intermediate process to start initializing");
1296 /* Get pid of attached process from intermediate process. */
1297 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1298 if (ret
!= sizeof(attached_pid
))
1299 goto close_mainloop
;
1300 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1302 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1303 if (options
->stdin_fd
== 0) {
1304 signal(SIGINT
, SIG_IGN
);
1305 signal(SIGQUIT
, SIG_IGN
);
1308 /* Reap intermediate process. */
1309 ret
= wait_for_pid(pid
);
1311 goto close_mainloop
;
1312 TRACE("Intermediate process %d exited", pid
);
1314 /* We will always have to reap the attached process now. */
1315 to_cleanup_pid
= attached_pid
;
1317 /* Open LSM fd and send it to child. */
1318 if ((options
->namespaces
& CLONE_NEWNS
) &&
1319 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1320 init_ctx
->lsm_label
) {
1325 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1326 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1328 goto close_mainloop
;
1329 TRACE("Opened LSM label file descriptor %d", labelfd
);
1331 /* Send child fd of the LSM security module to write to. */
1332 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1335 SYSERROR("%d", (int)ret
);
1336 goto close_mainloop
;
1338 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1341 /* We're done, the child process should now execute whatever it
1342 * is that the user requested. The parent can now track it with
1343 * waitpid() or similar.
1346 *attached_process
= attached_pid
;
1348 /* Now shut down communication with child, we're done. */
1349 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1350 close(ipc_sockets
[0]);
1351 ipc_sockets
[0] = -1;
1354 to_cleanup_pid
= -1;
1355 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1356 ret
= lxc_mainloop(&descr
, -1);
1359 to_cleanup_pid
= attached_pid
;
1364 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1365 lxc_mainloop_close(&descr
);
1368 if (ipc_sockets
[0] >= 0) {
1369 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1370 close(ipc_sockets
[0]);
1373 if (to_cleanup_pid
> 0)
1374 (void)wait_for_pid(to_cleanup_pid
);
1376 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1377 lxc_terminal_delete(&terminal
);
1378 lxc_terminal_conf_free(&terminal
);
1380 lxc_proc_put_context_info(init_ctx
);
1384 /* close unneeded file descriptors */
1385 close(ipc_sockets
[0]);
1386 ipc_sockets
[0] = -EBADF
;
1387 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1388 lxc_attach_terminal_close_master(&terminal
);
1389 lxc_attach_terminal_close_peer(&terminal
);
1390 lxc_attach_terminal_close_log(&terminal
);
1393 /* Wait for the parent to have setup cgroups. */
1394 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1395 if (ret
!= sizeof(status
)) {
1396 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1397 lxc_proc_put_context_info(init_ctx
);
1400 TRACE("Intermediate process starting to initialize");
1402 /* Attach now, create another subprocess later, since pid namespaces
1403 * only really affect the children of the current process.
1405 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1407 ERROR("Failed to enter namespaces");
1408 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1409 lxc_proc_put_context_info(init_ctx
);
1412 /* close namespace file descriptors */
1413 lxc_proc_close_ns_fd(init_ctx
);
1415 /* Attach succeeded, try to cwd. */
1416 if (options
->initial_cwd
)
1417 new_cwd
= options
->initial_cwd
;
1421 ret
= chdir(new_cwd
);
1423 WARN("Could not change directory to \"%s\"", new_cwd
);
1427 /* Create attached process. */
1428 payload
.ipc_socket
= ipc_sockets
[1];
1429 payload
.options
= options
;
1430 payload
.init_ctx
= init_ctx
;
1431 payload
.terminal_slave_fd
= terminal
.slave
;
1432 payload
.exec_function
= exec_function
;
1433 payload
.exec_payload
= exec_payload
;
1435 pid
= lxc_raw_clone(CLONE_PARENT
);
1437 SYSERROR("Failed to clone attached process");
1438 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1439 lxc_proc_put_context_info(init_ctx
);
1444 ret
= attach_child_main(&payload
);
1446 ERROR("Failed to exec");
1447 _exit(EXIT_FAILURE
);
1449 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1450 lxc_attach_terminal_close_slave(&terminal
);
1452 /* Tell grandparent the pid of the pid of the newly created child. */
1453 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1454 if (ret
!= sizeof(pid
)) {
1455 /* If this really happens here, this is very unfortunate, since
1456 * the parent will not know the pid of the attached process and
1457 * will not be able to wait for it (and we won't either due to
1458 * CLONE_PARENT) so the parent won't be able to reap it and the
1459 * attached process will remain a zombie.
1461 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1462 lxc_proc_put_context_info(init_ctx
);
1465 TRACE("Sending pid %d of attached process", pid
);
1467 /* The rest is in the hands of the initial and the attached process. */
1468 lxc_proc_put_context_info(init_ctx
);
1472 int lxc_attach_run_command(void* payload
)
1474 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1476 execvp(cmd
->program
, cmd
->argv
);
1477 SYSERROR("Failed to exec \"%s\".", cmd
->program
);
1481 int lxc_attach_run_shell(void* payload
)
1484 struct passwd pwent
;
1485 struct passwd
*pwentp
= NULL
;
1491 /* Ignore payload parameter. */
1496 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1500 buf
= malloc(bufsize
);
1502 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1505 WARN("Could not find matched password record.");
1507 WARN("Failed to get password record - %u", uid
);
1511 /* This probably happens because of incompatible nss implementations in
1512 * host and container (remember, this code is still using the host's
1513 * glibc but our mount namespace is in the container) we may try to get
1514 * the information by spawning a [getent passwd uid] process and parsing
1518 user_shell
= lxc_attach_getpwshell(uid
);
1520 user_shell
= pwent
.pw_shell
;
1522 execlp(user_shell
, user_shell
, (char *)NULL
);
1524 /* Executed if either no passwd entry or execvp fails, we will fall back
1525 * on /bin/sh as a default shell.
1527 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1528 SYSERROR("Failed to execute shell");