1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <linux/loop.h>
15 #include <netinet/in.h>
22 #include <sys/mount.h>
23 #include <sys/param.h>
24 #include <sys/prctl.h>
25 #include <sys/sendfile.h>
26 #include <sys/socket.h>
28 #include <sys/syscall.h>
29 #include <sys/sysmacros.h>
30 #include <sys/types.h>
31 #include <sys/utsname.h>
38 #include "cgroups/cgroup.h"
43 #include "confile_utils.h"
48 #include "lxcseccomp.h"
50 #include "memory_utils.h"
51 #include "mount_utils.h"
52 #include "namespace.h"
55 #include "process_utils.h"
58 #include "storage/storage.h"
59 #include "storage/overlay.h"
60 #include "syscall_wrappers.h"
66 #include <sys/mkdev.h>
70 #include <sys/statvfs.h>
76 #include <../include/openpty.h>
80 #include <sys/capability.h>
83 #if HAVE_SYS_PERSONALITY_H
84 #include <sys/personality.h>
88 #include "include/strlcat.h"
92 #include <../include/lxcmntent.h>
97 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
98 #include <../include/prlimit.h>
102 #include "include/strlcpy.h"
105 #ifndef HAVE_STRCHRNUL
106 #include "include/strchrnul.h"
109 lxc_log_define(conf
, lxc
);
112 * The lxc_conf of the container currently being worked on in an API call.
113 * This is used in the error calls.
115 thread_local
struct lxc_conf
*current_config
;
117 char *lxchook_names
[NUM_LXC_HOOKS
] = {
146 static struct mount_opt mount_opt
[] = {
147 { "async", 1, MS_SYNCHRONOUS
},
148 { "atime", 1, MS_NOATIME
},
149 { "bind", 0, MS_BIND
},
150 { "defaults", 0, 0 },
151 { "dev", 1, MS_NODEV
},
152 { "diratime", 1, MS_NODIRATIME
},
153 { "dirsync", 0, MS_DIRSYNC
},
154 { "exec", 1, MS_NOEXEC
},
155 { "lazytime", 0, MS_LAZYTIME
},
156 { "mand", 0, MS_MANDLOCK
},
157 { "noatime", 0, MS_NOATIME
},
158 { "nodev", 0, MS_NODEV
},
159 { "nodiratime", 0, MS_NODIRATIME
},
160 { "noexec", 0, MS_NOEXEC
},
161 { "nomand", 1, MS_MANDLOCK
},
162 { "norelatime", 1, MS_RELATIME
},
163 { "nostrictatime", 1, MS_STRICTATIME
},
164 { "nosuid", 0, MS_NOSUID
},
165 { "rbind", 0, MS_BIND
|MS_REC
},
166 { "relatime", 0, MS_RELATIME
},
167 { "remount", 0, MS_REMOUNT
},
168 { "ro", 0, MS_RDONLY
},
169 { "rw", 1, MS_RDONLY
},
170 { "strictatime", 0, MS_STRICTATIME
},
171 { "suid", 1, MS_NOSUID
},
172 { "sync", 0, MS_SYNCHRONOUS
},
176 static struct mount_opt propagation_opt
[] = {
177 { "private", 0, MS_PRIVATE
},
178 { "shared", 0, MS_SHARED
},
179 { "slave", 0, MS_SLAVE
},
180 { "unbindable", 0, MS_UNBINDABLE
},
181 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
182 { "rshared", 0, MS_SHARED
|MS_REC
},
183 { "rslave", 0, MS_SLAVE
|MS_REC
},
184 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
188 static struct caps_opt caps_opt
[] = {
190 { "chown", CAP_CHOWN
},
191 { "dac_override", CAP_DAC_OVERRIDE
},
192 { "dac_read_search", CAP_DAC_READ_SEARCH
},
193 { "fowner", CAP_FOWNER
},
194 { "fsetid", CAP_FSETID
},
195 { "kill", CAP_KILL
},
196 { "setgid", CAP_SETGID
},
197 { "setuid", CAP_SETUID
},
198 { "setpcap", CAP_SETPCAP
},
199 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
200 { "net_bind_service", CAP_NET_BIND_SERVICE
},
201 { "net_broadcast", CAP_NET_BROADCAST
},
202 { "net_admin", CAP_NET_ADMIN
},
203 { "net_raw", CAP_NET_RAW
},
204 { "ipc_lock", CAP_IPC_LOCK
},
205 { "ipc_owner", CAP_IPC_OWNER
},
206 { "sys_module", CAP_SYS_MODULE
},
207 { "sys_rawio", CAP_SYS_RAWIO
},
208 { "sys_chroot", CAP_SYS_CHROOT
},
209 { "sys_ptrace", CAP_SYS_PTRACE
},
210 { "sys_pacct", CAP_SYS_PACCT
},
211 { "sys_admin", CAP_SYS_ADMIN
},
212 { "sys_boot", CAP_SYS_BOOT
},
213 { "sys_nice", CAP_SYS_NICE
},
214 { "sys_resource", CAP_SYS_RESOURCE
},
215 { "sys_time", CAP_SYS_TIME
},
216 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
217 { "mknod", CAP_MKNOD
},
218 { "lease", CAP_LEASE
},
219 { "audit_write", CAP_AUDIT_WRITE
},
220 { "audit_control", CAP_AUDIT_CONTROL
},
221 { "setfcap", CAP_SETFCAP
},
222 { "mac_override", CAP_MAC_OVERRIDE
},
223 { "mac_admin", CAP_MAC_ADMIN
},
224 { "syslog", CAP_SYSLOG
},
225 { "wake_alarm", CAP_WAKE_ALARM
},
226 { "block_suspend", CAP_BLOCK_SUSPEND
},
227 { "audit_read", CAP_AUDIT_READ
},
228 { "perfmon", CAP_PERFMON
},
230 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE
},
234 static struct limit_opt limit_opt
[] = {
239 { "core", RLIMIT_CORE
},
242 { "cpu", RLIMIT_CPU
},
245 { "data", RLIMIT_DATA
},
248 { "fsize", RLIMIT_FSIZE
},
251 { "locks", RLIMIT_LOCKS
},
253 #ifdef RLIMIT_MEMLOCK
254 { "memlock", RLIMIT_MEMLOCK
},
256 #ifdef RLIMIT_MSGQUEUE
257 { "msgqueue", RLIMIT_MSGQUEUE
},
260 { "nice", RLIMIT_NICE
},
263 { "nofile", RLIMIT_NOFILE
},
266 { "nproc", RLIMIT_NPROC
},
269 { "rss", RLIMIT_RSS
},
272 { "rtprio", RLIMIT_RTPRIO
},
275 { "rttime", RLIMIT_RTTIME
},
277 #ifdef RLIMIT_SIGPENDING
278 { "sigpending", RLIMIT_SIGPENDING
},
281 { "stack", RLIMIT_STACK
},
285 static int run_buffer(char *buffer
)
287 __do_free
char *output
= NULL
;
288 __do_lxc_pclose
struct lxc_popen_FILE
*f
= NULL
;
291 f
= lxc_popen(buffer
);
293 return log_error_errno(-1, errno
, "Failed to popen() %s", buffer
);
295 output
= zalloc(LXC_LOG_BUFFER_SIZE
);
297 return log_error_errno(-1, ENOMEM
, "Failed to allocate memory for %s", buffer
);
301 return log_error_errno(-1, errno
, "Failed to retrieve underlying file descriptor");
303 for (int i
= 0; i
< 10; i
++) {
306 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
307 if (bytes_read
> 0) {
308 output
[bytes_read
] = '\0';
309 DEBUG("Script %s produced output: %s", buffer
, output
);
316 ret
= lxc_pclose(move_ptr(f
));
318 return log_error_errno(-1, errno
, "Script exited with error");
319 else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0)
320 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret
));
321 else if (WIFSIGNALED(ret
))
322 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret
));
327 int run_script_argv(const char *name
, unsigned int hook_version
,
328 const char *section
, const char *script
,
329 const char *hookname
, char **argv
)
331 __do_free
char *buffer
= NULL
;
335 if (hook_version
== 0)
336 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
337 script
, name
, section
);
339 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
341 for (i
= 0; argv
&& argv
[i
]; i
++)
342 size
+= strlen(argv
[i
]) + 1;
344 size
+= STRLITERALLEN("exec");
346 size
+= strlen(script
);
352 if (hook_version
== 0) {
353 size
+= strlen(hookname
);
356 size
+= strlen(name
);
359 size
+= strlen(section
);
366 buffer
= zalloc(size
);
370 if (hook_version
== 0)
371 buf_pos
= strnprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
373 buf_pos
= strnprintf(buffer
, size
, "exec %s", script
);
375 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
377 if (hook_version
== 1) {
378 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
380 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname
);
382 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
384 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
386 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section
);
387 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
389 if (strequal(section
, "net")) {
392 if (!argv
|| !argv
[0])
395 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
397 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_TYPE=%s", argv
[0]);
398 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
400 parent
= argv
[1] ? argv
[1] : "";
402 if (strequal(argv
[0], "macvlan")) {
403 ret
= setenv("LXC_NET_PARENT", parent
, 1);
405 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
406 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
407 } else if (strequal(argv
[0], "phys")) {
408 ret
= setenv("LXC_NET_PARENT", parent
, 1);
410 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
411 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
412 } else if (strequal(argv
[0], "veth")) {
413 char *peer
= argv
[2] ? argv
[2] : "";
415 ret
= setenv("LXC_NET_PEER", peer
, 1);
417 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PEER=%s", peer
);
418 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
420 ret
= setenv("LXC_NET_PARENT", parent
, 1);
422 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
423 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
428 for (i
= 0; argv
&& argv
[i
]; i
++) {
429 size_t len
= size
- buf_pos
;
431 ret
= strnprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
433 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
437 return run_buffer(buffer
);
440 int run_script(const char *name
, const char *section
, const char *script
, ...)
442 __do_free
char *buffer
= NULL
;
448 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
449 script
, name
, section
);
451 va_start(ap
, script
);
452 while ((p
= va_arg(ap
, char *)))
453 size
+= strlen(p
) + 1;
456 size
+= STRLITERALLEN("exec");
457 size
+= strlen(script
);
458 size
+= strlen(name
);
459 size
+= strlen(section
);
465 buffer
= must_realloc(NULL
, size
);
466 ret
= strnprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
470 va_start(ap
, script
);
471 while ((p
= va_arg(ap
, char *))) {
472 int len
= size
- ret
;
474 rc
= strnprintf(buffer
+ ret
, len
, " %s", p
);
483 return run_buffer(buffer
);
486 int lxc_storage_prepare(struct lxc_conf
*conf
)
489 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
492 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
494 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
496 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
497 if (rootfs
->dfd_mnt
< 0)
503 ret
= access(rootfs
->mount
, F_OK
);
505 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
508 rootfs
->storage
= storage_init(conf
);
509 if (!rootfs
->storage
)
510 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
511 rootfs
->path
, rootfs
->mount
,
512 rootfs
->options
? rootfs
->options
: "(null)");
517 void lxc_storage_put(struct lxc_conf
*conf
)
519 storage_put(conf
->rootfs
.storage
);
520 conf
->rootfs
.storage
= NULL
;
523 /* lxc_rootfs_prepare
524 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
525 * the duration of the container run, to prevent the container from marking
526 * the underlying fs readonly on shutdown. unlink the file immediately so
527 * no name pollution is happens.
528 * don't unlink on NFS to avoid random named stale handles.
530 int lxc_rootfs_init(struct lxc_conf
*conf
, bool userns
)
532 __do_close
int dfd_path
= -EBADF
, fd_pin
= -EBADF
, fd_userns
= -EBADF
;
536 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
538 ret
= lxc_storage_prepare(conf
);
540 return syserror_set(-EINVAL
, "Failed to prepare rootfs storage");
542 if (!is_empty_string(rootfs
->mnt_opts
.userns_path
)) {
544 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supported with separate rootfs for container");
546 if (rootfs
->bdev_type
&& !strequal(rootfs
->bdev_type
, "dir"))
547 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supports the \"dir\" storage driver");
551 if (rootfs
->bdev_type
&&
552 (strequal(rootfs
->bdev_type
, "overlay") ||
553 strequal(rootfs
->bdev_type
, "overlayfs")))
554 return log_trace_errno(0, EINVAL
, "Not pinning on stacking filesystem");
556 dfd_path
= open_at(-EBADF
, rootfs
->path
, PROTECT_OPATH_FILE
, 0, 0);
558 dfd_path
= open_at(-EBADF
, "/", PROTECT_OPATH_FILE
, PROTECT_LOOKUP_ABSOLUTE
, 0);
561 return syserror("Failed to open \"%s\"", rootfs
->path
);
564 TRACE("Not pinning because container does not have a rootfs");
569 TRACE("Not pinning because container runs in user namespace");
573 ret
= fstat(dfd_path
, &st
);
575 return log_trace_errno(-errno
, errno
, "Failed to retrieve file status");
577 if (!S_ISDIR(st
.st_mode
))
578 return log_trace_errno(0, ENOTDIR
, "Not pinning because file descriptor is not a directory");
580 fd_pin
= open_at(dfd_path
, ".lxc_keep",
581 PROTECT_OPEN
| O_CREAT
,
582 PROTECT_LOOKUP_BENEATH
,
585 return syserror("Failed to pin rootfs");
587 TRACE("Pinned rootfs %d(.lxc_keep)", fd_pin
);
589 ret
= fstatfs(fd_pin
, &stfs
);
591 SYSWARN("Failed to retrieve filesystem status");
595 if (stfs
.f_type
== NFS_SUPER_MAGIC
) {
596 DEBUG("Not unlinking pinned file on NFS");
600 if (unlinkat(dfd_path
, ".lxc_keep", 0))
601 SYSTRACE("Failed to unlink rootfs pinning file %d(.lxc_keep)", dfd_path
);
603 TRACE("Unlinked pinned file %d(.lxc_keep)", dfd_path
);
606 rootfs
->fd_path_pin
= move_fd(fd_pin
);
607 rootfs
->mnt_opts
.userns_fd
= move_fd(fd_userns
);
611 int lxc_rootfs_prepare_parent(struct lxc_handler
*handler
)
613 __do_close
int dfd_idmapped
= -EBADF
, fd_userns
= -EBADF
;
614 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
615 struct lxc_storage
*storage
= rootfs
->storage
;
617 const char *path_source
;
619 if (lxc_list_empty(&handler
->conf
->id_map
))
622 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
625 if (handler
->conf
->rootfs_setup
)
628 if (rootfs_is_blockdev(handler
->conf
))
629 return syserror_set(-EOPNOTSUPP
, "Idmapped mounts on block-backed storage not yet supported");
631 if (!can_use_bind_mounts())
632 return syserror_set(-EOPNOTSUPP
, "Kernel does not support the new mount api");
634 if (rootfs
->mnt_opts
.userns_self
)
635 fd_userns
= dup_cloexec(handler
->nsfd
[LXC_NS_USER
]);
637 fd_userns
= open_at(-EBADF
, rootfs
->mnt_opts
.userns_path
,
638 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
640 return syserror("Failed to open user namespace");
642 path_source
= lxc_storage_get_path(storage
->src
, storage
->type
);
644 dfd_idmapped
= create_detached_idmapped_mount(path_source
, fd_userns
, true);
645 if (dfd_idmapped
< 0)
646 return syserror("Failed to create detached idmapped mount");
648 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &dfd_idmapped
, 1, NULL
, 0);
650 return syserror("Failed to send detached idmapped mount fd");
652 TRACE("Created detached idmapped mount %d", dfd_idmapped
);
656 static int add_shmount_to_list(struct lxc_conf
*conf
)
658 char new_mount
[PATH_MAX
];
659 /* Offset for the leading '/' since the path_cont
660 * is absolute inside the container.
662 int offset
= 1, ret
= -1;
664 ret
= strnprintf(new_mount
, sizeof(new_mount
),
665 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
666 conf
->shmount
.path_cont
+ offset
);
670 return add_elem_to_mount_list(new_mount
, conf
);
673 static int lxc_mount_auto_mounts(struct lxc_handler
*handler
, int flags
)
680 const char *destination
;
684 bool requires_cap_net_admin
;
685 } default_mounts
[] = {
686 /* Read-only bind-mounting... In older kernels, doing that
687 * required to do one MS_BIND mount and then
688 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
689 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
690 * onwards. However, this apparently does not work on kernel
691 * 3.8. Unfortunately, on that very same kernel, doing the same
692 * trick as above doesn't seem to work either, there one needs
693 * to ALSO specify MS_BIND for the remount, otherwise the
694 * entire fs is remounted read-only or the mount fails because
695 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
696 * kernels as low as 2.6.32...
698 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
699 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
700 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
, true },
701 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
, false },
702 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
703 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
, true },
704 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
, false },
705 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
706 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
707 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
, false },
708 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
, false },
709 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
710 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
, false },
711 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
712 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
, false },
713 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys/devices/virtual/net/devices/virtual/net", "%r/sys/devices/virtual/net", NULL
, MS_BIND
, NULL
, false },
714 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys/devices/virtual/net", NULL
, MS_REMOUNT
|MS_BIND
|MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
, false },
715 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
, false }
717 struct lxc_conf
*conf
= handler
->conf
;
718 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
719 bool has_cap_net_admin
;
721 if (flags
& LXC_AUTO_PROC_MASK
) {
722 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc",
723 rootfs
->path
? rootfs
->mount
: "");
725 return ret_errno(EIO
);
727 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
729 SYSDEBUG("Tried to ensure procfs is unmounted");
731 ret
= mkdirat(rootfs
->dfd_mnt
, "proc" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
732 if (ret
< 0 && errno
!= EEXIST
)
733 return syserror("Failed to create procfs mountpoint under %d", rootfs
->dfd_mnt
);
736 if (flags
& LXC_AUTO_SYS_MASK
) {
737 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/sys",
738 rootfs
->path
? rootfs
->mount
: "");
740 return ret_errno(EIO
);
742 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
744 SYSDEBUG("Tried to ensure sysfs is unmounted");
746 ret
= mkdirat(rootfs
->dfd_mnt
, "sys" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
747 if (ret
< 0 && errno
!= EEXIST
)
748 return syserror("Failed to create sysfs mountpoint under %d", rootfs
->dfd_mnt
);
751 has_cap_net_admin
= lxc_wants_cap(CAP_NET_ADMIN
, conf
);
752 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
753 __do_free
char *destination
= NULL
, *source
= NULL
;
754 unsigned long mflags
;
756 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
759 if (default_mounts
[i
].source
) {
760 /* will act like strdup if %r is not present */
761 source
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].source
);
763 return syserror_set(-ENOMEM
, "Failed to create source path");
766 if (!default_mounts
[i
].destination
)
767 return syserror_set(-EINVAL
, "BUG: auto mounts destination %d was NULL", i
);
769 if (!has_cap_net_admin
&& default_mounts
[i
].requires_cap_net_admin
) {
770 TRACE("Container does not have CAP_NET_ADMIN. Skipping \"%s\" mount", default_mounts
[i
].source
?: "(null)");
774 /* will act like strdup if %r is not present */
775 destination
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].destination
);
777 return syserror_set(-ENOMEM
, "Failed to create target path");
779 mflags
= add_required_remount_flags(source
, destination
,
780 default_mounts
[i
].flags
);
781 ret
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
782 mflags
, default_mounts
[i
].options
,
783 rootfs
->path
? rootfs
->mount
: NULL
);
786 return syserror("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
788 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source
, destination
);
791 TRACE("Mounted automount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
794 if (flags
& LXC_AUTO_CGROUP_MASK
) {
797 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
798 /* If the type of cgroup mount was not specified, it depends on
799 * the container's capabilities as to what makes sense: if we
800 * have CAP_SYS_ADMIN, the read-only part can be remounted
801 * read-write anyway, so we may as well default to read-write;
802 * then the admin will not be given a false sense of security.
803 * (And if they really want mixed r/o r/w, then they can
804 * explicitly specify :mixed.) OTOH, if the container lacks
805 * CAP_SYS_ADMIN, do only default to :mixed, because then the
806 * container can't remount it read-write.
808 if ((cg_flags
== LXC_AUTO_CGROUP_NOSPEC
) || (cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
)) {
809 int has_sys_admin
= 0;
811 if (!lxc_list_empty(&conf
->keepcaps
))
812 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
814 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
816 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
817 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
819 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
822 if (flags
& LXC_AUTO_CGROUP_FORCE
)
823 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
825 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
, handler
, cg_flags
))
826 return log_error_errno(-1, errno
, "Failed to mount \"/sys/fs/cgroup\"");
829 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
830 ret
= add_shmount_to_list(conf
);
832 return log_error(-1, "Failed to add shmount entry to container config");
838 static int setup_utsname(struct utsname
*utsname
)
845 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
847 return log_error_errno(-1, errno
, "Failed to set the hostname to \"%s\"",
850 INFO("Set hostname to \"%s\"", utsname
->nodename
);
855 struct dev_symlinks
{
860 static const struct dev_symlinks dev_symlinks
[] = {
861 { "/proc/self/fd", "fd" },
862 { "/proc/self/fd/0", "stdin" },
863 { "/proc/self/fd/1", "stdout" },
864 { "/proc/self/fd/2", "stderr" },
867 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
869 for (int i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
872 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
875 * Stat the path first. If we don't get an error accept it as
876 * is and don't try to create it
878 ret
= fstatat(rootfs
->dfd_dev
, d
->name
, &s
, 0);
882 ret
= symlinkat(d
->oldpath
, rootfs
->dfd_dev
, d
->name
);
886 WARN("Failed to create \"%s\" on read-only filesystem", d
->name
);
891 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", d
->name
);
899 /* Build a space-separate list of ptys to pass to systemd. */
900 static bool append_ttyname(char **pp
, char *name
)
906 *pp
= zalloc(strlen(name
) + strlen("container_ttys=") + 1);
910 sprintf(*pp
, "container_ttys=%s", name
);
914 size
= strlen(*pp
) + strlen(name
) + 2;
915 p
= realloc(*pp
, size
);
920 (void)strlcat(p
, " ", size
);
921 (void)strlcat(p
, name
, size
);
926 static int lxc_setup_ttys(struct lxc_conf
*conf
)
929 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
930 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
931 char *ttydir
= ttys
->dir
;
933 if (!conf
->rootfs
.path
)
936 for (int i
= 0; i
< ttys
->max
; i
++) {
937 __do_close
int fd_to
= -EBADF
;
938 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
941 char *tty_name
, *tty_path
;
943 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
944 "/dev/%s/tty%d", ttydir
, i
+ 1);
946 return ret_errno(-EIO
);
948 tty_path
= &rootfs
->buf
[STRLITERALLEN("/dev/")];
949 tty_name
= tty_path
+ strlen(ttydir
) + 1;
951 /* create bind-mount target */
952 fd_to
= open_at(rootfs
->dfd_dev
, tty_path
,
953 PROTECT_OPEN_W
| O_CREAT
,
954 PROTECT_LOOKUP_BENEATH
, 0);
956 return log_error_errno(-errno
, errno
,
957 "Failed to create tty mount target %d(%s)",
958 rootfs
->dfd_dev
, tty_path
);
960 ret
= unlinkat(rootfs
->dfd_dev
, tty_name
, 0);
961 if (ret
< 0 && errno
!= ENOENT
)
962 return log_error_errno(-errno
, errno
,
963 "Failed to unlink %d(%s)",
964 rootfs
->dfd_dev
, tty_name
);
966 if (can_use_mount_api()) {
967 ret
= fd_bind_mount(tty
->pty
, "",
969 PROTECT_LOOKUP_BENEATH_XDEV
,
972 PROTECT_LOOKUP_BENEATH_XDEV
, 0,
975 ret
= mount(tty
->name
, rootfs
->buf
, "none", MS_BIND
, 0);
978 return log_error_errno(-errno
, errno
,
979 "Failed to bind mount \"%s\" onto \"%s\"",
980 tty
->name
, rootfs
->buf
);
981 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
983 ret
= symlinkat(tty_path
, rootfs
->dfd_dev
, tty_name
);
985 return log_error_errno(-errno
, errno
,
986 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
987 rootfs
->dfd_dev
, tty_name
,
988 rootfs
->dfd_dev
, tty_path
);
990 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "tty%d", i
+ 1);
992 return ret_errno(-EIO
);
994 /* If we populated /dev, then we need to create /dev/tty<idx>. */
995 fd_to
= open_at(rootfs
->dfd_dev
, rootfs
->buf
,
996 PROTECT_OPEN_W
| O_CREAT
,
997 PROTECT_LOOKUP_BENEATH
, 0);
999 return log_error_errno(-errno
, errno
,
1000 "Failed to create tty mount target %d(%s)",
1001 rootfs
->dfd_dev
, rootfs
->buf
);
1003 if (can_use_mount_api()) {
1004 ret
= fd_bind_mount(tty
->pty
, "",
1006 PROTECT_LOOKUP_BENEATH_XDEV
,
1009 PROTECT_LOOKUP_BENEATH
, 0,
1012 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/dev/tty%d", i
+ 1);
1014 return ret_errno(-EIO
);
1016 ret
= mount(tty
->name
, rootfs
->buf
, "none", MS_BIND
, 0);
1019 return log_error_errno(-errno
, errno
,
1020 "Failed to bind mount \"%s\" onto \"%s\"",
1021 tty
->name
, rootfs
->buf
);
1022 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1025 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
))
1026 return log_error(-1, "Error setting up container_ttys string");
1029 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
1033 define_cleanup_function(struct lxc_tty_info
*, lxc_delete_tty
);
1035 static int lxc_allocate_ttys(struct lxc_conf
*conf
)
1037 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*ttys
= &conf
->ttys
;
1040 /* no tty in the configuration */
1044 ttys
->tty
= zalloc(sizeof(struct lxc_terminal_info
) * ttys
->max
);
1048 for (size_t i
= 0; i
< conf
->ttys
.max
; i
++) {
1049 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1053 ret
= openpty(&tty
->ptx
, &tty
->pty
, NULL
, NULL
, NULL
);
1056 return log_error_errno(-ENOTTY
, ENOTTY
, "Failed to create tty %zu", i
);
1059 ret
= ttyname_r(tty
->pty
, tty
->name
, sizeof(tty
->name
));
1062 return log_error_errno(-ENOTTY
, ENOTTY
, "Failed to retrieve name of tty %zu pty", i
);
1065 DEBUG("Created tty with ptx fd %d and pty fd %d", tty
->ptx
, tty
->pty
);
1067 /* Prevent leaking the file descriptors to the container */
1068 ret
= fd_cloexec(tty
->ptx
, true);
1070 SYSWARN("Failed to set FD_CLOEXEC flag on ptx fd %d of tty device \"%s\"",
1071 tty
->ptx
, tty
->name
);
1073 ret
= fd_cloexec(tty
->pty
, true);
1075 SYSWARN("Failed to set FD_CLOEXEC flag on pty fd %d of tty device \"%s\"",
1076 tty
->pty
, tty
->name
);
1081 INFO("Finished creating %zu tty devices", ttys
->max
);
1086 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1091 for (int i
= 0; i
< ttys
->max
; i
++) {
1092 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1093 close_prot_errno_disarm(tty
->ptx
);
1094 close_prot_errno_disarm(tty
->pty
);
1097 free_disarm(ttys
->tty
);
1100 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1104 struct lxc_conf
*conf
= handler
->conf
;
1105 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1106 int sock
= handler
->data_sock
[0];
1111 for (i
= 0; i
< ttys
->max
; i
++) {
1113 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1115 ttyfds
[0] = tty
->ptx
;
1116 ttyfds
[1] = tty
->pty
;
1118 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1122 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1123 tty
->name
, tty
->ptx
, tty
->pty
);
1127 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1129 TRACE("Sent %zu ttys to parent", ttys
->max
);
1134 static int lxc_create_ttys(struct lxc_handler
*handler
)
1137 struct lxc_conf
*conf
= handler
->conf
;
1139 ret
= lxc_allocate_ttys(conf
);
1141 ERROR("Failed to allocate ttys");
1145 ret
= lxc_send_ttys_to_parent(handler
);
1147 ERROR("Failed to send ttys to parent");
1151 if (!conf
->is_execute
) {
1152 ret
= lxc_setup_ttys(conf
);
1154 ERROR("Failed to setup ttys");
1159 if (conf
->ttys
.tty_names
) {
1160 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1162 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1168 lxc_delete_tty(&conf
->ttys
);
1173 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1174 * error, log it but don't fail yet.
1176 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1177 int autodevtmpfssize
, const char *lxcpath
)
1179 __do_close
int fd_fs
= -EBADF
;
1180 const char *path
= rootfs
->path
? rootfs
->mount
: NULL
;
1181 size_t tmpfs_size
= (autodevtmpfssize
!= 0) ? autodevtmpfssize
: 500000;
1184 char mount_options
[128];
1186 INFO("Preparing \"/dev\"");
1188 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1189 ret
= mkdirat(rootfs
->dfd_mnt
, "dev" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1190 if (ret
< 0 && errno
!= EEXIST
) {
1191 SYSERROR("Failed to create \"/dev\" directory");
1196 if (can_use_mount_api()) {
1197 fd_fs
= fs_prepare("tmpfs", -EBADF
, "", 0, 0);
1199 return log_error_errno(-errno
, errno
, "Failed to prepare filesystem context for tmpfs");
1201 sprintf(mount_options
, "%zu", tmpfs_size
);
1203 ret
= fs_set_property(fd_fs
, "mode", "0755");
1205 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1207 ret
= fs_set_property(fd_fs
, "size", mount_options
);
1209 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1211 ret
= fs_attach(fd_fs
, rootfs
->dfd_mnt
, "dev", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH
, 0);
1213 __do_free
char *fallback_path
= NULL
;
1215 sprintf(mount_options
, "size=%zu,mode=755", tmpfs_size
);
1216 DEBUG("Using mount options: %s", mount_options
);
1219 fallback_path
= must_make_path(path
, "/dev", NULL
);
1220 ret
= safe_mount("none", fallback_path
, "tmpfs", 0, mount_options
, path
);
1222 ret
= safe_mount("none", "dev", "tmpfs", 0, mount_options
, NULL
);
1226 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1231 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1232 * If not, then create it and exit if that fails...
1234 ret
= mkdirat(rootfs
->dfd_mnt
, "dev/pts", S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1235 if (ret
< 0 && errno
!= EEXIST
) {
1236 SYSERROR("Failed to create directory \"dev/pts\"");
1244 (void)umask(cur_mask
);
1246 INFO("Prepared \"/dev\"");
1250 struct lxc_device_node
{
1257 static const struct lxc_device_node lxc_devices
[] = {
1258 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1259 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1260 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1261 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1262 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1263 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1270 LXC_DEVNODE_PARTIAL
,
1274 static int lxc_fill_autodev(struct lxc_rootfs
*rootfs
)
1278 int use_mknod
= LXC_DEVNODE_MKNOD
;
1280 if (rootfs
->dfd_dev
< 0)
1281 return log_info(0, "No /dev directory found, skipping setup");
1283 INFO("Populating \"/dev\"");
1285 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1286 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1287 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1289 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1290 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, device
->mode
, makedev(device
->maj
, device
->min
));
1291 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1292 DEBUG("Created device node \"%s\"", device
->name
);
1293 } else if (ret
< 0) {
1295 return log_error_errno(-1, errno
, "Failed to create device node \"%s\"", device
->name
);
1297 use_mknod
= LXC_DEVNODE_BIND
;
1300 /* Device nodes are fully useable. */
1301 if (use_mknod
== LXC_DEVNODE_OPEN
)
1304 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1305 __do_close
int fd
= -EBADF
;
1307 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1308 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1310 fd
= open_at(rootfs
->dfd_dev
, device
->name
, PROTECT_OPEN
, PROTECT_LOOKUP_BENEATH
, 0);
1312 /* Device nodes are fully useable. */
1313 use_mknod
= LXC_DEVNODE_OPEN
;
1317 SYSTRACE("Failed to open \"%s\" device", device
->name
);
1318 /* Device nodes are only partially useable. */
1319 use_mknod
= LXC_DEVNODE_PARTIAL
;
1323 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1324 /* If we are dealing with partially functional device
1325 * nodes the prio mknod() call will have created the
1326 * device node so we can use it as a bind-mount target.
1328 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, S_IFREG
| 0000, 0);
1329 if (ret
< 0 && errno
!= EEXIST
)
1330 return log_error_errno(-1, errno
, "Failed to create file \"%s\"", device
->name
);
1333 /* Fallback to bind-mounting the device from the host. */
1334 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "dev/%s", device
->name
);
1336 return ret_errno(EIO
);
1338 if (can_use_mount_api()) {
1339 ret
= fd_bind_mount(rootfs
->dfd_host
, rootfs
->buf
,
1341 PROTECT_LOOKUP_BENEATH_XDEV
,
1342 rootfs
->dfd_dev
, device
->name
,
1344 PROTECT_LOOKUP_BENEATH
, 0, false);
1346 char path
[PATH_MAX
];
1348 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/dev/%s", device
->name
);
1350 return ret_errno(EIO
);
1352 ret
= strnprintf(path
, sizeof(path
), "%s/dev/%s", get_rootfs_mnt(rootfs
), device
->name
);
1354 return log_error(-1, "Failed to create device path for %s", device
->name
);
1356 ret
= safe_mount(rootfs
->buf
, path
, 0, MS_BIND
, NULL
, get_rootfs_mnt(rootfs
));
1358 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1360 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1363 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs
->dfd_host
, rootfs
->buf
, rootfs
->dfd_dev
, device
->name
);
1367 INFO("Populated \"/dev\"");
1371 static int lxc_mount_rootfs(struct lxc_rootfs
*rootfs
)
1375 if (!rootfs
->path
) {
1376 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1378 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
1380 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1381 if (rootfs
->dfd_mnt
< 0)
1387 ret
= access(rootfs
->mount
, F_OK
);
1389 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1392 ret
= rootfs
->storage
->ops
->mount(rootfs
->storage
);
1394 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1395 rootfs
->path
, rootfs
->mount
,
1396 rootfs
->options
? rootfs
->options
: "(null)");
1398 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1399 rootfs
->path
, rootfs
->mount
,
1400 rootfs
->options
? rootfs
->options
: "(null)");
1402 rootfs
->dfd_mnt
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1403 if (rootfs
->dfd_mnt
< 0)
1409 static int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1411 __do_free
char *nroot
= NULL
;
1413 char *root
= rootfs
->mount
;
1415 nroot
= realpath(root
, NULL
);
1417 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1423 /* We could use here MS_MOVE, but in userns this mount is locked and
1426 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1428 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1430 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1432 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1434 /* The following code cleans up inherited mounts which are not required
1437 * The mountinfo file shows not all mounts, if a few points have been
1438 * unmounted between read operations from the mountinfo. So we need to
1439 * read mountinfo a few times.
1441 * This loop can be skipped if a container uses userns, because all
1442 * inherited mounts are locked and we should live with all this trash.
1445 __do_fclose
FILE *f
= NULL
;
1446 __do_free
char *line
= NULL
;
1447 char *slider1
, *slider2
;
1451 f
= fopen("./proc/self/mountinfo", "re");
1453 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1455 while (getline(&line
, &len
, f
) > 0) {
1456 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1457 slider1
= strchr(slider1
+ 1, ' ');
1462 slider2
= strchr(slider1
+ 1, ' ');
1469 if (strequal(slider1
+ 1, "/"))
1472 if (strequal(slider1
+ 1, "/proc"))
1475 ret
= umount2(slider1
, MNT_DETACH
);
1484 /* This also can be skipped if a container uses userns. */
1485 (void)umount2("./proc", MNT_DETACH
);
1487 /* It is weird, but chdir("..") moves us in a new root */
1490 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1494 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1499 /* (The following explanation is copied verbatim from the kernel.)
1501 * pivot_root Semantics:
1502 * Moves the root file system of the current process to the directory put_old,
1503 * makes new_root as the new root file system of the current process, and sets
1504 * root/cwd of all processes which had them on the current root to new_root.
1507 * The new_root and put_old must be directories, and must not be on the
1508 * same file system as the current process root. The put_old must be
1509 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1510 * pointed to by put_old must yield the same directory as new_root. No other
1511 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1513 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1514 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1515 * in this situation.
1518 * - we don't move root/cwd if they are not at the root (reason: if something
1519 * cared enough to change them, it's probably wrong to force them elsewhere)
1520 * - it's okay to pick a root that isn't the root of a file system, e.g.
1521 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1522 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1525 static int lxc_pivot_root(const struct lxc_rootfs
*rootfs
)
1527 __do_close
int fd_oldroot
= -EBADF
;
1530 fd_oldroot
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1532 return log_error_errno(-1, errno
, "Failed to open old root directory");
1534 /* change into new root fs */
1535 ret
= fchdir(rootfs
->dfd_mnt
);
1537 return log_error_errno(-errno
, errno
, "Failed to change into new root directory \"%s\"", rootfs
->mount
);
1539 /* pivot_root into our new root fs */
1540 ret
= pivot_root(".", ".");
1542 return log_error_errno(-errno
, errno
, "Failed to pivot into new root directory \"%s\"", rootfs
->mount
);
1544 /* At this point the old-root is mounted on top of our new-root. To
1545 * unmounted it we must not be chdir'd into it, so escape back to
1548 ret
= fchdir(fd_oldroot
);
1550 return log_error_errno(-errno
, errno
, "Failed to enter old root directory");
1553 * Make fd_oldroot a depedent mount to make sure our umounts don't
1554 * propagate to the host.
1556 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1558 return log_error_errno(-errno
, errno
, "Failed to recursively turn old root mount tree into dependent mount");
1560 ret
= umount2(".", MNT_DETACH
);
1562 return log_error_errno(-errno
, errno
, "Failed to detach old root directory");
1564 ret
= fchdir(rootfs
->dfd_mnt
);
1566 return log_error_errno(-errno
, errno
, "Failed to re-enter new root directory \"%s\"", rootfs
->mount
);
1568 TRACE("Changed into new rootfs \"%s\"", rootfs
->mount
);
1572 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1575 return log_debug(0, "Container does not have a rootfs");
1577 if (detect_ramfs_rootfs())
1578 return lxc_chroot(rootfs
);
1580 return lxc_pivot_root(rootfs
);
1583 static const struct id_map
*find_mapped_nsid_entry(const struct lxc_conf
*conf
,
1587 struct lxc_list
*it
;
1589 struct id_map
*retmap
= NULL
;
1591 /* Shortcut for container's root mappings. */
1593 if (idtype
== ID_TYPE_UID
)
1594 return conf
->root_nsuid_map
;
1596 if (idtype
== ID_TYPE_GID
)
1597 return conf
->root_nsgid_map
;
1600 lxc_list_for_each(it
, &conf
->id_map
) {
1602 if (map
->idtype
!= idtype
)
1605 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1614 int lxc_setup_devpts_parent(struct lxc_handler
*handler
)
1618 if (handler
->conf
->pty_max
<= 0)
1621 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1],
1622 &handler
->conf
->devpts_fd
,
1623 &handler
->conf
->devpts_fd
,
1624 sizeof(handler
->conf
->devpts_fd
));
1626 return log_error_errno(-1, errno
, "Failed to receive devpts fd from child");
1628 TRACE("Received devpts file descriptor %d from child", handler
->conf
->devpts_fd
);
1632 static int lxc_setup_devpts_child(struct lxc_handler
*handler
)
1634 __do_close
int devpts_fd
= -EBADF
;
1637 char devpts_mntopts
[256];
1638 char *mntopt_sets
[5];
1639 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1640 struct lxc_conf
*conf
= handler
->conf
;
1641 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1642 int sock
= handler
->data_sock
[0];
1644 if (conf
->pty_max
<= 0)
1645 return log_debug(0, "No new devpts instance will be mounted since no pts devices are requested");
1647 ret
= strnprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1648 default_devpts_mntopts
, conf
->pty_max
);
1652 (void)umount2("/dev/pts", MNT_DETACH
);
1654 /* Create mountpoint for devpts instance. */
1655 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1656 if (ret
< 0 && errno
!= EEXIST
)
1657 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1660 mntopt_sets
[0] = devpts_mntopts
;
1662 /* !gid=5 && max= */
1663 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1665 /* gid=5 && !max= */
1666 mntopt_sets
[2] = default_devpts_mntopts
;
1668 /* !gid=5 && !max= */
1669 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1672 mntopt_sets
[4] = NULL
;
1674 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1675 /* mount new devpts instance */
1676 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1682 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1683 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1685 devpts_fd
= open_at(rootfs
->dfd_dev
, "pts", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1686 if (devpts_fd
< 0) {
1688 TRACE("Failed to create detached devpts mount");
1689 ret
= lxc_abstract_unix_send_fds(sock
, NULL
, 0, &devpts_fd
, sizeof(int));
1691 ret
= lxc_abstract_unix_send_fds(sock
, &devpts_fd
, 1, NULL
, 0);
1694 return log_error_errno(-1, errno
, "Failed to send devpts fd to parent");
1696 TRACE("Sent devpts file descriptor %d to parent", devpts_fd
);
1698 /* Remove any pre-existing /dev/ptmx file. */
1699 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1701 if (errno
!= ENOENT
)
1702 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1704 DEBUG("Removed existing \"/dev/ptmx\" file");
1707 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1708 ret
= mknodat(rootfs
->dfd_dev
, "ptmx", S_IFREG
| 0000, 0);
1709 if (ret
< 0 && errno
!= EEXIST
)
1710 return log_error_errno(-1, errno
, "Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1711 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1713 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1714 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1716 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1718 /* Fallthrough and try to create a symlink. */
1719 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1721 /* Remove the dummy /dev/ptmx file we created above. */
1722 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1724 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1726 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1727 ret
= symlinkat("/dev/pts/ptmx", rootfs
->dfd_dev
, "/dev/ptmx");
1729 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1731 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1735 static int setup_personality(int persona
)
1739 #if HAVE_SYS_PERSONALITY_H
1743 ret
= personality(persona
);
1745 return log_error_errno(-1, errno
, "Failed to set personality to \"0x%x\"", persona
);
1747 INFO("Set personality to \"0x%x\"", persona
);
1753 static inline bool wants_console(const struct lxc_terminal
*terminal
)
1755 return !terminal
->path
|| !strequal(terminal
->path
, "none");
1758 static int lxc_bind_mount_console(const struct lxc_terminal
*console
,
1759 int dfd_to
, const char *path_to
)
1761 __do_close
int fd_pty
= -EBADF
;
1763 if (is_empty_string(console
->name
))
1764 return ret_errno(EINVAL
);
1767 * When the pty fd stashed in console->pty has been retrieved via the
1768 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1769 * allocating new pty devices we can't reopen it through openat2() or
1770 * created a detached mount through open_tree() from it. This means we
1771 * would need to mount using the path stased in console->name which is
1772 * unsafe. We could be mounting a device that isn't identical to the
1773 * one we've already safely opened and stashed in console->pty.
1774 * So, what we do is we open an O_PATH file descriptor for
1775 * console->name and verify that the opened fd and the fd we stashed in
1776 * console->pty refer to the same device. If they do we can go on and
1777 * created a detached mount based on the newly opened O_PATH file
1778 * descriptor and then safely mount.
1780 fd_pty
= open_at(-EBADF
, console
->name
, PROTECT_OPATH_FILE
,
1781 PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1783 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", console
->name
);
1785 if (!same_file_lax(console
->pty
, fd_pty
))
1786 return log_error_errno(-EINVAL
, EINVAL
, "Console file descriptor changed");
1789 * Note, there are intentionally no open or lookup restrictions since
1790 * we're operating directly on the fd.
1792 return fd_bind_mount(fd_pty
, "", 0, 0,
1793 dfd_to
, path_to
, PROTECT_OPATH_FILE
, PROTECT_LOOKUP_BENEATH
,
1797 static int lxc_setup_dev_console(struct lxc_rootfs
*rootfs
,
1798 const struct lxc_terminal
*console
)
1801 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1804 * When we are asked to setup a console we remove any previous
1805 * /dev/console bind-mounts.
1807 if (exists_file_at(rootfs
->dfd_dev
, "console")) {
1808 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
1812 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
1814 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
1816 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
1820 * For unprivileged containers autodev or automounts will already have
1821 * taken care of creating /dev/console.
1823 ret
= mknodat(rootfs
->dfd_dev
, "console", S_IFREG
| 0000, 0);
1824 if (ret
< 0 && errno
!= EEXIST
)
1825 return log_error_errno(-errno
, errno
, "Failed to create console");
1827 ret
= fchmod(console
->pty
, 0620);
1829 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1831 if (can_use_mount_api()) {
1832 ret
= lxc_bind_mount_console(console
, rootfs
->dfd_dev
, "console");
1834 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
1838 ret
= safe_mount(console
->name
, rootfs
->buf
, "none", MS_BIND
, NULL
, rootfs_path
);
1841 return log_error_errno(ret
, errno
, "Failed to mount %d(%s) on \"%s\"", console
->pty
, console
->name
, rootfs
->buf
);
1843 DEBUG("Mounted pty device %d(%s) onto \"/dev/console\"", console
->pty
, console
->name
);
1847 static int lxc_setup_ttydir_console(struct lxc_rootfs
*rootfs
,
1848 const struct lxc_terminal
*console
,
1852 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1853 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1855 /* create rootfs/dev/<ttydir> directory */
1856 ret
= strnprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1860 ret
= mkdir(path
, 0755);
1861 if (ret
&& errno
!= EEXIST
)
1862 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", path
);
1863 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1865 ret
= strnprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1869 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1870 if (ret
< 0 && errno
!= EEXIST
)
1871 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", lxcpath
);
1873 ret
= strnprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1877 if (file_exists(path
)) {
1878 ret
= lxc_unstack_mountpoint(path
, false);
1880 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", path
);
1882 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1885 ret
= mknod(path
, S_IFREG
| 0000, 0);
1886 if (ret
< 0 && errno
!= EEXIST
)
1887 return log_error_errno(-errno
, errno
, "Failed to create console");
1889 ret
= fchmod(console
->pty
, 0620);
1891 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1893 /* bind mount console->name to '/dev/<ttydir>/console' */
1894 if (can_use_mount_api()) {
1895 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/console", ttydir
);
1899 ret
= lxc_bind_mount_console(console
, rootfs
->dfd_dev
, rootfs
->buf
);
1901 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1904 return log_error_errno(ret
, errno
, "Failed to mount %d(%s) on \"%s\"", console
->pty
, console
->name
, lxcpath
);
1905 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1907 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1908 if (can_use_mount_api()) {
1909 ret
= fd_bind_mount(rootfs
->dfd_dev
, rootfs
->buf
,
1910 PROTECT_OPATH_FILE
, PROTECT_LOOKUP_BENEATH_XDEV
,
1911 rootfs
->dfd_dev
, "console",
1912 PROTECT_OPATH_FILE
, PROTECT_LOOKUP_BENEATH
,
1915 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1918 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1919 DEBUG("Mounted \"%s\" onto \"%s\"", lxcpath
, path
);
1921 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1925 static int lxc_setup_console(const struct lxc_handler
*handler
,
1926 struct lxc_rootfs
*rootfs
,
1927 struct lxc_terminal
*console
, char *ttydir
)
1929 __do_close
int fd_pty
= -EBADF
;
1932 if (!wants_console(console
))
1933 return log_trace(0, "Skipping console setup");
1936 ret
= lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1938 ret
= lxc_setup_dev_console(rootfs
, console
);
1939 fd_pty
= move_fd(console
->pty
);
1942 * Some init's such as busybox will set sane tty settings on stdin,
1943 * stdout, stderr which it thinks is the console. We already set them
1944 * the way we wanted on the real terminal, and we want init to do its
1945 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
1946 * make sure that that pty is stdin,stdout,stderr.
1949 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
1950 ret
= set_stdfds(fd_pty
);
1952 ret
= lxc_terminal_set_stdfds(fd_pty
);
1954 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", fd_pty
);
1960 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1964 /* If '=' is contained in opt, the option must go into data. */
1965 if (!strchr(opt
, '=')) {
1967 * If opt is found in mount_opt, set or clear flags.
1968 * Otherwise append it to data.
1970 size_t opt_len
= strlen(opt
);
1971 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1972 size_t mo_name_len
= strlen(mo
->name
);
1974 if (opt_len
== mo_name_len
&& strnequal(opt
, mo
->name
, mo_name_len
)) {
1976 *flags
&= ~mo
->flag
;
1984 if (strlen(*data
)) {
1985 ret
= strlcat(*data
, ",", size
);
1987 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
1990 ret
= strlcat(*data
, opt
, size
);
1992 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
1997 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1999 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2000 char *mntopt_cur
= NULL
;
2003 if (*mntdata
|| *mntflags
)
2004 return ret_errno(EINVAL
);
2009 mntopts_dup
= strdup(mntopts
);
2011 return ret_errno(ENOMEM
);
2013 size
= strlen(mntopts_dup
) + 1;
2014 mntopts_new
= zalloc(size
);
2016 return ret_errno(ENOMEM
);
2018 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
2019 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
2020 return ret_errno(EINVAL
);
2023 *mntdata
= move_ptr(mntopts_new
);
2028 static void parse_propagationopt(char *opt
, unsigned long *flags
)
2030 struct mount_opt
*mo
;
2032 /* If opt is found in propagation_opt, set or clear flags. */
2033 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
2034 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2038 *flags
&= ~mo
->flag
;
2046 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
2048 __do_free
char *s
= NULL
;
2054 s
= strdup(mntopts
);
2056 return log_error_errno(-ENOMEM
, errno
, "Failed to allocate memory");
2059 lxc_iterate_parts(p
, s
, ",")
2060 parse_propagationopt(p
, pflags
);
2065 static void null_endofword(char *word
)
2067 while (*word
&& *word
!= ' ' && *word
!= '\t')
2072 /* skip @nfields spaces in @src */
2073 static char *get_field(char *src
, int nfields
)
2078 for (i
= 0; i
< nfields
; i
++) {
2079 while (*p
&& *p
!= ' ' && *p
!= '\t')
2091 static int mount_entry(const char *fsname
, const char *target
,
2092 const char *fstype
, unsigned long mountflags
,
2093 unsigned long pflags
, const char *data
, bool optional
,
2094 bool dev
, bool relative
, const char *rootfs
)
2097 char srcbuf
[PATH_MAX
];
2098 const char *srcpath
= fsname
;
2104 ret
= strnprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2106 return log_error_errno(-1, errno
, "source path is too long");
2110 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2114 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2115 srcpath
? srcpath
: "(null)", target
);
2117 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2118 srcpath
? srcpath
: "(null)", target
);
2121 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2123 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2124 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2127 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2128 unsigned long required_flags
= 0;
2130 if (sb
.f_flag
& MS_NOSUID
)
2131 required_flags
|= MS_NOSUID
;
2133 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2134 required_flags
|= MS_NODEV
;
2136 if (sb
.f_flag
& MS_RDONLY
)
2137 required_flags
|= MS_RDONLY
;
2139 if (sb
.f_flag
& MS_NOEXEC
)
2140 required_flags
|= MS_NOEXEC
;
2142 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2143 srcpath
, sb
.f_flag
, required_flags
);
2145 /* If this was a bind mount request, and required_flags
2146 * does not have any flags which are not already in
2147 * mountflags, then skip the remount.
2149 if (!(mountflags
& MS_REMOUNT
) &&
2150 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
2151 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
2155 mountflags
|= required_flags
;
2159 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2162 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2163 srcpath
? srcpath
: "(null)",
2166 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2167 srcpath
? srcpath
: "(null)",
2176 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2179 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2181 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2183 DEBUG("Changed mount propagation for \"%s\"", target
);
2186 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2187 srcpath
? srcpath
: "(null)", target
, fstype
);
2192 const char *lxc_mount_options_info
[LXC_MOUNT_MAX
] = {
2200 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2201 int parse_lxc_mntopts(struct lxc_mount_options
*opts
, char *mnt_opts
)
2203 for (size_t i
= LXC_MOUNT_CREATE_DIR
; i
< LXC_MOUNT_MAX
; i
++) {
2204 __do_close
int fd_userns
= -EBADF
;
2205 const char *opt_name
= lxc_mount_options_info
[i
];
2207 char *idmap_path
, *opt
, *opt_next
;
2209 opt
= strstr(mnt_opts
, opt_name
);
2214 case LXC_MOUNT_CREATE_DIR
:
2215 opts
->create_dir
= 1;
2217 case LXC_MOUNT_CREATE_FILE
:
2218 opts
->create_file
= 1;
2220 case LXC_MOUNT_OPTIONAL
:
2223 case LXC_MOUNT_RELATIVE
:
2226 case LXC_MOUNT_IDMAP
:
2228 opt_next
+= STRLITERALLEN("idmap=");
2229 idmap_path
= strchrnul(opt_next
, ',');
2230 len
= idmap_path
- opt_next
+ 1;
2232 if (len
>= sizeof(opts
->userns_path
))
2233 return syserror_set(-EIO
, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2235 memcpy(opts
->userns_path
, opt_next
, len
);
2237 if (is_empty_string(opts
->userns_path
))
2238 return syserror_set(-EINVAL
, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2240 if (strequal(opts
->userns_path
, "container")) {
2241 opts
->userns_self
= 1;
2243 fd_userns
= open(opts
->userns_path
, O_RDONLY
| O_NOCTTY
| O_CLOEXEC
);
2245 return syserror("Failed to open user namespace");
2248 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns
, opts
->userns_path
);
2251 return syserror_set(-EINVAL
, "Unknown LXC specific mount option");
2254 opt_next
= strchr(opt
, ',');
2256 *opt
= '\0'; /* no more mntopts, so just chop it here */
2258 memmove(opt
, opt_next
+ 1, strlen(opt_next
+ 1) + 1);
2264 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2266 const struct lxc_rootfs
*rootfs
,
2267 const char *lxc_name
, const char *lxc_path
)
2269 __do_free
char *p1
= NULL
;
2273 if (strnequal(mntent
->mnt_type
, "overlay", 7)) {
2274 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2279 if (hasmntopt(mntent
, "create=dir")) {
2280 ret
= mkdir_p(path
, 0755);
2281 if (ret
< 0 && errno
!= EEXIST
)
2282 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2285 if (!hasmntopt(mntent
, "create=file"))
2288 ret
= access(path
, F_OK
);
2298 ret
= mkdir_p(p2
, 0755);
2299 if (ret
< 0 && errno
!= EEXIST
)
2300 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2302 ret
= mknod(path
, S_IFREG
| 0000, 0);
2303 if (ret
< 0 && errno
!= EEXIST
)
2309 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2310 * without a rootfs. */
2311 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2313 const struct lxc_rootfs
*rootfs
,
2314 const char *lxc_name
,
2315 const char *lxc_path
)
2317 __do_free
char *mntdata
= NULL
;
2318 unsigned long mntflags
= 0, pflags
= 0;
2319 char *rootfs_path
= NULL
;
2321 bool dev
, optional
, relative
;
2322 struct lxc_mount_options opts
= {};
2324 optional
= hasmntopt(mntent
, "optional") != NULL
;
2325 dev
= hasmntopt(mntent
, "dev") != NULL
;
2326 relative
= hasmntopt(mntent
, "relative") != NULL
;
2328 if (rootfs
&& rootfs
->path
)
2329 rootfs_path
= rootfs
->mount
;
2331 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2340 ret
= parse_lxc_mntopts(&opts
, mntent
->mnt_opts
);
2344 if (!is_empty_string(opts
.userns_path
))
2345 return syserror_set(-EINVAL
, "Idmapped mount entries not yet supported");
2347 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2351 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2355 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2356 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2361 static inline int mount_entry_on_systemfs(struct lxc_rootfs
*rootfs
,
2362 struct mntent
*mntent
)
2366 /* For containers created without a rootfs all mounts are treated as
2367 * absolute paths starting at / on the host.
2369 if (mntent
->mnt_dir
[0] != '/')
2370 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/%s", mntent
->mnt_dir
);
2372 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s", mntent
->mnt_dir
);
2376 return mount_entry_on_generic(mntent
, rootfs
->buf
, NULL
, NULL
, NULL
);
2379 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2380 struct lxc_rootfs
*rootfs
,
2381 const char *lxc_name
,
2382 const char *lxc_path
)
2386 const char *lxcpath
;
2389 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2393 /* If rootfs->path is a blockdev path, allow container fstab to use
2394 * <lxcpath>/<name>/rootfs" as the target prefix.
2396 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s/rootfs", lxcpath
, lxc_name
);
2400 aux
= strstr(mntent
->mnt_dir
, rootfs
->buf
);
2402 offset
= strlen(rootfs
->buf
);
2407 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2409 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2410 offset
= strlen(rootfs
->path
);
2413 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, aux
+ offset
);
2417 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2420 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2421 struct lxc_rootfs
*rootfs
,
2422 const char *lxc_name
,
2423 const char *lxc_path
)
2427 /* relative to root mount point */
2428 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2432 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2435 static int mount_file_entries(struct lxc_rootfs
*rootfs
, FILE *file
,
2436 const char *lxc_name
, const char *lxc_path
)
2439 struct mntent mntent
;
2441 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2445 ret
= mount_entry_on_systemfs(rootfs
, &mntent
);
2446 else if (mntent
.mnt_dir
[0] != '/')
2447 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2448 lxc_name
, lxc_path
);
2450 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2451 lxc_name
, lxc_path
);
2456 if (!feof(file
) || ferror(file
))
2457 return log_error(-1, "Failed to parse mount entries");
2462 static inline void __auto_endmntent__(FILE **f
)
2468 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2470 static int setup_mount_fstab(struct lxc_rootfs
*rootfs
, const char *fstab
,
2471 const char *lxc_name
, const char *lxc_path
)
2473 __do_endmntent
FILE *f
= NULL
;
2479 f
= setmntent(fstab
, "re");
2481 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2483 ret
= mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2485 ERROR("Failed to set up mount entries");
2491 * In order for nested containers to be able to mount /proc and /sys they need
2492 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2494 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2495 * apparmor rule to deny access to them. This is mostly for convenience: The
2496 * container's root user can mount them anyway and thus has access to the two
2497 * file systems. But a non-root user in the container should not be allowed to
2498 * access them as a side effect without explicitly allowing it.
2500 static const char nesting_helpers
[] =
2501 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2502 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2504 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2505 bool include_nesting_helpers
)
2507 __do_close
int fd
= -EBADF
;
2511 struct lxc_list
*iterator
;
2513 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2515 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2517 if (errno
!= ENOSYS
)
2520 fd
= lxc_make_tmpfile(template, true);
2522 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2524 TRACE("Created temporary mount file");
2527 lxc_list_for_each (iterator
, mount
) {
2530 mount_entry
= iterator
->elem
;
2531 len
= strlen(mount_entry
);
2533 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2537 ret
= lxc_write_nointr(fd
, "\n", 1);
2542 if (include_nesting_helpers
) {
2543 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2544 STRARRAYLEN(nesting_helpers
));
2545 if (ret
!= STRARRAYLEN(nesting_helpers
))
2549 ret
= lseek(fd
, 0, SEEK_SET
);
2553 f
= fdopen(fd
, "re+");
2555 move_fd(fd
); /* Transfer ownership of fd. */
2559 static int setup_mount_entries(const struct lxc_conf
*conf
,
2560 struct lxc_rootfs
*rootfs
, struct lxc_list
*mount
,
2561 const char *lxc_name
, const char *lxc_path
)
2563 __do_fclose
FILE *f
= NULL
;
2565 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2569 return mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2572 static int parse_cap(const char *cap
)
2576 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2579 if (strequal(cap
, "none"))
2582 for (i
= 0; i
< end
; i
++) {
2583 if (!strequal(cap
, caps_opt
[i
].name
))
2586 capid
= caps_opt
[i
].value
;
2591 /* Try to see if it's numeric, so the user may specify
2592 * capabilities that the running kernel knows about but we
2596 capid
= strtol(cap
, &ptr
, 10);
2597 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2598 /* not a valid number */
2600 else if (capid
> lxc_caps_last_cap())
2601 /* we have a number but it's not a valid
2609 int in_caplist(int cap
, struct lxc_list
*caps
)
2612 struct lxc_list
*iterator
;
2614 lxc_list_for_each (iterator
, caps
) {
2615 capid
= parse_cap(iterator
->elem
);
2623 static int setup_caps(struct lxc_list
*caps
)
2627 struct lxc_list
*iterator
;
2629 lxc_list_for_each (iterator
, caps
) {
2632 drop_entry
= iterator
->elem
;
2634 capid
= parse_cap(drop_entry
);
2636 return log_error(-1, "unknown capability %s", drop_entry
);
2638 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2639 prctl_arg(0), prctl_arg(0));
2641 return log_error_errno(-1, errno
, "Failed to remove %s capability", drop_entry
);
2642 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2645 DEBUG("Capabilities have been setup");
2649 static int dropcaps_except(struct lxc_list
*caps
)
2651 __do_free
int *caplist
= NULL
;
2652 int i
, capid
, numcaps
;
2654 struct lxc_list
*iterator
;
2656 numcaps
= lxc_caps_last_cap() + 1;
2657 if (numcaps
<= 0 || numcaps
> 200)
2659 TRACE("Found %d capabilities", numcaps
);
2661 /* caplist[i] is 1 if we keep capability i */
2662 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2663 memset(caplist
, 0, numcaps
* sizeof(int));
2665 lxc_list_for_each (iterator
, caps
) {
2666 keep_entry
= iterator
->elem
;
2668 capid
= parse_cap(keep_entry
);
2673 return log_error(-1, "Unknown capability %s", keep_entry
);
2675 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2679 for (i
= 0; i
< numcaps
; i
++) {
2685 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2686 prctl_arg(0), prctl_arg(0));
2688 return log_error_errno(-1, errno
, "Failed to remove capability %d", i
);
2691 DEBUG("Capabilities have been setup");
2695 static int parse_resource(const char *res
)
2701 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2702 if (strequal(res
, limit_opt
[i
].name
))
2703 return limit_opt
[i
].value
;
2705 /* Try to see if it's numeric, so the user may specify
2706 * resources that the running kernel knows about but
2709 ret
= lxc_safe_int(res
, &resid
);
2716 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2719 struct lxc_list
*it
;
2720 struct lxc_limit
*lim
;
2722 lxc_list_for_each (it
, limits
) {
2725 resid
= parse_resource(lim
->resource
);
2727 return log_error(-1, "Unknown resource %s", lim
->resource
);
2729 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2730 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
2731 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
2733 TRACE("Setup \"%s\" limit", lim
->resource
);
2735 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2742 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2744 __do_free
char *tmp
= NULL
;
2745 struct lxc_list
*it
;
2746 struct lxc_sysctl
*elem
;
2748 char filename
[PATH_MAX
] = {0};
2750 lxc_list_for_each (it
, sysctls
) {
2752 tmp
= lxc_string_replace(".", "/", elem
->key
);
2754 return log_error(-1, "Failed to replace key %s", elem
->key
);
2756 ret
= strnprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2758 return log_error(-1, "Error setting up sysctl parameters path");
2760 ret
= lxc_write_to_file(filename
, elem
->value
,
2761 strlen(elem
->value
), false, 0666);
2763 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
2764 elem
->key
, elem
->value
);
2770 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2772 __do_free
char *tmp
= NULL
;
2773 struct lxc_list
*it
;
2774 struct lxc_proc
*elem
;
2776 char filename
[PATH_MAX
] = {0};
2778 lxc_list_for_each (it
, procs
) {
2780 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2782 return log_error(-1, "Failed to replace key %s", elem
->filename
);
2784 ret
= strnprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2786 return log_error(-1, "Error setting up proc filesystem path");
2788 ret
= lxc_write_to_file(filename
, elem
->value
,
2789 strlen(elem
->value
), false, 0666);
2791 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s", elem
->filename
, elem
->value
);
2797 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2799 struct lxc_conf
*lxc_conf_init(void)
2802 struct lxc_conf
*new;
2804 new = zalloc(sizeof(*new));
2808 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2809 new->personality
= -1;
2811 new->console
.buffer_size
= 0;
2812 new->console
.log_path
= NULL
;
2813 new->console
.log_fd
= -1;
2814 new->console
.log_size
= 0;
2815 new->console
.path
= NULL
;
2816 new->console
.peer
= -1;
2817 new->console
.proxy
.busy
= -1;
2818 new->console
.proxy
.ptx
= -1;
2819 new->console
.proxy
.pty
= -1;
2820 new->console
.ptx
= -EBADF
;
2821 new->console
.pty
= -EBADF
;
2822 new->console
.name
[0] = '\0';
2823 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2824 new->maincmd_fd
= -1;
2825 new->monitor_signal_pdeath
= SIGKILL
;
2827 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2828 if (!new->rootfs
.mount
) {
2832 new->rootfs
.managed
= true;
2833 new->rootfs
.dfd_mnt
= -EBADF
;
2834 new->rootfs
.dfd_dev
= -EBADF
;
2835 new->rootfs
.dfd_host
= -EBADF
;
2836 new->rootfs
.fd_path_pin
= -EBADF
;
2837 new->rootfs
.dfd_idmapped
= -EBADF
;
2838 new->rootfs
.mnt_opts
.userns_fd
= -EBADF
;
2840 lxc_list_init(&new->cgroup
);
2841 lxc_list_init(&new->cgroup2
);
2842 /* Block ("allowlist") all devices by default. */
2843 new->bpf_devices
.list_type
= LXC_BPF_DEVICE_CGROUP_ALLOWLIST
;
2844 lxc_list_init(&(new->bpf_devices
).device_item
);
2845 lxc_list_init(&new->network
);
2846 lxc_list_init(&new->mount_list
);
2847 lxc_list_init(&new->caps
);
2848 lxc_list_init(&new->keepcaps
);
2849 lxc_list_init(&new->id_map
);
2850 new->root_nsuid_map
= NULL
;
2851 new->root_nsgid_map
= NULL
;
2852 lxc_list_init(&new->includes
);
2853 lxc_list_init(&new->aliens
);
2854 lxc_list_init(&new->environment
);
2855 lxc_list_init(&new->limits
);
2856 lxc_list_init(&new->sysctls
);
2857 lxc_list_init(&new->procs
);
2858 new->hooks_version
= 0;
2859 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2860 lxc_list_init(&new->hooks
[i
]);
2861 lxc_list_init(&new->groups
);
2862 lxc_list_init(&new->state_clients
);
2863 new->lsm_aa_profile
= NULL
;
2864 lxc_list_init(&new->lsm_aa_raw
);
2865 new->lsm_se_context
= NULL
;
2866 new->lsm_se_keyring_context
= NULL
;
2867 new->keyring_disable_session
= false;
2868 new->transient_procfs_mnt
= false;
2869 new->shmount
.path_host
= NULL
;
2870 new->shmount
.path_cont
= NULL
;
2872 /* if running in a new user namespace, init and COMMAND
2873 * default to running as UID/GID 0 when using lxc-execute */
2876 memset(&new->init_groups
, 0, sizeof(lxc_groups_t
));
2877 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2878 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2879 memset(&new->timens
, 0, sizeof(struct timens_offsets
));
2880 seccomp_conf_init(new);
2885 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2888 __do_close
int fd
= -EBADF
;
2890 char path
[PATH_MAX
];
2892 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2893 __do_close
int setgroups_fd
= -EBADF
;
2895 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/setgroups", pid
);
2899 setgroups_fd
= open(path
, O_WRONLY
);
2900 if (setgroups_fd
< 0 && errno
!= ENOENT
)
2901 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2903 if (setgroups_fd
>= 0) {
2904 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
2905 STRLITERALLEN("deny\n"));
2906 if (ret
!= STRLITERALLEN("deny\n"))
2907 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
2908 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2912 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/%cid_map", pid
,
2913 idtype
== ID_TYPE_UID
? 'u' : 'g');
2917 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
2919 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2921 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2922 if (ret
!= buf_size
)
2923 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
2924 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2929 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2931 * @return 1 if functional binary was found
2932 * @return 0 if binary exists but is lacking privilege
2933 * @return -ENOENT if binary does not exist
2934 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2936 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2938 __do_free
char *path
= NULL
;
2942 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2943 return ret_errno(EINVAL
);
2945 path
= on_path(binary
, NULL
);
2947 return ret_errno(ENOENT
);
2949 ret
= stat(path
, &st
);
2953 /* Check if the binary is setuid. */
2954 if (st
.st_mode
& S_ISUID
)
2955 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
2957 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2958 /* Check if it has the CAP_SETUID capability. */
2959 if ((cap
& CAP_SETUID
) &&
2960 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2961 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
2962 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2964 /* Check if it has the CAP_SETGID capability. */
2965 if ((cap
& CAP_SETGID
) &&
2966 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2967 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
2968 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2973 * If we cannot check for file capabilities we need to give the benefit
2974 * of the doubt. Otherwise we might fail even though all the necessary
2975 * file capabilities are set.
2977 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
2982 static int lxc_map_ids_exec_wrapper(void *args
)
2984 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2988 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2993 char cmd_output
[PATH_MAX
];
2995 struct lxc_list
*iterator
;
2997 int ret
= 0, gidmap
= 0, uidmap
= 0;
2998 char mapbuf
[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
2999 INTTYPE_TO_STRLEN(pid_t
) + STRLITERALLEN(" ") +
3000 LXC_IDMAPLEN
] = {0};
3001 bool had_entry
= false, use_shadow
= false;
3002 int hostuid
, hostgid
;
3004 hostuid
= geteuid();
3005 hostgid
= getegid();
3007 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3008 * ranges, then insist that root also reserve ranges in subuid. This
3009 * will protected it by preventing another user from being handed the
3012 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
3013 if (uidmap
== -ENOENT
)
3014 WARN("newuidmap binary is missing");
3016 WARN("newuidmap is lacking necessary privileges");
3018 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
3019 if (gidmap
== -ENOENT
)
3020 WARN("newgidmap binary is missing");
3022 WARN("newgidmap is lacking necessary privileges");
3024 if (uidmap
> 0 && gidmap
> 0) {
3025 DEBUG("Functional newuidmap and newgidmap binary found");
3028 /* In case unprivileged users run application containers via
3029 * execute() or a start*() there are valid cases where they may
3030 * only want to map their own {g,u}id. Let's not block them from
3031 * doing so by requiring geteuid() == 0.
3033 DEBUG("No newuidmap and newgidmap binary found. Trying to "
3034 "write directly with euid %d", hostuid
);
3037 /* Check if we really need to use newuidmap and newgidmap.
3038 * If the user is only remapping his own {g,u}id, we don't need it.
3040 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
3042 lxc_list_for_each(iterator
, idmap
) {
3043 map
= iterator
->elem
;
3044 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3045 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3047 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3048 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3055 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3056 type
++, u_or_g
= 'g') {
3060 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3062 lxc_list_for_each(iterator
, idmap
) {
3063 map
= iterator
->elem
;
3064 if (map
->idtype
!= type
)
3069 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3070 fill
= strnprintf(pos
, left
, "%s%lu %lu %lu%s",
3071 use_shadow
? " " : "", map
->nsid
,
3072 map
->hostid
, map
->range
,
3073 use_shadow
? "" : "\n");
3075 * The kernel only takes <= 4k for writes to
3076 * /proc/<pid>/{g,u}id_map
3079 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
3086 /* Try to catch the output of new{g,u}idmap to make debugging
3090 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3091 lxc_map_ids_exec_wrapper
,
3094 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
3095 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3097 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3099 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
3100 TRACE("Wrote mapping \"%s\"", mapbuf
);
3103 memset(mapbuf
, 0, sizeof(mapbuf
));
3110 * Return the host uid/gid to which the container root is mapped in val.
3111 * Return true if id was found, false otherwise.
3113 static id_t
get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
)
3117 struct lxc_list
*it
;
3119 if (idtype
== ID_TYPE_UID
)
3120 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3122 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3124 lxc_list_for_each (it
, &conf
->id_map
) {
3126 if (map
->idtype
!= idtype
)
3128 if (map
->nsid
!= nsid
)
3133 if (idtype
== ID_TYPE_UID
)
3134 return LXC_INVALID_UID
;
3136 return LXC_INVALID_GID
;
3139 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
3142 struct lxc_list
*it
;
3144 lxc_list_for_each (it
, &conf
->id_map
) {
3146 if (map
->idtype
!= idtype
)
3149 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3150 return (id
- map
->hostid
) + map
->nsid
;
3156 int find_unmapped_nsid(const struct lxc_conf
*conf
, enum idtype idtype
)
3159 struct lxc_list
*it
;
3160 unsigned int freeid
= 0;
3163 lxc_list_for_each (it
, &conf
->id_map
) {
3165 if (map
->idtype
!= idtype
)
3168 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3169 freeid
= map
->nsid
+ map
->range
;
3178 * Mount a proc under @rootfs if proc self points to a pid other than
3179 * my own. This is needed to have a known-good proc mount for setting
3180 * up LSMs both at container startup and attach.
3182 * NOTE: not to be called from inside the container namespace!
3184 static int lxc_transient_proc(struct lxc_rootfs
*rootfs
)
3186 __do_close
int fd_proc
= -EBADF
;
3187 int link_to_pid
, link_len
, pid_self
, ret
;
3188 char link
[INTTYPE_TO_STRLEN(pid_t
) + 1];
3190 link_len
= readlinkat(rootfs
->dfd_mnt
, "proc/self", link
, sizeof(link
));
3192 ret
= mkdirat(rootfs
->dfd_mnt
, "proc", 0000);
3193 if (ret
< 0 && errno
!= EEXIST
)
3194 return log_error_errno(-errno
, errno
, "Failed to create %d(proc)", rootfs
->dfd_mnt
);
3197 } else if (link_len
>= sizeof(link
)) {
3198 return log_error_errno(-EIO
, EIO
, "Truncated link target");
3200 link
[link_len
] = '\0';
3202 pid_self
= lxc_raw_getpid();
3203 INFO("Caller's PID is %d; /proc/self points to %s", pid_self
, link
);
3205 ret
= lxc_safe_int(link
, &link_to_pid
);
3207 return log_error_errno(-ret
, ret
, "Failed to parse %s", link
);
3209 /* Correct procfs is already mounted. */
3210 if (link_to_pid
== pid_self
)
3211 return log_trace(0, "Correct procfs instance mounted");
3213 fd_proc
= open_at(rootfs
->dfd_mnt
, "proc", PROTECT_OPATH_DIRECTORY
,
3214 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
3216 return log_error_errno(-errno
, errno
, "Failed to open transient procfs mountpoint");
3218 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/proc/self/fd/%d", fd_proc
);
3220 return ret_errno(EIO
);
3222 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
3224 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs
->buf
);
3227 /* rootfs is NULL */
3228 if (!rootfs
->path
) {
3229 ret
= mount("proc", rootfs
->buf
, "proc", 0, NULL
);
3231 ret
= safe_mount_beneath_at(rootfs
->dfd_mnt
, "none", "proc", "proc", 0, NULL
);
3233 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc", rootfs
->path
? rootfs
->mount
: "");
3235 return ret_errno(EIO
);
3237 ret
= safe_mount("proc", rootfs
->buf
, "proc", 0, NULL
, rootfs
->mount
);
3241 return log_error_errno(-1, errno
, "Failed to mount temporary procfs");
3243 INFO("Created transient procfs mount");
3247 /* NOTE: Must not be called from inside the container namespace! */
3248 static int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3252 mounted
= lxc_transient_proc(&conf
->rootfs
);
3253 if (mounted
== -1) {
3254 /* continue only if there is no rootfs */
3255 if (conf
->rootfs
.path
)
3256 return log_error_errno(-EPERM
, EPERM
, "Failed to create transient procfs mount");
3257 } else if (mounted
== 1) {
3258 conf
->transient_procfs_mnt
= true;
3264 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3266 if (lxc_conf
->transient_procfs_mnt
) {
3267 (void)umount2("/proc", MNT_DETACH
);
3268 lxc_conf
->transient_procfs_mnt
= false;
3272 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
3273 static void turn_into_dependent_mounts(const struct lxc_rootfs
*rootfs
)
3275 __do_free
char *line
= NULL
;
3276 __do_fclose
FILE *f
= NULL
;
3277 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3282 mntinfo_fd
= open_at(rootfs
->dfd_host
, "proc/self/mountinfo", PROTECT_OPEN
,
3283 (PROTECT_LOOKUP_BENEATH_XDEV
& ~RESOLVE_NO_SYMLINKS
), 0);
3284 if (mntinfo_fd
< 0) {
3285 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs
->dfd_host
);
3289 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3291 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3293 if (errno
!= ENOSYS
) {
3294 SYSERROR("Failed to create temporary in-memory file");
3298 memfd
= lxc_make_tmpfile(template, true);
3300 WARN("Failed to create temporary file");
3305 copied
= fd_to_fd(mntinfo_fd
, memfd
);
3307 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3311 ret
= lseek(memfd
, 0, SEEK_SET
);
3313 SYSERROR("Failed to reset file descriptor offset");
3317 f
= fdopen(memfd
, "re");
3319 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3324 * After a successful fdopen() memfd will be closed when calling
3325 * fclose(f). Calling close(memfd) afterwards is undefined.
3329 while (getline(&line
, &len
, f
) != -1) {
3330 char *opts
, *target
;
3332 target
= get_field(line
, 4);
3336 opts
= get_field(target
, 2);
3340 null_endofword(opts
);
3341 if (!strstr(opts
, "shared"))
3344 null_endofword(target
);
3345 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3347 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3351 TRACE("Turned all mount table entries into dependent mount");
3354 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3358 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3359 struct lxc_conf
*conf
= handler
->conf
;
3361 /* If init exists in the container, don't bind mount a static one */
3362 p
= choose_init(conf
->rootfs
.mount
);
3364 __do_free
char *old
= p
;
3366 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3370 INFO("Found existing init at \"%s\"", p
);
3374 ret
= strnprintf(path
, sizeof(path
), SBINDIR
"/init.lxc.static");
3378 if (!file_exists(path
))
3379 return log_error_errno(-1, errno
, "The file \"%s\" does not exist on host", path
);
3381 ret
= strnprintf(destpath
, sizeof(path
), "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3385 if (!file_exists(destpath
)) {
3386 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3387 if (ret
< 0 && errno
!= EEXIST
)
3388 return log_error_errno(-1, errno
, "Failed to create dummy \"%s\" file as bind mount target", destpath
);
3391 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3393 return log_error_errno(-1, errno
, "Failed to bind mount lxc.init.static into container");
3395 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3399 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3401 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3402 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3406 /* This does the work of remounting / if it is shared, calling the container
3407 * pre-mount hooks, and mounting the rootfs.
3409 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3410 const char *lxcpath
)
3414 conf
->rootfs
.dfd_host
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
3415 if (conf
->rootfs
.dfd_host
< 0)
3416 return log_error_errno(-errno
, errno
, "Failed to open \"/\"");
3418 turn_into_dependent_mounts(&conf
->rootfs
);
3420 if (conf
->rootfs_setup
) {
3421 const char *path
= conf
->rootfs
.mount
;
3424 * The rootfs was set up in another namespace. bind-mount it to
3425 * give us a mount in our own ns so we can pivot_root to it
3427 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3429 return log_error(-1, "Failed to bind mount container / onto itself");
3431 conf
->rootfs
.dfd_mnt
= openat(-EBADF
, path
, O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOCTTY
);
3432 if (conf
->rootfs
.dfd_mnt
< 0)
3433 return log_error_errno(-errno
, errno
, "Failed to open file descriptor for container rootfs");
3435 return log_trace(0, "Bind mounted container / onto itself");
3438 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3440 return log_error(-1, "Failed to run pre-mount hooks");
3442 ret
= lxc_mount_rootfs(&conf
->rootfs
);
3444 return log_error(-1, "Failed to setup rootfs for");
3446 conf
->rootfs_setup
= true;
3450 static bool verify_start_hooks(struct lxc_conf
*conf
)
3452 char path
[PATH_MAX
];
3453 struct lxc_list
*it
;
3455 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3457 char *hookname
= it
->elem
;
3459 ret
= strnprintf(path
, sizeof(path
), "%s%s",
3460 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3465 ret
= access(path
, X_OK
);
3467 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
3475 static bool execveat_supported(void)
3477 execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3478 if (errno
== ENOSYS
)
3484 static int lxc_setup_boot_id(void)
3487 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3488 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
3491 if (access(boot_id_path
, F_OK
))
3494 memset(&n
, 0, sizeof(n
));
3495 if (lxc_id128_randomize(&n
)) {
3496 SYSERROR("Failed to generate random data for uuid");
3500 ret
= lxc_id128_write(mock_boot_id_path
, n
);
3502 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
3506 ret
= chmod(mock_boot_id_path
, 0444);
3508 SYSERROR("Failed to chown %s", mock_boot_id_path
);
3509 (void)unlink(mock_boot_id_path
);
3513 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
3515 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
3517 (void)unlink(mock_boot_id_path
);
3521 ret
= mount(NULL
, boot_id_path
, NULL
,
3522 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
3526 SYSERROR("Failed to remount %s read-only", boot_id_path
);
3527 (void)unlink(mock_boot_id_path
);
3534 static int lxc_setup_keyring(struct lsm_ops
*lsm_ops
, const struct lxc_conf
*conf
)
3536 key_serial_t keyring
;
3539 if (conf
->lsm_se_keyring_context
)
3540 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_keyring_context
);
3541 else if (conf
->lsm_se_context
)
3542 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_context
);
3544 return log_error_errno(-1, errno
, "Failed to set keyring context");
3547 * Try to allocate a new session keyring for the container to prevent
3548 * information leaks.
3550 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
3551 prctl_arg(0), prctl_arg(0), prctl_arg(0));
3555 DEBUG("The keyctl() syscall is not supported or blocked");
3560 DEBUG("Failed to access kernel keyring. Continuing...");
3563 SYSERROR("Failed to create kernel keyring");
3571 static int lxc_rootfs_prepare_child(struct lxc_handler
*handler
)
3573 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
3574 int dfd_idmapped
= -EBADF
;
3577 if (lxc_list_empty(&handler
->conf
->id_map
))
3580 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
3583 if (handler
->conf
->rootfs_setup
)
3586 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1], &dfd_idmapped
, NULL
, 0);
3588 return syserror("Failed to receive idmapped mount fd");
3590 rootfs
->dfd_idmapped
= dfd_idmapped
;
3591 TRACE("Received detached idmapped mount %d", rootfs
->dfd_idmapped
);
3595 int lxc_setup(struct lxc_handler
*handler
)
3598 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3599 struct lxc_conf
*lxc_conf
= handler
->conf
;
3601 ret
= lxc_rootfs_prepare_child(handler
);
3603 return syserror("Failed to prepare rootfs");
3605 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3607 return log_error(-1, "Failed to setup rootfs");
3609 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
3610 ret
= setup_utsname(lxc_conf
->utsname
);
3612 return log_error(-1, "Failed to setup the utsname %s", name
);
3615 if (!lxc_conf
->keyring_disable_session
) {
3616 ret
= lxc_setup_keyring(handler
->lsm_ops
, lxc_conf
);
3618 return log_error(-1, "Failed to setup container keyring");
3621 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
3622 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
,
3623 &lxc_conf
->network
);
3625 return log_error(-1, "Failed to setup network");
3627 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3629 return log_error(-1, "Failed to send network device names and ifindices to parent");
3632 if (lxc_conf
->autodev
> 0) {
3633 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
3635 return log_error(-1, "Failed to mount \"/dev\"");
3638 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3639 * need to wait until other stuff has finished.
3641 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
);
3643 return log_error(-1, "Failed to setup first automatic mounts");
3645 ret
= setup_mount_fstab(&lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3647 return log_error(-1, "Failed to setup mounts");
3649 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3650 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3651 &lxc_conf
->mount_list
, name
, lxcpath
);
3653 return log_error(-1, "Failed to setup mount entries");
3656 lxc_conf
->rootfs
.dfd_dev
= open_at(lxc_conf
->rootfs
.dfd_mnt
, "dev",
3657 PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
3658 if (lxc_conf
->rootfs
.dfd_dev
< 0 && errno
!= ENOENT
)
3659 return log_error_errno(-errno
, errno
, "Failed to open \"/dev\"");
3661 if (lxc_conf
->is_execute
) {
3662 if (execveat_supported()) {
3664 char path
[STRLITERALLEN(SBINDIR
) + STRLITERALLEN("/init.lxc.static") + 1];
3666 ret
= strnprintf(path
, sizeof(path
), SBINDIR
"/init.lxc.static");
3668 return log_error(-1, "Path to init.lxc.static too long");
3670 fd
= open(path
, O_NOCTTY
| O_NOFOLLOW
| O_CLOEXEC
| O_PATH
);
3672 return log_error_errno(-1, errno
, "Unable to open lxc.init.static");
3674 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3675 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3677 ret
= lxc_execute_bind_init(handler
);
3679 return log_error(-1, "Failed to bind-mount the lxc init system");
3683 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3684 * mounted. It is guaranteed to be mounted now either through
3685 * automatically or via fstab entries.
3687 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
);
3689 return log_error(-1, "Failed to setup remaining automatic mounts");
3691 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3693 return log_error(-1, "Failed to run mount hooks");
3695 if (lxc_conf
->autodev
> 0) {
3696 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3698 return log_error(-1, "Failed to run autodev hooks");
3700 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3702 return log_error(-1, "Failed to populate \"/dev\"");
3705 /* Make sure any start hooks are in the container */
3706 if (!verify_start_hooks(lxc_conf
))
3707 return log_error(-1, "Failed to verify start hooks");
3709 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3711 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
3713 ret
= lxc_setup_console(handler
, &lxc_conf
->rootfs
, &lxc_conf
->console
,
3714 lxc_conf
->ttys
.dir
);
3716 return log_error(-1, "Failed to setup console");
3718 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3720 return log_error(-1, "Failed to setup \"/dev\" symlinks");
3722 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3724 return log_error(-1, "Failed to pivot root into rootfs");
3726 /* Setting the boot-id is best-effort for now. */
3727 if (lxc_conf
->autodev
> 0)
3728 (void)lxc_setup_boot_id();
3730 ret
= lxc_setup_devpts_child(handler
);
3732 return log_error(-1, "Failed to setup new devpts instance");
3734 ret
= lxc_create_ttys(handler
);
3738 ret
= setup_personality(lxc_conf
->personality
);
3740 return log_error(-1, "Failed to set personality");
3742 /* Set sysctl value to a path under /proc/sys as determined from the
3743 * key. For e.g. net.ipv4.ip_forward translated to
3744 * /proc/sys/net/ipv4/ip_forward.
3746 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3747 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3749 return log_error(-1, "Failed to setup sysctl parameters");
3752 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3753 if (!lxc_list_empty(&lxc_conf
->caps
))
3754 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
3756 if (dropcaps_except(&lxc_conf
->keepcaps
))
3757 return log_error(-1, "Failed to keep capabilities");
3758 } else if (setup_caps(&lxc_conf
->caps
)) {
3759 return log_error(-1, "Failed to drop capabilities");
3762 put_lxc_rootfs(&handler
->conf
->rootfs
, true);
3763 NOTICE("The container \"%s\" is set up", name
);
3768 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3771 struct lxc_list
*it
;
3774 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
3775 if (strequal(hookname
, lxchook_names
[which
]))
3779 if (which
>= NUM_LXC_HOOKS
)
3782 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3784 char *hook
= it
->elem
;
3786 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3795 int lxc_clear_config_caps(struct lxc_conf
*c
)
3797 struct lxc_list
*it
, *next
;
3799 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3805 lxc_list_init(&c
->caps
);
3809 static int lxc_free_idmap(struct lxc_list
*id_map
)
3811 struct lxc_list
*it
, *next
;
3813 lxc_list_for_each_safe(it
, id_map
, next
) {
3819 lxc_list_init(id_map
);
3823 static int __lxc_free_idmap(struct lxc_list
*id_map
)
3825 lxc_free_idmap(id_map
);
3829 define_cleanup_function(struct lxc_list
*, __lxc_free_idmap
);
3831 int lxc_clear_idmaps(struct lxc_conf
*c
)
3833 return lxc_free_idmap(&c
->id_map
);
3836 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3838 struct lxc_list
*it
, *next
;
3840 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3846 lxc_list_init(&c
->keepcaps
);
3850 int lxc_clear_namespace(struct lxc_conf
*c
)
3852 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
3853 free_disarm(c
->ns_share
[i
]);
3858 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3860 char *global_token
, *namespaced_token
;
3861 size_t namespaced_token_len
;
3862 struct lxc_list
*it
, *next
, *list
;
3863 const char *k
= key
;
3866 if (version
== CGROUP2_SUPER_MAGIC
) {
3867 global_token
= "lxc.cgroup2";
3868 namespaced_token
= "lxc.cgroup2.";
3869 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3871 } else if (version
== CGROUP_SUPER_MAGIC
) {
3872 global_token
= "lxc.cgroup";
3873 namespaced_token
= "lxc.cgroup.";
3874 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3877 return ret_errno(EINVAL
);
3880 if (strequal(key
, global_token
))
3882 else if (strnequal(key
, namespaced_token
, namespaced_token_len
))
3883 k
+= namespaced_token_len
;
3885 return ret_errno(EINVAL
);
3887 lxc_list_for_each_safe(it
, list
, next
) {
3888 struct lxc_cgroup
*cg
= it
->elem
;
3890 if (!all
&& !strequal(cg
->subsystem
, k
))
3894 free(cg
->subsystem
);
3901 lxc_list_init(list
);
3906 static inline void lxc_clear_cgroups_devices(struct lxc_conf
*conf
)
3908 lxc_clear_cgroup2_devices(&conf
->bpf_devices
);
3911 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3913 struct lxc_list
*it
, *next
;
3914 const char *k
= NULL
;
3917 if (strequal(key
, "lxc.limit") || strequal(key
, "lxc.prlimit"))
3919 else if (strnequal(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
3920 k
= key
+ STRLITERALLEN("lxc.limit.");
3921 else if (strnequal(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
3922 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3924 return ret_errno(EINVAL
);
3926 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3927 struct lxc_limit
*lim
= it
->elem
;
3929 if (!all
&& !strequal(lim
->resource
, k
))
3934 free_disarm(lim
->resource
);
3940 lxc_list_init(&c
->limits
);
3945 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3947 struct lxc_list
*it
, *next
;
3948 const char *k
= NULL
;
3951 if (strequal(key
, "lxc.sysctl"))
3953 else if (strnequal(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
3954 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3958 lxc_list_for_each_safe(it
, &c
->sysctls
, next
) {
3959 struct lxc_sysctl
*elem
= it
->elem
;
3961 if (!all
&& !strequal(elem
->key
, k
))
3972 lxc_list_init(&c
->sysctls
);
3977 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3979 struct lxc_list
*it
, *next
;
3980 const char *k
= NULL
;
3983 if (strequal(key
, "lxc.proc"))
3985 else if (strnequal(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
3986 k
= key
+ STRLITERALLEN("lxc.proc.");
3990 lxc_list_for_each_safe(it
, &c
->procs
, next
) {
3991 struct lxc_proc
*proc
= it
->elem
;
3993 if (!all
&& !strequal(proc
->filename
, k
))
3997 free(proc
->filename
);
4004 lxc_list_init(&c
->procs
);
4009 int lxc_clear_groups(struct lxc_conf
*c
)
4011 struct lxc_list
*it
, *next
;
4013 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
4019 lxc_list_init(&c
->groups
);
4023 int lxc_clear_environment(struct lxc_conf
*c
)
4025 struct lxc_list
*it
, *next
;
4027 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
4033 lxc_list_init(&c
->environment
);
4037 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4039 struct lxc_list
*it
, *next
;
4041 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
4047 lxc_list_init(&c
->mount_list
);
4051 int lxc_clear_automounts(struct lxc_conf
*c
)
4057 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4059 struct lxc_list
*it
, *next
;
4060 const char *k
= NULL
;
4061 bool all
= false, done
= false;
4063 if (strequal(key
, "lxc.hook"))
4065 else if (strnequal(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
4066 k
= key
+ STRLITERALLEN("lxc.hook.");
4070 for (int i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4071 if (all
|| strequal(k
, lxchook_names
[i
])) {
4072 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
4077 lxc_list_init(&c
->hooks
[i
]);
4084 return log_error(-1, "Invalid hook key: %s", key
);
4089 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4091 struct lxc_list
*it
, *next
;
4093 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4099 lxc_list_init(&conf
->aliens
);
4102 void lxc_clear_includes(struct lxc_conf
*conf
)
4104 struct lxc_list
*it
, *next
;
4106 lxc_list_for_each_safe(it
, &conf
->includes
, next
) {
4112 lxc_list_init(&conf
->includes
);
4115 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4117 struct lxc_list
*it
, *next
;
4119 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4125 lxc_list_init(&c
->lsm_aa_raw
);
4129 void lxc_conf_free(struct lxc_conf
*conf
)
4134 if (current_config
== conf
)
4135 current_config
= NULL
;
4136 lxc_terminal_conf_free(&conf
->console
);
4137 free(conf
->rootfs
.mount
);
4138 free(conf
->rootfs
.bdev_type
);
4139 free(conf
->rootfs
.options
);
4140 free(conf
->rootfs
.path
);
4141 put_lxc_rootfs(&conf
->rootfs
, true);
4142 free(conf
->logfile
);
4143 if (conf
->logfd
!= -1)
4145 free(conf
->utsname
);
4146 free(conf
->ttys
.dir
);
4147 free(conf
->ttys
.tty_names
);
4150 free(conf
->execute_cmd
);
4151 free(conf
->init_cmd
);
4152 free(conf
->init_groups
.list
);
4153 free(conf
->init_cwd
);
4154 free(conf
->unexpanded_config
);
4156 lxc_free_networks(&conf
->network
);
4157 free(conf
->lsm_aa_profile
);
4158 free(conf
->lsm_aa_profile_computed
);
4159 free(conf
->lsm_se_context
);
4160 free(conf
->lsm_se_keyring_context
);
4161 lxc_seccomp_free(&conf
->seccomp
);
4162 lxc_clear_config_caps(conf
);
4163 lxc_clear_config_keepcaps(conf
);
4164 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4165 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4166 lxc_clear_cgroups_devices(conf
);
4167 lxc_clear_hooks(conf
, "lxc.hook");
4168 lxc_clear_mount_entries(conf
);
4169 lxc_clear_idmaps(conf
);
4170 lxc_clear_groups(conf
);
4171 lxc_clear_includes(conf
);
4172 lxc_clear_aliens(conf
);
4173 lxc_clear_environment(conf
);
4174 lxc_clear_limits(conf
, "lxc.prlimit");
4175 lxc_clear_sysctls(conf
, "lxc.sysctl");
4176 lxc_clear_procs(conf
, "lxc.proc");
4177 lxc_clear_apparmor_raw(conf
);
4178 lxc_clear_namespace(conf
);
4179 free(conf
->cgroup_meta
.dir
);
4180 free(conf
->cgroup_meta
.monitor_dir
);
4181 free(conf
->cgroup_meta
.monitor_pivot_dir
);
4182 free(conf
->cgroup_meta
.container_dir
);
4183 free(conf
->cgroup_meta
.namespace_dir
);
4184 free(conf
->cgroup_meta
.controllers
);
4185 free(conf
->shmount
.path_host
);
4186 free(conf
->shmount
.path_cont
);
4190 struct userns_fn_data
{
4192 const char *fn_name
;
4197 static int run_userns_fn(void *data
)
4199 struct userns_fn_data
*d
= data
;
4203 close_prot_errno_disarm(d
->p
[1]);
4206 * Wait for parent to finish establishing a new mapping in the user
4207 * namespace we are executing in.
4209 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4210 close_prot_errno_disarm(d
->p
[0]);
4215 TRACE("Calling function \"%s\"", d
->fn_name
);
4217 /* Call function to run. */
4218 return d
->fn(d
->arg
);
4221 static struct id_map
*mapped_nsid_add(const struct lxc_conf
*conf
, unsigned id
,
4224 const struct id_map
*map
;
4225 struct id_map
*retmap
;
4227 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4231 retmap
= zalloc(sizeof(*retmap
));
4235 memcpy(retmap
, map
, sizeof(*retmap
));
4239 static struct id_map
*find_mapped_hostid_entry(const struct lxc_conf
*conf
,
4240 unsigned id
, enum idtype idtype
)
4243 struct lxc_list
*it
;
4244 struct id_map
*retmap
= NULL
;
4246 lxc_list_for_each (it
, &conf
->id_map
) {
4248 if (map
->idtype
!= idtype
)
4251 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4260 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4261 * existing one or establish a new one.
4263 static struct id_map
*mapped_hostid_add(const struct lxc_conf
*conf
, uid_t id
,
4266 __do_free
struct id_map
*entry
= NULL
;
4268 struct id_map
*tmp
= NULL
;
4270 entry
= zalloc(sizeof(*entry
));
4274 /* Reuse existing mapping. */
4275 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4277 memcpy(entry
, tmp
, sizeof(*entry
));
4279 /* Find new mapping. */
4280 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4281 if (hostid_mapped
< 0)
4282 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
4284 entry
->idtype
= type
;
4285 entry
->nsid
= hostid_mapped
;
4286 entry
->hostid
= (unsigned long)id
;
4290 return move_ptr(entry
);
4293 static struct lxc_list
*get_minimal_idmap(const struct lxc_conf
*conf
,
4294 uid_t
*resuid
, gid_t
*resgid
)
4296 __do_free
struct id_map
*container_root_uid
= NULL
,
4297 *container_root_gid
= NULL
,
4298 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4299 __do_free
struct lxc_list
*idmap
= NULL
;
4301 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4302 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4303 struct lxc_list
*tmplist
= NULL
;
4305 /* Find container root mappings. */
4306 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4307 if (!container_root_uid
)
4308 return log_debug(NULL
, "Failed to find mapping for namespace uid %d", 0);
4310 if (euid
>= container_root_uid
->hostid
&&
4311 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4312 host_uid_map
= move_ptr(container_root_uid
);
4314 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4315 if (!container_root_gid
)
4316 return log_debug(NULL
, "Failed to find mapping for namespace gid %d", 0);
4318 if (egid
>= container_root_gid
->hostid
&&
4319 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4320 host_gid_map
= move_ptr(container_root_gid
);
4322 /* Check whether the {g,u}id of the user has a mapping. */
4324 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4326 return log_debug(NULL
, "Failed to find mapping for uid %d", euid
);
4329 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4331 return log_debug(NULL
, "Failed to find mapping for gid %d", egid
);
4333 /* Allocate new {g,u}id map list. */
4334 idmap
= lxc_list_new();
4338 /* Add container root to the map. */
4339 tmplist
= lxc_list_new();
4342 /* idmap will now keep track of that memory. */
4343 lxc_list_add_elem(tmplist
, move_ptr(host_uid_map
));
4344 lxc_list_add_tail(idmap
, tmplist
);
4346 if (container_root_uid
) {
4347 /* Add container root to the map. */
4348 tmplist
= lxc_list_new();
4351 /* idmap will now keep track of that memory. */
4352 lxc_list_add_elem(tmplist
, move_ptr(container_root_uid
));
4353 lxc_list_add_tail(idmap
, tmplist
);
4356 tmplist
= lxc_list_new();
4359 /* idmap will now keep track of that memory. */
4360 lxc_list_add_elem(tmplist
, move_ptr(host_gid_map
));
4361 lxc_list_add_tail(idmap
, tmplist
);
4363 if (container_root_gid
) {
4364 tmplist
= lxc_list_new();
4367 /* idmap will now keep track of that memory. */
4368 lxc_list_add_elem(tmplist
, move_ptr(container_root_gid
));
4369 lxc_list_add_tail(idmap
, tmplist
);
4372 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid
, nsgid
);
4378 return move_ptr(idmap
);
4382 * Run a function in a new user namespace.
4383 * The caller's euid/egid will be mapped if it is not already.
4384 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4385 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4386 * This means we require only to establish a mapping from:
4387 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4388 * - the container root -> some sub{g,u}id
4389 * The former we add, if the user did not specify a mapping. The latter we
4390 * retrieve from the container's configured {g,u}id mappings as it must have been
4391 * there to start the container in the first place.
4393 int userns_exec_1(const struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4394 const char *fn_name
)
4396 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4397 int ret
= -1, status
= -1;
4399 struct userns_fn_data d
= {
4410 idmap
= get_minimal_idmap(conf
, NULL
, NULL
);
4412 return ret_errno(ENOENT
);
4414 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
4418 d
.p
[0] = pipe_fds
[0];
4419 d
.p
[1] = pipe_fds
[1];
4421 /* Clone child in new user namespace. */
4422 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4424 ERROR("Failed to clone process in new user namespace");
4428 close_prot_errno_disarm(pipe_fds
[0]);
4430 if (lxc_log_trace()) {
4432 struct lxc_list
*it
;
4434 lxc_list_for_each(it
, idmap
) {
4436 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4437 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4441 /* Set up {g,u}id mapping for user namespace of child process. */
4442 ret
= lxc_map_ids(idmap
, pid
);
4444 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4448 /* Tell child to proceed. */
4449 if (lxc_write_nointr(pipe_fds
[1], &c
, 1) != 1) {
4450 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4455 close_prot_errno_disarm(pipe_fds
[0]);
4456 close_prot_errno_disarm(pipe_fds
[1]);
4458 /* Wait for child to finish. */
4460 status
= wait_for_pid(pid
);
4468 int userns_exec_minimal(const struct lxc_conf
*conf
,
4469 int (*fn_parent
)(void *), void *fn_parent_data
,
4470 int (*fn_child
)(void *), void *fn_child_data
)
4472 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4473 uid_t resuid
= LXC_INVALID_UID
;
4474 gid_t resgid
= LXC_INVALID_GID
;
4480 if (!conf
|| !fn_child
)
4481 return ret_errno(EINVAL
);
4483 idmap
= get_minimal_idmap(conf
, &resuid
, &resgid
);
4485 return ret_errno(ENOENT
);
4487 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
4493 SYSERROR("Failed to create new process");
4498 close_prot_errno_disarm(sock_fds
[1]);
4500 ret
= unshare(CLONE_NEWUSER
);
4502 SYSERROR("Failed to unshare new user namespace");
4503 _exit(EXIT_FAILURE
);
4506 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
4508 _exit(EXIT_FAILURE
);
4510 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
4512 _exit(EXIT_FAILURE
);
4514 close_prot_errno_disarm(sock_fds
[0]);
4516 if (!lxc_drop_groups() && errno
!= EPERM
)
4517 _exit(EXIT_FAILURE
);
4519 ret
= setresgid(resgid
, resgid
, resgid
);
4521 SYSERROR("Failed to setresgid(%d, %d, %d)",
4522 resgid
, resgid
, resgid
);
4523 _exit(EXIT_FAILURE
);
4526 ret
= setresuid(resuid
, resuid
, resuid
);
4528 SYSERROR("Failed to setresuid(%d, %d, %d)",
4529 resuid
, resuid
, resuid
);
4530 _exit(EXIT_FAILURE
);
4533 ret
= fn_child(fn_child_data
);
4535 SYSERROR("Running function in new user namespace failed");
4536 _exit(EXIT_FAILURE
);
4539 _exit(EXIT_SUCCESS
);
4542 close_prot_errno_disarm(sock_fds
[0]);
4544 if (lxc_log_trace()) {
4546 struct lxc_list
*it
;
4548 lxc_list_for_each(it
, idmap
) {
4550 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4551 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4555 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
4557 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
4561 /* Set up {g,u}id mapping for user namespace of child process. */
4562 ret
= lxc_map_ids(idmap
, pid
);
4564 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4568 /* Tell child to proceed. */
4569 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
4571 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4575 if (fn_parent
&& fn_parent(fn_parent_data
)) {
4576 SYSERROR("Running parent function failed");
4577 _exit(EXIT_FAILURE
);
4581 close_prot_errno_disarm(sock_fds
[0]);
4582 close_prot_errno_disarm(sock_fds
[1]);
4584 /* Wait for child to finish. */
4588 return wait_for_pid(pid
);
4591 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4592 const char *fn_name
)
4598 struct lxc_list
*cur
;
4599 struct userns_fn_data d
;
4602 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4603 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4604 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4609 ret
= pipe2(p
, O_CLOEXEC
);
4611 SYSERROR("opening pipe");
4615 d
.fn_name
= fn_name
;
4620 /* Clone child in new user namespace. */
4621 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4623 ERROR("Failed to clone process in new user namespace");
4633 /* Allocate new {g,u}id map list. */
4634 idmap
= lxc_list_new();
4638 /* Find container root. */
4639 lxc_list_for_each (cur
, &conf
->id_map
) {
4640 struct id_map
*tmpmap
;
4642 tmplist
= lxc_list_new();
4646 tmpmap
= zalloc(sizeof(*tmpmap
));
4652 memset(tmpmap
, 0, sizeof(*tmpmap
));
4653 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4654 tmplist
->elem
= tmpmap
;
4656 lxc_list_add_tail(idmap
, tmplist
);
4660 if (map
->idtype
== ID_TYPE_UID
)
4661 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4664 if (map
->idtype
== ID_TYPE_GID
)
4665 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4671 if (map
->idtype
== ID_TYPE_UID
)
4672 if (container_root_uid
== NULL
)
4673 container_root_uid
= map
;
4675 if (map
->idtype
== ID_TYPE_GID
)
4676 if (container_root_gid
== NULL
)
4677 container_root_gid
= map
;
4680 if (!container_root_uid
|| !container_root_gid
) {
4681 ERROR("No mapping for container root found");
4685 /* Check whether the {g,u}id of the user has a mapping. */
4687 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4689 host_uid_map
= container_root_uid
;
4692 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4694 host_gid_map
= container_root_gid
;
4696 if (!host_uid_map
) {
4697 DEBUG("Failed to find mapping for uid %d", euid
);
4701 if (!host_gid_map
) {
4702 DEBUG("Failed to find mapping for gid %d", egid
);
4706 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4707 /* Add container root to the map. */
4708 tmplist
= lxc_list_new();
4711 lxc_list_add_elem(tmplist
, host_uid_map
);
4712 lxc_list_add_tail(idmap
, tmplist
);
4714 /* idmap will now keep track of that memory. */
4715 host_uid_map
= NULL
;
4717 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4718 tmplist
= lxc_list_new();
4721 lxc_list_add_elem(tmplist
, host_gid_map
);
4722 lxc_list_add_tail(idmap
, tmplist
);
4724 /* idmap will now keep track of that memory. */
4725 host_gid_map
= NULL
;
4727 if (lxc_log_trace()) {
4728 lxc_list_for_each (cur
, idmap
) {
4730 TRACE("establishing %cid mapping for \"%d\" in new "
4731 "user namespace: nsuid %lu - hostid %lu - range "
4733 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4734 map
->nsid
, map
->hostid
, map
->range
);
4738 /* Set up {g,u}id mapping for user namespace of child process. */
4739 ret
= lxc_map_ids(idmap
, pid
);
4741 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4745 /* Tell child to proceed. */
4746 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4747 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4756 /* Wait for child to finish. */
4758 ret
= wait_for_pid(pid
);
4761 __lxc_free_idmap(idmap
);
4763 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4765 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4771 static int add_idmap_entry(struct lxc_list
*idmap
, enum idtype idtype
,
4772 unsigned long nsid
, unsigned long hostid
,
4773 unsigned long range
)
4775 __do_free
struct id_map
*new_idmap
= NULL
;
4776 __do_free
struct lxc_list
*new_list
= NULL
;
4778 new_idmap
= zalloc(sizeof(*new_idmap
));
4780 return ret_errno(ENOMEM
);
4782 new_idmap
->idtype
= idtype
;
4783 new_idmap
->hostid
= hostid
;
4784 new_idmap
->nsid
= nsid
;
4785 new_idmap
->range
= range
;
4787 new_list
= zalloc(sizeof(*new_list
));
4789 return ret_errno(ENOMEM
);
4791 new_list
->elem
= move_ptr(new_idmap
);
4792 lxc_list_add_tail(idmap
, move_ptr(new_list
));
4794 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
4795 idtype
== ID_TYPE_UID
? 'u' : 'g', nsid
, hostid
, range
);
4799 int userns_exec_mapped_root(const char *path
, int path_fd
,
4800 const struct lxc_conf
*conf
)
4802 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
4803 __do_close
int fd
= -EBADF
;
4804 int target_fd
= -EBADF
;
4809 uid_t container_host_uid
, hostuid
;
4810 gid_t container_host_gid
, hostgid
;
4813 if (!conf
|| (!path
&& path_fd
< 0))
4814 return ret_errno(EINVAL
);
4819 container_host_uid
= get_mapped_rootid(conf
, ID_TYPE_UID
);
4820 if (!uid_valid(container_host_uid
))
4821 return log_error(-1, "No uid mapping for container root");
4823 container_host_gid
= get_mapped_rootid(conf
, ID_TYPE_GID
);
4824 if (!gid_valid(container_host_gid
))
4825 return log_error(-1, "No gid mapping for container root");
4828 fd
= open(path
, O_CLOEXEC
| O_NOCTTY
);
4830 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", path
);
4833 target_fd
= path_fd
;
4836 hostuid
= geteuid();
4837 /* We are root so chown directly. */
4839 ret
= fchown(target_fd
, container_host_uid
, container_host_gid
);
4841 return log_error_errno(-errno
, errno
,
4842 "Failed to fchown(%d(%s), %d, %d)",
4843 target_fd
, path
, container_host_uid
,
4844 container_host_gid
);
4845 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd
, path
,
4846 container_host_uid
, container_host_gid
);
4849 /* The container's root host id matches */
4850 if (container_host_uid
== hostuid
)
4851 return log_info(0, "Container root id is mapped to our uid");
4853 /* Get the current ids of our target. */
4854 ret
= fstat(target_fd
, &st
);
4856 return log_error_errno(-errno
, errno
, "Failed to stat \"%s\"", path
);
4858 hostgid
= getegid();
4859 if (st
.st_uid
== hostuid
&& mapped_hostid(st
.st_gid
, conf
, ID_TYPE_GID
) < 0) {
4860 ret
= fchown(target_fd
, -1, hostgid
);
4862 return log_error_errno(-errno
, errno
,
4863 "Failed to fchown(%d(%s), -1, %d)",
4864 target_fd
, path
, hostgid
);
4865 TRACE("Chowned %d(%s) to -1:%d", target_fd
, path
, hostgid
);
4868 idmap
= lxc_list_new();
4872 /* "u:0:rootuid:1" */
4873 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, 0, container_host_uid
, 1);
4875 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4877 /* "u:hostuid:hostuid:1" */
4878 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, hostuid
, hostuid
, 1);
4880 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4882 /* "g:0:rootgid:1" */
4883 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, 0, container_host_gid
, 1);
4885 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4887 /* "g:hostgid:hostgid:1" */
4888 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, hostgid
, hostgid
, 1);
4890 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4892 if (hostgid
!= st
.st_gid
) {
4893 /* "g:pathgid:rootgid+pathgid:1" */
4894 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, st
.st_gid
,
4895 container_host_gid
+ (gid_t
)st
.st_gid
, 1);
4897 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
4900 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
4906 SYSERROR("Failed to create new process");
4911 close_prot_errno_disarm(sock_fds
[1]);
4913 ret
= unshare(CLONE_NEWUSER
);
4915 SYSERROR("Failed to unshare new user namespace");
4916 _exit(EXIT_FAILURE
);
4919 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
4921 _exit(EXIT_FAILURE
);
4923 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
4925 _exit(EXIT_FAILURE
);
4927 close_prot_errno_disarm(sock_fds
[0]);
4929 if (!lxc_switch_uid_gid(0, 0))
4930 _exit(EXIT_FAILURE
);
4932 if (!lxc_drop_groups())
4933 _exit(EXIT_FAILURE
);
4935 ret
= fchown(target_fd
, 0, st
.st_gid
);
4937 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
4938 _exit(EXIT_FAILURE
);
4941 TRACE("Chowned %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
4942 _exit(EXIT_SUCCESS
);
4945 close_prot_errno_disarm(sock_fds
[0]);
4947 if (lxc_log_trace()) {
4949 struct lxc_list
*it
;
4951 lxc_list_for_each(it
, idmap
) {
4953 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
4954 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
4958 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
4960 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
4964 /* Set up {g,u}id mapping for user namespace of child process. */
4965 ret
= lxc_map_ids(idmap
, pid
);
4967 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4971 /* Tell child to proceed. */
4972 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
4974 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4979 close_prot_errno_disarm(sock_fds
[0]);
4980 close_prot_errno_disarm(sock_fds
[1]);
4982 /* Wait for child to finish. */
4986 return wait_for_pid(pid
);
4989 /* not thread-safe, do not use from api without first forking */
4990 static char *getuname(void)
4992 __do_free
char *buf
= NULL
;
4993 struct passwd pwent
;
4994 struct passwd
*pwentp
= NULL
;
4998 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
5002 buf
= zalloc(bufsize
);
5006 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
5009 WARN("Could not find matched password record.");
5011 return log_error(NULL
, "Failed to get password record - %u", geteuid());
5014 return strdup(pwent
.pw_name
);
5017 /* not thread-safe, do not use from api without first forking */
5018 static char *getgname(void)
5020 __do_free
char *buf
= NULL
;
5022 struct group
*grentp
= NULL
;
5026 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
5030 buf
= zalloc(bufsize
);
5034 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
5037 WARN("Could not find matched group record");
5039 return log_error(NULL
, "Failed to get group record - %u", getegid());
5042 return strdup(grent
.gr_name
);
5045 /* not thread-safe, do not use from api without first forking */
5046 void suggest_default_idmap(void)
5048 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
5049 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
5050 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
5061 subuid_f
= fopen(subuidfile
, "re");
5063 ERROR("Your system is not configured with subuids");
5067 while (getline(&line
, &len
, subuid_f
) != -1) {
5069 size_t no_newline
= 0;
5071 p
= strchr(line
, ':');
5079 if (!strequal(line
, uname
))
5082 p2
= strchr(p
, ':');
5089 no_newline
= strcspn(p2
, "\n");
5090 p2
[no_newline
] = '\0';
5092 if (lxc_safe_uint(p
, &uid
) < 0)
5093 WARN("Could not parse UID");
5094 if (lxc_safe_uint(p2
, &urange
) < 0)
5095 WARN("Could not parse UID range");
5098 subgid_f
= fopen(subgidfile
, "re");
5100 ERROR("Your system is not configured with subgids");
5104 while (getline(&line
, &len
, subgid_f
) != -1) {
5106 size_t no_newline
= 0;
5108 p
= strchr(line
, ':');
5116 if (!strequal(line
, uname
))
5119 p2
= strchr(p
, ':');
5126 no_newline
= strcspn(p2
, "\n");
5127 p2
[no_newline
] = '\0';
5129 if (lxc_safe_uint(p
, &gid
) < 0)
5130 WARN("Could not parse GID");
5131 if (lxc_safe_uint(p2
, &grange
) < 0)
5132 WARN("Could not parse GID range");
5135 if (!urange
|| !grange
) {
5136 ERROR("You do not have subuids or subgids allocated");
5137 ERROR("Unprivileged containers require subuids and subgids");
5141 ERROR("You must either run as root, or define uid mappings");
5142 ERROR("To pass uid mappings to lxc-create, you could create");
5143 ERROR("~/.config/lxc/default.conf:");
5144 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
5145 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
5146 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
5149 static void free_cgroup_settings(struct lxc_list
*result
)
5151 struct lxc_list
*iterator
, *next
;
5153 lxc_list_for_each_safe (iterator
, result
, next
) {
5154 lxc_list_del(iterator
);
5155 free_disarm(iterator
);
5157 free_disarm(result
);
5160 /* Return the list of cgroup_settings sorted according to the following rules
5161 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
5163 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
5165 struct lxc_list
*result
;
5166 struct lxc_cgroup
*cg
= NULL
;
5167 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
5169 result
= lxc_list_new();
5172 lxc_list_init(result
);
5174 /* Iterate over the cgroup settings and copy them to the output list. */
5175 lxc_list_for_each (it
, cgroup_settings
) {
5176 item
= zalloc(sizeof(*item
));
5178 free_cgroup_settings(result
);
5182 item
->elem
= it
->elem
;
5184 if (strequal(cg
->subsystem
, "memory.memsw.limit_in_bytes")) {
5185 /* Store the memsw_limit location */
5187 } else if (strequal(cg
->subsystem
, "memory.limit_in_bytes") &&
5188 memsw_limit
!= NULL
) {
5189 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
5190 * before lxc.cgroup.memory.limit_in_bytes, swap these
5192 item
->elem
= memsw_limit
->elem
;
5193 memsw_limit
->elem
= it
->elem
;
5195 lxc_list_add_tail(result
, item
);