2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <linux/unistd.h>
35 #include <sys/mount.h>
36 #include <sys/param.h>
37 #include <sys/prctl.h>
38 #include <sys/socket.h>
39 #include <sys/syscall.h>
42 #include <lxc/lxccontainer.h>
44 #ifndef HAVE_DECL_PR_CAPBSET_DROP
45 #define PR_CAPBSET_DROP 24
48 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
49 #define PR_SET_NO_NEW_PRIVS 38
52 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
53 #define PR_GET_NO_NEW_PRIVS 39
67 #include "lxcseccomp.h"
68 #include "namespace.h"
71 #if HAVE_SYS_PERSONALITY_H
72 #include <sys/personality.h>
76 #define SOCK_CLOEXEC 02000000
84 #define MS_SLAVE (1 << 19)
87 lxc_log_define(lxc_attach
, lxc
);
89 /* /proc/pid-to-str/current\0 = (5 + 21 + 7 + 1) */
90 #define __LSMATTRLEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
91 static int lsm_openat(int procfd
, pid_t pid
, int on_exec
)
96 char path
[__LSMATTRLEN
];
100 if (strcmp(name
, "nop") == 0)
103 if (strcmp(name
, "none") == 0)
106 /* We don't support on-exec with AppArmor */
107 if (strcmp(name
, "AppArmor") == 0)
111 ret
= snprintf(path
, __LSMATTRLEN
, "%d/attr/exec", pid
);
113 ret
= snprintf(path
, __LSMATTRLEN
, "%d/attr/current", pid
);
114 if (ret
< 0 || ret
>= __LSMATTRLEN
)
117 labelfd
= openat(procfd
, path
, O_RDWR
);
119 SYSERROR("Unable to open file descriptor to set LSM label.");
126 static int lsm_set_label_at(int lsm_labelfd
, int on_exec
, char *lsm_label
)
130 char *command
= NULL
;
134 if (strcmp(name
, "nop") == 0)
137 if (strcmp(name
, "none") == 0)
140 /* We don't support on-exec with AppArmor */
141 if (strcmp(name
, "AppArmor") == 0)
144 if (strcmp(name
, "AppArmor") == 0) {
148 malloc(strlen(lsm_label
) + strlen("changeprofile ") + 1);
150 SYSERROR("Failed to write apparmor profile.");
154 size
= sprintf(command
, "changeprofile %s", lsm_label
);
156 SYSERROR("Failed to write apparmor profile.");
160 if (write(lsm_labelfd
, command
, size
+ 1) < 0) {
161 SYSERROR("Unable to set LSM label: %s.", command
);
164 INFO("Set LSM label to: %s.", command
);
165 } else if (strcmp(name
, "SELinux") == 0) {
166 if (write(lsm_labelfd
, lsm_label
, strlen(lsm_label
) + 1) < 0) {
167 SYSERROR("Unable to set LSM label: %s.", lsm_label
);
170 INFO("Set LSM label to: %s.", lsm_label
);
172 ERROR("Unable to restore label for unknown LSM: %s.", name
);
180 if (lsm_labelfd
!= -1)
186 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
187 #define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
188 static struct lxc_proc_context_info
*lxc_proc_get_context_info(pid_t pid
)
193 char proc_fn
[__PROC_STATUS_LEN
];
194 size_t line_bufsz
= 0;
196 struct lxc_proc_context_info
*info
= NULL
;
198 /* Read capabilities. */
199 ret
= snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
200 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
203 proc_file
= fopen(proc_fn
, "r");
205 SYSERROR("Could not open %s.", proc_fn
);
209 info
= calloc(1, sizeof(*info
));
211 SYSERROR("Could not allocate memory.");
217 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
218 ret
= sscanf(line
, "CapBnd: %llx", &info
->capability_mask
);
219 if (ret
!= EOF
&& ret
== 1) {
229 SYSERROR("Could not read capability bounding set from %s.",
235 info
->lsm_label
= lsm_process_label_get(pid
);
236 info
->ns_inherited
= 0;
237 memset(info
->ns_fd
, -1, sizeof(int) * LXC_NS_MAX
);
246 static inline void lxc_proc_close_ns_fd(struct lxc_proc_context_info
*ctx
)
250 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
251 if (ctx
->ns_fd
[i
] < 0)
253 close(ctx
->ns_fd
[i
]);
254 ctx
->ns_fd
[i
] = -EBADF
;
258 static void lxc_proc_put_context_info(struct lxc_proc_context_info
*ctx
)
260 free(ctx
->lsm_label
);
262 lxc_container_put(ctx
->container
);
263 lxc_proc_close_ns_fd(ctx
);
268 * in_same_namespace - Check whether two processes are in the same namespace.
269 * @pid1 - PID of the first process.
270 * @pid2 - PID of the second process.
271 * @ns - Name of the namespace to check. Must correspond to one of the names
272 * for the namespaces as shown in /proc/<pid/ns/
274 * If the two processes are not in the same namespace returns an fd to the
275 * namespace of the second process identified by @pid2. If the two processes are
276 * in the same namespace returns -EINVAL, -1 if an error occurred.
278 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
280 int ns_fd1
= -1, ns_fd2
= -1, ret
= -1;
281 struct stat ns_st1
, ns_st2
;
283 ns_fd1
= lxc_preserve_ns(pid1
, ns
);
285 /* The kernel does not support this namespace. This is not an
294 ns_fd2
= lxc_preserve_ns(pid2
, ns
);
298 ret
= fstat(ns_fd1
, &ns_st1
);
302 ret
= fstat(ns_fd2
, &ns_st2
);
306 /* processes are in the same namespace */
308 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
311 /* processes are in different namespaces */
325 static int lxc_attach_to_ns(pid_t pid
, struct lxc_proc_context_info
*ctx
)
329 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
330 if (ctx
->ns_fd
[i
] < 0)
333 ret
= setns(ctx
->ns_fd
[i
], ns_info
[i
].clone_flag
);
335 SYSERROR("Failed to attach to %s namespace of %d",
336 ns_info
[i
].proc_name
, pid
);
340 DEBUG("Attached to %s namespace of %d", ns_info
[i
].proc_name
, pid
);
346 static int lxc_attach_remount_sys_proc(void)
350 ret
= unshare(CLONE_NEWNS
);
352 SYSERROR("Failed to unshare mount namespace.");
356 if (detect_shared_rootfs()) {
357 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
)) {
358 SYSERROR("Failed to make / rslave.");
359 ERROR("Continuing...");
363 /* Assume /proc is always mounted, so remount it. */
364 ret
= umount2("/proc", MNT_DETACH
);
366 SYSERROR("Failed to unmount /proc.");
370 ret
= mount("none", "/proc", "proc", 0, NULL
);
372 SYSERROR("Failed to remount /proc.");
376 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
377 * we ignore it because it may not have been mounted in the first place.
379 ret
= umount2("/sys", MNT_DETACH
);
380 if (ret
< 0 && errno
!= EINVAL
) {
381 SYSERROR("Failed to unmount /sys.");
383 } else if (ret
== 0) {
385 ret
= mount("none", "/sys", "sysfs", 0, NULL
);
387 SYSERROR("Failed to remount /sys.");
395 static int lxc_attach_drop_privs(struct lxc_proc_context_info
*ctx
)
399 last_cap
= lxc_caps_last_cap();
400 for (cap
= 0; cap
<= last_cap
; cap
++) {
401 if (ctx
->capability_mask
& (1LL << cap
))
404 if (prctl(PR_CAPBSET_DROP
, cap
, 0, 0, 0)) {
405 SYSERROR("Failed to remove capability id %d.", cap
);
413 static int lxc_attach_set_environment(enum lxc_attach_env_policy_t policy
,
414 char **extra_env
, char **extra_keep
)
416 if (policy
== LXC_ATTACH_CLEAR_ENV
) {
418 char **extra_keep_store
= NULL
;
423 for (count
= 0; extra_keep
[count
]; count
++);
425 extra_keep_store
= calloc(count
, sizeof(char *));
426 if (!extra_keep_store
) {
427 SYSERROR("Failed to allocate memory for storing current "
428 "environment variable values that will be kept.");
431 for (i
= 0; i
< count
; i
++) {
432 char *v
= getenv(extra_keep
[i
]);
434 extra_keep_store
[i
] = strdup(v
);
435 if (!extra_keep_store
[i
]) {
436 SYSERROR("Failed to allocate memory for storing current "
437 "environment variable values that will be kept.");
439 free(extra_keep_store
[--i
]);
440 free(extra_keep_store
);
443 if (strcmp(extra_keep
[i
], "PATH") == 0)
446 /* Calloc sets entire array to zero, so we don't
455 SYSERROR("Failed to clear environment.");
456 if (extra_keep_store
) {
457 for (p
= extra_keep_store
; *p
; p
++)
459 free(extra_keep_store
);
464 if (extra_keep_store
) {
467 for (i
= 0; extra_keep
[i
]; i
++) {
468 if (extra_keep_store
[i
]) {
469 if (setenv(extra_keep
[i
], extra_keep_store
[i
], 1) < 0)
470 SYSERROR("Unable to set environment variable.");
472 free(extra_keep_store
[i
]);
474 free(extra_keep_store
);
477 /* Always set a default path; shells and execlp tend to be fine
478 * without it, but there is a disturbing number of C programs
479 * out there that just assume that getenv("PATH") is never NULL
480 * and then die a painful segfault death.
483 setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
486 if (putenv("container=lxc")) {
487 SYSERROR("Failed to set environment variable.");
491 /* Set extra environment variables. */
493 for (; *extra_env
; extra_env
++) {
494 /* Duplicate the string, just to be on the safe side,
495 * because putenv does not do it for us.
497 char *p
= strdup(*extra_env
);
498 /* We just assume the user knows what they are doing, so
499 * we don't do any checks.
502 SYSERROR("Failed to allocate memory for additional environment "
513 static char *lxc_attach_getpwshell(uid_t uid
)
520 /* We need to fork off a process that runs the getent program, and we
521 * need to capture its output, so we use a pipe for that purpose.
538 size_t line_bufsz
= 0;
543 pipe_f
= fdopen(pipes
[0], "r");
544 while (getline(&line
, &line_bufsz
, pipe_f
) != -1) {
548 char *endptr
= NULL
, *saveptr
= NULL
;
550 /* If we already found something, just continue to read
551 * until the pipe doesn't deliver any more data, but
552 * don't modify the existing data structure.
557 /* Trim line on the right hand side. */
558 for (i
= strlen(line
); i
> 0 && (line
[i
- 1] == '\n' || line
[i
- 1] == '\r'); --i
)
561 /* Split into tokens: first: user name. */
562 token
= strtok_r(line
, ":", &saveptr
);
565 /* next: dummy password field */
566 token
= strtok_r(NULL
, ":", &saveptr
);
570 token
= strtok_r(NULL
, ":", &saveptr
);
571 value
= token
? strtol(token
, &endptr
, 10) : 0;
572 if (!token
|| !endptr
|| *endptr
|| value
== LONG_MIN
|| value
== LONG_MAX
)
574 /* dummy sanity check: user id matches */
575 if ((uid_t
) value
!= uid
)
577 /* skip fields: gid, gecos, dir, go to next field 'shell' */
578 for (i
= 0; i
< 4; i
++) {
579 token
= strtok_r(NULL
, ":", &saveptr
);
586 result
= strdup(token
);
588 /* Sanity check that there are no fields after that. */
589 token
= strtok_r(NULL
, ":", &saveptr
);
599 if (waitpid(pid
, &status
, 0) < 0) {
606 /* Some sanity checks. If anything even hinted at going wrong,
607 * we can't be sure we have a valid result, so we assume we
611 if (!WIFEXITED(status
)) {
616 if (WEXITSTATUS(status
) != 0) {
629 char *arguments
[] = {
638 /* We want to capture stdout. */
642 /* Get rid of stdin/stderr, so we try to associate it with
645 fd
= open("/dev/null", O_RDWR
);
655 /* Finish argument list. */
656 ret
= snprintf(uid_buf
, sizeof(uid_buf
), "%ld", (long) uid
);
660 /* Try to run getent program. */
661 (void) execvp("getent", arguments
);
666 static void lxc_attach_get_init_uidgid(uid_t
*init_uid
, gid_t
*init_gid
)
669 char proc_fn
[__PROC_STATUS_LEN
];
672 size_t line_bufsz
= 0;
674 uid_t uid
= (uid_t
)-1;
675 gid_t gid
= (gid_t
)-1;
677 /* Read capabilities. */
678 snprintf(proc_fn
, __PROC_STATUS_LEN
, "/proc/%d/status", 1);
680 proc_file
= fopen(proc_fn
, "r");
684 while (getline(&line
, &line_bufsz
, proc_file
) != -1) {
685 /* Format is: real, effective, saved set user, fs we only care
688 ret
= sscanf(line
, "Uid: %ld", &value
);
689 if (ret
!= EOF
&& ret
== 1) {
692 ret
= sscanf(line
, "Gid: %ld", &value
);
693 if (ret
!= EOF
&& ret
== 1)
696 if (uid
!= (uid_t
)-1 && gid
!= (gid_t
)-1)
703 /* Only override arguments if we found something. */
704 if (uid
!= (uid_t
)-1)
706 if (gid
!= (gid_t
)-1)
709 /* TODO: we should also parse supplementary groups and use
710 * setgroups() to set them.
714 struct attach_clone_payload
{
716 lxc_attach_options_t
*options
;
717 struct lxc_proc_context_info
*init_ctx
;
718 lxc_attach_exec_t exec_function
;
722 static int attach_child_main(void* data
);
724 /* Help the optimizer along if it doesn't know that exit always exits. */
732 /* Define default options if no options are supplied by the user. */
733 static lxc_attach_options_t attach_static_default_options
= LXC_ATTACH_OPTIONS_DEFAULT
;
735 static bool fetch_seccomp(struct lxc_container
*c
,
736 lxc_attach_options_t
*options
)
740 if (!(options
->namespaces
& CLONE_NEWNS
) ||
741 !(options
->attach_flags
& LXC_ATTACH_LSM
)) {
742 free(c
->lxc_conf
->seccomp
);
743 c
->lxc_conf
->seccomp
= NULL
;
747 /* Remove current setting. */
748 if (!c
->set_config_item(c
, "lxc.seccomp", "") &&
749 !c
->set_config_item(c
, "lxc.seccomp.profile", "")) {
753 /* Fetch the current profile path over the cmd interface. */
754 path
= c
->get_running_config_item(c
, "lxc.seccomp.profile");
756 INFO("Failed to get running config item for lxc.seccomp.profile");
757 path
= c
->get_running_config_item(c
, "lxc.seccomp");
760 INFO("Failed to get running config item for lxc.seccomp");
764 /* Copy the value into the new lxc_conf. */
765 if (!c
->set_config_item(c
, "lxc.seccomp.profile", path
)) {
771 /* Attempt to parse the resulting config. */
772 if (lxc_read_seccomp_config(c
->lxc_conf
) < 0) {
773 ERROR("Error reading seccomp policy.");
777 INFO("Retrieved seccomp policy.");
781 static bool no_new_privs(struct lxc_container
*c
, lxc_attach_options_t
*options
)
785 /* Remove current setting. */
786 if (!c
->set_config_item(c
, "lxc.no_new_privs", ""))
789 /* Retrieve currently active setting. */
790 val
= c
->get_running_config_item(c
, "lxc.no_new_privs");
792 INFO("Failed to get running config item for lxc.no_new_privs.");
796 /* Set currently active setting. */
797 if (!c
->set_config_item(c
, "lxc.no_new_privs", val
)) {
806 static signed long get_personality(const char *name
, const char *lxcpath
)
811 p
= lxc_cmd_get_config_item(name
, "lxc.arch", lxcpath
);
815 ret
= lxc_config_parse_arch(p
);
821 int lxc_attach(const char *name
, const char *lxcpath
,
822 lxc_attach_exec_t exec_function
, void *exec_payload
,
823 lxc_attach_options_t
*options
, pid_t
*attached_process
)
828 signed long personality
;
829 pid_t attached_pid
, expected
, init_pid
, pid
;
830 struct lxc_proc_context_info
*init_ctx
;
832 ret
= access("/proc/self/ns", X_OK
);
834 ERROR("Does this kernel version support namespaces?");
839 options
= &attach_static_default_options
;
841 init_pid
= lxc_cmd_get_init_pid(name
, lxcpath
);
843 ERROR("Failed to get init pid.");
847 init_ctx
= lxc_proc_get_context_info(init_pid
);
849 ERROR("Failed to get context of init process: %ld", (long)init_pid
);
853 personality
= get_personality(name
, lxcpath
);
854 if (init_ctx
->personality
< 0) {
855 ERROR("Failed to get personality of the container");
856 lxc_proc_put_context_info(init_ctx
);
859 init_ctx
->personality
= personality
;
861 init_ctx
->container
= lxc_container_new(name
, lxcpath
);
862 if (!init_ctx
->container
)
865 if (!init_ctx
->container
->lxc_conf
) {
866 init_ctx
->container
->lxc_conf
= lxc_conf_init();
867 if (!init_ctx
->container
->lxc_conf
)
871 if (!fetch_seccomp(init_ctx
->container
, options
))
872 WARN("Failed to get seccomp policy.");
874 if (!no_new_privs(init_ctx
->container
, options
))
875 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set.");
877 cwd
= getcwd(NULL
, 0);
879 /* Determine which namespaces the container was created with
880 * by asking lxc-start, if necessary.
882 if (options
->namespaces
== -1) {
883 options
->namespaces
= lxc_cmd_get_clone_flags(name
, lxcpath
);
885 if (options
->namespaces
== -1) {
886 ERROR("Failed to automatically determine the "
887 "namespaces which the container uses");
889 lxc_proc_put_context_info(init_ctx
);
893 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
894 if (ns_info
[i
].clone_flag
& CLONE_NEWCGROUP
)
895 if (!(options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) ||
899 if (ns_info
[i
].clone_flag
& options
->namespaces
)
902 init_ctx
->ns_inherited
|= ns_info
[i
].clone_flag
;
907 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
910 if (options
->namespaces
& ns_info
[i
].clone_flag
)
911 init_ctx
->ns_fd
[i
] = lxc_preserve_ns(init_pid
, ns_info
[i
].proc_name
);
912 else if (init_ctx
->ns_inherited
& ns_info
[i
].clone_flag
)
913 init_ctx
->ns_fd
[i
] = in_same_namespace(pid
, init_pid
, ns_info
[i
].proc_name
);
916 if (init_ctx
->ns_fd
[i
] >= 0)
919 if (init_ctx
->ns_fd
[i
] == -EINVAL
) {
920 DEBUG("Inheriting %s namespace from %d",
921 ns_info
[i
].proc_name
, pid
);
922 init_ctx
->ns_inherited
&= ~ns_info
[i
].clone_flag
;
926 /* We failed to preserve the namespace. */
928 /* Close all already opened file descriptors before we return an
929 * error, so we don't leak them.
931 for (j
= 0; j
< i
; j
++)
932 close(init_ctx
->ns_fd
[j
]);
935 SYSERROR("Failed to attach to %s namespace of %d",
936 ns_info
[i
].proc_name
, pid
);
938 lxc_proc_put_context_info(init_ctx
);
942 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
943 * to make sure we don't irritate other threads that want to fork+exec
946 * IMPORTANT: if the initial process is multithreaded and another call
947 * just fork()s away without exec'ing directly after, the socket fd will
948 * exist in the forked process from the other thread and any close() in
949 * our own child process will not really cause the socket to close
950 * properly, potentiall causing the parent to hang.
952 * For this reason, while IPC is still active, we have to use shutdown()
953 * if the child exits prematurely in order to signal that the socket is
954 * closed and cannot assume that the child exiting will automatically do
957 * IPC mechanism: (X is receiver)
958 * initial process intermediate attached
962 * send 0 ------------------------------------> X
963 * [do initialization]
964 * X <------------------------------------ send 1
965 * [add to cgroup, ...]
966 * send 2 ------------------------------------> X
967 * [set LXC_ATTACH_NO_NEW_PRIVS]
968 * X <------------------------------------ send 3
969 * [open LSM label fd]
970 * send 4 ------------------------------------> X
972 * close socket close socket
975 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, ipc_sockets
);
977 SYSERROR("Could not set up required IPC mechanism for attaching.");
979 lxc_proc_put_context_info(init_ctx
);
983 /* Create intermediate subprocess, three reasons:
984 * 1. Runs all pthread_atfork handlers and the child will no
985 * longer be threaded (we can't properly setns() in a threaded
987 * 2. We can't setns() in the child itself, since we want to make
988 * sure we are properly attached to the pidns.
989 * 3. Also, the initial thread has to put the attached process
990 * into the cgroup, which we can only do if we didn't already
991 * setns() (otherwise, user namespaces will hate us).
995 SYSERROR("Failed to create first subprocess.");
997 lxc_proc_put_context_info(init_ctx
);
1003 pid_t to_cleanup_pid
= pid
;
1005 /* close file namespace descriptors */
1006 lxc_proc_close_ns_fd(init_ctx
);
1008 /* Initial thread, we close the socket that is for the
1011 close(ipc_sockets
[1]);
1014 /* Attach to cgroup, if requested. */
1015 if (options
->attach_flags
& LXC_ATTACH_MOVE_TO_CGROUP
) {
1016 if (!cgroup_attach(name
, lxcpath
, pid
))
1020 /* Setup resource limits */
1021 if (!lxc_list_empty(&init_ctx
->container
->lxc_conf
->limits
))
1022 if (setup_resource_limits(&init_ctx
->container
->lxc_conf
->limits
, pid
) < 0)
1025 /* Open /proc before setns() to the containers namespace so we
1026 * don't rely on any information from inside the container.
1028 procfd
= open("/proc", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1030 SYSERROR("Unable to open /proc.");
1034 /* Let the child process know to go ahead. */
1036 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1038 ERROR("Intended to send sequence number 0: %s.",
1043 /* Get pid of attached process from intermediate process. */
1044 ret
= lxc_read_nointr_expect(ipc_sockets
[0], &attached_pid
,
1045 sizeof(attached_pid
), NULL
);
1048 ERROR("Expected to receive pid: %s.", strerror(errno
));
1052 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1053 if (options
->stdin_fd
== 0) {
1054 signal(SIGINT
, SIG_IGN
);
1055 signal(SIGQUIT
, SIG_IGN
);
1058 /* Reap intermediate process. */
1059 ret
= wait_for_pid(pid
);
1063 /* We will always have to reap the attached process now. */
1064 to_cleanup_pid
= attached_pid
;
1066 /* Tell attached process it may start initializing. */
1068 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1070 ERROR("Intended to send sequence number 0: %s.", strerror(errno
));
1074 /* Wait for the attached process to finish initializing. */
1076 ret
= lxc_read_nointr_expect(ipc_sockets
[0], &status
,
1077 sizeof(status
), &expected
);
1080 ERROR("Expected to receive sequence number 1: %s.", strerror(errno
));
1084 /* Tell attached process we're done. */
1086 ret
= lxc_write_nointr(ipc_sockets
[0], &status
, sizeof(status
));
1088 ERROR("Intended to send sequence number 2: %s.", strerror(errno
));
1092 /* Wait for the (grand)child to tell us that it's ready to set
1093 * up its LSM labels.
1096 ret
= lxc_read_nointr_expect(ipc_sockets
[0], &status
,
1097 sizeof(status
), &expected
);
1099 ERROR("Expected to receive sequence number 3: %s.",
1104 /* Open LSM fd and send it to child. */
1105 if ((options
->namespaces
& CLONE_NEWNS
) &&
1106 (options
->attach_flags
& LXC_ATTACH_LSM
) &&
1107 init_ctx
->lsm_label
) {
1108 int on_exec
, saved_errno
;
1111 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? 1 : 0;
1112 /* Open fd for the LSM security module. */
1113 labelfd
= lsm_openat(procfd
, attached_pid
, on_exec
);
1117 /* Send child fd of the LSM security module to write to. */
1118 ret
= lxc_abstract_unix_send_fds(ipc_sockets
[0], &labelfd
, 1, NULL
, 0);
1119 saved_errno
= errno
;
1122 ERROR("Intended to send file descriptor %d: %s.", labelfd
, strerror(saved_errno
));
1129 /* Now shut down communication with child, we're done. */
1130 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1131 close(ipc_sockets
[0]);
1132 lxc_proc_put_context_info(init_ctx
);
1134 /* We're done, the child process should now execute whatever it
1135 * is that the user requested. The parent can now track it with
1136 * waitpid() or similar.
1139 *attached_process
= attached_pid
;
1143 /* First shut down the socket, then wait for the pid, otherwise
1144 * the pid we're waiting for may never exit.
1148 shutdown(ipc_sockets
[0], SHUT_RDWR
);
1149 close(ipc_sockets
[0]);
1151 (void)wait_for_pid(to_cleanup_pid
);
1152 lxc_proc_put_context_info(init_ctx
);
1156 /* First subprocess begins here, we close the socket that is for the
1159 close(ipc_sockets
[0]);
1161 /* Wait for the parent to have setup cgroups. */
1164 ret
= lxc_read_nointr_expect(ipc_sockets
[1], &status
, sizeof(status
),
1167 ERROR("Expected to receive sequence number 0: %s.", strerror(errno
));
1168 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1172 /* Attach now, create another subprocess later, since pid namespaces
1173 * only really affect the children of the current process.
1175 ret
= lxc_attach_to_ns(init_pid
, init_ctx
);
1177 ERROR("Failed to enter namespaces.");
1178 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1181 /* close namespace file descriptors */
1182 lxc_proc_close_ns_fd(init_ctx
);
1184 /* Attach succeeded, try to cwd. */
1185 if (options
->initial_cwd
)
1186 new_cwd
= options
->initial_cwd
;
1189 ret
= chdir(new_cwd
);
1191 WARN("Could not change directory to \"%s\".", new_cwd
);
1194 /* Now create the real child process. */
1196 struct attach_clone_payload payload
= {
1197 .ipc_socket
= ipc_sockets
[1],
1199 .init_ctx
= init_ctx
,
1200 .exec_function
= exec_function
,
1201 .exec_payload
= exec_payload
,
1203 /* We use clone_parent here to make this subprocess a direct
1204 * child of the initial process. Then this intermediate process
1205 * can exit and the parent can directly track the attached
1208 pid
= lxc_clone(attach_child_main
, &payload
, CLONE_PARENT
);
1211 /* Shouldn't happen, clone() should always return positive pid. */
1213 SYSERROR("Failed to create subprocess.");
1214 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1218 /* Tell grandparent the pid of the pid of the newly created child. */
1219 ret
= lxc_write_nointr(ipc_sockets
[1], &pid
, sizeof(pid
));
1220 if (ret
!= sizeof(pid
)) {
1221 /* If this really happens here, this is very unfortunate, since
1222 * the parent will not know the pid of the attached process and
1223 * will not be able to wait for it (and we won't either due to
1224 * CLONE_PARENT) so the parent won't be able to reap it and the
1225 * attached process will remain a zombie.
1227 ERROR("Intended to send pid %d: %s.", pid
, strerror(errno
));
1228 shutdown(ipc_sockets
[1], SHUT_RDWR
);
1232 /* The rest is in the hands of the initial and the attached process. */
1236 static int attach_child_main(void* data
)
1238 int expected
, fd
, lsm_labelfd
, ret
, status
;
1240 #if HAVE_SYS_PERSONALITY_H
1241 long new_personality
;
1245 struct attach_clone_payload
* payload
= (struct attach_clone_payload
*)data
;
1246 int ipc_socket
= payload
->ipc_socket
;
1247 lxc_attach_options_t
* options
= payload
->options
;
1248 struct lxc_proc_context_info
* init_ctx
= payload
->init_ctx
;
1250 /* Wait for the initial thread to signal us that it's ready for us to
1251 * start initializing.
1255 ret
= lxc_read_nointr_expect(ipc_socket
, &status
, sizeof(status
), &expected
);
1257 ERROR("Expected to receive sequence number 0: %s.", strerror(errno
));
1258 shutdown(ipc_socket
, SHUT_RDWR
);
1262 /* A description of the purpose of this functionality is provided in the
1263 * lxc-attach(1) manual page. We have to remount here and not in the
1264 * parent process, otherwise /proc may not properly reflect the new pid
1267 if (!(options
->namespaces
& CLONE_NEWNS
) &&
1268 (options
->attach_flags
& LXC_ATTACH_REMOUNT_PROC_SYS
)) {
1269 ret
= lxc_attach_remount_sys_proc();
1271 shutdown(ipc_socket
, SHUT_RDWR
);
1276 /* Now perform additional attachments. */
1277 #if HAVE_SYS_PERSONALITY_H
1278 if (options
->personality
< 0)
1279 new_personality
= init_ctx
->personality
;
1281 new_personality
= options
->personality
;
1283 if (options
->attach_flags
& LXC_ATTACH_SET_PERSONALITY
) {
1284 ret
= personality(new_personality
);
1286 SYSERROR("Could not ensure correct architecture.");
1287 shutdown(ipc_socket
, SHUT_RDWR
);
1293 if (options
->attach_flags
& LXC_ATTACH_DROP_CAPABILITIES
) {
1294 ret
= lxc_attach_drop_privs(init_ctx
);
1296 ERROR("Could not drop privileges.");
1297 shutdown(ipc_socket
, SHUT_RDWR
);
1302 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
1303 * if you want this to be a no-op).
1305 ret
= lxc_attach_set_environment(options
->env_policy
,
1306 options
->extra_env_vars
,
1307 options
->extra_keep_env
);
1309 ERROR("Could not set initial environment for attached process.");
1310 shutdown(ipc_socket
, SHUT_RDWR
);
1317 /* Ignore errors, we will fall back to root in that case (/proc was not
1320 if (options
->namespaces
& CLONE_NEWUSER
)
1321 lxc_attach_get_init_uidgid(&new_uid
, &new_gid
);
1323 if (options
->uid
!= (uid_t
)-1)
1324 new_uid
= options
->uid
;
1325 if (options
->gid
!= (gid_t
)-1)
1326 new_gid
= options
->gid
;
1328 /* Setup the controlling tty. */
1329 if (options
->stdin_fd
&& isatty(options
->stdin_fd
)) {
1331 SYSERROR("Unable to setsid.");
1332 shutdown(ipc_socket
, SHUT_RDWR
);
1336 if (ioctl(options
->stdin_fd
, TIOCSCTTY
, (char *)NULL
) < 0) {
1337 SYSERROR("Unable to set TIOCSTTY.");
1338 shutdown(ipc_socket
, SHUT_RDWR
);
1343 /* Try to set the {u,g}id combination. */
1344 if ((new_gid
!= 0 || options
->namespaces
& CLONE_NEWUSER
)) {
1345 if (setgid(new_gid
) || setgroups(0, NULL
)) {
1346 SYSERROR("Switching to container gid.");
1347 shutdown(ipc_socket
, SHUT_RDWR
);
1351 if ((new_uid
!= 0 || options
->namespaces
& CLONE_NEWUSER
) &&
1353 SYSERROR("Switching to container uid.");
1354 shutdown(ipc_socket
, SHUT_RDWR
);
1358 /* Tell initial process it may now put us into cgroups. */
1360 ret
= lxc_write_nointr(ipc_socket
, &status
, sizeof(status
));
1361 if (ret
!= sizeof(status
)) {
1362 ERROR("Intended to send sequence number 1: %s.", strerror(errno
));
1363 shutdown(ipc_socket
, SHUT_RDWR
);
1367 /* Wait for the initial thread to signal us that it has done everything
1368 * for us when it comes to cgroups etc.
1372 ret
= lxc_read_nointr_expect(ipc_socket
, &status
, sizeof(status
), &expected
);
1374 ERROR("Expected to receive sequence number 2: %s", strerror(errno
));
1375 shutdown(ipc_socket
, SHUT_RDWR
);
1379 if ((init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
1380 init_ctx
->container
->lxc_conf
->no_new_privs
) ||
1381 (options
->attach_flags
& LXC_ATTACH_NO_NEW_PRIVS
)) {
1382 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
1383 SYSERROR("PR_SET_NO_NEW_PRIVS could not be set. "
1384 "Process can use execve() gainable "
1386 shutdown(ipc_socket
, SHUT_RDWR
);
1389 INFO("PR_SET_NO_NEW_PRIVS is set. Process cannot use execve() "
1390 "gainable privileges.");
1393 /* Tell the (grand)parent to send us LSM label fd. */
1395 ret
= lxc_write_nointr(ipc_socket
, &status
, sizeof(status
));
1397 ERROR("Intended to send sequence number 3: %s.", strerror(errno
));
1398 shutdown(ipc_socket
, SHUT_RDWR
);
1402 if ((options
->namespaces
& CLONE_NEWNS
) &&
1403 (options
->attach_flags
& LXC_ATTACH_LSM
) && init_ctx
->lsm_label
) {
1405 /* Receive fd for LSM security module. */
1406 ret
= lxc_abstract_unix_recv_fds(ipc_socket
, &lsm_labelfd
, 1, NULL
, 0);
1408 ERROR("Expected to receive file descriptor: %s.", strerror(errno
));
1409 shutdown(ipc_socket
, SHUT_RDWR
);
1413 /* Change into our new LSM profile. */
1414 on_exec
= options
->attach_flags
& LXC_ATTACH_LSM_EXEC
? 1 : 0;
1415 if (lsm_set_label_at(lsm_labelfd
, on_exec
, init_ctx
->lsm_label
) < 0) {
1416 SYSERROR("Failed to set LSM label.");
1417 shutdown(ipc_socket
, SHUT_RDWR
);
1424 if (init_ctx
->container
&& init_ctx
->container
->lxc_conf
&&
1425 init_ctx
->container
->lxc_conf
->seccomp
&&
1426 (lxc_seccomp_load(init_ctx
->container
->lxc_conf
) != 0)) {
1427 ERROR("Failed to load seccomp policy.");
1428 shutdown(ipc_socket
, SHUT_RDWR
);
1432 shutdown(ipc_socket
, SHUT_RDWR
);
1434 lxc_proc_put_context_info(init_ctx
);
1436 /* The following is done after the communication socket is shut down.
1437 * That way, all errors that might (though unlikely) occur up until this
1438 * point will have their messages printed to the original stderr (if
1439 * logging is so configured) and not the fd the user supplied, if any.
1442 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
1443 * may want to make sure the fds are closed, for example.
1445 if (options
->stdin_fd
>= 0 && options
->stdin_fd
!= 0)
1446 dup2(options
->stdin_fd
, 0);
1447 if (options
->stdout_fd
>= 0 && options
->stdout_fd
!= 1)
1448 dup2(options
->stdout_fd
, 1);
1449 if (options
->stderr_fd
>= 0 && options
->stderr_fd
!= 2)
1450 dup2(options
->stderr_fd
, 2);
1452 /* close the old fds */
1453 if (options
->stdin_fd
> 2)
1454 close(options
->stdin_fd
);
1455 if (options
->stdout_fd
> 2)
1456 close(options
->stdout_fd
);
1457 if (options
->stderr_fd
> 2)
1458 close(options
->stderr_fd
);
1460 /* Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
1461 * here, ignore errors.
1463 for (fd
= 0; fd
<= 2; fd
++) {
1464 flags
= fcntl(fd
, F_GETFL
);
1467 if (flags
& FD_CLOEXEC
)
1468 if (fcntl(fd
, F_SETFL
, flags
& ~FD_CLOEXEC
) < 0)
1469 SYSERROR("Unable to clear FD_CLOEXEC from file descriptor.");
1472 /* We're done, so we can now do whatever the user intended us to do. */
1473 rexit(payload
->exec_function(payload
->exec_payload
));
1476 int lxc_attach_run_command(void* payload
)
1478 lxc_attach_command_t
* cmd
= (lxc_attach_command_t
*)payload
;
1480 execvp(cmd
->program
, cmd
->argv
);
1481 SYSERROR("Failed to exec \"%s\".", cmd
->program
);
1485 int lxc_attach_run_shell(void* payload
)
1488 struct passwd
*passwd
;
1491 /* Ignore payload parameter. */
1495 passwd
= getpwuid(uid
);
1497 /* This probably happens because of incompatible nss implementations in
1498 * host and container (remember, this code is still using the host's
1499 * glibc but our mount namespace is in the container) we may try to get
1500 * the information by spawning a [getent passwd uid] process and parsing
1504 user_shell
= lxc_attach_getpwshell(uid
);
1506 user_shell
= passwd
->pw_shell
;
1509 execlp(user_shell
, user_shell
, (char *)NULL
);
1511 /* Executed if either no passwd entry or execvp fails, we will fall back
1512 * on /bin/sh as a default shell.
1514 execlp("/bin/sh", "/bin/sh", (char *)NULL
);
1515 SYSERROR("Failed to exec shell.");