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
28 #include <linux/unistd.h>
34 #include <sys/mount.h>
35 #include <sys/param.h>
36 #include <sys/prctl.h>
37 #include <sys/socket.h>
38 #include <sys/syscall.h>
43 #include <lxc/lxccontainer.h>
56 #include "lxcseccomp.h"
59 #include "namespace.h"
63 #if HAVE_SYS_PERSONALITY_H
64 #include <sys/personality.h>
67 lxc_log_define(attach
, lxc
);
69 /* Define default options if no options are supplied by the user. */
70 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
72 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
77 char proc_fn
[LXC_PROC_STATUS_LEN
];
78 size_t line_bufsz
= 0;
80 struct lxc_proc_context_info
*info
= NULL
;
82 /* Read capabilities. */
83 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", pid
);
84 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
87 proc_file
= fopen(proc_fn
, "r");
89 SYSERROR("Could not open %s", proc_fn
);
93 info
= calloc(1, sizeof(*info
));
95 SYSERROR("Could not allocate memory");
102 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
103 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
104 if (ret
!= EOF
&& ret
== 1) {
114 ERROR("Could not read capability bounding set from %s",
119 info
->lsm_label
= lsm_process_label_get(pid
);
120 info
->ns_inherited
= 0;
121 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
130 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
134 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
135 if (ctx
->ns_fd
[i
] < 0)
138 close(ctx
->ns_fd
[i
]);
139 ctx
->ns_fd
[i
] = -EBADF
;
143 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
145 free(ctx
->lsm_label
);
146 ctx
->lsm_label
= NULL
;
148 if (ctx
->container
) {
149 lxc_container_put(ctx
->container
);
150 ctx
->container
= NULL
;
153 lxc_proc_close_ns_fd(ctx
);
158 * in_same_namespace - Check whether two processes are in the same namespace.
159 * @pid1 - PID of the first process.
160 * @pid2 - PID of the second process.
161 * @ns - Name of the namespace to check. Must correspond to one of the names
162 * for the namespaces as shown in /proc/<pid/ns/
164 * If the two processes are not in the same namespace returns an fd to the
165 * namespace of the second process identified by @pid2. If the two processes are
166 * in the same namespace returns -EINVAL, -1 if an error occurred.
168 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
170 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
172 struct stat ns_st1
, ns_st2
;
174 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
176 /* The kernel does not support this namespace. This is not an
185 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
189 ret
= fstat(ns_fd1
, &ns_st1
);
193 ret
= fstat(ns_fd2
, &ns_st2
);
197 /* processes are in the same namespace */
198 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
)) {
203 /* processes are in different namespaces */
220 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
224 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
225 if (ctx
->ns_fd
[i
] < 0)
228 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
230 SYSERROR("Failed to attach to %s namespace of %d",
231 ns_info
[i
].proc_name
, pid
);
235 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
241 static int lxc_attach_remount_sys_proc(void)
245 ret
= unshare(CLONE_NEWNS
);
247 SYSERROR("Failed to unshare mount namespace");
251 if (detect_shared_rootfs()) {
252 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
253 SYSERROR("Failed to make / rslave");
254 ERROR("Continuing...");
258 /* Assume /proc is always mounted, so remount it. */
259 ret
= umount2("/proc", MNT_DETACH
);
261 SYSERROR("Failed to unmount /proc");
265 ret
= mount("none", "/proc", "proc", 0, NULL
);
267 SYSERROR("Failed to remount /proc");
271 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
272 * we ignore it because it may not have been mounted in the first place.
274 ret
= umount2("/sys", MNT_DETACH
);
275 if (ret
< 0 && errno
!= EINVAL
) {
276 SYSERROR("Failed to unmount /sys");
278 } else if (ret
== 0) {
280 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
282 SYSERROR("Failed to remount /sys");
290 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
294 last_cap
= lxc_caps_last_cap();
295 for (cap
= 0; cap
<= last_cap
; cap
++) {
296 if (ctx
->capability_mask
& (1LL << cap
))
299 if (prctl(PR_CAPBSET_DROP
, prctl_arg(cap
), prctl_arg(0),
300 prctl_arg(0), prctl_arg(0))) {
301 SYSERROR("Failed to drop capability %d", cap
);
305 TRACE("Dropped capability %d", cap
);
311 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
312 enum lxc_attach_env_policy_t policy
,
313 char **extra_env
, char **extra_keep
)
316 struct lxc_list
*iterator
;
318 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
320 char **extra_keep_store
= NULL
;
325 for (count
= 0; extra_keep
[count
]; count
++)
328 extra_keep_store
= calloc(count
, sizeof(char *));
329 if (!extra_keep_store
)
332 for (i
= 0; i
< count
; i
++) {
333 char *v
= getenv(extra_keep
[i
]);
335 extra_keep_store
[i
] = strdup(v
);
336 if (!extra_keep_store
[i
]) {
338 free(extra_keep_store
[--i
]);
340 free(extra_keep_store
);
344 if (strcmp(extra_keep
[i
], "PATH") == 0)
351 if (extra_keep_store
) {
354 for (p
= extra_keep_store
; *p
; p
++)
357 free(extra_keep_store
);
360 ERROR("Failed to clear environment");
364 if (extra_keep_store
) {
367 for (i
= 0; extra_keep
[i
]; i
++) {
368 if (extra_keep_store
[i
]) {
369 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
371 SYSWARN("Failed to set environment variable");
374 free(extra_keep_store
[i
]);
377 free(extra_keep_store
);
380 /* Always set a default path; shells and execlp tend to be fine
381 * without it, but there is a disturbing number of C programs
382 * out there that just assume that getenv("PATH") is never NULL
383 * and then die a painful segfault death.
386 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
388 SYSWARN("Failed to set environment variable");
392 ret
= putenv("container=lxc");
394 SYSWARN("Failed to set environment variable");
398 /* Set container environment variables.*/
399 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
400 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
403 env_tmp
= strdup((char *)iterator
->elem
);
407 ret
= putenv(env_tmp
);
409 SYSERROR("Failed to set environment variable: %s", (char *)iterator
->elem
);
415 /* Set extra environment variables. */
417 for (; *extra_env
; extra_env
++) {
420 /* We just assume the user knows what they are doing, so
421 * we don't do any checks.
423 p
= strdup(*extra_env
);
429 SYSWARN("Failed to set environment variable");
436 static char *lxc_attach_getpwshell(uid_t uid
)
443 size_t line_bufsz
= 0;
444 char *line
= NULL
, *result
= NULL
;
446 /* We need to fork off a process that runs the getent program, and we
447 * need to capture its output, so we use a pipe for that purpose.
449 ret
= pipe2(pipes
, O_CLOEXEC
);
462 char *arguments
[] = {
471 /* We want to capture stdout. */
472 ret
= dup2(pipes
[1], STDOUT_FILENO
);
477 /* Get rid of stdin/stderr, so we try to associate it with
483 close(STDERR_FILENO
);
485 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
486 (void)dup3(fd
, STDOUT_FILENO
, O_CLOEXEC
);
490 /* Finish argument list. */
491 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
492 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
495 /* Try to run getent program. */
496 (void)execvp("getent", arguments
);
502 pipe_f
= fdopen(pipes
[0], "r");
503 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
507 char *endptr
= NULL
, *saveptr
= NULL
;
509 /* If we already found something, just continue to read
510 * until the pipe doesn't deliver any more data, but
511 * don't modify the existing data structure.
519 /* Trim line on the right hand side. */
520 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
523 /* Split into tokens: first: user name. */
524 token
= strtok_r(line
, ":", &saveptr
);
528 /* next: dummy password field */
529 token
= strtok_r(NULL
, ":", &saveptr
);
534 token
= strtok_r(NULL
, ":", &saveptr
);
535 value
= token
? strtol(token
, &endptr
, 10) : 0;
536 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
540 /* dummy sanity check: user id matches */
541 if ((uid_t
)value
!= uid
)
544 /* skip fields: gid, gecos, dir, go to next field 'shell' */
545 for (i
= 0; i
< 4; i
++) {
546 token
= strtok_r(NULL
, ":", &saveptr
);
555 result
= strdup(token
);
557 /* Sanity check that there are no fields after that. */
558 token
= strtok_r(NULL
, ":", &saveptr
);
568 ret
= wait_for_pid(pid
);
582 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
585 char proc_fn
[LXC_PROC_STATUS_LEN
];
588 size_t line_bufsz
= 0;
590 uid_t uid
= (uid_t
)-1;
591 gid_t gid
= (gid_t
)-1;
593 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", 1);
594 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
597 proc_file
= fopen(proc_fn
, "r");
601 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
602 /* Format is: real, effective, saved set user, fs we only care
605 ret
= sscanf(line
, "Uid: %ld", &value
);
606 if (ret
!= EOF
&& ret
== 1) {
609 ret
= sscanf(line
, "Gid: %ld", &value
);
610 if (ret
!= EOF
&& ret
== 1)
614 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
621 /* Only override arguments if we found something. */
622 if (uid
!= (uid_t
)-1)
625 if (gid
!= (gid_t
)-1)
628 /* TODO: we should also parse supplementary groups and use
629 * setgroups() to set them.
633 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
639 if (!(options
->namespaces
& CLONE_NEWNS
) ||
640 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
641 free(c
->lxc_conf
->seccomp
);
642 c
->lxc_conf
->seccomp
= NULL
;
646 /* Remove current setting. */
647 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
648 !c
->set_config_item(c
, "lxc.seccomp", ""))
651 /* Fetch the current profile path over the cmd interface. */
652 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
654 INFO("Failed to retrieve lxc.seccomp.profile");
656 path
= c
->get_running_config_item(c
, "lxc.seccomp");
658 INFO("Failed to retrieve lxc.seccomp");
663 /* Copy the value into the new lxc_conf. */
664 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
669 /* Attempt to parse the resulting config. */
670 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
672 ERROR("Failed to retrieve seccomp policy");
676 INFO("Retrieved seccomp policy");
680 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
685 /* Remove current setting. */
686 if (!c
->set_config_item(c
, "lxc.no_new_privs", "")) {
687 INFO("Failed to unset lxc.no_new_privs");
691 /* Retrieve currently active setting. */
692 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
694 INFO("Failed to retrieve lxc.no_new_privs");
698 /* Set currently active setting. */
699 bret
= c
->set_config_item(c
, "lxc.no_new_privs", val
);
704 static signed long get_personality(const char *name
, const char *lxcpath
)
709 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
713 ret
= lxc_config_parse_arch(p
);
719 struct attach_clone_payload
{
721 int terminal_slave_fd
;
722 lxc_attach_options_t
*options
;
723 struct lxc_proc_context_info
*init_ctx
;
724 lxc_attach_exec_t exec_function
;
728 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
730 if (p
->ipc_socket
>= 0) {
731 shutdown(p
->ipc_socket
, SHUT_RDWR
);
732 close(p
->ipc_socket
);
733 p
->ipc_socket
= -EBADF
;
736 if (p
->terminal_slave_fd
>= 0) {
737 close(p
->terminal_slave_fd
);
738 p
->terminal_slave_fd
= -EBADF
;
742 lxc_proc_put_context_info(p
->init_ctx
);
747 static int attach_child_main(struct attach_clone_payload
*payload
)
752 lxc_attach_options_t
* options
= payload
->options
;
753 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
754 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
755 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
758 /* A description of the purpose of this functionality is provided in the
759 * lxc-attach(1) manual page. We have to remount here and not in the
760 * parent process, otherwise /proc may not properly reflect the new pid
763 if (!(options
->namespaces
& CLONE_NEWNS
) &&
764 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
765 ret
= lxc_attach_remount_sys_proc();
769 TRACE("Remounted \"/proc\" and \"/sys\"");
772 /* Now perform additional attachments. */
773 #if HAVE_SYS_PERSONALITY_H
774 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
775 long new_personality
;
777 if (options
->personality
< 0)
778 new_personality
= init_ctx
->personality
;
780 new_personality
= options
->personality
;
782 ret
= personality(new_personality
);
786 TRACE("Set new personality");
790 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
791 ret
= lxc_attach_drop_privs(init_ctx
);
795 TRACE("Dropped capabilities");
798 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
799 * if you want this to be a no-op).
801 ret
= lxc_attach_set_environment(init_ctx
,
803 options
->extra_env_vars
,
804 options
->extra_keep_env
);
808 TRACE("Set up environment");
810 /* This remark only affects fully unprivileged containers:
811 * Receive fd for LSM security module before we set{g,u}id(). The reason
812 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
813 * we will change our effective uid. This means our effective uid will
814 * be different from the effective uid of the process that created us
815 * which means that this processs no longer has capabilities in our
816 * namespace including CAP_SYS_PTRACE. This means we will not be able to
817 * read and /proc/<pid> files for the process anymore when /proc is
818 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
822 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
825 SYSERROR("Failed to receive lsm label fd");
830 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
833 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
834 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
843 /* Ignore errors, we will fall back to root in that case (/proc was not
846 if (options
->namespaces
& CLONE_NEWUSER
)
847 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
849 if (options
->uid
!= (uid_t
)-1)
850 new_uid
= options
->uid
;
852 if (options
->gid
!= (gid_t
)-1)
853 new_gid
= options
->gid
;
855 /* Try to set the {u,g}id combination. */
856 if (new_uid
!= 0 || new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) {
857 ret
= lxc_switch_uid_gid(new_uid
, new_gid
);
862 ret
= lxc_setgroups(0, NULL
);
863 if (ret
< 0 && errno
!= EPERM
)
866 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
867 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
868 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
869 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
870 prctl_arg(0), prctl_arg(0));
874 TRACE("Set PR_SET_NO_NEW_PRIVS");
880 /* Change into our new LSM profile. */
881 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
883 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
888 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
891 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
892 init_ctx
->container
->lxc_conf
->seccomp
) {
893 ret
= lxc_seccomp_load(init_ctx
->container
->lxc_conf
);
897 TRACE("Loaded seccomp profile");
900 shutdown(payload
->ipc_socket
, SHUT_RDWR
);
901 close(payload
->ipc_socket
);
902 payload
->ipc_socket
= -EBADF
;
903 lxc_proc_put_context_info(init_ctx
);
904 payload
->init_ctx
= NULL
;
906 /* The following is done after the communication socket is shut down.
907 * That way, all errors that might (though unlikely) occur up until this
908 * point will have their messages printed to the original stderr (if
909 * logging is so configured) and not the fd the user supplied, if any.
912 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
913 * may want to make sure the fds are closed, for example.
915 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
916 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
918 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
919 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
921 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
922 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
924 /* close the old fds */
925 if (options
->stdin_fd
> STDERR_FILENO
)
926 close(options
->stdin_fd
);
928 if (options
->stdout_fd
> STDERR_FILENO
)
929 close(options
->stdout_fd
);
931 if (options
->stderr_fd
> STDERR_FILENO
)
932 close(options
->stderr_fd
);
934 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
935 * here, ignore errors.
937 for (fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
938 ret
= fd_cloexec(fd
, false);
940 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
945 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
946 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
948 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
952 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
955 /* We're done, so we can now do whatever the user intended us to do. */
956 _exit(payload
->exec_function(payload
->exec_payload
));
959 lxc_put_attach_clone_payload(payload
);
963 static int lxc_attach_terminal(struct lxc_conf
*conf
,
964 struct lxc_terminal
*terminal
)
968 lxc_terminal_init(terminal
);
970 ret
= lxc_terminal_create(terminal
);
972 ERROR("Failed to create terminal");
976 /* Shift ttys to container. */
977 ret
= lxc_terminal_map_ids(conf
, terminal
);
979 ERROR("Failed to chown terminal");
986 lxc_terminal_delete(terminal
);
987 lxc_terminal_conf_free(terminal
);
991 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
992 struct lxc_epoll_descr
*descr
)
996 ret
= lxc_mainloop_open(descr
);
998 ERROR("Failed to create mainloop");
1002 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
1004 ERROR("Failed to add handlers to mainloop");
1005 lxc_mainloop_close(descr
);
1012 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
1014 if (terminal
->master
< 0)
1017 close(terminal
->master
);
1018 terminal
->master
= -EBADF
;
1021 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
1023 if (terminal
->slave
< 0)
1026 close(terminal
->slave
);
1027 terminal
->slave
= -EBADF
;
1030 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
1032 if (terminal
->peer
< 0)
1035 close(terminal
->peer
);
1036 terminal
->peer
= -EBADF
;
1039 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
1041 if (terminal
->log_fd
< 0)
1044 close(terminal
->log_fd
);
1045 terminal
->log_fd
= -EBADF
;
1048 int lxc_attach(const char *name
, const char *lxcpath
,
1049 lxc_attach_exec_t exec_function
, void *exec_payload
,
1050 lxc_attach_options_t
*options
, pid_t
*attached_process
)
1054 char *cwd
, *new_cwd
;
1055 signed long personality
;
1056 pid_t attached_pid
, init_pid
, pid
;
1057 struct lxc_proc_context_info
*init_ctx
;
1058 struct lxc_terminal terminal
;
1059 struct lxc_conf
*conf
;
1060 struct attach_clone_payload payload
= {0};
1062 ret
= access("/proc/self/ns", X_OK
);
1064 SYSERROR("Does this kernel version support namespaces?");
1069 options
= &attach_static_default_options
;
1071 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1073 ERROR("Failed to get init pid");
1077 init_ctx
= lxc_proc_get_context_info(init_pid
);
1079 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1083 personality
= get_personality(name
, lxcpath
);
1084 if (init_ctx
->personality
< 0) {
1085 ERROR("Failed to get personality of the container");
1086 lxc_proc_put_context_info(init_ctx
);
1089 init_ctx
->personality
= personality
;
1091 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
1092 if (!init_ctx
->container
) {
1093 lxc_proc_put_context_info(init_ctx
);
1097 if (!init_ctx
->container
->lxc_conf
) {
1098 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1099 if (!init_ctx
->container
->lxc_conf
) {
1100 lxc_proc_put_context_info(init_ctx
);
1104 conf
= init_ctx
->container
->lxc_conf
;
1106 if (!fetch_seccomp(init_ctx
->container
, options
))
1107 WARN("Failed to get seccomp policy");
1109 if (!no_new_privs(init_ctx
->container
, options
))
1110 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1112 cwd
= getcwd(NULL
, 0);
1114 /* Determine which namespaces the container was created with
1115 * by asking lxc-start, if necessary.
1117 if (options
->namespaces
== -1) {
1118 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1120 if (options
->namespaces
== -1) {
1121 ERROR("Failed to automatically determine the "
1122 "namespaces which the container uses");
1124 lxc_proc_put_context_info(init_ctx
);
1128 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1129 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1130 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1134 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1137 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1141 pid
= lxc_raw_getpid();
1143 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1146 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1147 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1148 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1149 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1153 if (init_ctx
->ns_fd
[i
] >= 0)
1156 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1157 DEBUG("Inheriting %s namespace from %d",
1158 ns_info
[i
].proc_name
, pid
);
1159 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1163 /* We failed to preserve the namespace. */
1164 SYSERROR("Failed to attach to %s namespace of %d",
1165 ns_info
[i
].proc_name
, pid
);
1167 /* Close all already opened file descriptors before we return an
1168 * error, so we don't leak them.
1170 for (j
= 0; j
< i
; j
++)
1171 close(init_ctx
->ns_fd
[j
]);
1174 lxc_proc_put_context_info(init_ctx
);
1178 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1179 ret
= lxc_attach_terminal(conf
, &terminal
);
1181 ERROR("Failed to setup new terminal");
1183 lxc_proc_put_context_info(init_ctx
);
1187 terminal
.log_fd
= options
->log_fd
;
1189 lxc_terminal_init(&terminal
);
1192 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1193 * to make sure we don't irritate other threads that want to fork+exec
1196 * IMPORTANT: if the initial process is multithreaded and another call
1197 * just fork()s away without exec'ing directly after, the socket fd will
1198 * exist in the forked process from the other thread and any close() in
1199 * our own child process will not really cause the socket to close
1200 * properly, potentiall causing the parent to hang.
1202 * For this reason, while IPC is still active, we have to use shutdown()
1203 * if the child exits prematurely in order to signal that the socket is
1204 * closed and cannot assume that the child exiting will automatically do
1207 * IPC mechanism: (X is receiver)
1208 * initial process intermediate attached
1209 * X <--- send pid of
1212 * send 0 ------------------------------------> X
1213 * [do initialization]
1214 * X <------------------------------------ send 1
1215 * [add to cgroup, ...]
1216 * send 2 ------------------------------------> X
1217 * [set LXC_ATTACH_NO_NEW_PRIVS]
1218 * X <------------------------------------ send 3
1219 * [open LSM label fd]
1220 * send 4 ------------------------------------> X
1222 * close socket close socket
1225 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1227 SYSERROR("Could not set up required IPC mechanism for attaching");
1229 lxc_proc_put_context_info(init_ctx
);
1233 /* Create intermediate subprocess, two reasons:
1234 * 1. We can't setns() in the child itself, since we want to make
1235 * sure we are properly attached to the pidns.
1236 * 2. Also, the initial thread has to put the attached process
1237 * into the cgroup, which we can only do if we didn't already
1238 * setns() (otherwise, user namespaces will hate us).
1242 SYSERROR("Failed to create first subprocess");
1244 lxc_proc_put_context_info(init_ctx
);
1249 int ret_parent
= -1;
1250 pid_t to_cleanup_pid
= pid
;
1251 struct lxc_epoll_descr descr
= {0};
1253 /* close unneeded file descriptors */
1254 close(ipc_sockets
[1]);
1256 lxc_proc_close_ns_fd(init_ctx
);
1257 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1258 lxc_attach_terminal_close_slave(&terminal
);
1260 /* Attach to cgroup, if requested. */
1261 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1262 struct cgroup_ops
*cgroup_ops
;
1264 cgroup_ops
= cgroup_init(conf
);
1268 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1271 cgroup_exit(cgroup_ops
);
1272 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1275 /* Setup /proc limits */
1276 if (!lxc_list_empty(&conf
->procs
)) {
1277 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1282 /* Setup resource limits */
1283 if (!lxc_list_empty(&conf
->limits
)) {
1284 ret
= setup_resource_limits(&conf
->limits
, pid
);
1289 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1290 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1294 TRACE("Initialized terminal mainloop");
1297 /* Let the child process know to go ahead. */
1299 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1300 if (ret
!= sizeof(status
))
1301 goto close_mainloop
;
1303 TRACE("Told intermediate process to start initializing");
1305 /* Get pid of attached process from intermediate process. */
1306 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1307 if (ret
!= sizeof(attached_pid
))
1308 goto close_mainloop
;
1310 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1312 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1313 if (options
->stdin_fd
== 0) {
1314 signal(SIGINT
, SIG_IGN
);
1315 signal(SIGQUIT
, SIG_IGN
);
1318 /* Reap intermediate process. */
1319 ret
= wait_for_pid(pid
);
1321 goto close_mainloop
;
1323 TRACE("Intermediate process %d exited", pid
);
1325 /* We will always have to reap the attached process now. */
1326 to_cleanup_pid
= attached_pid
;
1328 /* Open LSM fd and send it to child. */
1329 if ((options
->namespaces
& CLONE_NEWNS
) &&
1330 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1331 init_ctx
->lsm_label
) {
1336 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1337 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1339 goto close_mainloop
;
1341 TRACE("Opened LSM label file descriptor %d", labelfd
);
1343 /* Send child fd of the LSM security module to write to. */
1344 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1347 SYSERROR("Failed to send lsm label fd");
1350 goto close_mainloop
;
1354 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1357 /* We're done, the child process should now execute whatever it
1358 * is that the user requested. The parent can now track it with
1359 * waitpid() or similar.
1362 *attached_process
= attached_pid
;
1364 /* Now shut down communication with child, we're done. */
1365 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1366 close(ipc_sockets
[0]);
1367 ipc_sockets
[0] = -1;
1370 to_cleanup_pid
= -1;
1372 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1373 ret
= lxc_mainloop(&descr
, -1);
1376 to_cleanup_pid
= attached_pid
;
1381 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1382 lxc_mainloop_close(&descr
);
1385 if (ipc_sockets
[0] >= 0) {
1386 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1387 close(ipc_sockets
[0]);
1390 if (to_cleanup_pid
> 0)
1391 (void)wait_for_pid(to_cleanup_pid
);
1393 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1394 lxc_terminal_delete(&terminal
);
1395 lxc_terminal_conf_free(&terminal
);
1398 lxc_proc_put_context_info(init_ctx
);
1402 /* close unneeded file descriptors */
1403 close(ipc_sockets
[0]);
1404 ipc_sockets
[0] = -EBADF
;
1406 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1407 lxc_attach_terminal_close_master(&terminal
);
1408 lxc_attach_terminal_close_peer(&terminal
);
1409 lxc_attach_terminal_close_log(&terminal
);
1412 /* Wait for the parent to have setup cgroups. */
1413 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1414 if (ret
!= sizeof(status
)) {
1415 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1416 lxc_proc_put_context_info(init_ctx
);
1417 _exit(EXIT_FAILURE
);
1420 TRACE("Intermediate process starting to initialize");
1422 /* Attach now, create another subprocess later, since pid namespaces
1423 * only really affect the children of the current process.
1425 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1427 ERROR("Failed to enter namespaces");
1428 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1429 lxc_proc_put_context_info(init_ctx
);
1430 _exit(EXIT_FAILURE
);
1433 /* close namespace file descriptors */
1434 lxc_proc_close_ns_fd(init_ctx
);
1436 /* Attach succeeded, try to cwd. */
1437 if (options
->initial_cwd
)
1438 new_cwd
= options
->initial_cwd
;
1442 ret
= chdir(new_cwd
);
1444 WARN("Could not change directory to \"%s\"", new_cwd
);
1448 /* Create attached process. */
1449 payload
.ipc_socket
= ipc_sockets
[1];
1450 payload
.options
= options
;
1451 payload
.init_ctx
= init_ctx
;
1452 payload
.terminal_slave_fd
= terminal
.slave
;
1453 payload
.exec_function
= exec_function
;
1454 payload
.exec_payload
= exec_payload
;
1456 pid
= lxc_raw_clone(CLONE_PARENT
);
1458 SYSERROR("Failed to clone attached process");
1459 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1460 lxc_proc_put_context_info(init_ctx
);
1461 _exit(EXIT_FAILURE
);
1465 ret
= attach_child_main(&payload
);
1467 ERROR("Failed to exec");
1469 _exit(EXIT_FAILURE
);
1472 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1473 lxc_attach_terminal_close_slave(&terminal
);
1475 /* Tell grandparent the pid of the pid of the newly created child. */
1476 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1477 if (ret
!= sizeof(pid
)) {
1478 /* If this really happens here, this is very unfortunate, since
1479 * the parent will not know the pid of the attached process and
1480 * will not be able to wait for it (and we won't either due to
1481 * CLONE_PARENT) so the parent won't be able to reap it and the
1482 * attached process will remain a zombie.
1484 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1485 lxc_proc_put_context_info(init_ctx
);
1486 _exit(EXIT_FAILURE
);
1489 TRACE("Sending pid %d of attached process", pid
);
1491 /* The rest is in the hands of the initial and the attached process. */
1492 lxc_proc_put_context_info(init_ctx
);
1496 int lxc_attach_run_command(void* payload
)
1498 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1500 execvp(cmd
->program
, cmd
->argv
);
1502 SYSERROR("Failed to exec \"%s\"", cmd
->program
);
1506 int lxc_attach_run_shell(void* payload
)
1509 struct passwd pwent
;
1510 struct passwd
*pwentp
= NULL
;
1516 /* Ignore payload parameter. */
1521 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1525 buf
= malloc(bufsize
);
1527 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1530 WARN("Could not find matched password record");
1532 WARN("Failed to get password record - %u", uid
);
1536 /* This probably happens because of incompatible nss implementations in
1537 * host and container (remember, this code is still using the host's
1538 * glibc but our mount namespace is in the container) we may try to get
1539 * the information by spawning a [getent passwd uid] process and parsing
1543 user_shell
= lxc_attach_getpwshell(uid
);
1545 user_shell
= pwent
.pw_shell
;
1548 execlp(user_shell
, user_shell
, (char *)NULL
);
1550 /* Executed if either no passwd entry or execvp fails, we will fall back
1551 * on /bin/sh as a default shell.
1553 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1555 SYSERROR("Failed to execute shell");