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
;
61 __do_free
struct lxc_proc_context_info
*info
= NULL
;
64 char proc_fn
[LXC_PROC_STATUS_LEN
];
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
, "re");
74 return log_error_errno(NULL
, errno
, "Failed to open %s", proc_fn
);
76 info
= calloc(1, sizeof(*info
));
82 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
83 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
84 if (ret
!= EOF
&& ret
== 1) {
91 return log_error_errno(NULL
, ENOENT
, "Failed to read capability bounding set from %s", proc_fn
);
93 info
->lsm_label
= lsm_process_label_get(pid
);
94 info
->ns_inherited
= 0;
95 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
97 return move_ptr(info
);
100 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
102 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
103 close_prot_errno_disarm(ctx
->ns_fd
[i
]);
106 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
108 free(ctx
->lsm_label
);
109 ctx
->lsm_label
= NULL
;
111 if (ctx
->container
) {
112 lxc_container_put(ctx
->container
);
113 ctx
->container
= NULL
;
116 lxc_proc_close_ns_fd(ctx
);
121 * in_same_namespace - Check whether two processes are in the same namespace.
122 * @pid1 - PID of the first process.
123 * @pid2 - PID of the second process.
124 * @ns - Name of the namespace to check. Must correspond to one of the names
125 * for the namespaces as shown in /proc/<pid/ns/
127 * If the two processes are not in the same namespace returns an fd to the
128 * namespace of the second process identified by @pid2. If the two processes are
129 * in the same namespace returns -EINVAL, -1 if an error occurred.
131 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
133 __do_close_prot_errno
int ns_fd1
= -1, ns_fd2
= -1;
135 struct stat ns_st1
, ns_st2
;
137 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
139 /* The kernel does not support this namespace. This is not an
148 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
152 ret
= fstat(ns_fd1
, &ns_st1
);
156 ret
= fstat(ns_fd2
, &ns_st2
);
160 /* processes are in the same namespace */
161 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
164 /* processes are in different namespaces */
165 return move_fd(ns_fd2
);
168 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
170 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
173 if (ctx
->ns_fd
[i
] < 0)
176 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
178 return log_error_errno(-1,
179 errno
, "Failed to attach to %s namespace of %d",
180 ns_info
[i
].proc_name
, pid
);
182 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
188 int lxc_attach_remount_sys_proc(void)
192 ret
= unshare(CLONE_NEWNS
);
194 return log_error_errno(-1, errno
, "Failed to unshare mount namespace");
196 if (detect_shared_rootfs()) {
197 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
198 SYSERROR("Failed to make / rslave");
199 ERROR("Continuing...");
203 /* Assume /proc is always mounted, so remount it. */
204 ret
= umount2("/proc", MNT_DETACH
);
206 return log_error_errno(-1, errno
, "Failed to unmount /proc");
208 ret
= mount("none", "/proc", "proc", 0, NULL
);
210 return log_error_errno(-1, errno
, "Failed to remount /proc");
213 * Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
214 * we ignore it because it may not have been mounted in the first place.
216 ret
= umount2("/sys", MNT_DETACH
);
217 if (ret
< 0 && errno
!= EINVAL
)
218 return log_error_errno(-1, errno
, "Failed to unmount /sys");
221 if (ret
== 0 && mount("none", "/sys", "sysfs", 0, NULL
))
222 return log_error_errno(-1, errno
, "Failed to remount /sys");
227 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
231 last_cap
= lxc_caps_last_cap();
232 for (int cap
= 0; cap
<= last_cap
; cap
++) {
233 if (ctx
->capability_mask
& (1LL << cap
))
236 if (prctl(PR_CAPBSET_DROP
, prctl_arg(cap
), prctl_arg(0),
237 prctl_arg(0), prctl_arg(0)))
238 return log_error_errno(-1, errno
, "Failed to drop capability %d", cap
);
240 TRACE("Dropped capability %d", cap
);
246 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
247 enum lxc_attach_env_policy_t policy
,
248 char **extra_env
, char **extra_keep
)
251 struct lxc_list
*iterator
;
253 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
255 char **extra_keep_store
= NULL
;
260 for (count
= 0; extra_keep
[count
]; count
++)
263 extra_keep_store
= calloc(count
, sizeof(char *));
264 if (!extra_keep_store
)
267 for (i
= 0; i
< count
; i
++) {
268 char *v
= getenv(extra_keep
[i
]);
270 extra_keep_store
[i
] = strdup(v
);
271 if (!extra_keep_store
[i
]) {
273 free(extra_keep_store
[--i
]);
275 free(extra_keep_store
);
279 if (strcmp(extra_keep
[i
], "PATH") == 0)
286 if (extra_keep_store
) {
289 for (p
= extra_keep_store
; *p
; p
++)
292 free(extra_keep_store
);
295 return log_error(-1, "Failed to clear environment");
298 if (extra_keep_store
) {
301 for (i
= 0; extra_keep
[i
]; i
++) {
302 if (extra_keep_store
[i
]) {
303 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
305 SYSWARN("Failed to set environment variable");
308 free(extra_keep_store
[i
]);
311 free(extra_keep_store
);
314 /* Always set a default path; shells and execlp tend to be fine
315 * without it, but there is a disturbing number of C programs
316 * out there that just assume that getenv("PATH") is never NULL
317 * and then die a painful segfault death.
320 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
322 SYSWARN("Failed to set environment variable");
326 ret
= putenv("container=lxc");
328 return log_warn(-1, errno
, "Failed to set environment variable");
330 /* Set container environment variables.*/
331 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
332 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
335 env_tmp
= strdup((char *)iterator
->elem
);
339 ret
= putenv(env_tmp
);
341 return log_error_errno(-1, errno
, "Failed to set environment variable: %s", (char *)iterator
->elem
);
345 /* Set extra environment variables. */
347 for (; *extra_env
; extra_env
++) {
350 /* We just assume the user knows what they are doing, so
351 * we don't do any checks.
353 p
= strdup(*extra_env
);
359 SYSWARN("Failed to set environment variable");
366 static char *lxc_attach_getpwshell(uid_t uid
)
368 __do_free
char *line
= NULL
, *result
= NULL
;
369 __do_fclose
FILE *pipe_f
= NULL
;
374 size_t line_bufsz
= 0;
376 /* We need to fork off a process that runs the getent program, and we
377 * need to capture its output, so we use a pipe for that purpose.
379 ret
= pipe2(pipes
, O_CLOEXEC
);
392 char *arguments
[] = {
401 /* We want to capture stdout. */
402 ret
= dup2(pipes
[1], STDOUT_FILENO
);
407 /* Get rid of stdin/stderr, so we try to associate it with
413 close(STDERR_FILENO
);
415 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
416 (void)dup3(fd
, STDERR_FILENO
, O_CLOEXEC
);
420 /* Finish argument list. */
421 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
422 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
425 /* Try to run getent program. */
426 (void)execvp("getent", arguments
);
432 pipe_f
= fdopen(pipes
[0], "r");
437 /* Transfer ownership of pipes[0] to pipe_f. */
440 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
444 char *endptr
= NULL
, *saveptr
= NULL
;
446 /* If we already found something, just continue to read
447 * until the pipe doesn't deliver any more data, but
448 * don't modify the existing data structure.
456 /* Trim line on the right hand side. */
457 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
460 /* Split into tokens: first: user name. */
461 token
= strtok_r(line
, ":", &saveptr
);
465 /* next: dummy password field */
466 token
= strtok_r(NULL
, ":", &saveptr
);
471 token
= strtok_r(NULL
, ":", &saveptr
);
472 value
= token
? strtol(token
, &endptr
, 10) : 0;
473 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
477 /* dummy sanity check: user id matches */
478 if ((uid_t
)value
!= uid
)
481 /* skip fields: gid, gecos, dir, go to next field 'shell' */
482 for (i
= 0; i
< 4; i
++) {
483 token
= strtok_r(NULL
, ":", &saveptr
);
492 result
= strdup(token
);
494 /* Sanity check that there are no fields after that. */
495 token
= strtok_r(NULL
, ":", &saveptr
);
503 ret
= wait_for_pid(pid
);
510 return move_ptr(result
);
513 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
515 __do_free
char *line
= NULL
;
516 __do_fclose
FILE *proc_file
= NULL
;
517 char proc_fn
[LXC_PROC_STATUS_LEN
];
519 size_t line_bufsz
= 0;
521 uid_t uid
= (uid_t
)-1;
522 gid_t gid
= (gid_t
)-1;
524 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", 1);
525 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
528 proc_file
= fopen(proc_fn
, "r");
532 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
533 /* Format is: real, effective, saved set user, fs we only care
536 ret
= sscanf(line
, "Uid: %ld", &value
);
537 if (ret
!= EOF
&& ret
== 1) {
540 ret
= sscanf(line
, "Gid: %ld", &value
);
541 if (ret
!= EOF
&& ret
== 1)
545 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
549 /* Only override arguments if we found something. */
550 if (uid
!= (uid_t
)-1)
553 if (gid
!= (gid_t
)-1)
556 /* TODO: we should also parse supplementary groups and use
557 * setgroups() to set them.
561 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
563 __do_free
char *path
= NULL
;
567 if (!(options
->namespaces
& CLONE_NEWNS
) ||
568 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
569 free(c
->lxc_conf
->seccomp
.seccomp
);
570 c
->lxc_conf
->seccomp
.seccomp
= NULL
;
574 /* Remove current setting. */
575 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
576 !c
->set_config_item(c
, "lxc.seccomp", ""))
579 /* Fetch the current profile path over the cmd interface. */
580 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
582 INFO("Failed to retrieve lxc.seccomp.profile");
584 path
= c
->get_running_config_item(c
, "lxc.seccomp");
586 INFO("Failed to retrieve lxc.seccomp");
591 /* Copy the value into the new lxc_conf. */
592 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
596 /* Attempt to parse the resulting config. */
597 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
599 ERROR("Failed to retrieve seccomp policy");
603 INFO("Retrieved seccomp policy");
607 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
609 __do_free
char *val
= NULL
;
611 /* Remove current setting. */
612 if (!c
->set_config_item(c
, "lxc.no_new_privs", "")) {
613 INFO("Failed to unset lxc.no_new_privs");
617 /* Retrieve currently active setting. */
618 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
620 INFO("Failed to retrieve lxc.no_new_privs");
624 /* Set currently active setting. */
625 return c
->set_config_item(c
, "lxc.no_new_privs", val
);
628 static signed long get_personality(const char *name
, const char *lxcpath
)
630 __do_free
char *p
= NULL
;
632 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
636 return lxc_config_parse_arch(p
);
639 struct attach_clone_payload
{
641 int terminal_slave_fd
;
642 lxc_attach_options_t
*options
;
643 struct lxc_proc_context_info
*init_ctx
;
644 lxc_attach_exec_t exec_function
;
648 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
650 close_prot_errno_disarm(p
->ipc_socket
);
651 close_prot_errno_disarm(p
->terminal_slave_fd
);
653 lxc_proc_put_context_info(p
->init_ctx
);
658 static int attach_child_main(struct attach_clone_payload
*payload
)
663 uid_t ns_root_uid
= 0;
664 gid_t ns_root_gid
= 0;
665 lxc_attach_options_t
* options
= payload
->options
;
666 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
667 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
668 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
671 /* A description of the purpose of this functionality is provided in the
672 * lxc-attach(1) manual page. We have to remount here and not in the
673 * parent process, otherwise /proc may not properly reflect the new pid
676 if (!(options
->namespaces
& CLONE_NEWNS
) &&
677 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
678 ret
= lxc_attach_remount_sys_proc();
682 TRACE("Remounted \"/proc\" and \"/sys\"");
685 /* Now perform additional attachments. */
686 #if HAVE_SYS_PERSONALITY_H
687 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
688 long new_personality
;
690 if (options
->personality
< 0)
691 new_personality
= init_ctx
->personality
;
693 new_personality
= options
->personality
;
695 ret
= personality(new_personality
);
699 TRACE("Set new personality");
703 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
704 ret
= lxc_attach_drop_privs(init_ctx
);
708 TRACE("Dropped capabilities");
711 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
712 * if you want this to be a no-op).
714 ret
= lxc_attach_set_environment(init_ctx
,
716 options
->extra_env_vars
,
717 options
->extra_keep_env
);
721 TRACE("Set up environment");
723 /* This remark only affects fully unprivileged containers:
724 * Receive fd for LSM security module before we set{g,u}id(). The reason
725 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
726 * we will change our effective uid. This means our effective uid will
727 * be different from the effective uid of the process that created us
728 * which means that this processs no longer has capabilities in our
729 * namespace including CAP_SYS_PTRACE. This means we will not be able to
730 * read and /proc/<pid> files for the process anymore when /proc is
731 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
735 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
738 SYSERROR("Failed to receive lsm label fd");
743 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
746 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
747 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
752 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
755 if (options
->namespaces
& CLONE_NEWUSER
) {
756 /* Check whether nsuid 0 has a mapping. */
757 ns_root_uid
= get_ns_uid(0);
759 /* Check whether nsgid 0 has a mapping. */
760 ns_root_gid
= get_ns_gid(0);
762 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
763 * init was started with.
765 if (ns_root_uid
== LXC_INVALID_UID
)
766 lxc_attach_get_init_uidgid(&ns_root_uid
, &ns_root_gid
);
768 if (ns_root_uid
== LXC_INVALID_UID
)
771 if (!lxc_switch_uid_gid(ns_root_uid
, ns_root_gid
))
776 if (options
->uid
!= LXC_INVALID_UID
)
777 new_uid
= options
->uid
;
779 new_uid
= ns_root_uid
;
781 if (options
->gid
!= LXC_INVALID_GID
)
782 new_gid
= options
->gid
;
784 new_gid
= ns_root_gid
;
786 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
787 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
788 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
789 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
790 prctl_arg(0), prctl_arg(0));
794 TRACE("Set PR_SET_NO_NEW_PRIVS");
800 /* Change into our new LSM profile. */
801 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
803 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
808 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
811 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
812 init_ctx
->container
->lxc_conf
->seccomp
.seccomp
) {
813 struct lxc_conf
*conf
= init_ctx
->container
->lxc_conf
;
815 ret
= lxc_seccomp_load(conf
);
819 TRACE("Loaded seccomp profile");
821 ret
= lxc_seccomp_send_notifier_fd(&conf
->seccomp
, payload
->ipc_socket
);
826 close(payload
->ipc_socket
);
827 payload
->ipc_socket
= -EBADF
;
828 lxc_proc_put_context_info(init_ctx
);
829 payload
->init_ctx
= NULL
;
831 /* The following is done after the communication socket is shut down.
832 * That way, all errors that might (though unlikely) occur up until this
833 * point will have their messages printed to the original stderr (if
834 * logging is so configured) and not the fd the user supplied, if any.
837 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
838 * may want to make sure the fds are closed, for example.
840 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
841 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
843 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
844 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
846 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
847 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
849 /* close the old fds */
850 if (options
->stdin_fd
> STDERR_FILENO
)
851 close(options
->stdin_fd
);
853 if (options
->stdout_fd
> STDERR_FILENO
)
854 close(options
->stdout_fd
);
856 if (options
->stderr_fd
> STDERR_FILENO
)
857 close(options
->stderr_fd
);
860 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
861 * here, ignore errors.
863 for (int fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
864 ret
= fd_cloexec(fd
, false);
866 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
871 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
872 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
874 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
878 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
881 /* Avoid unnecessary syscalls. */
882 if (new_uid
== ns_root_uid
)
883 new_uid
= LXC_INVALID_UID
;
885 if (new_gid
== ns_root_gid
)
886 new_gid
= LXC_INVALID_GID
;
888 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
891 /* We're done, so we can now do whatever the user intended us to do. */
892 _exit(payload
->exec_function(payload
->exec_payload
));
895 lxc_put_attach_clone_payload(payload
);
899 static int lxc_attach_terminal(struct lxc_conf
*conf
,
900 struct lxc_terminal
*terminal
)
904 lxc_terminal_init(terminal
);
906 ret
= lxc_terminal_create(terminal
);
908 ERROR("Failed to create terminal");
912 /* Shift ttys to container. */
913 ret
= lxc_terminal_map_ids(conf
, terminal
);
915 ERROR("Failed to chown terminal");
922 lxc_terminal_delete(terminal
);
923 lxc_terminal_conf_free(terminal
);
927 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
928 struct lxc_epoll_descr
*descr
)
932 ret
= lxc_mainloop_open(descr
);
934 ERROR("Failed to create mainloop");
938 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
940 ERROR("Failed to add handlers to mainloop");
941 lxc_mainloop_close(descr
);
948 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
950 close_prot_errno_disarm(terminal
->master
);
953 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
955 close_prot_errno_disarm(terminal
->slave
);
958 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
960 close_prot_errno_disarm(terminal
->peer
);
963 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
965 close_prot_errno_disarm(terminal
->log_fd
);
968 int lxc_attach(struct lxc_container
*container
, lxc_attach_exec_t exec_function
,
969 void *exec_payload
, lxc_attach_options_t
*options
,
970 pid_t
*attached_process
)
975 signed long personality
;
976 pid_t attached_pid
, init_pid
, pid
;
977 struct lxc_proc_context_info
*init_ctx
;
978 struct lxc_terminal terminal
;
979 struct lxc_conf
*conf
;
980 char *name
, *lxcpath
;
981 struct attach_clone_payload payload
= {0};
983 ret
= access("/proc/self/ns", X_OK
);
985 SYSERROR("Does this kernel version support namespaces?");
990 return ret_set_errno(-1, EINVAL
);
992 if (!lxc_container_get(container
))
993 return ret_set_errno(-1, EINVAL
);
995 name
= container
->name
;
996 lxcpath
= container
->config_path
;
999 options
= &attach_static_default_options
;
1001 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
1003 ERROR("Failed to get init pid");
1004 lxc_container_put(container
);
1008 init_ctx
= lxc_proc_get_context_info(init_pid
);
1010 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
1011 lxc_container_put(container
);
1015 init_ctx
->container
= container
;
1017 personality
= get_personality(name
, lxcpath
);
1018 if (init_ctx
->personality
< 0) {
1019 ERROR("Failed to get personality of the container");
1020 lxc_proc_put_context_info(init_ctx
);
1023 init_ctx
->personality
= personality
;
1025 if (!init_ctx
->container
->lxc_conf
) {
1026 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1027 if (!init_ctx
->container
->lxc_conf
) {
1028 lxc_proc_put_context_info(init_ctx
);
1032 conf
= init_ctx
->container
->lxc_conf
;
1034 if (!fetch_seccomp(init_ctx
->container
, options
))
1035 WARN("Failed to get seccomp policy");
1037 if (!no_new_privs(init_ctx
->container
, options
))
1038 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1040 cwd
= getcwd(NULL
, 0);
1042 /* Determine which namespaces the container was created with
1043 * by asking lxc-start, if necessary.
1045 if (options
->namespaces
== -1) {
1046 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1048 if (options
->namespaces
== -1) {
1049 ERROR("Failed to automatically determine the "
1050 "namespaces which the container uses");
1052 lxc_proc_put_context_info(init_ctx
);
1056 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1057 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1058 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1062 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1065 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1069 pid
= lxc_raw_getpid();
1071 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1074 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1075 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1076 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1077 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1081 if (init_ctx
->ns_fd
[i
] >= 0)
1084 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1085 DEBUG("Inheriting %s namespace from %d",
1086 ns_info
[i
].proc_name
, pid
);
1087 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1091 /* We failed to preserve the namespace. */
1092 SYSERROR("Failed to attach to %s namespace of %d",
1093 ns_info
[i
].proc_name
, pid
);
1095 /* Close all already opened file descriptors before we return an
1096 * error, so we don't leak them.
1098 for (j
= 0; j
< i
; j
++)
1099 close(init_ctx
->ns_fd
[j
]);
1102 lxc_proc_put_context_info(init_ctx
);
1106 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1107 ret
= lxc_attach_terminal(conf
, &terminal
);
1109 ERROR("Failed to setup new terminal");
1111 lxc_proc_put_context_info(init_ctx
);
1115 terminal
.log_fd
= options
->log_fd
;
1117 lxc_terminal_init(&terminal
);
1120 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1121 * to make sure we don't irritate other threads that want to fork+exec
1124 * IMPORTANT: if the initial process is multithreaded and another call
1125 * just fork()s away without exec'ing directly after, the socket fd will
1126 * exist in the forked process from the other thread and any close() in
1127 * our own child process will not really cause the socket to close
1128 * properly, potentially causing the parent to hang.
1130 * For this reason, while IPC is still active, we have to use shutdown()
1131 * if the child exits prematurely in order to signal that the socket is
1132 * closed and cannot assume that the child exiting will automatically do
1135 * IPC mechanism: (X is receiver)
1136 * initial process intermediate attached
1137 * X <--- send pid of
1140 * send 0 ------------------------------------> X
1141 * [do initialization]
1142 * X <------------------------------------ send 1
1143 * [add to cgroup, ...]
1144 * send 2 ------------------------------------> X
1145 * [set LXC_ATTACH_NO_NEW_PRIVS]
1146 * X <------------------------------------ send 3
1147 * [open LSM label fd]
1148 * send 4 ------------------------------------> X
1150 * close socket close socket
1153 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1155 SYSERROR("Could not set up required IPC mechanism for attaching");
1157 lxc_proc_put_context_info(init_ctx
);
1161 /* Create intermediate subprocess, two reasons:
1162 * 1. We can't setns() in the child itself, since we want to make
1163 * sure we are properly attached to the pidns.
1164 * 2. Also, the initial thread has to put the attached process
1165 * into the cgroup, which we can only do if we didn't already
1166 * setns() (otherwise, user namespaces will hate us).
1170 SYSERROR("Failed to create first subprocess");
1172 lxc_proc_put_context_info(init_ctx
);
1177 int ret_parent
= -1;
1178 pid_t to_cleanup_pid
= pid
;
1179 struct lxc_epoll_descr descr
= {0};
1181 /* close unneeded file descriptors */
1182 close(ipc_sockets
[1]);
1184 lxc_proc_close_ns_fd(init_ctx
);
1185 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1186 lxc_attach_terminal_close_slave(&terminal
);
1188 /* Attach to cgroup, if requested. */
1189 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1191 * If this is the unified hierarchy cgroup_attach() is
1194 ret
= cgroup_attach(name
, lxcpath
, pid
);
1196 __do_cgroup_exit
struct cgroup_ops
*cgroup_ops
= NULL
;
1198 cgroup_ops
= cgroup_init(conf
);
1202 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1205 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1208 /* Setup /proc limits */
1209 if (!lxc_list_empty(&conf
->procs
)) {
1210 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1215 /* Setup resource limits */
1216 if (!lxc_list_empty(&conf
->limits
)) {
1217 ret
= setup_resource_limits(&conf
->limits
, pid
);
1222 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1223 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1227 TRACE("Initialized terminal mainloop");
1230 /* Let the child process know to go ahead. */
1232 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1233 if (ret
!= sizeof(status
))
1234 goto close_mainloop
;
1236 TRACE("Told intermediate process to start initializing");
1238 /* Get pid of attached process from intermediate process. */
1239 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1240 if (ret
!= sizeof(attached_pid
))
1241 goto close_mainloop
;
1243 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1245 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1246 if (options
->stdin_fd
== 0) {
1247 signal(SIGINT
, SIG_IGN
);
1248 signal(SIGQUIT
, SIG_IGN
);
1251 /* Reap intermediate process. */
1252 ret
= wait_for_pid(pid
);
1254 goto close_mainloop
;
1256 TRACE("Intermediate process %d exited", pid
);
1258 /* We will always have to reap the attached process now. */
1259 to_cleanup_pid
= attached_pid
;
1261 /* Open LSM fd and send it to child. */
1262 if ((options
->namespaces
& CLONE_NEWNS
) &&
1263 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1264 init_ctx
->lsm_label
) {
1269 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1270 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1272 goto close_mainloop
;
1274 TRACE("Opened LSM label file descriptor %d", labelfd
);
1276 /* Send child fd of the LSM security module to write to. */
1277 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1280 SYSERROR("Failed to send lsm label fd");
1283 goto close_mainloop
;
1287 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1290 if (conf
&& conf
->seccomp
.seccomp
) {
1291 ret
= lxc_seccomp_recv_notifier_fd(&conf
->seccomp
, ipc_sockets
[0]);
1293 goto close_mainloop
;
1295 ret
= lxc_seccomp_add_notifier(name
, lxcpath
, &conf
->seccomp
);
1297 goto close_mainloop
;
1300 /* We're done, the child process should now execute whatever it
1301 * is that the user requested. The parent can now track it with
1302 * waitpid() or similar.
1305 *attached_process
= attached_pid
;
1307 /* Now shut down communication with child, we're done. */
1308 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1309 close(ipc_sockets
[0]);
1310 ipc_sockets
[0] = -1;
1313 to_cleanup_pid
= -1;
1315 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1316 ret
= lxc_mainloop(&descr
, -1);
1319 to_cleanup_pid
= attached_pid
;
1324 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1325 lxc_mainloop_close(&descr
);
1328 if (ipc_sockets
[0] >= 0) {
1329 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1330 close(ipc_sockets
[0]);
1333 if (to_cleanup_pid
> 0)
1334 (void)wait_for_pid(to_cleanup_pid
);
1336 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1337 lxc_terminal_delete(&terminal
);
1338 lxc_terminal_conf_free(&terminal
);
1341 lxc_proc_put_context_info(init_ctx
);
1345 /* close unneeded file descriptors */
1346 close(ipc_sockets
[0]);
1347 ipc_sockets
[0] = -EBADF
;
1349 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1350 lxc_attach_terminal_close_master(&terminal
);
1351 lxc_attach_terminal_close_peer(&terminal
);
1352 lxc_attach_terminal_close_log(&terminal
);
1355 /* Wait for the parent to have setup cgroups. */
1356 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1357 if (ret
!= sizeof(status
)) {
1358 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1359 lxc_proc_put_context_info(init_ctx
);
1360 _exit(EXIT_FAILURE
);
1363 TRACE("Intermediate process starting to initialize");
1365 /* Attach now, create another subprocess later, since pid namespaces
1366 * only really affect the children of the current process.
1368 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1370 ERROR("Failed to enter namespaces");
1371 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1372 lxc_proc_put_context_info(init_ctx
);
1373 _exit(EXIT_FAILURE
);
1376 /* close namespace file descriptors */
1377 lxc_proc_close_ns_fd(init_ctx
);
1379 /* Attach succeeded, try to cwd. */
1380 if (options
->initial_cwd
)
1381 new_cwd
= options
->initial_cwd
;
1385 ret
= chdir(new_cwd
);
1387 WARN("Could not change directory to \"%s\"", new_cwd
);
1391 /* Create attached process. */
1392 payload
.ipc_socket
= ipc_sockets
[1];
1393 payload
.options
= options
;
1394 payload
.init_ctx
= init_ctx
;
1395 payload
.terminal_slave_fd
= terminal
.slave
;
1396 payload
.exec_function
= exec_function
;
1397 payload
.exec_payload
= exec_payload
;
1399 pid
= lxc_raw_clone(CLONE_PARENT
, NULL
);
1401 SYSERROR("Failed to clone attached process");
1402 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1403 lxc_proc_put_context_info(init_ctx
);
1404 _exit(EXIT_FAILURE
);
1408 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1409 ret
= pthread_sigmask(SIG_SETMASK
,
1410 &terminal
.tty_state
->oldmask
, NULL
);
1412 SYSERROR("Failed to reset signal mask");
1413 _exit(EXIT_FAILURE
);
1417 ret
= attach_child_main(&payload
);
1419 ERROR("Failed to exec");
1421 _exit(EXIT_FAILURE
);
1424 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1425 lxc_attach_terminal_close_slave(&terminal
);
1427 /* Tell grandparent the pid of the pid of the newly created child. */
1428 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1429 if (ret
!= sizeof(pid
)) {
1430 /* If this really happens here, this is very unfortunate, since
1431 * the parent will not know the pid of the attached process and
1432 * will not be able to wait for it (and we won't either due to
1433 * CLONE_PARENT) so the parent won't be able to reap it and the
1434 * attached process will remain a zombie.
1436 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1437 lxc_proc_put_context_info(init_ctx
);
1438 _exit(EXIT_FAILURE
);
1441 TRACE("Sending pid %d of attached process", pid
);
1443 /* The rest is in the hands of the initial and the attached process. */
1444 lxc_proc_put_context_info(init_ctx
);
1445 _exit(EXIT_SUCCESS
);
1448 int lxc_attach_run_command(void *payload
)
1451 lxc_attach_command_t
*cmd
= payload
;
1453 ret
= execvp(cmd
->program
, cmd
->argv
);
1465 SYSERROR("Failed to exec \"%s\"", cmd
->program
);
1469 int lxc_attach_run_shell(void* payload
)
1471 __do_free
char *buf
= NULL
;
1473 struct passwd pwent
;
1474 struct passwd
*pwentp
= NULL
;
1479 /* Ignore payload parameter. */
1484 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1488 buf
= malloc(bufsize
);
1490 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1493 WARN("Could not find matched password record");
1495 WARN("Failed to get password record - %u", uid
);
1499 /* This probably happens because of incompatible nss implementations in
1500 * host and container (remember, this code is still using the host's
1501 * glibc but our mount namespace is in the container) we may try to get
1502 * the information by spawning a [getent passwd uid] process and parsing
1506 user_shell
= lxc_attach_getpwshell(uid
);
1508 user_shell
= pwent
.pw_shell
;
1511 execlp(user_shell
, user_shell
, (char *)NULL
);
1513 /* Executed if either no passwd entry or execvp fails, we will fall back
1514 * on /bin/sh as a default shell.
1516 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1518 SYSERROR("Failed to execute shell");