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
= LXC_INVALID_UID
;
522 gid_t gid
= LXC_INVALID_GID
;
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
!= LXC_INVALID_UID
&& gid
!= LXC_INVALID_GID
)
549 /* Only override arguments if we found something. */
550 if (uid
!= LXC_INVALID_UID
)
553 if (gid
!= LXC_INVALID_GID
)
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_disarm(c
->lxc_conf
->seccomp
.seccomp
);
573 /* Remove current setting. */
574 if (!c
->set_config_item(c
, "lxc.seccomp.profile", "") &&
575 !c
->set_config_item(c
, "lxc.seccomp", ""))
578 /* Fetch the current profile path over the cmd interface. */
579 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
581 INFO("Failed to retrieve lxc.seccomp.profile");
583 path
= c
->get_running_config_item(c
, "lxc.seccomp");
585 return log_info(true, "Failed to retrieve lxc.seccomp");
588 /* Copy the value into the new lxc_conf. */
589 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
593 /* Attempt to parse the resulting config. */
594 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
596 return log_error(false, "Failed to retrieve seccomp policy");
598 return log_info(true, "Retrieved seccomp policy");
601 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
603 __do_free
char *val
= NULL
;
605 /* Remove current setting. */
606 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
607 return log_info(false, "Failed to unset lxc.no_new_privs");
609 /* Retrieve currently active setting. */
610 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
612 return log_info(false, "Failed to retrieve lxc.no_new_privs");
614 /* Set currently active setting. */
615 return c
->set_config_item(c
, "lxc.no_new_privs", val
);
618 static signed long get_personality(const char *name
, const char *lxcpath
)
620 __do_free
char *p
= NULL
;
622 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
626 return lxc_config_parse_arch(p
);
629 struct attach_clone_payload
{
631 int terminal_slave_fd
;
632 lxc_attach_options_t
*options
;
633 struct lxc_proc_context_info
*init_ctx
;
634 lxc_attach_exec_t exec_function
;
638 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
640 close_prot_errno_disarm(p
->ipc_socket
);
641 close_prot_errno_disarm(p
->terminal_slave_fd
);
643 lxc_proc_put_context_info(p
->init_ctx
);
648 static int attach_child_main(struct attach_clone_payload
*payload
)
653 uid_t ns_root_uid
= 0;
654 gid_t ns_root_gid
= 0;
655 lxc_attach_options_t
* options
= payload
->options
;
656 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
657 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
658 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
661 /* A description of the purpose of this functionality is provided in the
662 * lxc-attach(1) manual page. We have to remount here and not in the
663 * parent process, otherwise /proc may not properly reflect the new pid
666 if (!(options
->namespaces
& CLONE_NEWNS
) &&
667 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
668 ret
= lxc_attach_remount_sys_proc();
672 TRACE("Remounted \"/proc\" and \"/sys\"");
675 /* Now perform additional attachments. */
676 #if HAVE_SYS_PERSONALITY_H
677 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
678 long new_personality
;
680 if (options
->personality
< 0)
681 new_personality
= init_ctx
->personality
;
683 new_personality
= options
->personality
;
685 ret
= personality(new_personality
);
689 TRACE("Set new personality");
693 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
694 ret
= lxc_attach_drop_privs(init_ctx
);
698 TRACE("Dropped capabilities");
701 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
702 * if you want this to be a no-op).
704 ret
= lxc_attach_set_environment(init_ctx
,
706 options
->extra_env_vars
,
707 options
->extra_keep_env
);
711 TRACE("Set up environment");
713 /* This remark only affects fully unprivileged containers:
714 * Receive fd for LSM security module before we set{g,u}id(). The reason
715 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
716 * we will change our effective uid. This means our effective uid will
717 * be different from the effective uid of the process that created us
718 * which means that this processs no longer has capabilities in our
719 * namespace including CAP_SYS_PTRACE. This means we will not be able to
720 * read and /proc/<pid> files for the process anymore when /proc is
721 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
725 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
728 SYSERROR("Failed to receive lsm label fd");
733 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
736 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
737 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
742 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
745 if (options
->namespaces
& CLONE_NEWUSER
) {
746 /* Check whether nsuid 0 has a mapping. */
747 ns_root_uid
= get_ns_uid(0);
749 /* Check whether nsgid 0 has a mapping. */
750 ns_root_gid
= get_ns_gid(0);
752 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
753 * init was started with.
755 if (ns_root_uid
== LXC_INVALID_UID
)
756 lxc_attach_get_init_uidgid(&ns_root_uid
, &ns_root_gid
);
758 if (ns_root_uid
== LXC_INVALID_UID
)
761 if (!lxc_switch_uid_gid(ns_root_uid
, ns_root_gid
))
766 if (options
->uid
!= LXC_INVALID_UID
)
767 new_uid
= options
->uid
;
769 new_uid
= ns_root_uid
;
771 if (options
->gid
!= LXC_INVALID_GID
)
772 new_gid
= options
->gid
;
774 new_gid
= ns_root_gid
;
776 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
777 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
778 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
779 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
780 prctl_arg(0), prctl_arg(0));
784 TRACE("Set PR_SET_NO_NEW_PRIVS");
790 /* Change into our new LSM profile. */
791 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
793 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
798 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
801 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
802 init_ctx
->container
->lxc_conf
->seccomp
.seccomp
) {
803 struct lxc_conf
*conf
= init_ctx
->container
->lxc_conf
;
805 ret
= lxc_seccomp_load(conf
);
809 TRACE("Loaded seccomp profile");
811 ret
= lxc_seccomp_send_notifier_fd(&conf
->seccomp
, payload
->ipc_socket
);
816 close(payload
->ipc_socket
);
817 payload
->ipc_socket
= -EBADF
;
818 lxc_proc_put_context_info(init_ctx
);
819 payload
->init_ctx
= NULL
;
821 /* The following is done after the communication socket is shut down.
822 * That way, all errors that might (though unlikely) occur up until this
823 * point will have their messages printed to the original stderr (if
824 * logging is so configured) and not the fd the user supplied, if any.
827 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
828 * may want to make sure the fds are closed, for example.
830 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
831 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
833 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
834 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
836 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
837 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
839 /* close the old fds */
840 if (options
->stdin_fd
> STDERR_FILENO
)
841 close(options
->stdin_fd
);
843 if (options
->stdout_fd
> STDERR_FILENO
)
844 close(options
->stdout_fd
);
846 if (options
->stderr_fd
> STDERR_FILENO
)
847 close(options
->stderr_fd
);
850 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
851 * here, ignore errors.
853 for (int fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
854 ret
= fd_cloexec(fd
, false);
856 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
861 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
862 ret
= lxc_terminal_prepare_login(payload
->terminal_slave_fd
);
864 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_slave_fd
);
868 TRACE("Prepared terminal file descriptor %d", payload
->terminal_slave_fd
);
871 /* Avoid unnecessary syscalls. */
872 if (new_uid
== ns_root_uid
)
873 new_uid
= LXC_INVALID_UID
;
875 if (new_gid
== ns_root_gid
)
876 new_gid
= LXC_INVALID_GID
;
878 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
881 /* We're done, so we can now do whatever the user intended us to do. */
882 _exit(payload
->exec_function(payload
->exec_payload
));
885 lxc_put_attach_clone_payload(payload
);
889 static int lxc_attach_terminal(struct lxc_conf
*conf
,
890 struct lxc_terminal
*terminal
)
894 lxc_terminal_init(terminal
);
896 ret
= lxc_terminal_create(terminal
);
898 return log_error(-1, "Failed to create terminal");
900 /* Shift ttys to container. */
901 ret
= lxc_terminal_map_ids(conf
, terminal
);
903 ERROR("Failed to chown terminal");
910 lxc_terminal_delete(terminal
);
911 lxc_terminal_conf_free(terminal
);
915 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
916 struct lxc_epoll_descr
*descr
)
920 ret
= lxc_mainloop_open(descr
);
922 return log_error(-1, "Failed to create mainloop");
924 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
926 lxc_mainloop_close(descr
);
927 return log_error(-1, "Failed to add handlers to mainloop");
933 static inline void lxc_attach_terminal_close_master(struct lxc_terminal
*terminal
)
935 close_prot_errno_disarm(terminal
->master
);
938 static inline void lxc_attach_terminal_close_slave(struct lxc_terminal
*terminal
)
940 close_prot_errno_disarm(terminal
->slave
);
943 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
945 close_prot_errno_disarm(terminal
->peer
);
948 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
950 close_prot_errno_disarm(terminal
->log_fd
);
953 int lxc_attach(struct lxc_container
*container
, lxc_attach_exec_t exec_function
,
954 void *exec_payload
, lxc_attach_options_t
*options
,
955 pid_t
*attached_process
)
960 signed long personality
;
961 pid_t attached_pid
, init_pid
, pid
;
962 struct lxc_proc_context_info
*init_ctx
;
963 struct lxc_terminal terminal
;
964 struct lxc_conf
*conf
;
965 char *name
, *lxcpath
;
966 struct attach_clone_payload payload
= {0};
968 ret
= access("/proc/self/ns", X_OK
);
970 return log_error_errno(-1, errno
, "Does this kernel version support namespaces?");
973 return ret_set_errno(-1, EINVAL
);
975 if (!lxc_container_get(container
))
976 return ret_set_errno(-1, EINVAL
);
978 name
= container
->name
;
979 lxcpath
= container
->config_path
;
982 options
= &attach_static_default_options
;
984 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
986 lxc_container_put(container
);
987 return log_error(-1, "Failed to get init pid");
990 init_ctx
= lxc_proc_get_context_info(init_pid
);
992 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
993 lxc_container_put(container
);
997 init_ctx
->container
= container
;
999 personality
= get_personality(name
, lxcpath
);
1000 if (init_ctx
->personality
< 0) {
1001 ERROR("Failed to get personality of the container");
1002 lxc_proc_put_context_info(init_ctx
);
1005 init_ctx
->personality
= personality
;
1007 if (!init_ctx
->container
->lxc_conf
) {
1008 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1009 if (!init_ctx
->container
->lxc_conf
) {
1010 lxc_proc_put_context_info(init_ctx
);
1014 conf
= init_ctx
->container
->lxc_conf
;
1016 if (!fetch_seccomp(init_ctx
->container
, options
))
1017 WARN("Failed to get seccomp policy");
1019 if (!no_new_privs(init_ctx
->container
, options
))
1020 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1022 cwd
= getcwd(NULL
, 0);
1024 /* Determine which namespaces the container was created with
1025 * by asking lxc-start, if necessary.
1027 if (options
->namespaces
== -1) {
1028 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1030 if (options
->namespaces
== -1) {
1031 ERROR("Failed to automatically determine the "
1032 "namespaces which the container uses");
1034 lxc_proc_put_context_info(init_ctx
);
1038 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1039 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1040 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1044 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1047 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1051 pid
= lxc_raw_getpid();
1053 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1056 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1057 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1058 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1059 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1063 if (init_ctx
->ns_fd
[i
] >= 0)
1066 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1067 DEBUG("Inheriting %s namespace from %d",
1068 ns_info
[i
].proc_name
, pid
);
1069 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1073 /* We failed to preserve the namespace. */
1074 SYSERROR("Failed to attach to %s namespace of %d",
1075 ns_info
[i
].proc_name
, pid
);
1077 /* Close all already opened file descriptors before we return an
1078 * error, so we don't leak them.
1080 for (j
= 0; j
< i
; j
++)
1081 close(init_ctx
->ns_fd
[j
]);
1084 lxc_proc_put_context_info(init_ctx
);
1088 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1089 ret
= lxc_attach_terminal(conf
, &terminal
);
1091 ERROR("Failed to setup new terminal");
1093 lxc_proc_put_context_info(init_ctx
);
1097 terminal
.log_fd
= options
->log_fd
;
1099 lxc_terminal_init(&terminal
);
1102 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1103 * to make sure we don't irritate other threads that want to fork+exec
1106 * IMPORTANT: if the initial process is multithreaded and another call
1107 * just fork()s away without exec'ing directly after, the socket fd will
1108 * exist in the forked process from the other thread and any close() in
1109 * our own child process will not really cause the socket to close
1110 * properly, potentially causing the parent to hang.
1112 * For this reason, while IPC is still active, we have to use shutdown()
1113 * if the child exits prematurely in order to signal that the socket is
1114 * closed and cannot assume that the child exiting will automatically do
1117 * IPC mechanism: (X is receiver)
1118 * initial process intermediate attached
1119 * X <--- send pid of
1122 * send 0 ------------------------------------> X
1123 * [do initialization]
1124 * X <------------------------------------ send 1
1125 * [add to cgroup, ...]
1126 * send 2 ------------------------------------> X
1127 * [set LXC_ATTACH_NO_NEW_PRIVS]
1128 * X <------------------------------------ send 3
1129 * [open LSM label fd]
1130 * send 4 ------------------------------------> X
1132 * close socket close socket
1135 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1137 SYSERROR("Could not set up required IPC mechanism for attaching");
1139 lxc_proc_put_context_info(init_ctx
);
1143 /* Create intermediate subprocess, two reasons:
1144 * 1. We can't setns() in the child itself, since we want to make
1145 * sure we are properly attached to the pidns.
1146 * 2. Also, the initial thread has to put the attached process
1147 * into the cgroup, which we can only do if we didn't already
1148 * setns() (otherwise, user namespaces will hate us).
1152 SYSERROR("Failed to create first subprocess");
1154 lxc_proc_put_context_info(init_ctx
);
1159 int ret_parent
= -1;
1160 pid_t to_cleanup_pid
= pid
;
1161 struct lxc_epoll_descr descr
= {0};
1163 /* close unneeded file descriptors */
1164 close(ipc_sockets
[1]);
1166 lxc_proc_close_ns_fd(init_ctx
);
1167 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1168 lxc_attach_terminal_close_slave(&terminal
);
1170 /* Attach to cgroup, if requested. */
1171 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1173 * If this is the unified hierarchy cgroup_attach() is
1176 ret
= cgroup_attach(name
, lxcpath
, pid
);
1178 __do_cgroup_exit
struct cgroup_ops
*cgroup_ops
= NULL
;
1180 cgroup_ops
= cgroup_init(conf
);
1184 if (!cgroup_ops
->attach(cgroup_ops
, name
, lxcpath
, pid
))
1187 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1190 /* Setup /proc limits */
1191 if (!lxc_list_empty(&conf
->procs
)) {
1192 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1197 /* Setup resource limits */
1198 if (!lxc_list_empty(&conf
->limits
)) {
1199 ret
= setup_resource_limits(&conf
->limits
, pid
);
1204 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1205 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1209 TRACE("Initialized terminal mainloop");
1212 /* Let the child process know to go ahead. */
1214 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1215 if (ret
!= sizeof(status
))
1216 goto close_mainloop
;
1218 TRACE("Told intermediate process to start initializing");
1220 /* Get pid of attached process from intermediate process. */
1221 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1222 if (ret
!= sizeof(attached_pid
))
1223 goto close_mainloop
;
1225 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1227 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1228 if (options
->stdin_fd
== 0) {
1229 signal(SIGINT
, SIG_IGN
);
1230 signal(SIGQUIT
, SIG_IGN
);
1233 /* Reap intermediate process. */
1234 ret
= wait_for_pid(pid
);
1236 goto close_mainloop
;
1238 TRACE("Intermediate process %d exited", pid
);
1240 /* We will always have to reap the attached process now. */
1241 to_cleanup_pid
= attached_pid
;
1243 /* Open LSM fd and send it to child. */
1244 if ((options
->namespaces
& CLONE_NEWNS
) &&
1245 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1246 init_ctx
->lsm_label
) {
1251 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1252 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1254 goto close_mainloop
;
1256 TRACE("Opened LSM label file descriptor %d", labelfd
);
1258 /* Send child fd of the LSM security module to write to. */
1259 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1262 SYSERROR("Failed to send lsm label fd");
1265 goto close_mainloop
;
1269 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1272 if (conf
&& conf
->seccomp
.seccomp
) {
1273 ret
= lxc_seccomp_recv_notifier_fd(&conf
->seccomp
, ipc_sockets
[0]);
1275 goto close_mainloop
;
1277 ret
= lxc_seccomp_add_notifier(name
, lxcpath
, &conf
->seccomp
);
1279 goto close_mainloop
;
1282 /* We're done, the child process should now execute whatever it
1283 * is that the user requested. The parent can now track it with
1284 * waitpid() or similar.
1287 *attached_process
= attached_pid
;
1289 /* Now shut down communication with child, we're done. */
1290 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1291 close(ipc_sockets
[0]);
1292 ipc_sockets
[0] = -1;
1295 to_cleanup_pid
= -1;
1297 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1298 ret
= lxc_mainloop(&descr
, -1);
1301 to_cleanup_pid
= attached_pid
;
1306 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1307 lxc_mainloop_close(&descr
);
1310 if (ipc_sockets
[0] >= 0) {
1311 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1312 close(ipc_sockets
[0]);
1315 if (to_cleanup_pid
> 0)
1316 (void)wait_for_pid(to_cleanup_pid
);
1318 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1319 lxc_terminal_delete(&terminal
);
1320 lxc_terminal_conf_free(&terminal
);
1323 lxc_proc_put_context_info(init_ctx
);
1327 /* close unneeded file descriptors */
1328 close(ipc_sockets
[0]);
1329 ipc_sockets
[0] = -EBADF
;
1331 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1332 lxc_attach_terminal_close_master(&terminal
);
1333 lxc_attach_terminal_close_peer(&terminal
);
1334 lxc_attach_terminal_close_log(&terminal
);
1337 /* Wait for the parent to have setup cgroups. */
1338 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1339 if (ret
!= sizeof(status
)) {
1340 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1341 lxc_proc_put_context_info(init_ctx
);
1342 _exit(EXIT_FAILURE
);
1345 TRACE("Intermediate process starting to initialize");
1347 /* Attach now, create another subprocess later, since pid namespaces
1348 * only really affect the children of the current process.
1350 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1352 ERROR("Failed to enter namespaces");
1353 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1354 lxc_proc_put_context_info(init_ctx
);
1355 _exit(EXIT_FAILURE
);
1358 /* close namespace file descriptors */
1359 lxc_proc_close_ns_fd(init_ctx
);
1361 /* Attach succeeded, try to cwd. */
1362 if (options
->initial_cwd
)
1363 new_cwd
= options
->initial_cwd
;
1367 ret
= chdir(new_cwd
);
1369 WARN("Could not change directory to \"%s\"", new_cwd
);
1373 /* Create attached process. */
1374 payload
.ipc_socket
= ipc_sockets
[1];
1375 payload
.options
= options
;
1376 payload
.init_ctx
= init_ctx
;
1377 payload
.terminal_slave_fd
= terminal
.slave
;
1378 payload
.exec_function
= exec_function
;
1379 payload
.exec_payload
= exec_payload
;
1381 pid
= lxc_raw_clone(CLONE_PARENT
, NULL
);
1383 SYSERROR("Failed to clone attached process");
1384 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1385 lxc_proc_put_context_info(init_ctx
);
1386 _exit(EXIT_FAILURE
);
1390 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1391 ret
= pthread_sigmask(SIG_SETMASK
,
1392 &terminal
.tty_state
->oldmask
, NULL
);
1394 SYSERROR("Failed to reset signal mask");
1395 _exit(EXIT_FAILURE
);
1399 ret
= attach_child_main(&payload
);
1401 ERROR("Failed to exec");
1403 _exit(EXIT_FAILURE
);
1406 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1407 lxc_attach_terminal_close_slave(&terminal
);
1409 /* Tell grandparent the pid of the pid of the newly created child. */
1410 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1411 if (ret
!= sizeof(pid
)) {
1412 /* If this really happens here, this is very unfortunate, since
1413 * the parent will not know the pid of the attached process and
1414 * will not be able to wait for it (and we won't either due to
1415 * CLONE_PARENT) so the parent won't be able to reap it and the
1416 * attached process will remain a zombie.
1418 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1419 lxc_proc_put_context_info(init_ctx
);
1420 _exit(EXIT_FAILURE
);
1423 TRACE("Sending pid %d of attached process", pid
);
1425 /* The rest is in the hands of the initial and the attached process. */
1426 lxc_proc_put_context_info(init_ctx
);
1427 _exit(EXIT_SUCCESS
);
1430 int lxc_attach_run_command(void *payload
)
1433 lxc_attach_command_t
*cmd
= payload
;
1435 ret
= execvp(cmd
->program
, cmd
->argv
);
1447 return log_error_errno(ret
, errno
, "Failed to exec \"%s\"", cmd
->program
);
1450 int lxc_attach_run_shell(void* payload
)
1452 __do_free
char *buf
= NULL
;
1454 struct passwd pwent
;
1455 struct passwd
*pwentp
= NULL
;
1460 /* Ignore payload parameter. */
1465 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1469 buf
= malloc(bufsize
);
1471 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1474 WARN("Could not find matched password record");
1476 WARN("Failed to get password record - %u", uid
);
1480 /* This probably happens because of incompatible nss implementations in
1481 * host and container (remember, this code is still using the host's
1482 * glibc but our mount namespace is in the container) we may try to get
1483 * the information by spawning a [getent passwd uid] process and parsing
1487 user_shell
= lxc_attach_getpwshell(uid
);
1489 user_shell
= pwent
.pw_shell
;
1492 execlp(user_shell
, user_shell
, (char *)NULL
);
1494 /* Executed if either no passwd entry or execvp fails, we will fall back
1495 * on /bin/sh as a default shell.
1497 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1499 SYSERROR("Failed to execute shell");