1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include <linux/unistd.h>
16 #include <sys/mount.h>
17 #include <sys/param.h>
18 #include <sys/prctl.h>
19 #include <sys/socket.h>
20 #include <sys/syscall.h>
25 #include <lxc/lxccontainer.h>
38 #include "lxcseccomp.h"
41 #include "memory_utils.h"
42 #include "namespace.h"
43 #include "raw_syscalls.h"
44 #include "syscall_wrappers.h"
48 #if HAVE_SYS_PERSONALITY_H
49 #include <sys/personality.h>
52 lxc_log_define(attach
, lxc
);
54 /* Define default options if no options are supplied by the user. */
55 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
57 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
59 __do_free
char *line
= NULL
;
60 __do_fclose
FILE *proc_file
= NULL
;
63 char proc_fn
[LXC_PROC_STATUS_LEN
];
64 struct lxc_proc_context_info
*info
;
65 size_t line_bufsz
= 0;
67 /* Read capabilities. */
68 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", pid
);
69 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
72 proc_file
= fopen(proc_fn
, "r");
74 SYSERROR("Failed to open %s", proc_fn
);
78 info
= calloc(1, sizeof(*info
));
84 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
85 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
86 if (ret
!= EOF
&& ret
== 1) {
93 ERROR("Could not read capability bounding set from %s", proc_fn
);
98 info
->lsm_label
= lsm_process_label_get(pid
);
99 info
->ns_inherited
= 0;
100 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
105 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
107 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
108 __do_close_prot_errno
int fd ATTR_UNUSED
= move_fd(ctx
->ns_fd
[i
]);
112 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
114 free(ctx
->lsm_label
);
115 ctx
->lsm_label
= NULL
;
117 if (ctx
->container
) {
118 lxc_container_put(ctx
->container
);
119 ctx
->container
= NULL
;
122 lxc_proc_close_ns_fd(ctx
);
127 * in_same_namespace - Check whether two processes are in the same namespace.
128 * @pid1 - PID of the first process.
129 * @pid2 - PID of the second process.
130 * @ns - Name of the namespace to check. Must correspond to one of the names
131 * for the namespaces as shown in /proc/<pid/ns/
133 * If the two processes are not in the same namespace returns an fd to the
134 * namespace of the second process identified by @pid2. If the two processes are
135 * in the same namespace returns -EINVAL, -1 if an error occurred.
137 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
139 __do_close_prot_errno
int ns_fd1
= -1, ns_fd2
= -1;
141 struct stat ns_st1
, ns_st2
;
143 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
145 /* The kernel does not support this namespace. This is not an
154 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
158 ret
= fstat(ns_fd1
, &ns_st1
);
162 ret
= fstat(ns_fd2
, &ns_st2
);
166 /* processes are in the same namespace */
167 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
170 /* processes are in different namespaces */
171 return move_fd(ns_fd2
);
174 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
178 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
179 if (ctx
->ns_fd
[i
] < 0)
182 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
184 SYSERROR("Failed to attach to %s namespace of %d",
185 ns_info
[i
].proc_name
, pid
);
189 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
195 int lxc_attach_remount_sys_proc(void)
199 ret
= unshare(CLONE_NEWNS
);
201 SYSERROR("Failed to unshare mount namespace");
205 if (detect_shared_rootfs()) {
206 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
207 SYSERROR("Failed to make / rslave");
208 ERROR("Continuing...");
212 /* Assume /proc is always mounted, so remount it. */
213 ret
= umount2("/proc", MNT_DETACH
);
215 SYSERROR("Failed to unmount /proc");
219 ret
= mount("none", "/proc", "proc", 0, NULL
);
221 SYSERROR("Failed to remount /proc");
225 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
226 * we ignore it because it may not have been mounted in the first place.
228 ret
= umount2("/sys", MNT_DETACH
);
229 if (ret
< 0 && errno
!= EINVAL
) {
230 SYSERROR("Failed to unmount /sys");
232 } else if (ret
== 0) {
234 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
236 SYSERROR("Failed to remount /sys");
244 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
248 last_cap
= lxc_caps_last_cap();
249 for (cap
= 0; cap
<= last_cap
; cap
++) {
250 if (ctx
->capability_mask
& (1LL << cap
))
253 if (prctl(PR_CAPBSET_DROP
, prctl_arg(cap
), prctl_arg(0),
254 prctl_arg(0), prctl_arg(0))) {
255 SYSERROR("Failed to drop capability %d", cap
);
259 TRACE("Dropped capability %d", cap
);
265 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
266 enum lxc_attach_env_policy_t policy
,
267 char **extra_env
, char **extra_keep
)
270 struct lxc_list
*iterator
;
272 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
274 char **extra_keep_store
= NULL
;
279 for (count
= 0; extra_keep
[count
]; count
++)
282 extra_keep_store
= calloc(count
, sizeof(char *));
283 if (!extra_keep_store
)
286 for (i
= 0; i
< count
; i
++) {
287 char *v
= getenv(extra_keep
[i
]);
289 extra_keep_store
[i
] = strdup(v
);
290 if (!extra_keep_store
[i
]) {
292 free(extra_keep_store
[--i
]);
294 free(extra_keep_store
);
298 if (strcmp(extra_keep
[i
], "PATH") == 0)
305 if (extra_keep_store
) {
308 for (p
= extra_keep_store
; *p
; p
++)
311 free(extra_keep_store
);
314 ERROR("Failed to clear environment");
318 if (extra_keep_store
) {
321 for (i
= 0; extra_keep
[i
]; i
++) {
322 if (extra_keep_store
[i
]) {
323 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
325 SYSWARN("Failed to set environment variable");
328 free(extra_keep_store
[i
]);
331 free(extra_keep_store
);
334 /* Always set a default path; shells and execlp tend to be fine
335 * without it, but there is a disturbing number of C programs
336 * out there that just assume that getenv("PATH") is never NULL
337 * and then die a painful segfault death.
340 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
342 SYSWARN("Failed to set environment variable");
346 ret
= putenv("container=lxc");
348 SYSWARN("Failed to set environment variable");
352 /* Set container environment variables.*/
353 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
354 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
357 env_tmp
= strdup((char *)iterator
->elem
);
361 ret
= putenv(env_tmp
);
363 SYSERROR("Failed to set environment variable: %s", (char *)iterator
->elem
);
369 /* Set extra environment variables. */
371 for (; *extra_env
; extra_env
++) {
374 /* We just assume the user knows what they are doing, so
375 * we don't do any checks.
377 p
= strdup(*extra_env
);
383 SYSWARN("Failed to set environment variable");
390 static char *lxc_attach_getpwshell(uid_t uid
)
392 __do_free
char *line
= NULL
;
393 __do_fclose
FILE *pipe_f
= NULL
;
398 size_t line_bufsz
= 0;
401 /* We need to fork off a process that runs the getent program, and we
402 * need to capture its output, so we use a pipe for that purpose.
404 ret
= pipe2(pipes
, O_CLOEXEC
);
417 char *arguments
[] = {
426 /* We want to capture stdout. */
427 ret
= dup2(pipes
[1], STDOUT_FILENO
);
432 /* Get rid of stdin/stderr, so we try to associate it with
438 close(STDERR_FILENO
);
440 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
441 (void)dup3(fd
, STDERR_FILENO
, O_CLOEXEC
);
445 /* Finish argument list. */
446 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
447 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
450 /* Try to run getent program. */
451 (void)execvp("getent", arguments
);
457 pipe_f
= fdopen(pipes
[0], "r");
458 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
462 char *endptr
= NULL
, *saveptr
= NULL
;
464 /* If we already found something, just continue to read
465 * until the pipe doesn't deliver any more data, but
466 * don't modify the existing data structure.
474 /* Trim line on the right hand side. */
475 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
478 /* Split into tokens: first: user name. */
479 token
= strtok_r(line
, ":", &saveptr
);
483 /* next: dummy password field */
484 token
= strtok_r(NULL
, ":", &saveptr
);
489 token
= strtok_r(NULL
, ":", &saveptr
);
490 value
= token
? strtol(token
, &endptr
, 10) : 0;
491 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
495 /* dummy sanity check: user id matches */
496 if ((uid_t
)value
!= uid
)
499 /* skip fields: gid, gecos, dir, go to next field 'shell' */
500 for (i
= 0; i
< 4; i
++) {
501 token
= strtok_r(NULL
, ":", &saveptr
);
510 result
= strdup(token
);
512 /* Sanity check that there are no fields after that. */
513 token
= strtok_r(NULL
, ":", &saveptr
);
520 ret
= wait_for_pid(pid
);
534 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
536 __do_free
char *line
= NULL
;
537 __do_fclose
FILE *proc_file
= NULL
;
538 char proc_fn
[LXC_PROC_STATUS_LEN
];
540 size_t line_bufsz
= 0;
542 uid_t uid
= (uid_t
)-1;
543 gid_t gid
= (gid_t
)-1;
545 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", 1);
546 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
549 proc_file
= fopen(proc_fn
, "r");
553 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
554 /* Format is: real, effective, saved set user, fs we only care
557 ret
= sscanf(line
, "Uid: %ld", &value
);
558 if (ret
!= EOF
&& ret
== 1) {
561 ret
= sscanf(line
, "Gid: %ld", &value
);
562 if (ret
!= EOF
&& ret
== 1)
566 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
570 /* Only override arguments if we found something. */
571 if (uid
!= (uid_t
)-1)
574 if (gid
!= (gid_t
)-1)
577 /* TODO: we should also parse supplementary groups and use
578 * setgroups() to set them.
582 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
584 __do_free
char *path
= NULL
;
588 if (!(options
->namespaces
& CLONE_NEWNS
) ||
589 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
590 free(c
->lxc_conf
->seccomp
.seccomp
);
591 c
->lxc_conf
->seccomp
.seccomp
= NULL
;
595 /* Remove current setting. */
596 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
597 !c
->set_config_item(c
, "lxc.seccomp", ""))
600 /* Fetch the current profile path over the cmd interface. */
601 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
603 INFO("Failed to retrieve lxc.seccomp.profile");
605 path
= c
->get_running_config_item(c
, "lxc.seccomp");
607 INFO("Failed to retrieve lxc.seccomp");
612 /* Copy the value into the new lxc_conf. */
613 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
617 /* Attempt to parse the resulting config. */
618 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
620 ERROR("Failed to retrieve seccomp policy");
624 INFO("Retrieved seccomp policy");
628 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
630 __do_free
char *val
= NULL
;
632 /* Remove current setting. */
633 if (!c
->set_config_item(c
, "lxc.no_new_privs", "")) {
634 INFO("Failed to unset lxc.no_new_privs");
638 /* Retrieve currently active setting. */
639 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
641 INFO("Failed to retrieve lxc.no_new_privs");
645 /* Set currently active setting. */
646 return c
->set_config_item(c
, "lxc.no_new_privs", val
);
649 static signed long get_personality(const char *name
, const char *lxcpath
)
651 __do_free
char *p
= NULL
;
653 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
657 return lxc_config_parse_arch(p
);
660 struct attach_clone_payload
{
662 int terminal_slave_fd
;
663 lxc_attach_options_t
*options
;
664 struct lxc_proc_context_info
*init_ctx
;
665 lxc_attach_exec_t exec_function
;
669 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
671 __do_close_prot_errno
int ipc_socket ATTR_UNUSED
= p
->ipc_socket
;
672 __do_close_prot_errno
int terminal_slave_fd ATTR_UNUSED
= p
->terminal_slave_fd
;
675 lxc_proc_put_context_info(p
->init_ctx
);
680 static int attach_child_main(struct attach_clone_payload
*payload
)
685 uid_t ns_root_uid
= 0;
686 gid_t ns_root_gid
= 0;
687 lxc_attach_options_t
* options
= payload
->options
;
688 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
689 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
690 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
693 /* A description of the purpose of this functionality is provided in the
694 * lxc-attach(1) manual page. We have to remount here and not in the
695 * parent process, otherwise /proc may not properly reflect the new pid
698 if (!(options
->namespaces
& CLONE_NEWNS
) &&
699 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
700 ret
= lxc_attach_remount_sys_proc();
704 TRACE("Remounted \"/proc\" and \"/sys\"");
707 /* Now perform additional attachments. */
708 #if HAVE_SYS_PERSONALITY_H
709 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
710 long new_personality
;
712 if (options
->personality
< 0)
713 new_personality
= init_ctx
->personality
;
715 new_personality
= options
->personality
;
717 ret
= personality(new_personality
);
721 TRACE("Set new personality");
725 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
726 ret
= lxc_attach_drop_privs(init_ctx
);
730 TRACE("Dropped capabilities");
733 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
734 * if you want this to be a no-op).
736 ret
= lxc_attach_set_environment(init_ctx
,
738 options
->extra_env_vars
,
739 options
->extra_keep_env
);
743 TRACE("Set up environment");
745 /* This remark only affects fully unprivileged containers:
746 * Receive fd for LSM security module before we set{g,u}id(). The reason
747 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
748 * we will change our effective uid. This means our effective uid will
749 * be different from the effective uid of the process that created us
750 * which means that this processs no longer has capabilities in our
751 * namespace including CAP_SYS_PTRACE. This means we will not be able to
752 * read and /proc/<pid> files for the process anymore when /proc is
753 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
757 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
760 SYSERROR("Failed to receive lsm label fd");
765 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
768 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
769 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
774 if (options
->namespaces
& CLONE_NEWUSER
) {
775 /* Check whether nsuid 0 has a mapping. */
776 ns_root_uid
= get_ns_uid(0);
778 /* Check whether nsgid 0 has a mapping. */
779 ns_root_gid
= get_ns_gid(0);
781 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
782 * init was started with.
784 if (ns_root_uid
== LXC_INVALID_UID
)
785 lxc_attach_get_init_uidgid(&ns_root_uid
, &ns_root_gid
);
787 if (ns_root_uid
== LXC_INVALID_UID
)
790 if (!lxc_switch_uid_gid(ns_root_uid
, ns_root_gid
))
794 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
798 if (options
->uid
!= LXC_INVALID_UID
)
799 new_uid
= options
->uid
;
801 new_uid
= ns_root_uid
;
803 if (options
->gid
!= LXC_INVALID_GID
)
804 new_gid
= options
->gid
;
806 new_gid
= ns_root_gid
;
808 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
809 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
810 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
811 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
812 prctl_arg(0), prctl_arg(0));
816 TRACE("Set PR_SET_NO_NEW_PRIVS");
822 /* Change into our new LSM profile. */
823 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
825 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
830 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
833 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
834 init_ctx
->container
->lxc_conf
->seccomp
.seccomp
) {
835 struct lxc_conf
*conf
= init_ctx
->container
->lxc_conf
;
837 ret
= lxc_seccomp_load(conf
);
841 TRACE("Loaded seccomp profile");
843 ret
= lxc_seccomp_send_notifier_fd(&conf
->seccomp
, payload
->ipc_socket
);
848 close(payload
->ipc_socket
);
849 payload
->ipc_socket
= -EBADF
;
850 lxc_proc_put_context_info(init_ctx
);
851 payload
->init_ctx
= NULL
;
853 /* The following is done after the communication socket is shut down.
854 * That way, all errors that might (though unlikely) occur up until this
855 * point will have their messages printed to the original stderr (if
856 * logging is so configured) and not the fd the user supplied, if any.
859 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
860 * may want to make sure the fds are closed, for example.
862 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
863 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
865 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
866 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
868 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
869 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
871 /* close the old fds */
872 if (options
->stdin_fd
> STDERR_FILENO
)
873 close(options
->stdin_fd
);
875 if (options
->stdout_fd
> STDERR_FILENO
)
876 close(options
->stdout_fd
);
878 if (options
->stderr_fd
> STDERR_FILENO
)
879 close(options
->stderr_fd
);
882 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
883 * here, ignore errors.
885 for (int fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
886 ret
= fd_cloexec(fd
, false);
888 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
893 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
894 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
896 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
900 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
903 /* Avoid unnecessary syscalls. */
904 if (new_uid
== ns_root_uid
)
905 new_uid
= LXC_INVALID_UID
;
907 if (new_gid
== ns_root_gid
)
908 new_gid
= LXC_INVALID_GID
;
910 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
913 /* We're done, so we can now do whatever the user intended us to do. */
914 _exit(payload
->exec_function(payload
->exec_payload
));
917 lxc_put_attach_clone_payload(payload
);
921 static int lxc_attach_terminal(struct lxc_conf
*conf
,
922 struct lxc_terminal
*terminal
)
926 lxc_terminal_init(terminal
);
928 ret
= lxc_terminal_create(terminal
);
930 ERROR("Failed to create terminal");
934 /* Shift ttys to container. */
935 ret
= lxc_terminal_map_ids(conf
, terminal
);
937 ERROR("Failed to chown terminal");
944 lxc_terminal_delete(terminal
);
945 lxc_terminal_conf_free(terminal
);
949 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
950 struct lxc_epoll_descr
*descr
)
954 ret
= lxc_mainloop_open(descr
);
956 ERROR("Failed to create mainloop");
960 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
962 ERROR("Failed to add handlers to mainloop");
963 lxc_mainloop_close(descr
);
970 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
972 close_prot_errno_disarm(terminal
->master
);
975 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
977 close_prot_errno_disarm(terminal
->slave
);
980 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
982 close_prot_errno_disarm(terminal
->peer
);
985 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
987 close_prot_errno_disarm(terminal
->log_fd
);
990 int lxc_attach(struct lxc_container
*container
, lxc_attach_exec_t exec_function
,
991 void *exec_payload
, lxc_attach_options_t
*options
,
992 pid_t
*attached_process
)
997 signed long personality
;
998 pid_t attached_pid
, init_pid
, pid
;
999 struct lxc_proc_context_info
*init_ctx
;
1000 struct lxc_terminal terminal
;
1001 struct lxc_conf
*conf
;
1002 char *name
, *lxcpath
;
1003 struct attach_clone_payload payload
= {0};
1005 ret
= access("/proc/self/ns", X_OK
);
1007 SYSERROR("Does this kernel version support namespaces?");
1012 return ret_set_errno(-1, EINVAL
);
1014 if (!lxc_container_get(container
))
1015 return ret_set_errno(-1, EINVAL
);
1017 name
= container
->name
;
1018 lxcpath
= container
->config_path
;
1021 options
= &attach_static_default_options
;
1023 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1025 ERROR("Failed to get init pid");
1026 lxc_container_put(container
);
1030 init_ctx
= lxc_proc_get_context_info(init_pid
);
1032 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1033 lxc_container_put(container
);
1037 init_ctx
->container
= container
;
1039 personality
= get_personality(name
, lxcpath
);
1040 if (init_ctx
->personality
< 0) {
1041 ERROR("Failed to get personality of the container");
1042 lxc_proc_put_context_info(init_ctx
);
1045 init_ctx
->personality
= personality
;
1047 if (!init_ctx
->container
->lxc_conf
) {
1048 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1049 if (!init_ctx
->container
->lxc_conf
) {
1050 lxc_proc_put_context_info(init_ctx
);
1054 conf
= init_ctx
->container
->lxc_conf
;
1056 if (!fetch_seccomp(init_ctx
->container
, options
))
1057 WARN("Failed to get seccomp policy");
1059 if (!no_new_privs(init_ctx
->container
, options
))
1060 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1062 cwd
= getcwd(NULL
, 0);
1064 /* Determine which namespaces the container was created with
1065 * by asking lxc-start, if necessary.
1067 if (options
->namespaces
== -1) {
1068 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1070 if (options
->namespaces
== -1) {
1071 ERROR("Failed to automatically determine the "
1072 "namespaces which the container uses");
1074 lxc_proc_put_context_info(init_ctx
);
1078 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1079 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1080 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1084 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1087 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1091 pid
= lxc_raw_getpid();
1093 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1096 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1097 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1098 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1099 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1103 if (init_ctx
->ns_fd
[i
] >= 0)
1106 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1107 DEBUG("Inheriting %s namespace from %d",
1108 ns_info
[i
].proc_name
, pid
);
1109 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1113 /* We failed to preserve the namespace. */
1114 SYSERROR("Failed to attach to %s namespace of %d",
1115 ns_info
[i
].proc_name
, pid
);
1117 /* Close all already opened file descriptors before we return an
1118 * error, so we don't leak them.
1120 for (j
= 0; j
< i
; j
++)
1121 close(init_ctx
->ns_fd
[j
]);
1124 lxc_proc_put_context_info(init_ctx
);
1128 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1129 ret
= lxc_attach_terminal(conf
, &terminal
);
1131 ERROR("Failed to setup new terminal");
1133 lxc_proc_put_context_info(init_ctx
);
1137 terminal
.log_fd
= options
->log_fd
;
1139 lxc_terminal_init(&terminal
);
1142 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1143 * to make sure we don't irritate other threads that want to fork+exec
1146 * IMPORTANT: if the initial process is multithreaded and another call
1147 * just fork()s away without exec'ing directly after, the socket fd will
1148 * exist in the forked process from the other thread and any close() in
1149 * our own child process will not really cause the socket to close
1150 * properly, potentially causing the parent to hang.
1152 * For this reason, while IPC is still active, we have to use shutdown()
1153 * if the child exits prematurely in order to signal that the socket is
1154 * closed and cannot assume that the child exiting will automatically do
1157 * IPC mechanism: (X is receiver)
1158 * initial process intermediate attached
1159 * X <--- send pid of
1162 * send 0 ------------------------------------> X
1163 * [do initialization]
1164 * X <------------------------------------ send 1
1165 * [add to cgroup, ...]
1166 * send 2 ------------------------------------> X
1167 * [set LXC_ATTACH_NO_NEW_PRIVS]
1168 * X <------------------------------------ send 3
1169 * [open LSM label fd]
1170 * send 4 ------------------------------------> X
1172 * close socket close socket
1175 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1177 SYSERROR("Could not set up required IPC mechanism for attaching");
1179 lxc_proc_put_context_info(init_ctx
);
1183 /* Create intermediate subprocess, two reasons:
1184 * 1. We can't setns() in the child itself, since we want to make
1185 * sure we are properly attached to the pidns.
1186 * 2. Also, the initial thread has to put the attached process
1187 * into the cgroup, which we can only do if we didn't already
1188 * setns() (otherwise, user namespaces will hate us).
1192 SYSERROR("Failed to create first subprocess");
1194 lxc_proc_put_context_info(init_ctx
);
1199 int ret_parent
= -1;
1200 pid_t to_cleanup_pid
= pid
;
1201 struct lxc_epoll_descr descr
= {0};
1203 /* close unneeded file descriptors */
1204 close(ipc_sockets
[1]);
1206 lxc_proc_close_ns_fd(init_ctx
);
1207 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1208 lxc_attach_terminal_close_slave(&terminal
);
1210 /* Attach to cgroup, if requested. */
1211 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1213 * If this is the unified hierarchy cgroup_attach() is
1216 ret
= cgroup_attach(name
, lxcpath
, pid
);
1218 __do_cgroup_exit
struct cgroup_ops
*cgroup_ops
= NULL
;
1220 cgroup_ops
= cgroup_init(conf
);
1224 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1227 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1230 /* Setup /proc limits */
1231 if (!lxc_list_empty(&conf
->procs
)) {
1232 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1237 /* Setup resource limits */
1238 if (!lxc_list_empty(&conf
->limits
)) {
1239 ret
= setup_resource_limits(&conf
->limits
, pid
);
1244 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1245 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1249 TRACE("Initialized terminal mainloop");
1252 /* Let the child process know to go ahead. */
1254 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1255 if (ret
!= sizeof(status
))
1256 goto close_mainloop
;
1258 TRACE("Told intermediate process to start initializing");
1260 /* Get pid of attached process from intermediate process. */
1261 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1262 if (ret
!= sizeof(attached_pid
))
1263 goto close_mainloop
;
1265 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1267 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1268 if (options
->stdin_fd
== 0) {
1269 signal(SIGINT
, SIG_IGN
);
1270 signal(SIGQUIT
, SIG_IGN
);
1273 /* Reap intermediate process. */
1274 ret
= wait_for_pid(pid
);
1276 goto close_mainloop
;
1278 TRACE("Intermediate process %d exited", pid
);
1280 /* We will always have to reap the attached process now. */
1281 to_cleanup_pid
= attached_pid
;
1283 /* Open LSM fd and send it to child. */
1284 if ((options
->namespaces
& CLONE_NEWNS
) &&
1285 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1286 init_ctx
->lsm_label
) {
1291 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1292 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1294 goto close_mainloop
;
1296 TRACE("Opened LSM label file descriptor %d", labelfd
);
1298 /* Send child fd of the LSM security module to write to. */
1299 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1302 SYSERROR("Failed to send lsm label fd");
1305 goto close_mainloop
;
1309 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1312 if (conf
&& conf
->seccomp
.seccomp
) {
1313 ret
= lxc_seccomp_recv_notifier_fd(&conf
->seccomp
, ipc_sockets
[0]);
1315 goto close_mainloop
;
1317 ret
= lxc_seccomp_add_notifier(name
, lxcpath
, &conf
->seccomp
);
1319 goto close_mainloop
;
1322 /* We're done, the child process should now execute whatever it
1323 * is that the user requested. The parent can now track it with
1324 * waitpid() or similar.
1327 *attached_process
= attached_pid
;
1329 /* Now shut down communication with child, we're done. */
1330 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1331 close(ipc_sockets
[0]);
1332 ipc_sockets
[0] = -1;
1335 to_cleanup_pid
= -1;
1337 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1338 ret
= lxc_mainloop(&descr
, -1);
1341 to_cleanup_pid
= attached_pid
;
1346 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1347 lxc_mainloop_close(&descr
);
1350 if (ipc_sockets
[0] >= 0) {
1351 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1352 close(ipc_sockets
[0]);
1355 if (to_cleanup_pid
> 0)
1356 (void)wait_for_pid(to_cleanup_pid
);
1358 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1359 lxc_terminal_delete(&terminal
);
1360 lxc_terminal_conf_free(&terminal
);
1363 lxc_proc_put_context_info(init_ctx
);
1367 /* close unneeded file descriptors */
1368 close(ipc_sockets
[0]);
1369 ipc_sockets
[0] = -EBADF
;
1371 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1372 lxc_attach_terminal_close_master(&terminal
);
1373 lxc_attach_terminal_close_peer(&terminal
);
1374 lxc_attach_terminal_close_log(&terminal
);
1377 /* Wait for the parent to have setup cgroups. */
1378 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1379 if (ret
!= sizeof(status
)) {
1380 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1381 lxc_proc_put_context_info(init_ctx
);
1382 _exit(EXIT_FAILURE
);
1385 TRACE("Intermediate process starting to initialize");
1387 /* Attach now, create another subprocess later, since pid namespaces
1388 * only really affect the children of the current process.
1390 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1392 ERROR("Failed to enter namespaces");
1393 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1394 lxc_proc_put_context_info(init_ctx
);
1395 _exit(EXIT_FAILURE
);
1398 /* close namespace file descriptors */
1399 lxc_proc_close_ns_fd(init_ctx
);
1401 /* Attach succeeded, try to cwd. */
1402 if (options
->initial_cwd
)
1403 new_cwd
= options
->initial_cwd
;
1407 ret
= chdir(new_cwd
);
1409 WARN("Could not change directory to \"%s\"", new_cwd
);
1413 /* Create attached process. */
1414 payload
.ipc_socket
= ipc_sockets
[1];
1415 payload
.options
= options
;
1416 payload
.init_ctx
= init_ctx
;
1417 payload
.terminal_slave_fd
= terminal
.slave
;
1418 payload
.exec_function
= exec_function
;
1419 payload
.exec_payload
= exec_payload
;
1421 pid
= lxc_raw_clone(CLONE_PARENT
, NULL
);
1423 SYSERROR("Failed to clone attached process");
1424 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1425 lxc_proc_put_context_info(init_ctx
);
1426 _exit(EXIT_FAILURE
);
1430 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1431 ret
= pthread_sigmask(SIG_SETMASK
,
1432 &terminal
.tty_state
->oldmask
, NULL
);
1434 SYSERROR("Failed to reset signal mask");
1435 _exit(EXIT_FAILURE
);
1439 ret
= attach_child_main(&payload
);
1441 ERROR("Failed to exec");
1443 _exit(EXIT_FAILURE
);
1446 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1447 lxc_attach_terminal_close_slave(&terminal
);
1449 /* Tell grandparent the pid of the pid of the newly created child. */
1450 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1451 if (ret
!= sizeof(pid
)) {
1452 /* If this really happens here, this is very unfortunate, since
1453 * the parent will not know the pid of the attached process and
1454 * will not be able to wait for it (and we won't either due to
1455 * CLONE_PARENT) so the parent won't be able to reap it and the
1456 * attached process will remain a zombie.
1458 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1459 lxc_proc_put_context_info(init_ctx
);
1460 _exit(EXIT_FAILURE
);
1463 TRACE("Sending pid %d of attached process", pid
);
1465 /* The rest is in the hands of the initial and the attached process. */
1466 lxc_proc_put_context_info(init_ctx
);
1467 _exit(EXIT_SUCCESS
);
1470 int lxc_attach_run_command(void *payload
)
1473 lxc_attach_command_t
*cmd
= payload
;
1475 ret
= execvp(cmd
->program
, cmd
->argv
);
1487 SYSERROR("Failed to exec \"%s\"", cmd
->program
);
1491 int lxc_attach_run_shell(void* payload
)
1493 __do_free
char *buf
= NULL
;
1495 struct passwd pwent
;
1496 struct passwd
*pwentp
= NULL
;
1501 /* Ignore payload parameter. */
1506 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1510 buf
= malloc(bufsize
);
1512 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1515 WARN("Could not find matched password record");
1517 WARN("Failed to get password record - %u", uid
);
1521 /* This probably happens because of incompatible nss implementations in
1522 * host and container (remember, this code is still using the host's
1523 * glibc but our mount namespace is in the container) we may try to get
1524 * the information by spawning a [getent passwd uid] process and parsing
1528 user_shell
= lxc_attach_getpwshell(uid
);
1530 user_shell
= pwent
.pw_shell
;
1533 execlp(user_shell
, user_shell
, (char *)NULL
);
1535 /* Executed if either no passwd entry or execvp fails, we will fall back
1536 * on /bin/sh as a default shell.
1538 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1540 SYSERROR("Failed to execute shell");