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 "process_utils.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 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
96 info
->ns_fd
[i
] = -EBADF
;
98 return move_ptr(info
);
101 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
103 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
104 close_prot_errno_disarm(ctx
->ns_fd
[i
]);
107 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
109 free(ctx
->lsm_label
);
110 ctx
->lsm_label
= NULL
;
112 if (ctx
->container
) {
113 lxc_container_put(ctx
->container
);
114 ctx
->container
= NULL
;
117 lxc_proc_close_ns_fd(ctx
);
122 * in_same_namespace - Check whether two processes are in the same namespace.
123 * @pid1 - PID of the first process.
124 * @pid2 - PID of the second process.
125 * @ns - Name of the namespace to check. Must correspond to one of the names
126 * for the namespaces as shown in /proc/<pid/ns/
128 * If the two processes are not in the same namespace returns an fd to the
129 * namespace of the second process identified by @pid2. If the two processes are
130 * in the same namespace returns -EINVAL, -1 if an error occurred.
132 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
134 __do_close
int ns_fd1
= -EBADF
, ns_fd2
= -EBADF
;
136 struct stat ns_st1
, ns_st2
;
138 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
140 /* The kernel does not support this namespace. This is not an
149 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
153 ret
= fstat(ns_fd1
, &ns_st1
);
157 ret
= fstat(ns_fd2
, &ns_st2
);
161 /* processes are in the same namespace */
162 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
165 /* processes are in different namespaces */
166 return move_fd(ns_fd2
);
169 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
171 for (int i
= 0; i
< LXC_NS_MAX
; i
++) {
174 if (ctx
->ns_fd
[i
] < 0)
177 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
179 return log_error_errno(-1,
180 errno
, "Failed to attach to %s namespace of %d",
181 ns_info
[i
].proc_name
, pid
);
183 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
189 int lxc_attach_remount_sys_proc(void)
193 ret
= unshare(CLONE_NEWNS
);
195 return log_error_errno(-1, errno
, "Failed to unshare mount namespace");
197 if (detect_shared_rootfs()) {
198 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
199 SYSERROR("Failed to make / rslave");
200 ERROR("Continuing...");
204 /* Assume /proc is always mounted, so remount it. */
205 ret
= umount2("/proc", MNT_DETACH
);
207 return log_error_errno(-1, errno
, "Failed to unmount /proc");
209 ret
= mount("none", "/proc", "proc", 0, NULL
);
211 return log_error_errno(-1, errno
, "Failed to remount /proc");
214 * Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
215 * we ignore it because it may not have been mounted in the first place.
217 ret
= umount2("/sys", MNT_DETACH
);
218 if (ret
< 0 && errno
!= EINVAL
)
219 return log_error_errno(-1, errno
, "Failed to unmount /sys");
222 if (ret
== 0 && mount("none", "/sys", "sysfs", 0, NULL
))
223 return log_error_errno(-1, errno
, "Failed to remount /sys");
228 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
232 last_cap
= lxc_caps_last_cap();
233 for (int cap
= 0; cap
<= last_cap
; cap
++) {
234 if (ctx
->capability_mask
& (1LL << cap
))
237 if (prctl(PR_CAPBSET_DROP
, prctl_arg(cap
), prctl_arg(0),
238 prctl_arg(0), prctl_arg(0)))
239 return log_error_errno(-1, errno
, "Failed to drop capability %d", cap
);
241 TRACE("Dropped capability %d", cap
);
247 static int lxc_attach_set_environment(struct lxc_proc_context_info
*init_ctx
,
248 enum lxc_attach_env_policy_t policy
,
249 char **extra_env
, char **extra_keep
)
252 struct lxc_list
*iterator
;
254 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
256 char **extra_keep_store
= NULL
;
261 for (count
= 0; extra_keep
[count
]; count
++)
264 extra_keep_store
= calloc(count
, sizeof(char *));
265 if (!extra_keep_store
)
268 for (i
= 0; i
< count
; i
++) {
269 char *v
= getenv(extra_keep
[i
]);
271 extra_keep_store
[i
] = strdup(v
);
272 if (!extra_keep_store
[i
]) {
274 free(extra_keep_store
[--i
]);
276 free(extra_keep_store
);
280 if (strcmp(extra_keep
[i
], "PATH") == 0)
287 if (extra_keep_store
) {
290 for (p
= extra_keep_store
; *p
; p
++)
293 free(extra_keep_store
);
296 return log_error(-1, "Failed to clear environment");
299 if (extra_keep_store
) {
302 for (i
= 0; extra_keep
[i
]; i
++) {
303 if (extra_keep_store
[i
]) {
304 ret
= setenv(extra_keep
[i
], extra_keep_store
[i
], 1);
306 SYSWARN("Failed to set environment variable");
309 free(extra_keep_store
[i
]);
312 free(extra_keep_store
);
315 /* Always set a default path; shells and execlp tend to be fine
316 * without it, but there is a disturbing number of C programs
317 * out there that just assume that getenv("PATH") is never NULL
318 * and then die a painful segfault death.
321 ret
= setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
323 SYSWARN("Failed to set environment variable");
327 ret
= putenv("container=lxc");
329 return log_warn(-1, "Failed to set environment variable");
331 /* Set container environment variables.*/
332 if (init_ctx
&& init_ctx
->container
&& init_ctx
->container
->lxc_conf
) {
333 lxc_list_for_each(iterator
, &init_ctx
->container
->lxc_conf
->environment
) {
336 env_tmp
= strdup((char *)iterator
->elem
);
340 ret
= putenv(env_tmp
);
342 return log_error_errno(-1, errno
, "Failed to set environment variable: %s", (char *)iterator
->elem
);
346 /* Set extra environment variables. */
348 for (; *extra_env
; extra_env
++) {
351 /* We just assume the user knows what they are doing, so
352 * we don't do any checks.
354 p
= strdup(*extra_env
);
360 SYSWARN("Failed to set environment variable");
367 static char *lxc_attach_getpwshell(uid_t uid
)
369 __do_free
char *line
= NULL
, *result
= NULL
;
370 __do_fclose
FILE *pipe_f
= NULL
;
375 size_t line_bufsz
= 0;
377 /* We need to fork off a process that runs the getent program, and we
378 * need to capture its output, so we use a pipe for that purpose.
380 ret
= pipe2(pipes
, O_CLOEXEC
);
393 char *arguments
[] = {
402 /* We want to capture stdout. */
403 ret
= dup2(pipes
[1], STDOUT_FILENO
);
408 /* Get rid of stdin/stderr, so we try to associate it with
414 close(STDERR_FILENO
);
416 (void)dup3(fd
, STDIN_FILENO
, O_CLOEXEC
);
417 (void)dup3(fd
, STDERR_FILENO
, O_CLOEXEC
);
421 /* Finish argument list. */
422 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long)uid
);
423 if (ret
<= 0 || ret
>= sizeof(uid_buf
))
426 /* Try to run getent program. */
427 (void)execvp("getent", arguments
);
433 pipe_f
= fdopen(pipes
[0], "re");
438 /* Transfer ownership of pipes[0] to pipe_f. */
441 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
445 char *endptr
= NULL
, *saveptr
= NULL
;
447 /* If we already found something, just continue to read
448 * until the pipe doesn't deliver any more data, but
449 * don't modify the existing data structure.
457 /* Trim line on the right hand side. */
458 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
461 /* Split into tokens: first: user name. */
462 token
= strtok_r(line
, ":", &saveptr
);
466 /* next: dummy password field */
467 token
= strtok_r(NULL
, ":", &saveptr
);
472 token
= strtok_r(NULL
, ":", &saveptr
);
473 value
= token
? strtol(token
, &endptr
, 10) : 0;
474 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
||
478 /* dummy sanity check: user id matches */
479 if ((uid_t
)value
!= uid
)
482 /* skip fields: gid, gecos, dir, go to next field 'shell' */
483 for (i
= 0; i
< 4; i
++) {
484 token
= strtok_r(NULL
, ":", &saveptr
);
493 result
= strdup(token
);
495 /* Sanity check that there are no fields after that. */
496 token
= strtok_r(NULL
, ":", &saveptr
);
504 ret
= wait_for_pid(pid
);
511 return move_ptr(result
);
514 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
516 __do_free
char *line
= NULL
;
517 __do_fclose
FILE *proc_file
= NULL
;
518 char proc_fn
[LXC_PROC_STATUS_LEN
];
520 size_t line_bufsz
= 0;
522 uid_t uid
= LXC_INVALID_UID
;
523 gid_t gid
= LXC_INVALID_GID
;
525 ret
= snprintf(proc_fn
, LXC_PROC_STATUS_LEN
, "/proc/%d/status", 1);
526 if (ret
< 0 || ret
>= LXC_PROC_STATUS_LEN
)
529 proc_file
= fopen(proc_fn
, "re");
533 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
534 /* Format is: real, effective, saved set user, fs we only care
537 ret
= sscanf(line
, "Uid: %ld", &value
);
538 if (ret
!= EOF
&& ret
== 1) {
541 ret
= sscanf(line
, "Gid: %ld", &value
);
542 if (ret
!= EOF
&& ret
== 1)
546 if (uid
!= LXC_INVALID_UID
&& gid
!= LXC_INVALID_GID
)
550 /* Only override arguments if we found something. */
551 if (uid
!= LXC_INVALID_UID
)
554 if (gid
!= LXC_INVALID_GID
)
557 /* TODO: we should also parse supplementary groups and use
558 * setgroups() to set them.
562 static bool fetch_seccomp(struct lxc_container
*c
, lxc_attach_options_t
*options
)
564 __do_free
char *path
= NULL
;
568 if (!(options
->namespaces
& CLONE_NEWNS
) ||
569 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
570 free_disarm(c
->lxc_conf
->seccomp
.seccomp
);
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 return log_info(true, "Failed to retrieve lxc.seccomp");
589 /* Copy the value into the new lxc_conf. */
590 bret
= c
->set_config_item(c
, "lxc.seccomp.profile", path
);
594 /* Attempt to parse the resulting config. */
595 ret
= lxc_read_seccomp_config(c
->lxc_conf
);
597 return log_error(false, "Failed to retrieve seccomp policy");
599 return log_info(true, "Retrieved seccomp policy");
602 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
604 __do_free
char *val
= NULL
;
606 /* Remove current setting. */
607 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
608 return log_info(false, "Failed to unset lxc.no_new_privs");
610 /* Retrieve currently active setting. */
611 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
613 return log_info(false, "Failed to retrieve lxc.no_new_privs");
615 /* Set currently active setting. */
616 return c
->set_config_item(c
, "lxc.no_new_privs", val
);
619 static signed long get_personality(const char *name
, const char *lxcpath
)
621 __do_free
char *p
= NULL
;
623 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
627 return lxc_config_parse_arch(p
);
630 struct attach_clone_payload
{
633 lxc_attach_options_t
*options
;
634 struct lxc_proc_context_info
*init_ctx
;
635 lxc_attach_exec_t exec_function
;
639 static void lxc_put_attach_clone_payload(struct attach_clone_payload
*p
)
641 close_prot_errno_disarm(p
->ipc_socket
);
642 close_prot_errno_disarm(p
->terminal_pts_fd
);
644 lxc_proc_put_context_info(p
->init_ctx
);
649 static int attach_child_main(struct attach_clone_payload
*payload
)
654 uid_t ns_root_uid
= 0;
655 gid_t ns_root_gid
= 0;
656 lxc_attach_options_t
* options
= payload
->options
;
657 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
658 bool needs_lsm
= (options
->namespaces
& CLONE_NEWNS
) &&
659 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
662 /* A description of the purpose of this functionality is provided in the
663 * lxc-attach(1) manual page. We have to remount here and not in the
664 * parent process, otherwise /proc may not properly reflect the new pid
667 if (!(options
->namespaces
& CLONE_NEWNS
) &&
668 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
669 ret
= lxc_attach_remount_sys_proc();
673 TRACE("Remounted \"/proc\" and \"/sys\"");
676 /* Now perform additional attachments. */
677 #if HAVE_SYS_PERSONALITY_H
678 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
679 long new_personality
;
681 if (options
->personality
< 0)
682 new_personality
= init_ctx
->personality
;
684 new_personality
= options
->personality
;
686 ret
= personality(new_personality
);
690 TRACE("Set new personality");
694 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
695 ret
= lxc_attach_drop_privs(init_ctx
);
699 TRACE("Dropped capabilities");
702 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
703 * if you want this to be a no-op).
705 ret
= lxc_attach_set_environment(init_ctx
,
707 options
->extra_env_vars
,
708 options
->extra_keep_env
);
712 TRACE("Set up environment");
714 /* This remark only affects fully unprivileged containers:
715 * Receive fd for LSM security module before we set{g,u}id(). The reason
716 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
717 * we will change our effective uid. This means our effective uid will
718 * be different from the effective uid of the process that created us
719 * which means that this processs no longer has capabilities in our
720 * namespace including CAP_SYS_PTRACE. This means we will not be able to
721 * read and /proc/<pid> files for the process anymore when /proc is
722 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
726 ret
= lxc_abstract_unix_recv_fds(payload
->ipc_socket
, &lsm_fd
, 1, NULL
, 0);
729 SYSERROR("Failed to receive lsm label fd");
734 TRACE("Received LSM label file descriptor %d from parent", lsm_fd
);
737 if (options
->stdin_fd
> 0 && isatty(options
->stdin_fd
)) {
738 ret
= lxc_make_controlling_terminal(options
->stdin_fd
);
743 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
746 if (options
->namespaces
& CLONE_NEWUSER
) {
747 /* Check whether nsuid 0 has a mapping. */
748 ns_root_uid
= get_ns_uid(0);
750 /* Check whether nsgid 0 has a mapping. */
751 ns_root_gid
= get_ns_gid(0);
753 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
754 * init was started with.
756 if (ns_root_uid
== LXC_INVALID_UID
)
757 lxc_attach_get_init_uidgid(&ns_root_uid
, &ns_root_gid
);
759 if (ns_root_uid
== LXC_INVALID_UID
)
762 if (!lxc_switch_uid_gid(ns_root_uid
, ns_root_gid
))
767 if (options
->uid
!= LXC_INVALID_UID
)
768 new_uid
= options
->uid
;
770 new_uid
= ns_root_uid
;
772 if (options
->gid
!= LXC_INVALID_GID
)
773 new_gid
= options
->gid
;
775 new_gid
= ns_root_gid
;
777 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
778 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
779 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
780 ret
= prctl(PR_SET_NO_NEW_PRIVS
, prctl_arg(1), prctl_arg(0),
781 prctl_arg(0), prctl_arg(0));
785 TRACE("Set PR_SET_NO_NEW_PRIVS");
791 /* Change into our new LSM profile. */
792 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
794 ret
= lsm_process_label_set_at(lsm_fd
, init_ctx
->lsm_label
, on_exec
);
799 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx
->lsm_label
);
802 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
803 init_ctx
->container
->lxc_conf
->seccomp
.seccomp
) {
804 struct lxc_conf
*conf
= init_ctx
->container
->lxc_conf
;
806 ret
= lxc_seccomp_load(conf
);
810 TRACE("Loaded seccomp profile");
812 ret
= lxc_seccomp_send_notifier_fd(&conf
->seccomp
, payload
->ipc_socket
);
817 close(payload
->ipc_socket
);
818 payload
->ipc_socket
= -EBADF
;
819 lxc_proc_put_context_info(init_ctx
);
820 payload
->init_ctx
= NULL
;
822 /* The following is done after the communication socket is shut down.
823 * That way, all errors that might (though unlikely) occur up until this
824 * point will have their messages printed to the original stderr (if
825 * logging is so configured) and not the fd the user supplied, if any.
828 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
829 * may want to make sure the fds are closed, for example.
831 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= STDIN_FILENO
)
832 (void)dup2(options
->stdin_fd
, STDIN_FILENO
);
834 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= STDOUT_FILENO
)
835 (void)dup2(options
->stdout_fd
, STDOUT_FILENO
);
837 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= STDERR_FILENO
)
838 (void)dup2(options
->stderr_fd
, STDERR_FILENO
);
840 /* close the old fds */
841 if (options
->stdin_fd
> STDERR_FILENO
)
842 close(options
->stdin_fd
);
844 if (options
->stdout_fd
> STDERR_FILENO
)
845 close(options
->stdout_fd
);
847 if (options
->stderr_fd
> STDERR_FILENO
)
848 close(options
->stderr_fd
);
851 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
852 * here, ignore errors.
854 for (int fd
= STDIN_FILENO
; fd
<= STDERR_FILENO
; fd
++) {
855 ret
= fd_cloexec(fd
, false);
857 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd
);
862 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
863 ret
= lxc_terminal_prepare_login(payload
->terminal_pts_fd
);
865 SYSERROR("Failed to prepare terminal file descriptor %d", payload
->terminal_pts_fd
);
869 TRACE("Prepared terminal file descriptor %d", payload
->terminal_pts_fd
);
872 /* Avoid unnecessary syscalls. */
873 if (new_uid
== ns_root_uid
)
874 new_uid
= LXC_INVALID_UID
;
876 if (new_gid
== ns_root_gid
)
877 new_gid
= LXC_INVALID_GID
;
879 /* Make sure that the processes STDIO is correctly owned by the user that we are switching to */
880 ret
= fix_stdio_permissions(new_uid
);
882 WARN("Failed to ajust stdio permissions");
884 if (!lxc_switch_uid_gid(new_uid
, new_gid
))
887 /* We're done, so we can now do whatever the user intended us to do. */
888 _exit(payload
->exec_function(payload
->exec_payload
));
891 lxc_put_attach_clone_payload(payload
);
895 static int lxc_attach_terminal(struct lxc_conf
*conf
,
896 struct lxc_terminal
*terminal
)
900 lxc_terminal_init(terminal
);
902 ret
= lxc_terminal_create(terminal
);
904 return log_error(-1, "Failed to create terminal");
906 /* Shift ttys to container. */
907 ret
= lxc_terminal_map_ids(conf
, terminal
);
909 ERROR("Failed to chown terminal");
916 lxc_terminal_delete(terminal
);
917 lxc_terminal_conf_free(terminal
);
921 static int lxc_attach_terminal_mainloop_init(struct lxc_terminal
*terminal
,
922 struct lxc_epoll_descr
*descr
)
926 ret
= lxc_mainloop_open(descr
);
928 return log_error(-1, "Failed to create mainloop");
930 ret
= lxc_terminal_mainloop_add(descr
, terminal
);
932 lxc_mainloop_close(descr
);
933 return log_error(-1, "Failed to add handlers to mainloop");
939 static inline void lxc_attach_terminal_close_ptmx(struct lxc_terminal
*terminal
)
941 close_prot_errno_disarm(terminal
->ptmx
);
944 static inline void lxc_attach_terminal_close_pts(struct lxc_terminal
*terminal
)
946 close_prot_errno_disarm(terminal
->pts
);
949 static inline void lxc_attach_terminal_close_peer(struct lxc_terminal
*terminal
)
951 close_prot_errno_disarm(terminal
->peer
);
954 static inline void lxc_attach_terminal_close_log(struct lxc_terminal
*terminal
)
956 close_prot_errno_disarm(terminal
->log_fd
);
959 int lxc_attach(struct lxc_container
*container
, lxc_attach_exec_t exec_function
,
960 void *exec_payload
, lxc_attach_options_t
*options
,
961 pid_t
*attached_process
)
966 signed long personality
;
967 pid_t attached_pid
, init_pid
, pid
;
968 struct lxc_proc_context_info
*init_ctx
;
969 struct lxc_terminal terminal
;
970 struct lxc_conf
*conf
;
971 char *name
, *lxcpath
;
972 struct attach_clone_payload payload
= {0};
974 ret
= access("/proc/self/ns", X_OK
);
976 return log_error_errno(-1, errno
, "Does this kernel version support namespaces?");
979 return ret_set_errno(-1, EINVAL
);
981 if (!lxc_container_get(container
))
982 return ret_set_errno(-1, EINVAL
);
984 name
= container
->name
;
985 lxcpath
= container
->config_path
;
988 options
= &attach_static_default_options
;
990 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
992 lxc_container_put(container
);
993 return log_error(-1, "Failed to get init pid");
996 init_ctx
= lxc_proc_get_context_info(init_pid
);
998 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
999 lxc_container_put(container
);
1003 init_ctx
->container
= container
;
1005 personality
= get_personality(name
, lxcpath
);
1006 if (init_ctx
->personality
< 0) {
1007 ERROR("Failed to get personality of the container");
1008 lxc_proc_put_context_info(init_ctx
);
1011 init_ctx
->personality
= personality
;
1013 if (!init_ctx
->container
->lxc_conf
) {
1014 init_ctx
->container
->lxc_conf
= lxc_conf_init();
1015 if (!init_ctx
->container
->lxc_conf
) {
1016 lxc_proc_put_context_info(init_ctx
);
1020 conf
= init_ctx
->container
->lxc_conf
;
1022 return log_error_errno(-EINVAL
, EINVAL
, "Missing container confifg");
1024 if (!fetch_seccomp(init_ctx
->container
, options
))
1025 WARN("Failed to get seccomp policy");
1027 if (!no_new_privs(init_ctx
->container
, options
))
1028 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1030 cwd
= getcwd(NULL
, 0);
1032 /* Determine which namespaces the container was created with
1033 * by asking lxc-start, if necessary.
1035 if (options
->namespaces
== -1) {
1036 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
1038 if (options
->namespaces
== -1) {
1039 ERROR("Failed to automatically determine the "
1040 "namespaces which the container uses");
1042 lxc_proc_put_context_info(init_ctx
);
1046 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1047 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
1048 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
1052 if (ns_info
[i
].clone_flag
& options
->namespaces
)
1055 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
1059 pid
= lxc_raw_getpid();
1061 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
1064 if (options
->namespaces
& ns_info
[i
].clone_flag
)
1065 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
1066 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
1067 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
1071 if (init_ctx
->ns_fd
[i
] >= 0)
1074 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
1075 DEBUG("Inheriting %s namespace from %d",
1076 ns_info
[i
].proc_name
, pid
);
1077 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
1081 /* We failed to preserve the namespace. */
1082 SYSERROR("Failed to attach to %s namespace of %d",
1083 ns_info
[i
].proc_name
, pid
);
1085 /* Close all already opened file descriptors before we return an
1086 * error, so we don't leak them.
1088 for (j
= 0; j
< i
; j
++)
1089 close(init_ctx
->ns_fd
[j
]);
1092 lxc_proc_put_context_info(init_ctx
);
1096 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1097 ret
= lxc_attach_terminal(conf
, &terminal
);
1099 ERROR("Failed to setup new terminal");
1101 lxc_proc_put_context_info(init_ctx
);
1105 terminal
.log_fd
= options
->log_fd
;
1107 lxc_terminal_init(&terminal
);
1110 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1111 * to make sure we don't irritate other threads that want to fork+exec
1114 * IMPORTANT: if the initial process is multithreaded and another call
1115 * just fork()s away without exec'ing directly after, the socket fd will
1116 * exist in the forked process from the other thread and any close() in
1117 * our own child process will not really cause the socket to close
1118 * properly, potentially causing the parent to hang.
1120 * For this reason, while IPC is still active, we have to use shutdown()
1121 * if the child exits prematurely in order to signal that the socket is
1122 * closed and cannot assume that the child exiting will automatically do
1125 * IPC mechanism: (X is receiver)
1126 * initial process intermediate attached
1127 * X <--- send pid of
1130 * send 0 ------------------------------------> X
1131 * [do initialization]
1132 * X <------------------------------------ send 1
1133 * [add to cgroup, ...]
1134 * send 2 ------------------------------------> X
1135 * [set LXC_ATTACH_NO_NEW_PRIVS]
1136 * X <------------------------------------ send 3
1137 * [open LSM label fd]
1138 * send 4 ------------------------------------> X
1140 * close socket close socket
1143 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
1145 SYSERROR("Could not set up required IPC mechanism for attaching");
1147 lxc_proc_put_context_info(init_ctx
);
1151 /* Create intermediate subprocess, two reasons:
1152 * 1. We can't setns() in the child itself, since we want to make
1153 * sure we are properly attached to the pidns.
1154 * 2. Also, the initial thread has to put the attached process
1155 * into the cgroup, which we can only do if we didn't already
1156 * setns() (otherwise, user namespaces will hate us).
1160 SYSERROR("Failed to create first subprocess");
1162 lxc_proc_put_context_info(init_ctx
);
1167 int ret_parent
= -1;
1168 pid_t to_cleanup_pid
= pid
;
1169 struct lxc_epoll_descr descr
= {0};
1171 /* close unneeded file descriptors */
1172 close(ipc_sockets
[1]);
1174 lxc_proc_close_ns_fd(init_ctx
);
1175 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1176 lxc_attach_terminal_close_pts(&terminal
);
1178 /* Attach to cgroup, if requested. */
1179 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1181 * If this is the unified hierarchy cgroup_attach() is
1184 ret
= cgroup_attach(conf
, name
, lxcpath
, pid
);
1186 call_cleaner(cgroup_exit
) struct cgroup_ops
*cgroup_ops
= NULL
;
1188 cgroup_ops
= cgroup_init(conf
);
1192 if (!cgroup_ops
->attach(cgroup_ops
, conf
, name
, lxcpath
, pid
))
1195 TRACE("Moved intermediate process %d into container's cgroups", pid
);
1198 /* Setup /proc limits */
1199 if (!lxc_list_empty(&conf
->procs
)) {
1200 ret
= setup_proc_filesystem(&conf
->procs
, pid
);
1205 /* Setup resource limits */
1206 if (!lxc_list_empty(&conf
->limits
)) {
1207 ret
= setup_resource_limits(&conf
->limits
, pid
);
1212 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1213 ret
= lxc_attach_terminal_mainloop_init(&terminal
, &descr
);
1217 TRACE("Initialized terminal mainloop");
1220 /* Let the child process know to go ahead. */
1222 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1223 if (ret
!= sizeof(status
))
1224 goto close_mainloop
;
1226 TRACE("Told intermediate process to start initializing");
1228 /* Get pid of attached process from intermediate process. */
1229 ret
= lxc_read_nointr(ipc_sockets
[0], &attached_pid
, sizeof(attached_pid
));
1230 if (ret
!= sizeof(attached_pid
))
1231 goto close_mainloop
;
1233 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid
);
1235 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1236 if (options
->stdin_fd
== 0) {
1237 signal(SIGINT
, SIG_IGN
);
1238 signal(SIGQUIT
, SIG_IGN
);
1241 /* Reap intermediate process. */
1242 ret
= wait_for_pid(pid
);
1244 goto close_mainloop
;
1246 TRACE("Intermediate process %d exited", pid
);
1248 /* We will always have to reap the attached process now. */
1249 to_cleanup_pid
= attached_pid
;
1251 /* Open LSM fd and send it to child. */
1252 if ((options
->namespaces
& CLONE_NEWNS
) &&
1253 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1254 init_ctx
->lsm_label
) {
1259 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? true : false;
1260 labelfd
= lsm_process_label_fd_get(attached_pid
, on_exec
);
1262 goto close_mainloop
;
1264 TRACE("Opened LSM label file descriptor %d", labelfd
);
1266 /* Send child fd of the LSM security module to write to. */
1267 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1270 SYSERROR("Failed to send lsm label fd");
1273 goto close_mainloop
;
1277 TRACE("Sent LSM label file descriptor %d to child", labelfd
);
1280 if (conf
->seccomp
.seccomp
) {
1281 ret
= lxc_seccomp_recv_notifier_fd(&conf
->seccomp
, ipc_sockets
[0]);
1283 goto close_mainloop
;
1285 ret
= lxc_seccomp_add_notifier(name
, lxcpath
, &conf
->seccomp
);
1287 goto close_mainloop
;
1290 /* We're done, the child process should now execute whatever it
1291 * is that the user requested. The parent can now track it with
1292 * waitpid() or similar.
1295 *attached_process
= attached_pid
;
1297 /* Now shut down communication with child, we're done. */
1298 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1299 close(ipc_sockets
[0]);
1300 ipc_sockets
[0] = -1;
1303 to_cleanup_pid
= -1;
1305 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1306 ret
= lxc_mainloop(&descr
, -1);
1309 to_cleanup_pid
= attached_pid
;
1314 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1315 lxc_mainloop_close(&descr
);
1318 if (ipc_sockets
[0] >= 0) {
1319 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1320 close(ipc_sockets
[0]);
1323 if (to_cleanup_pid
> 0)
1324 (void)wait_for_pid(to_cleanup_pid
);
1326 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1327 lxc_terminal_delete(&terminal
);
1328 lxc_terminal_conf_free(&terminal
);
1331 lxc_proc_put_context_info(init_ctx
);
1335 /* close unneeded file descriptors */
1336 close_prot_errno_disarm(ipc_sockets
[0]);
1338 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1339 lxc_attach_terminal_close_ptmx(&terminal
);
1340 lxc_attach_terminal_close_peer(&terminal
);
1341 lxc_attach_terminal_close_log(&terminal
);
1344 /* Wait for the parent to have setup cgroups. */
1345 ret
= lxc_read_nointr(ipc_sockets
[1], &status
, sizeof(status
));
1346 if (ret
!= sizeof(status
)) {
1347 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1348 lxc_proc_put_context_info(init_ctx
);
1349 _exit(EXIT_FAILURE
);
1352 TRACE("Intermediate process starting to initialize");
1354 /* Attach now, create another subprocess later, since pid namespaces
1355 * only really affect the children of the current process.
1357 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1359 ERROR("Failed to enter namespaces");
1360 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1361 lxc_proc_put_context_info(init_ctx
);
1362 _exit(EXIT_FAILURE
);
1365 /* close namespace file descriptors */
1366 lxc_proc_close_ns_fd(init_ctx
);
1368 /* Attach succeeded, try to cwd. */
1369 if (options
->initial_cwd
)
1370 new_cwd
= options
->initial_cwd
;
1374 ret
= chdir(new_cwd
);
1376 WARN("Could not change directory to \"%s\"", new_cwd
);
1380 /* Create attached process. */
1381 payload
.ipc_socket
= ipc_sockets
[1];
1382 payload
.options
= options
;
1383 payload
.init_ctx
= init_ctx
;
1384 payload
.terminal_pts_fd
= terminal
.pts
;
1385 payload
.exec_function
= exec_function
;
1386 payload
.exec_payload
= exec_payload
;
1388 pid
= lxc_raw_clone(CLONE_PARENT
, NULL
);
1390 SYSERROR("Failed to clone attached process");
1391 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1392 lxc_proc_put_context_info(init_ctx
);
1393 _exit(EXIT_FAILURE
);
1397 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
) {
1398 ret
= pthread_sigmask(SIG_SETMASK
,
1399 &terminal
.tty_state
->oldmask
, NULL
);
1401 SYSERROR("Failed to reset signal mask");
1402 _exit(EXIT_FAILURE
);
1406 ret
= attach_child_main(&payload
);
1408 ERROR("Failed to exec");
1410 _exit(EXIT_FAILURE
);
1413 if (options
->attach_flags
& LXC_ATTACH_TERMINAL
)
1414 lxc_attach_terminal_close_pts(&terminal
);
1416 /* Tell grandparent the pid of the pid of the newly created child. */
1417 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1418 if (ret
!= sizeof(pid
)) {
1419 /* If this really happens here, this is very unfortunate, since
1420 * the parent will not know the pid of the attached process and
1421 * will not be able to wait for it (and we won't either due to
1422 * CLONE_PARENT) so the parent won't be able to reap it and the
1423 * attached process will remain a zombie.
1425 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1426 lxc_proc_put_context_info(init_ctx
);
1427 _exit(EXIT_FAILURE
);
1430 TRACE("Sending pid %d of attached process", pid
);
1432 /* The rest is in the hands of the initial and the attached process. */
1433 lxc_proc_put_context_info(init_ctx
);
1434 _exit(EXIT_SUCCESS
);
1437 int lxc_attach_run_command(void *payload
)
1440 lxc_attach_command_t
*cmd
= payload
;
1442 ret
= execvp(cmd
->program
, cmd
->argv
);
1454 return log_error_errno(ret
, errno
, "Failed to exec \"%s\"", cmd
->program
);
1457 int lxc_attach_run_shell(void* payload
)
1459 __do_free
char *buf
= NULL
;
1461 struct passwd pwent
;
1462 struct passwd
*pwentp
= NULL
;
1467 /* Ignore payload parameter. */
1472 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1476 buf
= malloc(bufsize
);
1478 ret
= getpwuid_r(uid
, &pwent
, buf
, bufsize
, &pwentp
);
1481 WARN("Could not find matched password record");
1483 WARN("Failed to get password record - %u", uid
);
1487 /* This probably happens because of incompatible nss implementations in
1488 * host and container (remember, this code is still using the host's
1489 * glibc but our mount namespace is in the container) we may try to get
1490 * the information by spawning a [getent passwd uid] process and parsing
1494 user_shell
= lxc_attach_getpwshell(uid
);
1496 user_shell
= pwent
.pw_shell
;
1499 execlp(user_shell
, user_shell
, (char *)NULL
);
1501 /* Executed if either no passwd entry or execvp fails, we will fall back
1502 * on /bin/sh as a default shell.
1504 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1506 SYSERROR("Failed to execute shell");