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
39 #include <sys/mount.h>
40 #include <sys/param.h>
41 #include <sys/prctl.h>
42 #include <sys/socket.h>
44 #include <sys/syscall.h>
45 #include <sys/types.h>
50 #include <sys/capability.h>
53 #ifndef HAVE_DECL_PR_CAPBSET_DROP
54 #define PR_CAPBSET_DROP 24
57 #ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
58 #define PR_SET_NO_NEW_PRIVS 38
61 #ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
62 #define PR_GET_NO_NEW_PRIVS 39
75 #include "lxcseccomp.h"
79 #include "namespace.h"
85 lxc_log_define(lxc_start
, lxc
);
87 extern void mod_all_rdeps(struct lxc_container
*c
, bool inc
);
88 static bool do_destroy_container(struct lxc_conf
*conf
);
89 static int lxc_rmdir_onedev_wrapper(void *data
);
90 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
93 static void print_top_failing_dir(const char *path
)
95 size_t len
= strlen(path
);
96 char *copy
= alloca(len
+ 1), *p
, *e
, saved
;
102 while (p
< e
&& *p
== '/')
104 while (p
< e
&& *p
!= '/')
108 if (access(copy
, X_OK
)) {
109 SYSERROR("Could not access %s. Please grant it x "
110 "access, or add an ACL for the container "
118 static void close_ns(int ns_fd
[LXC_NS_MAX
])
122 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
130 /* preserve_ns: open /proc/@pid/ns/@ns for each namespace specified
132 * Return true on success, false on failure.
134 static bool preserve_ns(int ns_fd
[LXC_NS_MAX
], int clone_flags
, pid_t pid
)
138 for (i
= 0; i
< LXC_NS_MAX
; i
++)
141 ret
= lxc_preserve_ns(pid
, "");
143 SYSERROR("Kernel does not support attaching to namespaces.");
149 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
150 if ((clone_flags
& ns_info
[i
].clone_flag
) == 0)
152 ns_fd
[i
] = lxc_preserve_ns(pid
, ns_info
[i
].proc_name
);
161 SYSERROR("Kernel does not support attaching to %s namespaces.", ns_info
[i
].proc_name
);
163 SYSERROR("Failed to open file descriptor for %s namespace: %s.", ns_info
[i
].proc_name
, strerror(errno
));
168 static int attach_ns(const int ns_fd
[LXC_NS_MAX
]) {
171 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
175 if (setns(ns_fd
[i
], 0) != 0)
181 SYSERROR("Failed to attach %s namespace.", ns_info
[i
].proc_name
);
185 static int match_fd(int fd
)
187 return (fd
== 0 || fd
== 1 || fd
== 2);
190 /* Check for any fds we need to close.
191 * - If fd_to_ignore != -1, then if we find that fd open we will ignore it.
192 * - By default we warn about open fds we find.
193 * - If closeall is true, we will close open fds.
194 * - If lxc-start was passed "-C", then conf->close_all_fds will be true, in
195 * which case we also close all open fds.
196 * - A daemonized container will always pass closeall=true.
198 int lxc_check_inherited(struct lxc_conf
*conf
, bool closeall
, int fd_to_ignore
)
200 struct dirent
*direntp
;
204 if (conf
&& conf
->close_all_fds
)
208 dir
= opendir("/proc/self/fd");
210 WARN("Failed to open directory: %m.");
216 while ((direntp
= readdir(dir
))) {
220 if (!strcmp(direntp
->d_name
, "."))
223 if (!strcmp(direntp
->d_name
, ".."))
226 if (lxc_safe_int(direntp
->d_name
, &fd
) < 0) {
227 INFO("Could not parse file descriptor for: %s", direntp
->d_name
);
231 if (fd
== fddir
|| fd
== lxc_log_fd
|| fd
== fd_to_ignore
)
234 if (current_config
&& fd
== current_config
->logfd
)
243 INFO("Closed inherited fd: %d.", fd
);
246 WARN("Inherited fd: %d.", fd
);
249 /* Only enable syslog at this point to avoid the above logging function
250 * to open a new fd and make the check_inherited function enter an
253 lxc_log_enable_syslog();
255 closedir(dir
); /* cannot fail */
259 static int setup_signal_fd(sigset_t
*oldmask
)
264 /* Block everything except serious error signals. */
265 if (sigfillset(&mask
) ||
266 sigdelset(&mask
, SIGILL
) ||
267 sigdelset(&mask
, SIGSEGV
) ||
268 sigdelset(&mask
, SIGBUS
) ||
269 sigdelset(&mask
, SIGWINCH
) ||
270 sigprocmask(SIG_BLOCK
, &mask
, oldmask
)) {
271 SYSERROR("Failed to set signal mask.");
275 fd
= signalfd(-1, &mask
, 0);
277 SYSERROR("Failed to create signal file descriptor.");
281 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
)) {
282 SYSERROR("Failed to set FD_CLOEXEC on the signal file descriptor: %d.", fd
);
287 DEBUG("Set SIGCHLD handler with file descriptor: %d.", fd
);
292 static int signal_handler(int fd
, uint32_t events
, void *data
,
293 struct lxc_epoll_descr
*descr
)
295 struct signalfd_siginfo siginfo
;
299 bool init_died
= false;
301 ret
= read(fd
, &siginfo
, sizeof(siginfo
));
303 ERROR("Failed to read signal info from signal file descriptor: %d.", fd
);
307 if (ret
!= sizeof(siginfo
)) {
308 ERROR("Unexpected size for siginfo struct.");
312 /* Check whether init is running. */
314 ret
= waitid(P_PID
, *pid
, &info
, WEXITED
| WNOWAIT
| WNOHANG
);
315 if (ret
== 0 && info
.si_pid
== *pid
)
318 if (siginfo
.ssi_signo
!= SIGCHLD
) {
319 kill(*pid
, siginfo
.ssi_signo
);
320 INFO("Forwarded signal %d to pid %d.", siginfo
.ssi_signo
, *pid
);
321 return init_died
? 1 : 0;
324 if (siginfo
.ssi_code
== CLD_STOPPED
) {
325 INFO("Container init process was stopped.");
326 return init_died
? 1 : 0;
327 } else if (siginfo
.ssi_code
== CLD_CONTINUED
) {
328 INFO("Container init process was continued.");
329 return init_died
? 1 : 0;
332 /* More robustness, protect ourself from a SIGCHLD sent
333 * by a process different from the container init.
335 if (siginfo
.ssi_pid
!= *pid
) {
336 NOTICE("Received SIGCHLD from pid %d instead of container init %d.", siginfo
.ssi_pid
, *pid
);
337 return init_died
? 1 : 0;
340 DEBUG("Container init process %d exited.", *pid
);
344 int lxc_set_state(const char *name
, struct lxc_handler
*handler
, lxc_state_t state
)
346 handler
->state
= state
;
347 lxc_monitor_send_state(name
, state
, handler
->lxcpath
);
351 int lxc_poll(const char *name
, struct lxc_handler
*handler
)
353 int sigfd
= handler
->sigfd
;
354 int pid
= handler
->pid
;
355 struct lxc_epoll_descr descr
;
357 if (lxc_mainloop_open(&descr
)) {
358 ERROR("Failed to create LXC mainloop.");
362 if (lxc_mainloop_add_handler(&descr
, sigfd
, signal_handler
, &pid
)) {
363 ERROR("Failed to add signal handler with file descriptor %d to LXC mainloop.", sigfd
);
364 goto out_mainloop_open
;
367 if (lxc_console_mainloop_add(&descr
, handler
->conf
)) {
368 ERROR("Failed to add console handler to LXC mainloop.");
369 goto out_mainloop_open
;
372 if (lxc_cmd_mainloop_add(name
, &descr
, handler
)) {
373 ERROR("Failed to add command handler to LXC mainloop.");
374 goto out_mainloop_open
;
377 if (handler
->conf
->need_utmp_watch
) {
379 if (lxc_utmp_mainloop_add(&descr
, handler
)) {
380 ERROR("Failed to add utmp handler to LXC mainloop.");
381 goto out_mainloop_open
;
384 DEBUG("Not starting utmp handler as CAP_SYS_BOOT cannot be dropped without capabilities support.");
388 return lxc_mainloop(&descr
, -1);
391 lxc_mainloop_close(&descr
);
399 struct lxc_handler
*lxc_init(const char *name
, struct lxc_conf
*conf
, const char *lxcpath
)
402 struct lxc_handler
*handler
;
404 handler
= malloc(sizeof(*handler
));
408 memset(handler
, 0, sizeof(*handler
));
410 handler
->ttysock
[0] = handler
->ttysock
[1] = -1;
411 handler
->conf
= conf
;
412 handler
->lxcpath
= lxcpath
;
415 for (i
= 0; i
< LXC_NS_MAX
; i
++)
416 handler
->nsfd
[i
] = -1;
420 handler
->name
= strdup(name
);
421 if (!handler
->name
) {
422 ERROR("Failed to allocate memory.");
426 if (lxc_cmd_init(name
, handler
, lxcpath
))
429 if (lxc_read_seccomp_config(conf
) != 0) {
430 ERROR("Failed loading seccomp policy.");
431 goto out_close_maincmd_fd
;
434 /* Begin by setting the state to STARTING. */
435 if (lxc_set_state(name
, handler
, STARTING
)) {
436 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
, lxc_state2str(STARTING
));
437 goto out_close_maincmd_fd
;
440 /* Start of environment variable setup for hooks. */
441 if (name
&& setenv("LXC_NAME", name
, 1))
442 SYSERROR("Failed to set environment variable: LXC_NAME=%s.", name
);
444 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
445 SYSERROR("Failed to set environment variable: LXC_CONFIG_FILE=%s.", conf
->rcfile
);
447 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
448 SYSERROR("Failed to set environment variable: LXC_ROOTFS_MOUNT=%s.", conf
->rootfs
.mount
);
450 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
451 SYSERROR("Failed to set environment variable: LXC_ROOTFS_PATH=%s.", conf
->rootfs
.path
);
453 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
454 SYSERROR("Failed to set environment variable: LXC_CONSOLE=%s.", conf
->console
.path
);
456 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
457 SYSERROR("Failed to set environment variable: LXC_CONSOLE_LOGPATH=%s.", conf
->console
.log_path
);
459 if (setenv("LXC_CGNS_AWARE", "1", 1))
460 SYSERROR("Failed to set environment variable LXC_CGNS_AWARE=1.");
461 /* End of environment variable setup for hooks. */
463 if (run_lxc_hooks(name
, "pre-start", conf
, handler
->lxcpath
, NULL
)) {
464 ERROR("Failed to run lxc.hook.pre-start for container \"%s\".", name
);
468 /* The signal fd has to be created before forking otherwise if the child
469 * process exits before we setup the signal fd, the event will be lost
470 * and the command will be stuck.
472 handler
->sigfd
= setup_signal_fd(&handler
->oldmask
);
473 if (handler
->sigfd
< 0) {
474 ERROR("Failed to setup SIGCHLD fd handler.");
478 /* Do this after setting up signals since it might unblock SIGWINCH. */
479 if (lxc_console_create(conf
)) {
480 ERROR("Failed to create console for container \"%s\".", name
);
481 goto out_restore_sigmask
;
484 if (ttys_shift_ids(conf
) < 0) {
485 ERROR("Failed to shift tty into container.");
486 goto out_restore_sigmask
;
489 INFO("Container \"%s\" is initialized.", name
);
493 sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
);
495 lxc_delete_tty(&conf
->tty_info
);
497 lxc_set_state(name
, handler
, ABORTING
);
498 out_close_maincmd_fd
:
499 close(conf
->maincmd_fd
);
500 conf
->maincmd_fd
= -1;
503 handler
->name
= NULL
;
509 void lxc_fini(const char *name
, struct lxc_handler
*handler
)
512 pid_t self
= getpid();
513 char *namespaces
[LXC_NS_MAX
+1];
514 size_t namespace_count
= 0;
516 /* The STOPPING state is there for future cleanup code which can take
519 lxc_set_state(name
, handler
, STOPPING
);
521 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
522 if (handler
->nsfd
[i
] != -1) {
523 rc
= asprintf(&namespaces
[namespace_count
], "%s:/proc/%d/fd/%d",
524 ns_info
[i
].proc_name
, self
, handler
->nsfd
[i
]);
526 SYSERROR("Failed to allocate memory.");
532 namespaces
[namespace_count
] = NULL
;
534 if (handler
->conf
->reboot
&& setenv("LXC_TARGET", "reboot", 1))
535 SYSERROR("Failed to set environment variable: LXC_TARGET=reboot.");
537 if (!handler
->conf
->reboot
&& setenv("LXC_TARGET", "stop", 1))
538 SYSERROR("Failed to set environment variable: LXC_TARGET=stop.");
540 if (run_lxc_hooks(name
, "stop", handler
->conf
, handler
->lxcpath
, namespaces
))
541 ERROR("Failed to run lxc.hook.stop for container \"%s\".", name
);
543 while (namespace_count
--)
544 free(namespaces
[namespace_count
]);
545 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
546 if (handler
->nsfd
[i
] != -1) {
547 close(handler
->nsfd
[i
]);
548 handler
->nsfd
[i
] = -1;
552 if (handler
->netnsfd
>= 0) {
553 close(handler
->netnsfd
);
554 handler
->netnsfd
= -1;
557 lxc_set_state(name
, handler
, STOPPED
);
559 if (run_lxc_hooks(name
, "post-stop", handler
->conf
, handler
->lxcpath
, NULL
)) {
560 ERROR("Failed to run lxc.hook.post-stop for container \"%s\".", name
);
561 if (handler
->conf
->reboot
) {
562 WARN("Container will be stopped instead of rebooted.");
563 handler
->conf
->reboot
= 0;
564 if (setenv("LXC_TARGET", "stop", 1))
565 WARN("Failed to set environment variable: LXC_TARGET=stop.");
569 /* Reset mask set by setup_signal_fd. */
570 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
))
571 WARN("Failed to restore signal mask.");
573 lxc_console_delete(&handler
->conf
->console
);
574 lxc_delete_tty(&handler
->conf
->tty_info
);
575 close(handler
->conf
->maincmd_fd
);
576 handler
->conf
->maincmd_fd
= -1;
578 if (handler
->ttysock
[0] != -1) {
579 close(handler
->ttysock
[0]);
580 close(handler
->ttysock
[1]);
583 if (handler
->conf
->ephemeral
== 1 && handler
->conf
->reboot
!= 1)
584 lxc_destroy_container_on_signal(handler
, name
);
586 cgroup_destroy(handler
);
590 void lxc_abort(const char *name
, struct lxc_handler
*handler
)
594 lxc_set_state(name
, handler
, ABORTING
);
595 if (handler
->pid
> 0)
596 kill(handler
->pid
, SIGKILL
);
597 while ((ret
= waitpid(-1, &status
, 0)) > 0) {
602 #include <sys/reboot.h>
603 #include <linux/reboot.h>
605 /* reboot(LINUX_REBOOT_CMD_CAD_ON) will return -EINVAL in a child pid namespace
606 * if container reboot support exists. Otherwise, it will either succeed or
609 static int container_reboot_supported(void *arg
)
615 if (ret
== -1 && errno
== EINVAL
)
620 static int must_drop_cap_sys_boot(struct lxc_conf
*conf
)
623 int ret
, cmd
, v
, flags
;
624 long stack_size
= 4096;
625 void *stack
= alloca(stack_size
);
629 f
= fopen("/proc/sys/kernel/ctrl-alt-del", "r");
631 DEBUG("failed to open /proc/sys/kernel/ctrl-alt-del");
635 ret
= fscanf(f
, "%d", &v
);
638 DEBUG("Failed to read /proc/sys/kernel/ctrl-alt-del.");
641 cmd
= v
? LINUX_REBOOT_CMD_CAD_ON
: LINUX_REBOOT_CMD_CAD_OFF
;
643 flags
= CLONE_NEWPID
| SIGCHLD
;
644 if (!lxc_list_empty(&conf
->id_map
))
645 flags
|= CLONE_NEWUSER
;
648 pid
= __clone2(container_reboot_supported
, stack
, stack_size
, flags
, &cmd
);
651 pid
= clone(container_reboot_supported
, stack
, flags
, &cmd
);
654 if (flags
& CLONE_NEWUSER
)
655 ERROR("Failed to clone (%#x): %s (includes CLONE_NEWUSER).", flags
, strerror(errno
));
657 ERROR("Failed to clone (%#x): %s.", flags
, strerror(errno
));
660 if (wait(&status
) < 0) {
661 SYSERROR("Unexpected wait error: %m.");
665 if (WEXITSTATUS(status
) != 1)
671 /* netpipe is used in the unprivileged case to transfer the ifindexes from
674 static int netpipe
= -1;
676 static inline int count_veths(struct lxc_list
*network
)
678 struct lxc_list
*iterator
;
679 struct lxc_netdev
*netdev
;
682 lxc_list_for_each(iterator
, network
) {
683 netdev
= iterator
->elem
;
684 if (netdev
->type
!= LXC_NET_VETH
)
691 static int read_unpriv_netifindex(struct lxc_list
*network
)
693 struct lxc_list
*iterator
;
694 struct lxc_netdev
*netdev
;
698 lxc_list_for_each(iterator
, network
) {
699 netdev
= iterator
->elem
;
700 if (netdev
->type
!= LXC_NET_VETH
)
702 if (!(netdev
->name
= malloc(IFNAMSIZ
))) {
703 ERROR("Out of memory.");
707 if (read(netpipe
, netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
716 static int do_start(void *data
)
718 struct lxc_list
*iterator
;
719 struct lxc_handler
*handler
= data
;
720 int devnull_fd
= -1, ret
;
723 if (sigprocmask(SIG_SETMASK
, &handler
->oldmask
, NULL
)) {
724 SYSERROR("Failed to set signal mask.");
728 /* This prctl must be before the synchro, so if the parent dies before
729 * we set the parent death signal, we will detect its death with the
730 * synchro right after, otherwise we have a window where the parent can
731 * exit before we set the pdeath signal leading to a unsupervized
734 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0)) {
735 SYSERROR("Failed to set PR_SET_PDEATHSIG to SIGKILL.");
739 lxc_sync_fini_parent(handler
);
741 /* Don't leak the pinfd to the container. */
742 if (handler
->pinfd
>= 0) {
743 close(handler
->pinfd
);
746 if (lxc_sync_wait_parent(handler
, LXC_SYNC_STARTUP
))
749 /* Unshare CLONE_NEWNET after CLONE_NEWUSER. See
750 * https://github.com/lxc/lxd/issues/1978.
752 if ((handler
->clone_flags
& (CLONE_NEWNET
| CLONE_NEWUSER
)) ==
753 (CLONE_NEWNET
| CLONE_NEWUSER
)) {
754 ret
= unshare(CLONE_NEWNET
);
756 SYSERROR("Failed to unshare CLONE_NEWNET.");
757 goto out_warn_father
;
759 INFO("Unshared CLONE_NEWNET.");
762 /* Tell the parent task it can begin to configure the container and wait
765 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CONFIGURE
))
768 if (read_unpriv_netifindex(&handler
->conf
->network
) < 0)
769 goto out_warn_father
;
771 /* If we are in a new user namespace, become root there to have
772 * privilege over our namespace.
774 if (!lxc_list_empty(&handler
->conf
->id_map
)) {
775 if (lxc_switch_uid_gid(0, 0) < 0)
776 goto out_warn_father
;
778 /* Drop groups only after we switched to a valid gid in the new
781 if (lxc_setgroups(0, NULL
) < 0)
782 goto out_warn_father
;
785 if (access(handler
->lxcpath
, X_OK
)) {
786 print_top_failing_dir(handler
->lxcpath
);
787 goto out_warn_father
;
791 if (handler
->conf
->need_utmp_watch
) {
792 if (prctl(PR_CAPBSET_DROP
, CAP_SYS_BOOT
, 0, 0, 0)) {
793 SYSERROR("Failed to remove the CAP_SYS_BOOT capability.");
794 goto out_warn_father
;
796 DEBUG("Dropped the CAP_SYS_BOOT capability.");
800 ret
= snprintf(path
, sizeof(path
), "%s/dev/null", handler
->conf
->rootfs
.mount
);
801 if (ret
< 0 || ret
>= sizeof(path
))
802 goto out_warn_father
;
804 /* In order to checkpoint restore, we need to have everything in the
805 * same mount namespace. However, some containers may not have a
806 * reasonable /dev (in particular, they may not have /dev/null), so we
807 * can't set init's std fds to /dev/null by opening it from inside the
810 * If that's the case, fall back to using the host's /dev/null. This
811 * means that migration won't work, but at least we won't spew output
812 * where it isn't wanted.
814 if (handler
->backgrounded
&& !handler
->conf
->autodev
&& access(path
, F_OK
) < 0) {
815 devnull_fd
= open_devnull();
818 goto out_warn_father
;
819 WARN("Using /dev/null from the host for container init's "
820 "standard file descriptors. Migration will not work.");
823 /* Setup the container, ip, names, utsname, ... */
824 if (lxc_setup(handler
)) {
825 ERROR("Failed to setup container \"%s\".", handler
->name
);
826 goto out_warn_father
;
829 /* Ask father to setup cgroups and wait for him to finish. */
830 if (lxc_sync_barrier_parent(handler
, LXC_SYNC_CGROUP
))
833 /* Unshare cgroup namespace after we have setup our cgroups. If we do it
834 * earlier we end up with a wrong view of /proc/self/cgroup. For
835 * example, assume we unshare(CLONE_NEWCGROUP) first, and then create
836 * the cgroup for the container, say /sys/fs/cgroup/cpuset/lxc/c, then
837 * /proc/self/cgroup would show us:
841 * whereas it should actually show
845 if (cgns_supported()) {
846 if (unshare(CLONE_NEWCGROUP
) < 0) {
847 INFO("Failed to unshare CLONE_NEWCGROUP.");
848 goto out_warn_father
;
850 INFO("Unshared CLONE_NEWCGROUP.");
853 /* Set the label to change to when we exec(2) the container's init. */
854 if (lsm_process_label_set(NULL
, handler
->conf
, 1, 1) < 0)
855 goto out_warn_father
;
857 /* Set PR_SET_NO_NEW_PRIVS after we changed the lsm label. If we do it
858 * before we aren't allowed anymore.
860 if (handler
->conf
->no_new_privs
) {
861 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
862 SYSERROR("Could not set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
863 goto out_warn_father
;
865 DEBUG("Set PR_SET_NO_NEW_PRIVS to block execve() gainable privileges.");
868 /* Some init's such as busybox will set sane tty settings on stdin,
869 * stdout, stderr which it thinks is the console. We already set them
870 * the way we wanted on the real terminal, and we want init to do its
871 * setup on its console ie. the pty allocated in lxc_console_create() so
872 * make sure that that pty is stdin,stdout,stderr.
874 if (lxc_console_set_stdfds(handler
->conf
->console
.slave
) < 0)
875 goto out_warn_father
;
877 /* If we mounted a temporary proc, then unmount it now. */
878 tmp_proc_unmount(handler
->conf
);
880 if (lxc_seccomp_load(handler
->conf
) != 0)
881 goto out_warn_father
;
883 if (run_lxc_hooks(handler
->name
, "start", handler
->conf
, handler
->lxcpath
, NULL
)) {
884 ERROR("Failed to run lxc.hook.start for container \"%s\".", handler
->name
);
885 goto out_warn_father
;
888 /* The container has been setup. We can now switch to an unprivileged
891 if (handler
->conf
->is_execute
) {
892 bool have_cap_setgid
;
893 uid_t new_uid
= handler
->conf
->init_uid
;
894 gid_t new_gid
= handler
->conf
->init_gid
;
896 /* If we are in a new user namespace we already dropped all
897 * groups when we switched to root in the new user namespace
898 * further above. Only drop groups if we can, so ensure that we
899 * have necessary privilege.
902 have_cap_setgid
= lxc_proc_cap_is_set(CAP_SETGID
, CAP_EFFECTIVE
);
904 have_cap_setgid
= false;
906 if (lxc_list_empty(&handler
->conf
->id_map
) && have_cap_setgid
) {
907 if (lxc_setgroups(0, NULL
) < 0)
908 goto out_warn_father
;
911 if (lxc_switch_uid_gid(new_uid
, new_gid
) < 0)
912 goto out_warn_father
;
915 /* The clearenv() and putenv() calls have been moved here to allow us to
916 * use environment variables passed to the various hooks, such as the
917 * start hook above. Not all of the variables like CONFIG_PATH or ROOTFS
918 * are valid in this context but others are.
921 SYSERROR("Failed to clear environment.");
922 /* Don't error out though. */
925 lxc_list_for_each(iterator
, &handler
->conf
->environment
) {
926 if (putenv((char *)iterator
->elem
)) {
927 SYSERROR("Failed to set environment variable: %s.", (char *)iterator
->elem
);
928 goto out_warn_father
;
932 if (putenv("container=lxc")) {
933 SYSERROR("Failed to set environment variable: container=lxc.");
934 goto out_warn_father
;
937 if (handler
->conf
->pty_names
) {
938 if (putenv(handler
->conf
->pty_names
)) {
939 SYSERROR("Failed to set environment variable for container ptys.");
940 goto out_warn_father
;
944 close(handler
->sigfd
);
946 if (devnull_fd
< 0) {
947 devnull_fd
= open_devnull();
950 goto out_warn_father
;
953 if (handler
->backgrounded
&& set_stdfds(devnull_fd
))
954 goto out_warn_father
;
956 if (devnull_fd
>= 0) {
963 /* After this call, we are in error because this ops should not return
966 handler
->ops
->start(handler
, handler
->data
);
969 /* We want the parent to know something went wrong, so we return a
970 * special error code.
972 lxc_sync_wake_parent(handler
, LXC_SYNC_ERROR
);
981 static int save_phys_nics(struct lxc_conf
*conf
)
983 struct lxc_list
*iterator
;
984 int am_root
= (getuid() == 0);
989 lxc_list_for_each(iterator
, &conf
->network
) {
990 struct lxc_netdev
*netdev
= iterator
->elem
;
992 if (netdev
->type
!= LXC_NET_PHYS
)
994 conf
->saved_nics
= realloc(conf
->saved_nics
,
995 (conf
->num_savednics
+1)*sizeof(struct saved_nic
));
996 if (!conf
->saved_nics
)
998 conf
->saved_nics
[conf
->num_savednics
].ifindex
= netdev
->ifindex
;
999 conf
->saved_nics
[conf
->num_savednics
].orig_name
= strdup(netdev
->link
);
1000 if (!conf
->saved_nics
[conf
->num_savednics
].orig_name
)
1002 INFO("Stored saved_nic #%d idx %d name %s.", conf
->num_savednics
,
1003 conf
->saved_nics
[conf
->num_savednics
].ifindex
,
1004 conf
->saved_nics
[conf
->num_savednics
].orig_name
);
1005 conf
->num_savednics
++;
1011 static int recv_fd(int sock
, int *fd
)
1013 if (lxc_abstract_unix_recv_fd(sock
, fd
, NULL
, 0) < 0) {
1014 SYSERROR("Error receiving tty file descriptor from child process.");
1022 static int recv_ttys_from_child(struct lxc_handler
*handler
)
1025 int sock
= handler
->ttysock
[1];
1026 struct lxc_conf
*conf
= handler
->conf
;
1027 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
1032 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
1033 if (!tty_info
->pty_info
)
1036 for (i
= 0; i
< conf
->tty
; i
++) {
1037 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
1039 ret
= recv_fd(sock
, &pty_info
->slave
);
1041 recv_fd(sock
, &pty_info
->master
);
1043 ERROR("failed to receive pty with master fd %d and "
1044 "slave fd %d from child: %s",
1045 pty_info
->master
, pty_info
->slave
,
1049 TRACE("received pty with master fd %d and slave fd %d from child",
1050 pty_info
->master
, pty_info
->slave
);
1052 tty_info
->nbtty
= conf
->tty
;
1057 void resolve_clone_flags(struct lxc_handler
*handler
)
1059 handler
->clone_flags
= CLONE_NEWPID
| CLONE_NEWNS
;
1061 if (!lxc_list_empty(&handler
->conf
->id_map
))
1062 handler
->clone_flags
|= CLONE_NEWUSER
;
1064 if (handler
->conf
->inherit_ns_fd
[LXC_NS_NET
] == -1) {
1065 if (!lxc_requests_empty_network(handler
))
1066 handler
->clone_flags
|= CLONE_NEWNET
;
1068 INFO("Inheriting a NET namespace.");
1071 if (handler
->conf
->inherit_ns_fd
[LXC_NS_IPC
] == -1)
1072 handler
->clone_flags
|= CLONE_NEWIPC
;
1074 INFO("Inheriting an IPC namespace.");
1076 if (handler
->conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1)
1077 handler
->clone_flags
|= CLONE_NEWUTS
;
1079 INFO("Inheriting a UTS namespace.");
1082 /* lxc_spawn() performs crucial setup tasks and clone()s the new process which
1083 * exec()s the requested container binary.
1084 * Note that lxc_spawn() runs in the parent namespaces. Any operations performed
1085 * right here should be double checked if they'd pose a security risk. (For
1086 * example, any {u}mount() operations performed here will be reflected on the
1089 static int lxc_spawn(struct lxc_handler
*handler
)
1091 int failed_before_rename
= 0;
1092 const char *name
= handler
->name
;
1093 bool cgroups_connected
= false;
1094 int saved_ns_fd
[LXC_NS_MAX
];
1095 int preserve_mask
= 0, i
, flags
;
1096 int netpipepair
[2], nveths
;
1097 bool wants_to_map_ids
;
1098 struct lxc_list
*id_map
;
1101 id_map
= &handler
->conf
->id_map
;
1102 wants_to_map_ids
= !lxc_list_empty(id_map
);
1104 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1105 if (handler
->conf
->inherit_ns_fd
[i
] != -1)
1106 preserve_mask
|= ns_info
[i
].clone_flag
;
1108 if (lxc_sync_init(handler
))
1111 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, handler
->ttysock
) < 0) {
1112 lxc_sync_fini(handler
);
1116 resolve_clone_flags(handler
);
1118 if (handler
->clone_flags
& CLONE_NEWNET
) {
1119 if (!lxc_list_empty(&handler
->conf
->network
)) {
1121 /* Find gateway addresses from the link device, which is
1122 * no longer accessible inside the container. Do this
1123 * before creating network interfaces, since goto
1124 * out_delete_net does not work before lxc_clone.
1126 if (lxc_find_gateway_addresses(handler
)) {
1127 ERROR("Failed to find gateway addresses.");
1128 lxc_sync_fini(handler
);
1132 /* That should be done before the clone because we will
1133 * fill the netdev index and use them in the child.
1135 if (lxc_create_network(handler
)) {
1136 ERROR("Failed to create the network.");
1137 lxc_sync_fini(handler
);
1142 if (save_phys_nics(handler
->conf
)) {
1143 ERROR("Failed to save physical nic info.");
1148 if (!cgroup_init(handler
)) {
1149 ERROR("Failed initializing cgroup support.");
1150 goto out_delete_net
;
1153 cgroups_connected
= true;
1155 if (!cgroup_create(handler
)) {
1156 ERROR("Failed creating cgroups.");
1157 goto out_delete_net
;
1160 /* If the rootfs is not a blockdev, prevent the container from marking
1162 * If the container is unprivileged then skip rootfs pinning.
1164 if (!wants_to_map_ids
) {
1165 handler
->pinfd
= pin_rootfs(handler
->conf
->rootfs
.path
);
1166 if (handler
->pinfd
== -1)
1167 INFO("Failed to pin the rootfs for container \"%s\".", handler
->name
);
1170 if (!preserve_ns(saved_ns_fd
, preserve_mask
, getpid()))
1171 goto out_delete_net
;
1173 if (attach_ns(handler
->conf
->inherit_ns_fd
) < 0)
1174 goto out_delete_net
;
1176 if (am_unpriv() && (nveths
= count_veths(&handler
->conf
->network
))) {
1177 if (pipe(netpipepair
) < 0) {
1178 SYSERROR("Failed to create pipe.");
1179 goto out_delete_net
;
1181 /* Store netpipe in the global var for do_start's use. */
1182 netpipe
= netpipepair
[0];
1185 /* Create a process in a new set of namespaces. */
1186 flags
= handler
->clone_flags
;
1187 if (handler
->clone_flags
& CLONE_NEWUSER
) {
1188 /* If CLONE_NEWUSER and CLONE_NEWNET was requested, we need to
1189 * clone a new user namespace first and only later unshare our
1190 * network namespace to ensure that network devices ownership is
1193 flags
&= ~CLONE_NEWNET
;
1195 handler
->pid
= lxc_clone(do_start
, handler
, flags
);
1196 if (handler
->pid
< 0) {
1197 SYSERROR("Failed to clone a new set of namespaces.");
1198 goto out_delete_net
;
1200 for (i
= 0; i
< LXC_NS_MAX
; i
++)
1201 if (flags
& ns_info
[i
].clone_flag
)
1202 INFO("Cloned %s.", ns_info
[i
].flag_name
);
1204 if (!preserve_ns(handler
->nsfd
, handler
->clone_flags
| preserve_mask
, handler
->pid
))
1205 INFO("Failed to preserve namespace for lxc.hook.stop.");
1207 if (attach_ns(saved_ns_fd
))
1208 WARN("Failed to restore saved namespaces.");
1210 lxc_sync_fini_child(handler
);
1212 /* Map the container uids. The container became an invalid userid the
1213 * moment it was cloned with CLONE_NEWUSER. This call doesn't change
1214 * anything immediately, but allows the container to setuid(0) (0 being
1215 * mapped to something else on the host.) later to become a valid uid
1218 if (wants_to_map_ids
&& lxc_map_ids(id_map
, handler
->pid
)) {
1219 ERROR("Failed to set up id mapping.");
1220 goto out_delete_net
;
1223 if (lxc_sync_wake_child(handler
, LXC_SYNC_STARTUP
)) {
1224 failed_before_rename
= 1;
1225 goto out_delete_net
;
1228 if (lxc_sync_wait_child(handler
, LXC_SYNC_CONFIGURE
)) {
1229 failed_before_rename
= 1;
1230 goto out_delete_net
;
1233 if (!cgroup_create_legacy(handler
)) {
1234 ERROR("Failed to setup legacy cgroups for container \"%s\".", name
);
1235 goto out_delete_net
;
1237 if (!cgroup_setup_limits(handler
, false)) {
1238 ERROR("Failed to setup cgroup limits for container \"%s\".", name
);
1239 goto out_delete_net
;
1242 if (!cgroup_enter(handler
))
1243 goto out_delete_net
;
1245 if (!cgroup_chown(handler
))
1246 goto out_delete_net
;
1248 if (failed_before_rename
)
1249 goto out_delete_net
;
1251 /* Create the network configuration. */
1252 if (handler
->clone_flags
& CLONE_NEWNET
) {
1253 if (lxc_assign_network(handler
->lxcpath
, handler
->name
,
1254 &handler
->conf
->network
, handler
->pid
)) {
1255 ERROR("Failed to create the configured network.");
1256 goto out_delete_net
;
1260 if (netpipe
!= -1) {
1261 struct lxc_list
*iterator
;
1262 struct lxc_netdev
*netdev
;
1265 lxc_list_for_each(iterator
, &handler
->conf
->network
) {
1266 netdev
= iterator
->elem
;
1267 if (netdev
->type
!= LXC_NET_VETH
)
1269 if (write(netpipepair
[1], netdev
->name
, IFNAMSIZ
) != IFNAMSIZ
) {
1270 ERROR("Error writing veth name to container.");
1271 goto out_delete_net
;
1274 close(netpipepair
[1]);
1277 /* Tell the child to continue its initialization. We'll get
1278 * LXC_SYNC_CGROUP when it is ready for us to setup cgroups.
1280 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CONFIGURE
))
1281 goto out_delete_net
;
1283 if (!lxc_list_empty(&handler
->conf
->limits
) && setup_resource_limits(&handler
->conf
->limits
, handler
->pid
)) {
1284 ERROR("failed to setup resource limits for '%s'", name
);
1285 goto out_delete_net
;
1288 if (!cgroup_setup_limits(handler
, true)) {
1289 ERROR("Failed to setup the devices cgroup for container \"%s\".", name
);
1290 goto out_delete_net
;
1293 cgroup_disconnect();
1294 cgroups_connected
= false;
1296 /* Read tty fds allocated by child. */
1297 if (recv_ttys_from_child(handler
) < 0) {
1298 ERROR("Failed to receive tty info from child process.");
1299 goto out_delete_net
;
1302 /* Tell the child to complete its initialization and wait for it to exec
1303 * or return an error. (The child will never return
1304 * LXC_SYNC_POST_CGROUP+1. It will either close the sync pipe, causing
1305 * lxc_sync_barrier_child to return success, or return a different
1306 * value, causing us to error out).
1308 if (lxc_sync_barrier_child(handler
, LXC_SYNC_POST_CGROUP
))
1311 if (handler
->ops
->post_start(handler
, handler
->data
))
1314 if (lxc_set_state(name
, handler
, RUNNING
)) {
1315 ERROR("Failed to set state for container \"%s\" to \"%s\".", name
,
1316 lxc_state2str(RUNNING
));
1320 lxc_sync_fini(handler
);
1321 handler
->netnsfd
= lxc_preserve_ns(handler
->pid
, "net");
1326 if (cgroups_connected
)
1327 cgroup_disconnect();
1328 if (handler
->clone_flags
& CLONE_NEWNET
)
1329 lxc_delete_network(handler
);
1331 lxc_abort(name
, handler
);
1332 lxc_sync_fini(handler
);
1333 if (handler
->pinfd
>= 0) {
1334 close(handler
->pinfd
);
1335 handler
->pinfd
= -1;
1341 int __lxc_start(const char *name
, struct lxc_conf
*conf
,
1342 struct lxc_operations
* ops
, void *data
, const char *lxcpath
,
1345 struct lxc_handler
*handler
;
1348 bool removed_all_netdevs
= true;
1350 handler
= lxc_init(name
, conf
, lxcpath
);
1352 ERROR("Failed to initialize container \"%s\".", name
);
1356 handler
->data
= data
;
1357 handler
->backgrounded
= backgrounded
;
1358 handler
->netnsfd
= -1;
1360 if (must_drop_cap_sys_boot(handler
->conf
)) {
1362 DEBUG("Dropping CAP_SYS_BOOT capability.");
1364 DEBUG("Not dropping CAP_SYS_BOOT capability as capabilities aren't supported.");
1367 DEBUG("Not dropping CAP_SYS_BOOT or watching utmp.");
1368 handler
->conf
->need_utmp_watch
= 0;
1371 if (!attach_block_device(handler
->conf
)) {
1372 ERROR("Failed to attach block device.");
1373 goto out_fini_nonet
;
1376 if (geteuid() == 0 && !lxc_list_empty(&conf
->id_map
)) {
1377 /* If the backing store is a device, mount it here and now. */
1378 if (rootfs_is_blockdev(conf
)) {
1379 if (unshare(CLONE_NEWNS
) < 0) {
1380 ERROR("Failed to unshare CLONE_NEWNS.");
1381 goto out_fini_nonet
;
1383 INFO("Unshared CLONE_NEWNS.");
1385 remount_all_slave();
1386 if (do_rootfs_setup(conf
, name
, lxcpath
) < 0) {
1387 ERROR("Error setting up rootfs mount as root before spawn.");
1388 goto out_fini_nonet
;
1390 INFO("Set up container rootfs as host root.");
1394 err
= lxc_spawn(handler
);
1396 ERROR("Failed to spawn container \"%s\".", name
);
1397 goto out_detach_blockdev
;
1400 handler
->conf
->reboot
= 0;
1402 err
= lxc_poll(name
, handler
);
1404 ERROR("LXC mainloop exited with error: %d.", err
);
1405 if (handler
->netnsfd
>= 0) {
1406 close(handler
->netnsfd
);
1407 handler
->netnsfd
= -1;
1412 while (waitpid(handler
->pid
, &status
, 0) < 0 && errno
== EINTR
)
1415 /* If the child process exited but was not signaled, it didn't call
1416 * reboot. This should mean it was an lxc-execute which simply exited.
1417 * In any case, treat it as a 'halt'.
1419 if (WIFSIGNALED(status
)) {
1420 switch(WTERMSIG(status
)) {
1421 case SIGINT
: /* halt */
1422 DEBUG("Container \"%s\" is halting.", name
);
1424 case SIGHUP
: /* reboot */
1425 DEBUG("Container \"%s\" is rebooting.", name
);
1426 handler
->conf
->reboot
= 1;
1428 case SIGSYS
: /* seccomp */
1429 DEBUG("Container \"%s\" violated its seccomp policy.", name
);
1432 DEBUG("Unknown exit status for container \"%s\" init %d.", name
, WTERMSIG(status
));
1437 DEBUG("Pushing physical nics back to host namespace");
1438 lxc_restore_phys_nics_to_netns(handler
->netnsfd
, handler
->conf
);
1440 DEBUG("Tearing down virtual network devices used by container \"%s\".", name
);
1441 removed_all_netdevs
= lxc_delete_network(handler
);
1443 if (handler
->pinfd
>= 0) {
1444 close(handler
->pinfd
);
1445 handler
->pinfd
= -1;
1448 lxc_monitor_send_exit_code(name
, status
, handler
->lxcpath
);
1449 err
= lxc_error_set_and_log(handler
->pid
, status
);
1451 if (!removed_all_netdevs
) {
1452 DEBUG("Failed tearing down network devices used by container. Trying again!");
1453 removed_all_netdevs
= lxc_delete_network(handler
);
1454 if (!removed_all_netdevs
)
1455 DEBUG("Failed tearing down network devices used by container. Not trying again!");
1458 out_detach_blockdev
:
1459 detach_block_device(handler
->conf
);
1462 lxc_fini(name
, handler
);
1466 lxc_abort(name
, handler
);
1474 static int start(struct lxc_handler
*handler
, void* data
)
1476 struct start_args
*arg
= data
;
1478 NOTICE("Exec'ing \"%s\".", arg
->argv
[0]);
1480 execvp(arg
->argv
[0], arg
->argv
);
1481 SYSERROR("Failed to exec \"%s\".", arg
->argv
[0]);
1485 static int post_start(struct lxc_handler
*handler
, void* data
)
1487 struct start_args
*arg
= data
;
1489 NOTICE("Started \"%s\" with pid \"%d\".", arg
->argv
[0], handler
->pid
);
1493 static struct lxc_operations start_ops
= {
1495 .post_start
= post_start
1498 int lxc_start(const char *name
, char *const argv
[], struct lxc_conf
*conf
,
1499 const char *lxcpath
, bool backgrounded
)
1501 struct start_args start_arg
= {
1505 conf
->need_utmp_watch
= 1;
1506 return __lxc_start(name
, conf
, &start_ops
, &start_arg
, lxcpath
, backgrounded
);
1509 static void lxc_destroy_container_on_signal(struct lxc_handler
*handler
,
1512 char destroy
[MAXPATHLEN
];
1515 struct lxc_container
*c
;
1516 if (handler
->conf
->rootfs
.path
&& handler
->conf
->rootfs
.mount
) {
1517 bret
= do_destroy_container(handler
->conf
);
1519 ERROR("Error destroying rootfs for container \"%s\".", name
);
1523 INFO("Destroyed rootfs for container \"%s\".", name
);
1525 ret
= snprintf(destroy
, MAXPATHLEN
, "%s/%s", handler
->lxcpath
, name
);
1526 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1527 ERROR("Error destroying directory for container \"%s\".", name
);
1531 c
= lxc_container_new(name
, handler
->lxcpath
);
1533 if (container_disk_lock(c
)) {
1534 INFO("Could not update lxc_snapshots file.");
1535 lxc_container_put(c
);
1537 mod_all_rdeps(c
, false);
1538 container_disk_unlock(c
);
1539 lxc_container_put(c
);
1544 ret
= userns_exec_1(handler
->conf
, lxc_rmdir_onedev_wrapper
,
1545 destroy
, "lxc_rmdir_onedev_wrapper");
1547 ret
= lxc_rmdir_onedev(destroy
, NULL
);
1550 ERROR("Error destroying directory for container \"%s\".", name
);
1553 INFO("Destroyed directory for container \"%s\".", name
);
1556 static int lxc_rmdir_onedev_wrapper(void *data
)
1558 char *arg
= (char *) data
;
1559 return lxc_rmdir_onedev(arg
, NULL
);
1562 static bool do_destroy_container(struct lxc_conf
*conf
) {
1564 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
,
1565 "bdev_destroy_wrapper") < 0)
1569 return bdev_destroy(conf
);