1 /* SPDX-License-Identifier: LGPL-2.1+ */
12 #include <linux/loop.h>
14 #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>
39 #include "cgroups/cgroup.h"
42 #include "confile_utils.h"
47 #include "lxcseccomp.h"
49 #include "memory_utils.h"
50 #include "mount_utils.h"
51 #include "namespace.h"
54 #include "process_utils.h"
57 #include "storage/storage.h"
58 #include "storage/overlay.h"
60 #include "syscall_wrappers.h"
66 #include <sys/mkdev.h>
70 #include <sys/statvfs.h>
80 #include <sys/capability.h>
88 #include "lxcmntent.h"
93 #if !HAVE_PRLIMIT && HAVE_PRLIMIT64
102 #include "strchrnul.h"
105 lxc_log_define(conf
, lxc
);
108 * The lxc_conf of the container currently being worked on in an API call.
109 * This is used in the error calls.
111 thread_local
struct lxc_conf
*current_config
;
113 char *lxchook_names
[NUM_LXC_HOOKS
] = {
144 static struct mount_opt mount_opt
[] = {
145 { "atime", 1, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
146 { "dev", 1, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
147 { "diratime", 1, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
148 { "exec", 1, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
149 { "noatime", 0, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
150 { "nodev", 0, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
151 { "nodiratime", 0, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
152 { "noexec", 0, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
153 { "norelatime", 1, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
154 { "nostrictatime", 1, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
155 { "nosuid", 0, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
156 { "relatime", 0, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
157 { "ro", 0, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
158 { "rw", 1, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
159 { "strictatime", 0, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
160 { "suid", 1, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
162 { "bind", 0, false, 0, MS_BIND
},
163 { "defaults", 0, false, 0, 0 },
164 { "rbind", 0, true, 0, MS_BIND
| MS_REC
},
166 { "sync", 0, false, ~0, MS_SYNCHRONOUS
},
167 { "async", 1, false, ~0, MS_SYNCHRONOUS
},
168 { "dirsync", 0, false, ~0, MS_DIRSYNC
},
169 { "lazytime", 0, false, ~0, MS_LAZYTIME
},
170 { "mand", 0, false, ~0, MS_MANDLOCK
},
171 { "nomand", 1, false, ~0, MS_MANDLOCK
},
172 { "remount", 0, false, ~0, MS_REMOUNT
},
174 { NULL
, 0, false, ~0, ~0 },
177 static struct mount_opt propagation_opt
[] = {
178 { "private", 0, false, MS_PRIVATE
, MS_PRIVATE
},
179 { "shared", 0, false, MS_SHARED
, MS_SHARED
},
180 { "slave", 0, false, MS_SLAVE
, MS_SLAVE
},
181 { "unbindable", 0, false, MS_UNBINDABLE
, MS_UNBINDABLE
},
182 { "rprivate", 0, true, MS_PRIVATE
, MS_PRIVATE
| MS_REC
},
183 { "rshared", 0, true, MS_SHARED
, MS_SHARED
| MS_REC
},
184 { "rslave", 0, true, MS_SLAVE
, MS_SLAVE
| MS_REC
},
185 { "runbindable", 0, true, MS_UNBINDABLE
, MS_UNBINDABLE
| MS_REC
},
186 { NULL
, 0, false, 0, 0 },
189 static struct caps_opt caps_opt
[] = {
191 { "chown", CAP_CHOWN
},
192 { "dac_override", CAP_DAC_OVERRIDE
},
193 { "dac_read_search", CAP_DAC_READ_SEARCH
},
194 { "fowner", CAP_FOWNER
},
195 { "fsetid", CAP_FSETID
},
196 { "kill", CAP_KILL
},
197 { "setgid", CAP_SETGID
},
198 { "setuid", CAP_SETUID
},
199 { "setpcap", CAP_SETPCAP
},
200 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
201 { "net_bind_service", CAP_NET_BIND_SERVICE
},
202 { "net_broadcast", CAP_NET_BROADCAST
},
203 { "net_admin", CAP_NET_ADMIN
},
204 { "net_raw", CAP_NET_RAW
},
205 { "ipc_lock", CAP_IPC_LOCK
},
206 { "ipc_owner", CAP_IPC_OWNER
},
207 { "sys_module", CAP_SYS_MODULE
},
208 { "sys_rawio", CAP_SYS_RAWIO
},
209 { "sys_chroot", CAP_SYS_CHROOT
},
210 { "sys_ptrace", CAP_SYS_PTRACE
},
211 { "sys_pacct", CAP_SYS_PACCT
},
212 { "sys_admin", CAP_SYS_ADMIN
},
213 { "sys_boot", CAP_SYS_BOOT
},
214 { "sys_nice", CAP_SYS_NICE
},
215 { "sys_resource", CAP_SYS_RESOURCE
},
216 { "sys_time", CAP_SYS_TIME
},
217 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
218 { "mknod", CAP_MKNOD
},
219 { "lease", CAP_LEASE
},
220 { "audit_write", CAP_AUDIT_WRITE
},
221 { "audit_control", CAP_AUDIT_CONTROL
},
222 { "setfcap", CAP_SETFCAP
},
223 { "mac_override", CAP_MAC_OVERRIDE
},
224 { "mac_admin", CAP_MAC_ADMIN
},
225 { "syslog", CAP_SYSLOG
},
226 { "wake_alarm", CAP_WAKE_ALARM
},
227 { "block_suspend", CAP_BLOCK_SUSPEND
},
228 { "audit_read", CAP_AUDIT_READ
},
229 { "perfmon", CAP_PERFMON
},
231 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE
},
235 static struct limit_opt limit_opt
[] = {
240 { "core", RLIMIT_CORE
},
243 { "cpu", RLIMIT_CPU
},
246 { "data", RLIMIT_DATA
},
249 { "fsize", RLIMIT_FSIZE
},
252 { "locks", RLIMIT_LOCKS
},
254 #ifdef RLIMIT_MEMLOCK
255 { "memlock", RLIMIT_MEMLOCK
},
257 #ifdef RLIMIT_MSGQUEUE
258 { "msgqueue", RLIMIT_MSGQUEUE
},
261 { "nice", RLIMIT_NICE
},
264 { "nofile", RLIMIT_NOFILE
},
267 { "nproc", RLIMIT_NPROC
},
270 { "rss", RLIMIT_RSS
},
273 { "rtprio", RLIMIT_RTPRIO
},
276 { "rttime", RLIMIT_RTTIME
},
278 #ifdef RLIMIT_SIGPENDING
279 { "sigpending", RLIMIT_SIGPENDING
},
282 { "stack", RLIMIT_STACK
},
286 static int run_buffer(char *buffer
)
288 __do_free
char *output
= NULL
;
289 __do_lxc_pclose
struct lxc_popen_FILE
*f
= NULL
;
292 f
= lxc_popen(buffer
);
294 return log_error_errno(-1, errno
, "Failed to popen() %s", buffer
);
296 output
= zalloc(LXC_LOG_BUFFER_SIZE
);
298 return log_error_errno(-1, ENOMEM
, "Failed to allocate memory for %s", buffer
);
302 return log_error_errno(-1, errno
, "Failed to retrieve underlying file descriptor");
304 for (int i
= 0; i
< 10; i
++) {
307 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
308 if (bytes_read
> 0) {
309 output
[bytes_read
] = '\0';
310 DEBUG("Script %s produced output: %s", buffer
, output
);
317 ret
= lxc_pclose(move_ptr(f
));
319 return log_error_errno(-1, errno
, "Script exited with error");
320 else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0)
321 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret
));
322 else if (WIFSIGNALED(ret
))
323 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret
));
328 int run_script_argv(const char *name
, unsigned int hook_version
,
329 const char *section
, const char *script
,
330 const char *hookname
, char **argv
)
332 __do_free
char *buffer
= NULL
;
336 if (hook_version
== 0)
337 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
338 script
, name
, section
);
340 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
342 for (i
= 0; argv
&& argv
[i
]; i
++)
343 size
+= strlen(argv
[i
]) + 1;
345 size
+= STRLITERALLEN("exec");
347 size
+= strlen(script
);
353 if (hook_version
== 0) {
354 size
+= strlen(hookname
);
357 size
+= strlen(name
);
360 size
+= strlen(section
);
367 buffer
= zalloc(size
);
371 if (hook_version
== 0)
372 buf_pos
= strnprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
374 buf_pos
= strnprintf(buffer
, size
, "exec %s", script
);
376 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
378 if (hook_version
== 1) {
379 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
381 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname
);
383 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
385 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
387 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section
);
388 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
390 if (strequal(section
, "net")) {
393 if (!argv
|| !argv
[0])
396 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
398 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_TYPE=%s", argv
[0]);
399 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
401 parent
= argv
[1] ? argv
[1] : "";
403 if (strequal(argv
[0], "macvlan")) {
404 ret
= setenv("LXC_NET_PARENT", parent
, 1);
406 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
407 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
408 } else if (strequal(argv
[0], "phys")) {
409 ret
= setenv("LXC_NET_PARENT", parent
, 1);
411 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
412 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
413 } else if (strequal(argv
[0], "veth")) {
414 char *peer
= argv
[2] ? argv
[2] : "";
416 ret
= setenv("LXC_NET_PEER", peer
, 1);
418 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PEER=%s", peer
);
419 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
421 ret
= setenv("LXC_NET_PARENT", parent
, 1);
423 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
424 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
429 for (i
= 0; argv
&& argv
[i
]; i
++) {
430 size_t len
= size
- buf_pos
;
432 ret
= strnprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
434 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
438 return run_buffer(buffer
);
441 int run_script(const char *name
, const char *section
, const char *script
, ...)
443 __do_free
char *buffer
= NULL
;
449 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
450 script
, name
, section
);
452 va_start(ap
, script
);
453 while ((p
= va_arg(ap
, char *)))
454 size
+= strlen(p
) + 1;
457 size
+= STRLITERALLEN("exec");
458 size
+= strlen(script
);
459 size
+= strlen(name
);
460 size
+= strlen(section
);
466 buffer
= must_realloc(NULL
, size
);
467 ret
= strnprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
471 va_start(ap
, script
);
472 while ((p
= va_arg(ap
, char *))) {
473 int len
= size
- ret
;
475 rc
= strnprintf(buffer
+ ret
, len
, " %s", p
);
484 return run_buffer(buffer
);
487 int lxc_storage_prepare(struct lxc_conf
*conf
)
490 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
493 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
495 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
497 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
498 if (rootfs
->dfd_mnt
< 0)
504 ret
= access(rootfs
->mount
, F_OK
);
506 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
509 rootfs
->storage
= storage_init(conf
);
510 if (!rootfs
->storage
)
511 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
512 rootfs
->path
, rootfs
->mount
,
513 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
518 void lxc_storage_put(struct lxc_conf
*conf
)
520 storage_put(conf
->rootfs
.storage
);
521 conf
->rootfs
.storage
= NULL
;
524 /* lxc_rootfs_prepare
525 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
526 * the duration of the container run, to prevent the container from marking
527 * the underlying fs readonly on shutdown. unlink the file immediately so
528 * no name pollution is happens.
529 * don't unlink on NFS to avoid random named stale handles.
531 int lxc_rootfs_init(struct lxc_conf
*conf
, bool userns
)
533 __do_close
int dfd_path
= -EBADF
, fd_pin
= -EBADF
;
537 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
539 ret
= lxc_storage_prepare(conf
);
541 return syserror_set(-EINVAL
, "Failed to prepare rootfs storage");
543 if (!is_empty_string(rootfs
->mnt_opts
.userns_path
)) {
545 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supported with separate rootfs for container");
547 if (rootfs
->bdev_type
&& !strequal(rootfs
->bdev_type
, "dir"))
548 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supports the \"dir\" storage driver");
552 return log_trace(0, "Not pinning because container does not have a rootfs");
555 return log_trace(0, "Not pinning because container runs in user namespace");
557 if (rootfs
->bdev_type
) {
558 if (strequal(rootfs
->bdev_type
, "overlay") ||
559 strequal(rootfs
->bdev_type
, "overlayfs"))
560 return log_trace_errno(0, EINVAL
, "Not pinning on stacking filesystem");
562 if (strequal(rootfs
->bdev_type
, "zfs"))
563 return log_trace_errno(0, EINVAL
, "Not pinning on ZFS filesystem");
566 dfd_path
= open_at(-EBADF
, rootfs
->path
, PROTECT_OPATH_FILE
, 0, 0);
568 return syserror("Failed to open \"%s\"", rootfs
->path
);
570 ret
= fstat(dfd_path
, &st
);
572 return log_trace_errno(-errno
, errno
, "Failed to retrieve file status");
574 if (!S_ISDIR(st
.st_mode
))
575 return log_trace_errno(0, ENOTDIR
, "Not pinning because file descriptor is not a directory");
577 fd_pin
= open_at(dfd_path
, ".lxc_keep",
578 PROTECT_OPEN
| O_CREAT
,
579 PROTECT_LOOKUP_BENEATH
,
583 return log_trace_errno(0, EROFS
, "Not pinning on read-only filesystem");
584 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
);
610 int lxc_rootfs_prepare_parent(struct lxc_handler
*handler
)
612 __do_close
int dfd_idmapped
= -EBADF
, fd_userns
= -EBADF
;
613 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
614 struct lxc_storage
*storage
= rootfs
->storage
;
615 const struct lxc_mount_options
*mnt_opts
= &rootfs
->mnt_opts
;
617 const char *path_source
;
619 if (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 (strequal(rootfs
->mnt_opts
.userns_path
, "container"))
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 mnt_opts
->attr
.attr_set
,
646 mnt_opts
->attr
.attr_clr
);
647 if (dfd_idmapped
< 0)
648 return syserror("Failed to create detached idmapped mount");
650 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &dfd_idmapped
, 1, NULL
, 0);
652 return syserror("Failed to send detached idmapped mount fd");
654 TRACE("Created detached idmapped mount %d", dfd_idmapped
);
658 static int add_shmount_to_list(struct lxc_conf
*conf
)
660 char new_mount
[PATH_MAX
];
661 /* Offset for the leading '/' since the path_cont
662 * is absolute inside the container.
664 int offset
= 1, ret
= -1;
666 ret
= strnprintf(new_mount
, sizeof(new_mount
),
667 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
668 conf
->shmount
.path_cont
+ offset
);
672 return add_elem_to_mount_list(new_mount
, conf
);
675 static int lxc_mount_auto_mounts(struct lxc_handler
*handler
, int flags
)
682 const char *destination
;
686 bool requires_cap_net_admin
;
687 } default_mounts
[] = {
688 /* Read-only bind-mounting... In older kernels, doing that
689 * required to do one MS_BIND mount and then
690 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
691 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
692 * onwards. However, this apparently does not work on kernel
693 * 3.8. Unfortunately, on that very same kernel, doing the same
694 * trick as above doesn't seem to work either, there one needs
695 * to ALSO specify MS_BIND for the remount, otherwise the
696 * entire fs is remounted read-only or the mount fails because
697 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
698 * kernels as low as 2.6.32...
700 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
701 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
702 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
, true, },
703 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
, false },
704 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
705 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
, true },
706 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
, false },
707 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
708 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
709 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
, false },
710 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
, false },
711 /* /proc/sys is used as a temporary staging directory for the read-write sysfs mount and unmounted after binding net */
712 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/proc/sys", "sysfs", MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
, false },
713 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
|MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
, false },
714 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/proc/sys/devices/virtual/net", "%r/sys/devices/virtual/net", NULL
, MS_BIND
, NULL
, false },
715 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/proc/sys", NULL
, NULL
, 0, NULL
, false },
716 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
, false }
718 struct lxc_conf
*conf
= handler
->conf
;
719 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
720 bool has_cap_net_admin
;
722 if (flags
& LXC_AUTO_PROC_MASK
) {
725 * Only unmount procfs if we have a separate rootfs so
726 * we can still access it in safe_mount() below.
728 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc",
729 rootfs
->path
? rootfs
->mount
: "");
731 return ret_errno(EIO
);
733 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
735 SYSDEBUG("Tried to ensure procfs is unmounted");
738 ret
= mkdirat(rootfs
->dfd_mnt
, "proc" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
739 if (ret
< 0 && errno
!= EEXIST
)
740 return syserror("Failed to create procfs mountpoint under %d", rootfs
->dfd_mnt
);
742 TRACE("Created procfs mountpoint under %d", rootfs
->dfd_mnt
);
745 if (flags
& LXC_AUTO_SYS_MASK
) {
748 * Only unmount sysfs if we have a separate rootfs so
749 * we can still access it in safe_mount() below.
751 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/sys",
752 rootfs
->path
? rootfs
->mount
: "");
754 return ret_errno(EIO
);
756 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
758 SYSDEBUG("Tried to ensure sysfs is unmounted");
761 ret
= mkdirat(rootfs
->dfd_mnt
, "sys" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
762 if (ret
< 0 && errno
!= EEXIST
)
763 return syserror("Failed to create sysfs mountpoint under %d", rootfs
->dfd_mnt
);
765 TRACE("Created sysfs mountpoint under %d", rootfs
->dfd_mnt
);
768 has_cap_net_admin
= lxc_wants_cap(CAP_NET_ADMIN
, conf
);
769 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
770 __do_free
char *destination
= NULL
, *source
= NULL
;
771 unsigned long mflags
= default_mounts
[i
].flags
;
773 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
776 if (default_mounts
[i
].source
) {
777 /* will act like strdup if %r is not present */
778 source
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].source
);
780 return syserror_set(-ENOMEM
, "Failed to create source path");
783 if (!has_cap_net_admin
&& default_mounts
[i
].requires_cap_net_admin
) {
784 TRACE("Container does not have CAP_NET_ADMIN. Skipping \"%s\" mount", default_mounts
[i
].source
?: "(null)");
788 if (!default_mounts
[i
].destination
) {
789 ret
= umount2(source
, MNT_DETACH
);
791 return log_error_errno(-1, errno
,
792 "Failed to unmount \"%s\"",
794 TRACE("Unmounted automount \"%s\"", source
);
798 /* will act like strdup if %r is not present */
799 destination
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].destination
);
801 return syserror_set(-ENOMEM
, "Failed to create target path");
803 ret
= safe_mount(source
, destination
,
804 default_mounts
[i
].fstype
,
806 default_mounts
[i
].options
,
807 rootfs
->path
? rootfs
->mount
: NULL
);
810 return syserror("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
812 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source
, destination
);
816 if (mflags
& MS_REMOUNT
)
817 TRACE("Remounted automount \"%s\" on \"%s\" %s with flags %lu", source
, destination
, (mflags
& MS_RDONLY
) ? "read-only" : "read-write", mflags
);
819 TRACE("Mounted automount \"%s\" on \"%s\" %s with flags %lu", source
, destination
, (mflags
& MS_RDONLY
) ? "read-only" : "read-write", mflags
);
822 if (flags
& LXC_AUTO_CGROUP_MASK
) {
825 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
826 /* If the type of cgroup mount was not specified, it depends on
827 * the container's capabilities as to what makes sense: if we
828 * have CAP_SYS_ADMIN, the read-only part can be remounted
829 * read-write anyway, so we may as well default to read-write;
830 * then the admin will not be given a false sense of security.
831 * (And if they really want mixed r/o r/w, then they can
832 * explicitly specify :mixed.) OTOH, if the container lacks
833 * CAP_SYS_ADMIN, do only default to :mixed, because then the
834 * container can't remount it read-write.
836 if ((cg_flags
== LXC_AUTO_CGROUP_NOSPEC
) || (cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
)) {
837 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
838 cg_flags
= has_cap(CAP_SYS_ADMIN
, conf
)
840 : LXC_AUTO_CGROUP_MIXED
;
842 cg_flags
= has_cap(CAP_SYS_ADMIN
, conf
)
843 ? LXC_AUTO_CGROUP_FULL_RW
844 : LXC_AUTO_CGROUP_FULL_MIXED
;
847 if (flags
& LXC_AUTO_CGROUP_FORCE
)
848 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
850 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
, handler
, cg_flags
))
851 return log_error_errno(-1, errno
, "Failed to mount \"/sys/fs/cgroup\"");
854 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
855 ret
= add_shmount_to_list(conf
);
857 return log_error(-1, "Failed to add shmount entry to container config");
863 static int setup_utsname(struct utsname
*utsname
)
870 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
872 return log_error_errno(-1, errno
, "Failed to set the hostname to \"%s\"",
875 INFO("Set hostname to \"%s\"", utsname
->nodename
);
880 struct dev_symlinks
{
885 static const struct dev_symlinks dev_symlinks
[] = {
886 { "/proc/self/fd", "fd" },
887 { "/proc/self/fd/0", "stdin" },
888 { "/proc/self/fd/1", "stdout" },
889 { "/proc/self/fd/2", "stderr" },
892 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
894 for (size_t i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
897 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
900 * Stat the path first. If we don't get an error accept it as
901 * is and don't try to create it
903 ret
= fstatat(rootfs
->dfd_dev
, d
->name
, &s
, 0);
907 ret
= symlinkat(d
->oldpath
, rootfs
->dfd_dev
, d
->name
);
911 WARN("Failed to create \"%s\" on read-only filesystem", d
->name
);
916 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", d
->name
);
924 /* Build a space-separate list of ptys to pass to systemd. */
925 static bool append_ttyname(char **pp
, char *name
)
931 *pp
= zalloc(strlen(name
) + strlen("container_ttys=") + 1);
935 sprintf(*pp
, "container_ttys=%s", name
);
939 size
= strlen(*pp
) + strlen(name
) + 2;
940 p
= realloc(*pp
, size
);
945 (void)strlcat(p
, " ", size
);
946 (void)strlcat(p
, name
, size
);
951 static int open_ttymnt_at(int dfd
, const char *path
)
955 fd
= open_at(dfd
, path
,
956 PROTECT_OPEN
| O_CREAT
| O_EXCL
,
957 PROTECT_LOOKUP_BENEATH
,
960 if (!IN_SET(errno
, ENXIO
, EEXIST
))
961 return syserror("Failed to create \"%d/\%s\"", dfd
, path
);
963 SYSINFO("Failed to create \"%d/\%s\"", dfd
, path
);
964 fd
= open_at(dfd
, path
,
966 PROTECT_LOOKUP_BENEATH
,
973 static int lxc_setup_ttys(struct lxc_conf
*conf
)
976 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
977 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
978 char *ttydir
= ttys
->dir
;
980 if (!conf
->rootfs
.path
)
983 for (size_t i
= 0; i
< ttys
->max
; i
++) {
984 __do_close
int fd_to
= -EBADF
;
985 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
988 char *tty_name
, *tty_path
;
990 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
991 "/dev/%s/tty%zu", ttydir
, i
+ 1);
993 return ret_errno(-EIO
);
995 tty_path
= &rootfs
->buf
[STRLITERALLEN("/dev/")];
996 tty_name
= tty_path
+ strlen(ttydir
) + 1;
998 /* create bind-mount target */
999 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, tty_path
);
1001 return log_error_errno(-errno
, errno
,
1002 "Failed to create tty mount target %d(%s)",
1003 rootfs
->dfd_dev
, tty_path
);
1005 ret
= unlinkat(rootfs
->dfd_dev
, tty_name
, 0);
1006 if (ret
< 0 && errno
!= ENOENT
)
1007 return log_error_errno(-errno
, errno
,
1008 "Failed to unlink %d(%s)",
1009 rootfs
->dfd_dev
, tty_name
);
1011 if (can_use_mount_api())
1012 ret
= fd_bind_mount(tty
->pty
, "",
1014 PROTECT_LOOKUP_BENEATH_XDEV
,
1017 PROTECT_LOOKUP_BENEATH_XDEV
,
1023 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1025 return log_error_errno(-errno
, errno
,
1026 "Failed to bind mount \"%s\" onto \"%s\"",
1027 tty
->name
, rootfs
->buf
);
1028 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1030 ret
= symlinkat(tty_path
, rootfs
->dfd_dev
, tty_name
);
1032 return log_error_errno(-errno
, errno
,
1033 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
1034 rootfs
->dfd_dev
, tty_name
,
1035 rootfs
->dfd_dev
, tty_path
);
1037 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "tty%zu", i
+ 1);
1039 return ret_errno(-EIO
);
1041 /* If we populated /dev, then we need to create /dev/tty<idx>. */
1042 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, rootfs
->buf
);
1044 return log_error_errno(-errno
, errno
,
1045 "Failed to create tty mount target %d(%s)",
1046 rootfs
->dfd_dev
, rootfs
->buf
);
1048 if (can_use_mount_api())
1049 ret
= fd_bind_mount(tty
->pty
, "",
1051 PROTECT_LOOKUP_BENEATH_XDEV
,
1054 PROTECT_LOOKUP_BENEATH
,
1060 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1062 return log_error_errno(-errno
, errno
,
1063 "Failed to bind mount \"%s\" onto \"%s\"",
1064 tty
->name
, rootfs
->buf
);
1065 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1068 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
))
1069 return log_error(-1, "Error setting up container_ttys string");
1072 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
1076 define_cleanup_function(struct lxc_tty_info
*, lxc_delete_tty
);
1078 static int lxc_allocate_ttys(struct lxc_conf
*conf
)
1080 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*ttys
= &conf
->ttys
;
1083 /* no tty in the configuration */
1087 ttys
->tty
= zalloc(sizeof(struct lxc_terminal_info
) * ttys
->max
);
1091 for (size_t i
= 0; i
< conf
->ttys
.max
; i
++) {
1092 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1094 ret
= lxc_devpts_terminal(conf
->devpts_fd
, &tty
->ptx
,
1095 &tty
->pty
, &tty
->pty_nr
, false);
1098 return syserror_set(-ENOTTY
, "Failed to create tty %zu", i
);
1100 ret
= strnprintf(tty
->name
, sizeof(tty
->name
), "pts/%d", tty
->pty_nr
);
1102 return syserror("Failed to create tty %zu", i
);
1104 DEBUG("Created tty with ptx fd %d and pty fd %d and index %d",
1105 tty
->ptx
, tty
->pty
, tty
->pty_nr
);
1109 INFO("Finished creating %zu tty devices", ttys
->max
);
1114 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1116 if (!ttys
|| !ttys
->tty
)
1119 for (size_t i
= 0; i
< ttys
->max
; i
++) {
1120 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1121 close_prot_errno_disarm(tty
->ptx
);
1122 close_prot_errno_disarm(tty
->pty
);
1125 free_disarm(ttys
->tty
);
1128 static int __lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1131 struct lxc_conf
*conf
= handler
->conf
;
1132 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1133 int sock
= handler
->data_sock
[0];
1138 for (size_t i
= 0; i
< ttys
->max
; i
++) {
1140 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1142 ttyfds
[0] = tty
->ptx
;
1143 ttyfds
[1] = tty
->pty
;
1145 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1149 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1150 tty
->name
, tty
->ptx
, tty
->pty
);
1154 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1156 TRACE("Sent %zu ttys to parent", ttys
->max
);
1161 static int lxc_create_ttys(struct lxc_handler
*handler
)
1164 struct lxc_conf
*conf
= handler
->conf
;
1166 ret
= lxc_allocate_ttys(conf
);
1168 ERROR("Failed to allocate ttys");
1172 if (!conf
->is_execute
) {
1173 ret
= lxc_setup_ttys(conf
);
1175 ERROR("Failed to setup ttys");
1180 if (conf
->ttys
.tty_names
) {
1181 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1183 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1186 TRACE("Set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1192 lxc_delete_tty(&conf
->ttys
);
1197 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1201 ret
= __lxc_send_ttys_to_parent(handler
);
1202 lxc_delete_tty(&handler
->conf
->ttys
);
1206 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1207 * error, log it but don't fail yet.
1209 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1210 int autodevtmpfssize
, const char *lxcpath
)
1212 __do_close
int fd_fs
= -EBADF
;
1213 const char *path
= rootfs
->path
? rootfs
->mount
: NULL
;
1214 size_t tmpfs_size
= (autodevtmpfssize
!= 0) ? autodevtmpfssize
: 500000;
1217 char mount_options
[128];
1219 INFO("Preparing \"/dev\"");
1221 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1222 ret
= mkdirat(rootfs
->dfd_mnt
, "dev" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1223 if (ret
< 0 && errno
!= EEXIST
) {
1224 SYSERROR("Failed to create \"/dev\" directory");
1229 if (can_use_mount_api()) {
1230 fd_fs
= fs_prepare("tmpfs", -EBADF
, "", 0, 0);
1232 return log_error_errno(-errno
, errno
, "Failed to prepare filesystem context for tmpfs");
1234 sprintf(mount_options
, "%zu", tmpfs_size
);
1236 ret
= fs_set_property(fd_fs
, "mode", "0755");
1238 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1240 ret
= fs_set_property(fd_fs
, "size", mount_options
);
1242 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1244 ret
= fs_attach(fd_fs
, rootfs
->dfd_mnt
, "dev",
1245 PROTECT_OPATH_DIRECTORY
,
1246 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1248 __do_free
char *fallback_path
= NULL
;
1250 sprintf(mount_options
, "size=%zu,mode=755", tmpfs_size
);
1251 DEBUG("Using mount options: %s", mount_options
);
1254 fallback_path
= must_make_path(path
, "/dev", NULL
);
1255 ret
= safe_mount("none", fallback_path
, "tmpfs", 0, mount_options
, path
);
1257 ret
= safe_mount("none", "dev", "tmpfs", 0, mount_options
, NULL
);
1261 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1265 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1266 * If not, then create it and exit if that fails...
1268 ret
= mkdirat(rootfs
->dfd_mnt
, "dev/pts", S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1269 if (ret
< 0 && errno
!= EEXIST
) {
1270 SYSERROR("Failed to create directory \"dev/pts\"");
1278 (void)umask(cur_mask
);
1280 INFO("Prepared \"/dev\"");
1284 struct lxc_device_node
{
1291 static const struct lxc_device_node lxc_devices
[] = {
1292 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1293 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1294 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1295 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1296 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1297 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1304 LXC_DEVNODE_PARTIAL
,
1308 static int lxc_fill_autodev(struct lxc_rootfs
*rootfs
)
1312 int use_mknod
= LXC_DEVNODE_MKNOD
;
1314 if (rootfs
->dfd_dev
< 0)
1315 return log_info(0, "No /dev directory found, skipping setup");
1317 INFO("Populating \"/dev\"");
1319 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1320 for (size_t i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1321 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1323 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1324 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, device
->mode
, makedev(device
->maj
, device
->min
));
1325 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1326 DEBUG("Created device node \"%s\"", device
->name
);
1327 } else if (ret
< 0) {
1329 return log_error_errno(-1, errno
, "Failed to create device node \"%s\"", device
->name
);
1331 use_mknod
= LXC_DEVNODE_BIND
;
1334 /* Device nodes are fully useable. */
1335 if (use_mknod
== LXC_DEVNODE_OPEN
)
1338 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1339 __do_close
int fd
= -EBADF
;
1341 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1342 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1344 fd
= open_at(rootfs
->dfd_dev
, device
->name
, PROTECT_OPEN
, PROTECT_LOOKUP_BENEATH
, 0);
1346 /* Device nodes are fully useable. */
1347 use_mknod
= LXC_DEVNODE_OPEN
;
1351 SYSTRACE("Failed to open \"%s\" device", device
->name
);
1352 /* Device nodes are only partially useable. */
1353 use_mknod
= LXC_DEVNODE_PARTIAL
;
1357 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1358 /* If we are dealing with partially functional device
1359 * nodes the prio mknod() call will have created the
1360 * device node so we can use it as a bind-mount target.
1362 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, S_IFREG
| 0000, 0);
1363 if (ret
< 0 && errno
!= EEXIST
)
1364 return log_error_errno(-1, errno
, "Failed to create file \"%s\"", device
->name
);
1367 /* Fallback to bind-mounting the device from the host. */
1368 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "dev/%s", device
->name
);
1370 return ret_errno(EIO
);
1372 if (can_use_mount_api()) {
1373 ret
= fd_bind_mount(rootfs
->dfd_host
, rootfs
->buf
,
1375 PROTECT_LOOKUP_BENEATH_XDEV
,
1376 rootfs
->dfd_dev
, device
->name
,
1378 PROTECT_LOOKUP_BENEATH
,
1384 char path
[PATH_MAX
];
1386 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/dev/%s", device
->name
);
1388 return ret_errno(EIO
);
1390 ret
= strnprintf(path
, sizeof(path
), "%s/dev/%s", get_rootfs_mnt(rootfs
), device
->name
);
1392 return log_error(-1, "Failed to create device path for %s", device
->name
);
1394 ret
= safe_mount(rootfs
->buf
, path
, 0, MS_BIND
, NULL
, get_rootfs_mnt(rootfs
));
1396 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1398 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1401 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs
->dfd_host
, rootfs
->buf
, rootfs
->dfd_dev
, device
->name
);
1405 INFO("Populated \"/dev\"");
1409 static int lxc_mount_rootfs(struct lxc_rootfs
*rootfs
)
1413 if (!rootfs
->path
) {
1414 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1416 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
1418 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1419 if (rootfs
->dfd_mnt
< 0)
1422 return log_trace(0, "Container doesn't use separate rootfs. Opened host's rootfs");
1425 ret
= access(rootfs
->mount
, F_OK
);
1427 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1430 ret
= rootfs
->storage
->ops
->mount(rootfs
->storage
);
1432 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1433 rootfs
->path
, rootfs
->mount
,
1434 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
1436 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1437 rootfs
->path
, rootfs
->mount
,
1438 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
1440 rootfs
->dfd_mnt
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1441 if (rootfs
->dfd_mnt
< 0)
1444 return log_trace(0, "Container uses separate rootfs. Opened container's rootfs");
1447 static bool lxc_rootfs_overmounted(struct lxc_rootfs
*rootfs
)
1449 __do_close
int fd_rootfs
= -EBADF
;
1452 fd_rootfs
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1454 fd_rootfs
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1458 if (!same_file_lax(rootfs
->dfd_mnt
, fd_rootfs
))
1459 return syswarn_ret(true, "Rootfs seems to have changed after setting up mounts");
1464 static int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1466 __do_free
char *nroot
= NULL
;
1468 char *root
= rootfs
->mount
;
1470 nroot
= realpath(root
, NULL
);
1472 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1478 /* We could use here MS_MOVE, but in userns this mount is locked and
1481 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1483 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1485 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1487 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1489 /* The following code cleans up inherited mounts which are not required
1492 * The mountinfo file shows not all mounts, if a few points have been
1493 * unmounted between read operations from the mountinfo. So we need to
1494 * read mountinfo a few times.
1496 * This loop can be skipped if a container uses userns, because all
1497 * inherited mounts are locked and we should live with all this trash.
1500 __do_fclose
FILE *f
= NULL
;
1501 __do_free
char *line
= NULL
;
1502 char *slider1
, *slider2
;
1506 f
= fopen("./proc/self/mountinfo", "re");
1508 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1510 while (getline(&line
, &len
, f
) > 0) {
1511 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1512 slider1
= strchr(slider1
+ 1, ' ');
1517 slider2
= strchr(slider1
+ 1, ' ');
1524 if (strequal(slider1
+ 1, "/"))
1527 if (strequal(slider1
+ 1, "/proc"))
1530 ret
= umount2(slider1
, MNT_DETACH
);
1539 /* This also can be skipped if a container uses userns. */
1540 (void)umount2("./proc", MNT_DETACH
);
1542 /* It is weird, but chdir("..") moves us in a new root */
1545 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1549 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1554 /* (The following explanation is copied verbatim from the kernel.)
1556 * pivot_root Semantics:
1557 * Moves the root file system of the current process to the directory put_old,
1558 * makes new_root as the new root file system of the current process, and sets
1559 * root/cwd of all processes which had them on the current root to new_root.
1562 * The new_root and put_old must be directories, and must not be on the
1563 * same file system as the current process root. The put_old must be
1564 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1565 * pointed to by put_old must yield the same directory as new_root. No other
1566 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1568 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1569 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1570 * in this situation.
1573 * - we don't move root/cwd if they are not at the root (reason: if something
1574 * cared enough to change them, it's probably wrong to force them elsewhere)
1575 * - it's okay to pick a root that isn't the root of a file system, e.g.
1576 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1577 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1580 static int lxc_pivot_root(const struct lxc_rootfs
*rootfs
)
1582 __do_close
int fd_oldroot
= -EBADF
;
1585 fd_oldroot
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1587 return log_error_errno(-1, errno
, "Failed to open old root directory");
1589 /* change into new root fs */
1590 ret
= fchdir(rootfs
->dfd_mnt
);
1592 return log_error_errno(-errno
, errno
, "Failed to change into new root directory \"%s\"", rootfs
->mount
);
1594 /* pivot_root into our new root fs */
1595 ret
= pivot_root(".", ".");
1597 return log_error_errno(-errno
, errno
, "Failed to pivot into new root directory \"%s\"", rootfs
->mount
);
1599 /* At this point the old-root is mounted on top of our new-root. To
1600 * unmounted it we must not be chdir'd into it, so escape back to
1603 ret
= fchdir(fd_oldroot
);
1605 return log_error_errno(-errno
, errno
, "Failed to enter old root directory");
1608 * Make fd_oldroot a depedent mount to make sure our umounts don't
1609 * propagate to the host.
1611 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1613 return log_error_errno(-errno
, errno
, "Failed to recursively turn old root mount tree into dependent mount");
1615 ret
= umount2(".", MNT_DETACH
);
1617 return log_error_errno(-errno
, errno
, "Failed to detach old root directory");
1619 ret
= fchdir(rootfs
->dfd_mnt
);
1621 return log_error_errno(-errno
, errno
, "Failed to re-enter new root directory \"%s\"", rootfs
->mount
);
1623 TRACE("Changed into new rootfs \"%s\"", rootfs
->mount
);
1627 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1630 return log_debug(0, "Container does not have a rootfs");
1632 if (detect_ramfs_rootfs())
1633 return lxc_chroot(rootfs
);
1635 return lxc_pivot_root(rootfs
);
1638 static const struct id_map
*find_mapped_nsid_entry(const struct lxc_conf
*conf
,
1643 struct id_map
*retmap
= NULL
;
1645 /* Shortcut for container's root mappings. */
1647 if (idtype
== ID_TYPE_UID
)
1648 return conf
->root_nsuid_map
;
1650 if (idtype
== ID_TYPE_GID
)
1651 return conf
->root_nsgid_map
;
1654 list_for_each_entry(map
, &conf
->id_map
, head
) {
1655 if (map
->idtype
!= idtype
)
1658 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1667 static int lxc_recv_devpts_from_child(struct lxc_handler
*handler
)
1671 if (handler
->conf
->pty_max
<= 0)
1674 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1],
1675 &handler
->conf
->devpts_fd
,
1676 &handler
->conf
->devpts_fd
,
1677 sizeof(handler
->conf
->devpts_fd
));
1679 return log_error_errno(-1, errno
, "Failed to receive devpts fd from child");
1681 TRACE("Received devpts file descriptor %d from child", handler
->conf
->devpts_fd
);
1685 static int lxc_setup_devpts_child(struct lxc_handler
*handler
)
1687 __do_close
int devpts_fd
= -EBADF
, fd_fs
= -EBADF
;
1688 struct lxc_conf
*conf
= handler
->conf
;
1689 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1690 size_t pty_max
= conf
->pty_max
;
1693 pty_max
+= conf
->ttys
.max
;
1695 return log_debug(0, "No new devpts instance will be mounted since no pts devices are required");
1697 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
1698 "/proc/self/fd/%d/pts", rootfs
->dfd_dev
);
1700 return syserror("Failed to create path");
1702 (void)umount2(rootfs
->buf
, MNT_DETACH
);
1704 /* Create mountpoint for devpts instance. */
1705 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1706 if (ret
< 0 && errno
!= EEXIST
)
1707 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1709 if (can_use_mount_api()) {
1710 fd_fs
= fs_prepare("devpts", -EBADF
, "", 0, 0);
1712 return syserror("Failed to prepare filesystem context for devpts");
1714 ret
= fs_set_property(fd_fs
, "source", "devpts");
1716 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs
);
1718 ret
= fs_set_property(fd_fs
, "gid", "5");
1720 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs
);
1722 ret
= fs_set_flag(fd_fs
, "newinstance");
1724 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs
);
1726 ret
= fs_set_property(fd_fs
, "ptmxmode", "0666");
1728 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs
);
1730 ret
= fs_set_property(fd_fs
, "mode", "0620");
1732 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs
);
1734 ret
= fs_set_property(fd_fs
, "max", fdstr(pty_max
));
1736 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf
->pty_max
, fd_fs
);
1738 ret
= fsconfig(fd_fs
, FSCONFIG_CMD_CREATE
, NULL
, NULL
, 0);
1740 return syserror("Failed to finalize filesystem context %d", fd_fs
);
1742 devpts_fd
= fsmount(fd_fs
, FSMOUNT_CLOEXEC
, MOUNT_ATTR_NOSUID
| MOUNT_ATTR_NOEXEC
);
1744 return syserror("Failed to create new mount for filesystem context %d", fd_fs
);
1745 TRACE("Created detached devpts mount %d", devpts_fd
);
1747 ret
= move_mount(devpts_fd
, "", rootfs
->dfd_dev
, "pts", MOVE_MOUNT_F_EMPTY_PATH
);
1749 return syserror("Failed to attach devpts mount %d to %d/pts", conf
->devpts_fd
, rootfs
->dfd_dev
);
1751 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd
, rootfs
->dfd_dev
);
1754 char devpts_mntopts
[256];
1755 char *mntopt_sets
[5];
1756 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1759 * Fallback codepath in case the new mount API can't be used to
1760 * create detached mounts.
1763 ret
= strnprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1764 default_devpts_mntopts
, pty_max
);
1768 /* Create mountpoint for devpts instance. */
1769 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1770 if (ret
< 0 && errno
!= EEXIST
)
1771 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1774 mntopt_sets
[0] = devpts_mntopts
;
1776 /* !gid=5 && max= */
1777 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1779 /* gid=5 && !max= */
1780 mntopt_sets
[2] = default_devpts_mntopts
;
1782 /* !gid=5 && !max= */
1783 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1786 mntopt_sets
[4] = NULL
;
1788 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1789 /* mount new devpts instance */
1790 ret
= mount_at(rootfs
->dfd_dev
, "", 0,
1791 rootfs
->dfd_dev
, "pts", PROTECT_LOOKUP_BENEATH
,
1792 "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1797 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1799 devpts_fd
= open_at(rootfs
->dfd_dev
, "pts", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1800 if (devpts_fd
< 0) {
1802 TRACE("Failed to create detached devpts mount");
1805 DEBUG("Mounted new devpts instance with options \"%s\"", *opts
);
1808 handler
->conf
->devpts_fd
= move_fd(devpts_fd
);
1811 * In order to allocate terminal devices the devpts filesystem will
1812 * have to be attached to the filesystem at least ones in the new mount
1813 * api. The reason is lengthy but the gist is that until the new mount
1814 * has been attached to the filesystem it is a detached mount with an
1815 * anonymous mount mamespace attached to it for which the kernel
1816 * refuses certain operations.
1817 * We end up here if the user has requested to allocate tty devices
1818 * while not requestig pty devices be made available to the container.
1819 * We only need the devpts_fd to allocate tty devices.
1821 if (conf
->pty_max
<= 0)
1824 /* Remove any pre-existing /dev/ptmx file. */
1825 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1827 if (errno
!= ENOENT
)
1828 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1830 DEBUG("Removed existing \"/dev/ptmx\" file");
1833 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1834 ret
= mknodat(rootfs
->dfd_dev
, "ptmx", S_IFREG
| 0000, 0);
1835 if (ret
< 0 && errno
!= EEXIST
)
1836 return log_error_errno(-1, errno
, "Failed to create \"/dev/ptmx\" file as bind mount target");
1837 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
1839 /* Main option: use a bind-mount to please AppArmor */
1840 ret
= mount_at(rootfs
->dfd_dev
, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1841 rootfs
->dfd_dev
, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1842 NULL
, MS_BIND
, NULL
);
1844 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1846 /* Fallthrough and try to create a symlink. */
1847 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1849 /* Remove the placeholder /dev/ptmx file we created above. */
1850 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1852 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1854 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1855 ret
= symlinkat("/dev/pts/ptmx", rootfs
->dfd_dev
, "dev/ptmx");
1857 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1859 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1863 static int lxc_finish_devpts_child(struct lxc_handler
*handler
)
1865 struct lxc_conf
*conf
= handler
->conf
;
1866 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1869 if (conf
->pty_max
> 0)
1873 * We end up here if the user has requested to allocate tty devices
1874 * while not requestig pty devices be made available to the container.
1875 * This means we can unmount the devpts instance. We only need the
1876 * devpts_fd to allocate tty devices.
1878 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
1879 "/proc/self/fd/%d/pts", rootfs
->dfd_dev
);
1881 return syserror("Failed to create path");
1883 close_prot_errno_disarm(conf
->devpts_fd
);
1884 (void)umount2(rootfs
->buf
, MNT_DETACH
);
1888 static int lxc_send_devpts_to_parent(struct lxc_handler
*handler
)
1892 if (handler
->conf
->pty_max
<= 0)
1893 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1895 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->conf
->devpts_fd
, 1, NULL
, 0);
1897 SYSERROR("Failed to send devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1899 TRACE("Sent devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1901 close_prot_errno_disarm(handler
->conf
->devpts_fd
);
1906 static int setup_personality(personality_t persona
)
1910 if (persona
== LXC_ARCH_UNCHANGED
)
1911 return log_debug(0, "Retaining original personality");
1913 ret
= lxc_personality(persona
);
1915 return syserror("Failed to set personality to \"0lx%lx\"", persona
);
1917 INFO("Set personality to \"0lx%lx\"", persona
);
1921 static int bind_mount_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1922 struct lxc_terminal
*console
, int fd_to
)
1924 __do_close
int fd_pty
= -EBADF
;
1926 if (is_empty_string(console
->name
))
1927 return ret_errno(EINVAL
);
1930 * When the pty fd stashed in console->pty has been retrieved via the
1931 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1932 * allocating new pty devices we can't reopen it through openat2() or
1933 * created a detached mount through open_tree() from it. This means we
1934 * would need to mount using the path stased in console->name which is
1935 * unsafe. We could be mounting a device that isn't identical to the
1936 * one we've already safely opened and stashed in console->pty.
1937 * So, what we do is we open an O_PATH file descriptor for
1938 * console->name and verify that the opened fd and the fd we stashed in
1939 * console->pty refer to the same device. If they do we can go on and
1940 * created a detached mount based on the newly opened O_PATH file
1941 * descriptor and then safely mount.
1943 fd_pty
= open_at_same(console
->pty
, fd_devpts
, fdstr(console
->pty_nr
),
1944 PROTECT_OPATH_FILE
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1946 return syserror("Failed to open \"%s\"", console
->name
);
1949 * Note, there are intentionally no open or lookup restrictions since
1950 * we're operating directly on the fd.
1952 if (can_use_mount_api())
1953 return fd_bind_mount(fd_pty
, "", 0, 0, fd_to
, "", 0, 0, 0, 0, 0, false);
1955 return mount_fd(fd_pty
, fd_to
, "none", MS_BIND
, 0);
1958 static int lxc_setup_dev_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1959 struct lxc_terminal
*console
)
1961 __do_close
int fd_console
= -EBADF
;
1965 * When we are asked to setup a console we remove any previous
1966 * /dev/console bind-mounts.
1968 if (exists_file_at(rootfs
->dfd_dev
, "console")) {
1969 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1971 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
1975 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
1977 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
1979 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
1983 * For unprivileged containers autodev or automounts will already have
1984 * taken care of creating /dev/console.
1986 fd_console
= open_at(rootfs
->dfd_dev
,
1988 PROTECT_OPEN
| O_CREAT
,
1989 PROTECT_LOOKUP_BENEATH
,
1992 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
1994 ret
= fchmod(console
->pty
, 0620);
1996 return syserror("Failed to change console mode");
1998 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_console
);
2000 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2001 console
->pty
, console
->name
, fd_console
);
2003 TRACE("Setup console \"%s\"", console
->name
);
2007 static int lxc_setup_ttydir_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
2008 struct lxc_terminal
*console
,
2011 __do_close
int fd_ttydir
= -EBADF
, fd_dev_console
= -EBADF
,
2012 fd_reg_console
= -EBADF
, fd_reg_ttydir_console
= -EBADF
;
2015 /* create dev/<ttydir> */
2016 ret
= mkdirat(rootfs
->dfd_dev
, ttydir
, 0755);
2017 if (ret
< 0 && errno
!= EEXIST
)
2018 return syserror("Failed to create \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
2020 fd_ttydir
= open_at(rootfs
->dfd_dev
,
2022 PROTECT_OPATH_DIRECTORY
,
2023 PROTECT_LOOKUP_BENEATH
,
2026 return syserror("Failed to open \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
2028 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/console", ttydir
);
2032 /* create dev/<ttydir>/console */
2033 fd_reg_ttydir_console
= open_at(fd_ttydir
,
2035 PROTECT_OPEN
| O_CREAT
,
2036 PROTECT_LOOKUP_BENEATH
,
2038 if (fd_reg_ttydir_console
< 0)
2039 return syserror("Failed to create \"%d/console\"", fd_ttydir
);
2041 if (file_exists(rootfs
->buf
)) {
2042 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
2044 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
2048 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
2050 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
2052 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
2055 /* create dev/console */
2056 fd_reg_console
= open_at(rootfs
->dfd_dev
,
2058 PROTECT_OPEN
| O_CREAT
,
2059 PROTECT_LOOKUP_BENEATH
,
2061 if (fd_reg_console
< 0)
2062 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
2064 ret
= fchmod(console
->pty
, 0620);
2066 return syserror("Failed to change console mode");
2068 /* bind mount console to '/dev/<ttydir>/console' */
2069 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_reg_ttydir_console
);
2071 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2072 console
->pty
, console
->name
, fd_reg_ttydir_console
);
2074 fd_dev_console
= open_at_same(console
->pty
,
2078 PROTECT_LOOKUP_BENEATH_XDEV
,
2080 if (fd_dev_console
< 0)
2081 return syserror("Failed to open \"%d/console\"", fd_ttydir
);
2083 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
2084 if (can_use_mount_api())
2085 ret
= fd_bind_mount(fd_dev_console
,
2088 PROTECT_LOOKUP_BENEATH_XDEV
,
2092 PROTECT_LOOKUP_BENEATH
,
2098 ret
= mount_fd(fd_dev_console
, fd_reg_console
, "none", MS_BIND
, 0);
2100 return syserror("Failed to mount \"%d\" on \"%d\"",
2101 fd_dev_console
, fd_reg_console
);
2103 TRACE("Setup console \"%s\"", console
->name
);
2107 static int lxc_setup_console(const struct lxc_handler
*handler
,
2108 struct lxc_rootfs
*rootfs
,
2109 struct lxc_terminal
*console
, char *ttydir
)
2111 __do_close
int fd_devpts_host
= -EBADF
;
2112 int fd_devpts
= handler
->conf
->devpts_fd
;
2115 if (!wants_console(console
))
2116 return log_trace(0, "Skipping console setup");
2118 if (console
->pty
< 0) {
2120 * Allocate a console from the container's devpts instance. We
2121 * have checked on the host that we have enough pty devices
2124 ret
= lxc_devpts_terminal(handler
->conf
->devpts_fd
, &console
->ptx
,
2125 &console
->pty
, &console
->pty_nr
, false);
2127 return syserror("Failed to allocate console from container's devpts instance");
2129 ret
= strnprintf(console
->name
, sizeof(console
->name
),
2130 "/dev/pts/%d", console
->pty_nr
);
2132 return syserror("Failed to create console path");
2135 * We're using a console from the host's devpts instance. Open
2136 * it again so we can later verify that the console we're
2137 * supposed to use is still the same as the one we opened on
2140 fd_devpts_host
= open_at(rootfs
->dfd_host
,
2142 PROTECT_OPATH_DIRECTORY
,
2143 PROTECT_LOOKUP_BENEATH_XDEV
,
2145 if (fd_devpts_host
< 0)
2146 return syserror("Failed to open host devpts");
2148 fd_devpts
= fd_devpts_host
;
2152 ret
= lxc_setup_ttydir_console(fd_devpts
, rootfs
, console
, ttydir
);
2154 ret
= lxc_setup_dev_console(fd_devpts
, rootfs
, console
);
2156 return syserror("Failed to setup console");
2159 * Some init's such as busybox will set sane tty settings on stdin,
2160 * stdout, stderr which it thinks is the console. We already set them
2161 * the way we wanted on the real terminal, and we want init to do its
2162 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2163 * make sure that that pty is stdin,stdout,stderr.
2165 if (console
->pty
>= 0) {
2166 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
2167 ret
= set_stdfds(console
->pty
);
2169 ret
= lxc_terminal_set_stdfds(console
->pty
);
2171 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console
->pty
);
2174 * If the console has been allocated from the host's devpts
2175 * we're done and we don't need to send fds to the parent.
2177 if (fd_devpts_host
>= 0)
2178 lxc_terminal_delete(console
);
2184 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
2188 /* If '=' is contained in opt, the option must go into data. */
2189 if (!strchr(opt
, '=')) {
2191 * If opt is found in mount_opt, set or clear flags.
2192 * Otherwise append it to data.
2194 size_t opt_len
= strlen(opt
);
2195 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2196 size_t mo_name_len
= strlen(mo
->name
);
2198 if (opt_len
== mo_name_len
&& strnequal(opt
, mo
->name
, mo_name_len
)) {
2200 *flags
&= ~mo
->legacy_flag
;
2202 *flags
|= mo
->legacy_flag
;
2208 if (strlen(*data
)) {
2209 ret
= strlcat(*data
, ",", size
);
2211 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
2214 ret
= strlcat(*data
, opt
, size
);
2216 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
2221 int parse_mntopts_legacy(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
2223 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2224 char *mntopt_cur
= NULL
;
2227 if (*mntdata
|| *mntflags
)
2228 return ret_errno(EINVAL
);
2233 mntopts_dup
= strdup(mntopts
);
2235 return ret_errno(ENOMEM
);
2237 size
= strlen(mntopts_dup
) + 1;
2238 mntopts_new
= zalloc(size
);
2240 return ret_errno(ENOMEM
);
2242 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
2243 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
2244 return ret_errno(EINVAL
);
2247 *mntdata
= move_ptr(mntopts_new
);
2252 static int parse_vfs_attr(struct lxc_mount_options
*opts
, char *opt
, size_t size
)
2255 * If opt is found in mount_opt, set or clear flags.
2256 * Otherwise append it to data.
2258 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2259 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2262 /* This is a recursive bind-mount. */
2263 if (strequal(mo
->name
, "rbind")) {
2264 opts
->bind_recursively
= 1;
2266 opts
->mnt_flags
|= mo
->legacy_flag
; /* MS_BIND | MS_REC */
2270 /* This is a bind-mount. */
2271 if (strequal(mo
->name
, "bind")) {
2273 opts
->mnt_flags
|= mo
->legacy_flag
; /* MS_BIND */
2277 if (mo
->flag
== (__u64
)~0)
2278 return log_info(0, "Ignoring %s mount option", mo
->name
);
2281 opts
->attr
.attr_clr
|= mo
->flag
;
2282 opts
->mnt_flags
&= ~mo
->legacy_flag
;
2283 TRACE("Lowering %s", mo
->name
);
2285 opts
->attr
.attr_set
|= mo
->flag
;
2286 opts
->mnt_flags
|= mo
->legacy_flag
;
2287 TRACE("Raising %s", mo
->name
);
2293 for (struct mount_opt
*mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
2294 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2297 if (strequal(mo
->name
, "rslave") ||
2298 strequal(mo
->name
, "rshared") ||
2299 strequal(mo
->name
, "runbindable") ||
2300 strequal(mo
->name
, "rprivate"))
2301 opts
->propagate_recursively
= 1;
2303 opts
->attr
.propagation
= mo
->flag
;
2304 opts
->prop_flags
|= mo
->legacy_flag
;
2311 int parse_mount_attrs(struct lxc_mount_options
*opts
, const char *mntopts
)
2313 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2314 char *end
= NULL
, *mntopt_cur
= NULL
;
2319 return ret_errno(EINVAL
);
2324 mntopts_dup
= strdup(mntopts
);
2326 return ret_errno(ENOMEM
);
2328 size
= strlen(mntopts_dup
) + 1;
2329 mntopts_new
= zalloc(size
);
2331 return ret_errno(ENOMEM
);
2333 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",") {
2334 /* This is a filesystem specific option. */
2335 if (strchr(mntopt_cur
, '=')) {
2337 end
= stpcpy(mntopts_new
, mntopt_cur
);
2339 end
= stpcpy(end
, ",");
2340 end
= stpcpy(end
, mntopt_cur
);
2346 /* This is a generic vfs option. */
2347 ret
= parse_vfs_attr(opts
, mntopt_cur
, size
);
2349 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur
);
2353 opts
->data
= move_ptr(mntopts_new
);
2358 static void null_endofword(char *word
)
2360 while (*word
&& *word
!= ' ' && *word
!= '\t')
2365 /* skip @nfields spaces in @src */
2366 static char *get_field(char *src
, int nfields
)
2371 for (i
= 0; i
< nfields
; i
++) {
2372 while (*p
&& *p
!= ' ' && *p
!= '\t')
2384 static int mount_entry(const char *fsname
, const char *target
,
2385 const char *fstype
, unsigned long mountflags
,
2386 unsigned long pflags
, const char *data
, bool optional
,
2387 bool dev
, bool relative
, const char *rootfs
)
2390 char srcbuf
[PATH_MAX
];
2391 const char *srcpath
= fsname
;
2397 ret
= strnprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2399 return log_error_errno(-1, errno
, "source path is too long");
2403 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2407 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2408 srcpath
? srcpath
: "(null)", target
);
2410 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2411 srcpath
? srcpath
: "(null)", target
);
2414 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2416 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2417 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2420 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2421 unsigned long required_flags
= 0;
2423 if (sb
.f_flag
& MS_NOSUID
)
2424 required_flags
|= MS_NOSUID
;
2426 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2427 required_flags
|= MS_NODEV
;
2429 if (sb
.f_flag
& MS_RDONLY
)
2430 required_flags
|= MS_RDONLY
;
2432 if (sb
.f_flag
& MS_NOEXEC
)
2433 required_flags
|= MS_NOEXEC
;
2435 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2436 srcpath
, sb
.f_flag
, required_flags
);
2438 /* If this was a bind mount request, and required_flags
2439 * does not have any flags which are not already in
2440 * mountflags, then skip the remount.
2442 if (!(mountflags
& MS_REMOUNT
) &&
2443 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
2444 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
2448 mountflags
|= required_flags
;
2452 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2455 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2456 srcpath
? srcpath
: "(null)",
2459 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2460 srcpath
? srcpath
: "(null)",
2469 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2472 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2474 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2476 DEBUG("Changed mount propagation for \"%s\"", target
);
2479 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2480 srcpath
? srcpath
: "(null)", target
, fstype
);
2485 const char *lxc_mount_options_info
[LXC_MOUNT_MAX
] = {
2493 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2494 int parse_lxc_mount_attrs(struct lxc_mount_options
*opts
, char *mnt_opts
)
2496 for (size_t i
= LXC_MOUNT_CREATE_DIR
; i
< LXC_MOUNT_MAX
; i
++) {
2497 __do_close
int fd_userns
= -EBADF
;
2498 const char *opt_name
= lxc_mount_options_info
[i
];
2500 char *idmap_path
, *opt
, *opt_next
;
2502 opt
= strstr(mnt_opts
, opt_name
);
2507 case LXC_MOUNT_CREATE_DIR
:
2508 opts
->create_dir
= 1;
2510 case LXC_MOUNT_CREATE_FILE
:
2511 opts
->create_file
= 1;
2513 case LXC_MOUNT_OPTIONAL
:
2516 case LXC_MOUNT_RELATIVE
:
2519 case LXC_MOUNT_IDMAP
:
2521 opt_next
+= STRLITERALLEN("idmap=");
2522 idmap_path
= strchrnul(opt_next
, ',');
2523 len
= idmap_path
- opt_next
+ 1;
2525 if (len
>= sizeof(opts
->userns_path
))
2526 return syserror_set(-EIO
, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2528 strlcpy(opts
->userns_path
, opt_next
, len
);
2530 if (is_empty_string(opts
->userns_path
))
2531 return syserror_set(-EINVAL
, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2533 if (!strequal(opts
->userns_path
, "container")) {
2534 fd_userns
= open(opts
->userns_path
, O_RDONLY
| O_NOCTTY
| O_CLOEXEC
);
2536 return syserror("Failed to open user namespace %s", opts
->userns_path
);
2539 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns
, opts
->userns_path
);
2542 return syserror_set(-EINVAL
, "Unknown LXC specific mount option");
2545 opt_next
= strchr(opt
, ',');
2547 *opt
= '\0'; /* no more mntopts, so just chop it here */
2549 memmove(opt
, opt_next
+ 1, strlen(opt_next
+ 1) + 1);
2555 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2557 const struct lxc_rootfs
*rootfs
,
2558 const char *lxc_name
, const char *lxc_path
)
2560 __do_free
char *p1
= NULL
;
2564 if (strnequal(mntent
->mnt_type
, "overlay", 7)) {
2565 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2570 if (hasmntopt(mntent
, "create=dir")) {
2571 ret
= mkdir_p(path
, 0755);
2572 if (ret
< 0 && errno
!= EEXIST
)
2573 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2576 if (!hasmntopt(mntent
, "create=file"))
2579 ret
= access(path
, F_OK
);
2589 ret
= mkdir_p(p2
, 0755);
2590 if (ret
< 0 && errno
!= EEXIST
)
2591 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2593 ret
= mknod(path
, S_IFREG
| 0000, 0);
2594 if (ret
< 0 && errno
!= EEXIST
)
2600 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2601 * without a rootfs. */
2602 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2604 const struct lxc_rootfs
*rootfs
,
2605 const char *lxc_name
,
2606 const char *lxc_path
)
2608 __do_free
char *mntdata
= NULL
;
2609 char *rootfs_path
= NULL
;
2611 bool dev
, optional
, relative
;
2612 struct lxc_mount_options opts
= {};
2614 optional
= hasmntopt(mntent
, "optional") != NULL
;
2615 dev
= hasmntopt(mntent
, "dev") != NULL
;
2616 relative
= hasmntopt(mntent
, "relative") != NULL
;
2618 if (rootfs
&& rootfs
->path
)
2619 rootfs_path
= rootfs
->mount
;
2621 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2630 ret
= parse_lxc_mount_attrs(&opts
, mntent
->mnt_opts
);
2635 * Idmapped mount entries will be setup by the parent for us. Note that
2636 * we rely on mount_entry_create_dir_file() above to have already
2637 * created the target path for us. So the parent can just open the
2638 * target and send us the target fd.
2641 if (!is_empty_string(opts
.userns_path
))
2642 return systrace_ret(0, "Skipping idmapped mount entry");
2644 ret
= parse_mount_attrs(&opts
, mntent
->mnt_opts
);
2648 ret
= mount_entry(mntent
->mnt_fsname
,
2662 static inline int mount_entry_on_systemfs(struct lxc_rootfs
*rootfs
,
2663 struct mntent
*mntent
)
2667 /* For containers created without a rootfs all mounts are treated as
2668 * absolute paths starting at / on the host.
2670 if (mntent
->mnt_dir
[0] != '/')
2671 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/%s", mntent
->mnt_dir
);
2673 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s", mntent
->mnt_dir
);
2677 return mount_entry_on_generic(mntent
, rootfs
->buf
, NULL
, NULL
, NULL
);
2680 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2681 struct lxc_rootfs
*rootfs
,
2682 const char *lxc_name
,
2683 const char *lxc_path
)
2687 const char *lxcpath
;
2690 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2694 /* If rootfs->path is a blockdev path, allow container fstab to use
2695 * <lxcpath>/<name>/rootfs" as the target prefix.
2697 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s/rootfs", lxcpath
, lxc_name
);
2701 aux
= strstr(mntent
->mnt_dir
, rootfs
->buf
);
2703 offset
= strlen(rootfs
->buf
);
2708 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2710 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2711 offset
= strlen(rootfs
->path
);
2714 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, aux
+ offset
);
2718 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2721 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2722 struct lxc_rootfs
*rootfs
,
2723 const char *lxc_name
,
2724 const char *lxc_path
)
2728 /* relative to root mount point */
2729 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2733 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2736 static int mount_file_entries(struct lxc_rootfs
*rootfs
, FILE *file
,
2737 const char *lxc_name
, const char *lxc_path
)
2740 struct mntent mntent
;
2742 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2746 ret
= mount_entry_on_systemfs(rootfs
, &mntent
);
2747 else if (mntent
.mnt_dir
[0] != '/')
2748 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2749 lxc_name
, lxc_path
);
2751 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2752 lxc_name
, lxc_path
);
2757 if (!feof(file
) || ferror(file
))
2758 return log_error(-1, "Failed to parse mount entries");
2763 static inline void __auto_endmntent__(FILE **f
)
2769 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2771 static int setup_mount_fstab(struct lxc_rootfs
*rootfs
, const char *fstab
,
2772 const char *lxc_name
, const char *lxc_path
)
2774 __do_endmntent
FILE *f
= NULL
;
2780 f
= setmntent(fstab
, "re");
2782 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2784 ret
= mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2786 ERROR("Failed to set up mount entries");
2792 * In order for nested containers to be able to mount /proc and /sys they need
2793 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2795 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2796 * apparmor rule to deny access to them. This is mostly for convenience: The
2797 * container's root user can mount them anyway and thus has access to the two
2798 * file systems. But a non-root user in the container should not be allowed to
2799 * access them as a side effect without explicitly allowing it.
2801 static const char nesting_helpers
[] =
2802 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2803 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2805 FILE *make_anonymous_mount_file(const struct list_head
*mount_entries
,
2806 bool include_nesting_helpers
)
2808 __do_close
int fd
= -EBADF
;
2811 struct string_entry
*entry
;
2813 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2815 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2817 if (errno
!= ENOSYS
)
2820 fd
= lxc_make_tmpfile(template, true);
2822 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2824 TRACE("Created temporary mount file");
2827 list_for_each_entry(entry
, mount_entries
, head
) {
2830 len
= strlen(entry
->val
);
2832 ret
= lxc_write_nointr(fd
, entry
->val
, len
);
2833 if (ret
< 0 || (size_t)ret
!= len
)
2836 ret
= lxc_write_nointr(fd
, "\n", 1);
2841 if (include_nesting_helpers
) {
2842 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2843 STRARRAYLEN(nesting_helpers
));
2844 if (ret
!= STRARRAYLEN(nesting_helpers
))
2848 ret
= lseek(fd
, 0, SEEK_SET
);
2852 f
= fdopen(fd
, "re+");
2854 move_fd(fd
); /* Transfer ownership of fd. */
2858 static int setup_mount_entries(const struct lxc_conf
*conf
,
2859 struct lxc_rootfs
*rootfs
,
2860 const char *lxc_name
, const char *lxc_path
)
2862 __do_fclose
FILE *f
= NULL
;
2864 f
= make_anonymous_mount_file(&conf
->mount_entries
, conf
->lsm_aa_allow_nesting
);
2868 return mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2871 static int __lxc_idmapped_mounts_child(struct lxc_handler
*handler
, FILE *f
)
2873 struct lxc_conf
*conf
= handler
->conf
;
2874 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
2878 struct mntent mntent
;
2880 while (getmntent_r(f
, &mntent
, buf
, sizeof(buf
))) {
2881 __do_close
int fd_from
= -EBADF
, fd_to
= -EBADF
,
2883 __do_free
char *__data
= NULL
;
2884 int cur_mnt_seq
= -1;
2885 struct lxc_mount_options opts
= {};
2887 const char *source_relative
, *target_relative
;
2888 struct lxc_mount_attr attr
= {};
2890 ret
= parse_lxc_mount_attrs(&opts
, mntent
.mnt_opts
);
2892 return syserror("Failed to parse LXC specific mount options");
2895 ret
= parse_mount_attrs(&opts
, mntent
.mnt_opts
);
2897 return syserror("Failed to parse mount options");
2899 /* No idmapped mount entry so skip it. */
2900 if (is_empty_string(opts
.userns_path
))
2903 if (!can_use_bind_mounts())
2904 return syserror_set(-EINVAL
, "Kernel does not support idmapped mounts");
2907 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2909 /* We don't support new filesystem mounts yet. */
2910 if (!is_empty_string(mntent
.mnt_type
) &&
2911 !strequal(mntent
.mnt_type
, "none"))
2912 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2914 /* Someone specified additional mount options for a bind-mount. */
2915 if (!is_empty_string(opts
.data
))
2916 return syserror_set(-EINVAL
, "Bind mounts don't support non-generic mount options");
2919 * The source path is supposed to be taken relative to the
2920 * container's rootfs mount or - if the container does not have
2921 * a separate rootfs - to the host's /.
2923 source_relative
= deabs(mntent
.mnt_fsname
);
2924 if (opts
.relative
|| !rootfs
->path
)
2925 dfd_from
= rootfs
->dfd_mnt
;
2927 dfd_from
= rootfs
->dfd_host
;
2928 fd_from
= open_tree(dfd_from
, source_relative
,
2929 OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
|
2930 (opts
.bind_recursively
? AT_RECURSIVE
: 0));
2932 return syserror("Failed to create detached %smount of %d/%s",
2933 opts
.bind_recursively
? "recursive " : "",
2934 dfd_from
, source_relative
);
2936 if (strequal(opts
.userns_path
, "container"))
2937 fd_userns
= openat(dfd_from
, "proc/self/ns/user", O_RDONLY
| O_CLOEXEC
);
2939 fd_userns
= open_at(-EBADF
, opts
.userns_path
,
2940 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
2941 if (fd_userns
< 0) {
2942 if (opts
.optional
) {
2943 TRACE("Skipping optional idmapped mount");
2947 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
2948 opts
.userns_path
, opts
.bind_recursively
? "recursive " : "",
2949 dfd_from
, source_relative
);
2952 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
2954 &opts
, sizeof(opts
));
2956 if (opts
.optional
) {
2957 TRACE("Skipping optional idmapped mount");
2961 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
2962 fd_from
, opts
.bind_recursively
? "recursive " : "",
2963 dfd_from
, source_relative
, fd_userns
,
2967 ret
= lxc_abstract_unix_rcv_credential(handler
->data_sock
[0],
2969 sizeof(cur_mnt_seq
));
2971 if (opts
.optional
) {
2972 TRACE("Skipping optional idmapped mount");
2976 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2977 opts
.bind_recursively
? "recursive " : "",
2978 dfd_from
, source_relative
, fd_userns
);
2981 if (mnt_seq
!= cur_mnt_seq
)
2982 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
2983 mnt_seq
, cur_mnt_seq
);
2986 /* Set regular mount options. */
2988 attr
.propagation
= 0;
2989 ret
= mount_setattr(fd_from
,
2992 (opts
.bind_recursively
? AT_RECURSIVE
: 0),
2996 if (opts
.optional
) {
2997 TRACE("Skipping optional idmapped mount");
3001 return syserror("Failed to set %smount options on detached %d/%s",
3002 opts
.bind_recursively
? "recursive " : "",
3003 dfd_from
, source_relative
);
3006 /* Set propagation mount options. */
3007 if (opts
.attr
.propagation
) {
3008 attr
= (struct lxc_mount_attr
) {
3009 .propagation
= opts
.attr
.propagation
,
3012 ret
= mount_setattr(fd_from
,
3015 (opts
.propagate_recursively
? AT_RECURSIVE
: 0),
3019 if (opts
.optional
) {
3020 TRACE("Skipping optional idmapped mount");
3024 return syserror("Failed to set %spropagation mount options on detached %d/%s",
3025 opts
.bind_recursively
? "recursive " : "",
3026 dfd_from
, source_relative
);
3032 * In contrast to the legacy mount codepath we will simplify
3033 * our lifes and just always treat the target mountpoint to be
3034 * relative to the container's rootfs mountpoint or - if the
3035 * container does not have a separate rootfs - to the host's /.
3038 target_relative
= deabs(mntent
.mnt_dir
);
3040 dfd_from
= rootfs
->dfd_mnt
;
3042 dfd_from
= rootfs
->dfd_host
;
3043 fd_to
= open_at(dfd_from
, target_relative
, PROTECT_OPATH_FILE
, PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
, 0);
3045 if (opts
.optional
) {
3046 TRACE("Skipping optional idmapped mount");
3050 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
3051 dfd_from
, target_relative
,
3052 opts
.bind_recursively
? "recursive " : "",
3053 fd_userns
, dfd_from
, source_relative
);
3056 ret
= move_detached_mount(fd_from
, fd_to
, "", 0, 0);
3058 if (opts
.optional
) {
3059 TRACE("Skipping optional idmapped mount");
3063 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3064 opts
.bind_recursively
? "recursive " : "",
3065 fd_userns
, dfd_from
, source_relative
, dfd_from
, target_relative
);
3068 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3069 opts
.bind_recursively
? "recursive " : "", fd_userns
, dfd_from
,
3070 source_relative
, dfd_from
, target_relative
);
3073 if (!feof(f
) || ferror(f
))
3074 return syserror_set(-EINVAL
, "Failed to parse mount entries");
3079 static int lxc_idmapped_mounts_child(struct lxc_handler
*handler
)
3081 __do_fclose
FILE *f_entries
= NULL
;
3083 struct lxc_conf
*conf
= handler
->conf
;
3084 const char *fstab
= conf
->fstab
;
3087 f_entries
= make_anonymous_mount_file(&conf
->mount_entries
,
3088 conf
->lsm_aa_allow_nesting
);
3090 SYSERROR("Failed to create anonymous mount file");
3094 ret
= __lxc_idmapped_mounts_child(handler
, f_entries
);
3096 SYSERROR("Failed to setup idmapped mount entries");
3100 TRACE("Finished setting up idmapped mounts");
3103 __do_endmntent
FILE *f_fstab
= NULL
;
3105 f_fstab
= setmntent(fstab
, "re");
3107 SYSERROR("Failed to open fstab format file \"%s\"", fstab
);
3111 ret
= __lxc_idmapped_mounts_child(handler
, f_fstab
);
3113 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3117 TRACE("Finished setting up idmapped mounts specified in fstab");
3123 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[0], NULL
, 0);
3125 return syserror("Failed to inform parent that we are done setting up mounts");
3130 int parse_cap(const char *cap_name
, __u32
*cap
)
3132 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
3137 if (strequal(cap_name
, "none"))
3140 for (size_t i
= 0; i
< end
; i
++) {
3141 if (!strequal(cap_name
, caps_opt
[i
].name
))
3144 *cap
= caps_opt
[i
].value
;
3149 * Try to see if it's numeric, so the user may specify
3150 * capabilities that the running kernel knows about but we
3153 ret
= lxc_safe_uint(cap_name
, &res
);
3157 ret
= lxc_caps_last_cap(&last_cap
);
3161 if ((__u32
)res
> last_cap
)
3168 bool has_cap(__u32 cap
, struct lxc_conf
*conf
)
3170 bool cap_in_list
= false;
3171 struct cap_entry
*cap_entry
;
3173 list_for_each_entry(cap_entry
, &conf
->caps
.list
, head
) {
3174 if (cap_entry
->cap
!= cap
)
3180 /* The capability is kept. */
3181 if (conf
->caps
.keep
)
3184 /* The capability is not dropped. */
3185 return !cap_in_list
;
3188 static int capabilities_deny(struct lxc_conf
*conf
)
3190 struct cap_entry
*cap
;
3192 list_for_each_entry(cap
, &conf
->caps
.list
, head
) {
3195 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(cap
->cap
), prctl_arg(0),
3196 prctl_arg(0), prctl_arg(0));
3198 return syserror("Failed to remove %s capability", cap
->cap_name
);
3200 DEBUG("Dropped %s (%d) capability", cap
->cap_name
, cap
->cap
);
3203 DEBUG("Capabilities have been setup");
3207 static int capabilities_allow(struct lxc_conf
*conf
)
3209 __do_free __u32
*keep_bits
= NULL
;
3211 struct cap_entry
*cap
;
3212 __u32 last_cap
, nr_u32
;
3214 ret
= lxc_caps_last_cap(&last_cap
);
3215 if (ret
|| last_cap
> 200)
3216 return ret_errno(EINVAL
);
3218 TRACE("Found %d capabilities", last_cap
);
3220 nr_u32
= BITS_TO_LONGS(last_cap
);
3221 keep_bits
= zalloc(nr_u32
* sizeof(__u32
));
3223 return ret_errno(ENOMEM
);
3225 list_for_each_entry(cap
, &conf
->caps
.list
, head
) {
3226 if (cap
->cap
> last_cap
)
3229 set_bit(cap
->cap
, keep_bits
);
3230 DEBUG("Keeping %s (%d) capability", cap
->cap_name
, cap
->cap
);
3233 for (__u32 cap_bit
= 0; cap_bit
<= last_cap
; cap_bit
++) {
3234 if (is_set(cap_bit
, keep_bits
))
3237 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(cap_bit
), prctl_arg(0),
3238 prctl_arg(0), prctl_arg(0));
3240 return syserror("Failed to remove capability %d", cap_bit
);
3242 TRACE("Dropped capability %d", cap_bit
);
3245 DEBUG("Capabilities have been setup");
3249 static int parse_resource(const char *res
)
3255 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
3256 if (strequal(res
, limit_opt
[i
].name
))
3257 return limit_opt
[i
].value
;
3259 /* Try to see if it's numeric, so the user may specify
3260 * resources that the running kernel knows about but
3263 ret
= lxc_safe_int(res
, &resid
);
3270 int setup_resource_limits(struct lxc_conf
*conf
, pid_t pid
)
3273 struct lxc_limit
*lim
;
3275 if (list_empty(&conf
->limits
))
3278 list_for_each_entry(lim
, &conf
->limits
, head
) {
3279 resid
= parse_resource(lim
->resource
);
3281 return log_error(-1, "Unknown resource %s", lim
->resource
);
3283 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
3284 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
3285 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
3287 TRACE("Setup \"%s\" limit", lim
->resource
);
3289 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
3293 TRACE("Setup resource limits");
3297 int setup_sysctl_parameters(struct lxc_conf
*conf
)
3299 __do_free
char *tmp
= NULL
;
3301 char filename
[PATH_MAX
] = {0};
3302 struct lxc_sysctl
*sysctl
, *nsysctl
;
3304 if (list_empty(&conf
->sysctls
))
3307 list_for_each_entry_safe(sysctl
, nsysctl
, &conf
->sysctls
, head
) {
3308 tmp
= lxc_string_replace(".", "/", sysctl
->key
);
3310 return log_error(-1, "Failed to replace key %s", sysctl
->key
);
3312 ret
= strnprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
3314 return log_error(-1, "Error setting up sysctl parameters path");
3316 ret
= lxc_write_to_file(filename
, sysctl
->value
,
3317 strlen(sysctl
->value
), false, 0666);
3319 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
3320 sysctl
->key
, sysctl
->value
);
3322 TRACE("Setting %s to %s", filename
, sysctl
->value
);
3325 TRACE("Setup /proc/sys settings");
3329 int setup_proc_filesystem(struct lxc_conf
*conf
, pid_t pid
)
3331 __do_free
char *tmp
= NULL
;
3333 char filename
[PATH_MAX
] = {0};
3334 struct lxc_proc
*proc
;
3336 if (list_empty(&conf
->procs
))
3339 list_for_each_entry(proc
, &conf
->procs
, head
) {
3340 tmp
= lxc_string_replace(".", "/", proc
->filename
);
3342 return log_error(-1, "Failed to replace key %s", proc
->filename
);
3344 ret
= strnprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
3346 return log_error(-1, "Error setting up proc filesystem path");
3348 ret
= lxc_write_to_file(filename
, proc
->value
,
3349 strlen(proc
->value
), false, 0666);
3351 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s",
3352 proc
->filename
, proc
->value
);
3354 TRACE("Setting %s to %s", filename
, proc
->value
);
3357 TRACE("Setup /proc/%d settings", pid
);
3361 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
3363 struct lxc_conf
*lxc_conf_init(void)
3366 struct lxc_conf
*new;
3368 new = zalloc(sizeof(*new));
3372 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
3373 new->personality
= LXC_ARCH_UNCHANGED
;
3375 new->console
.buffer_size
= 0;
3376 new->console
.log_path
= NULL
;
3377 new->console
.log_fd
= -1;
3378 new->console
.log_size
= 0;
3379 new->console
.path
= NULL
;
3380 new->console
.peer
= -1;
3381 new->console
.proxy
.busy
= -1;
3382 new->console
.proxy
.ptx
= -1;
3383 new->console
.proxy
.pty
= -1;
3384 new->console
.ptx
= -EBADF
;
3385 new->console
.pty
= -EBADF
;
3386 new->console
.pty_nr
= -1;
3387 new->console
.name
[0] = '\0';
3388 new->devpts_fd
= -EBADF
;
3389 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
3390 new->maincmd_fd
= -1;
3391 new->monitor_signal_pdeath
= SIGKILL
;
3393 new->rootfs
.mount
= strdup(default_rootfs_mount
);
3394 if (!new->rootfs
.mount
) {
3398 new->rootfs
.managed
= true;
3399 new->rootfs
.dfd_mnt
= -EBADF
;
3400 new->rootfs
.dfd_dev
= -EBADF
;
3401 new->rootfs
.dfd_host
= -EBADF
;
3402 new->rootfs
.fd_path_pin
= -EBADF
;
3403 new->rootfs
.dfd_idmapped
= -EBADF
;
3405 INIT_LIST_HEAD(&new->cgroup
);
3406 INIT_LIST_HEAD(&new->cgroup2
);
3407 /* Block ("allowlist") all devices by default. */
3408 new->bpf_devices
.list_type
= LXC_BPF_DEVICE_CGROUP_ALLOWLIST
;
3409 INIT_LIST_HEAD(&(new->bpf_devices
).devices
);
3410 INIT_LIST_HEAD(&new->mount_entries
);
3411 INIT_LIST_HEAD(&new->caps
.list
);
3412 INIT_LIST_HEAD(&new->id_map
);
3413 new->root_nsuid_map
= NULL
;
3414 new->root_nsgid_map
= NULL
;
3415 INIT_LIST_HEAD(&new->environment
);
3416 INIT_LIST_HEAD(&new->limits
);
3417 INIT_LIST_HEAD(&new->sysctls
);
3418 INIT_LIST_HEAD(&new->procs
);
3419 new->hooks_version
= 0;
3420 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
3421 INIT_LIST_HEAD(&new->hooks
[i
]);
3422 INIT_LIST_HEAD(&new->groups
);
3423 INIT_LIST_HEAD(&new->state_clients
);
3424 new->lsm_aa_profile
= NULL
;
3425 INIT_LIST_HEAD(&new->lsm_aa_raw
);
3426 new->lsm_se_context
= NULL
;
3427 new->lsm_se_keyring_context
= NULL
;
3428 new->keyring_disable_session
= false;
3429 new->transient_procfs_mnt
= false;
3430 new->shmount
.path_host
= NULL
;
3431 new->shmount
.path_cont
= NULL
;
3432 new->sched_core
= false;
3433 new->sched_core_cookie
= INVALID_SCHED_CORE_COOKIE
;
3435 /* if running in a new user namespace, init and COMMAND
3436 * default to running as UID/GID 0 when using lxc-execute */
3439 memset(&new->init_groups
, 0, sizeof(lxc_groups_t
));
3440 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
3441 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
3442 memset(&new->timens
, 0, sizeof(struct timens_offsets
));
3443 seccomp_conf_init(new);
3445 INIT_LIST_HEAD(&new->netdevs
);
3450 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
3453 __do_close
int fd
= -EBADF
;
3455 char path
[PATH_MAX
];
3457 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
3458 __do_close
int setgroups_fd
= -EBADF
;
3460 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/setgroups", pid
);
3464 setgroups_fd
= open(path
, O_WRONLY
);
3465 if (setgroups_fd
< 0 && errno
!= ENOENT
)
3466 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3468 if (setgroups_fd
>= 0) {
3469 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
3470 STRLITERALLEN("deny\n"));
3471 if (ret
!= STRLITERALLEN("deny\n"))
3472 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
3473 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
3477 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/%cid_map", pid
,
3478 idtype
== ID_TYPE_UID
? 'u' : 'g');
3482 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
3484 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3486 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
3487 if (ret
< 0 || (size_t)ret
!= buf_size
)
3488 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
3489 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
3494 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3496 * @return 1 if functional binary was found
3497 * @return 0 if binary exists but is lacking privilege
3498 * @return -ENOENT if binary does not exist
3499 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
3501 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
3503 __do_free
char *path
= NULL
;
3507 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
3508 return ret_errno(EINVAL
);
3510 path
= on_path(binary
, NULL
);
3512 return ret_errno(ENOENT
);
3514 ret
= stat(path
, &st
);
3518 /* Check if the binary is setuid. */
3519 if (st
.st_mode
& S_ISUID
)
3520 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
3522 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
3523 /* Check if it has the CAP_SETUID capability. */
3524 if ((cap
& CAP_SETUID
) &&
3525 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
3526 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
3527 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3529 /* Check if it has the CAP_SETGID capability. */
3530 if ((cap
& CAP_SETGID
) &&
3531 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
3532 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
3533 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3538 * If we cannot check for file capabilities we need to give the benefit
3539 * of the doubt. Otherwise we might fail even though all the necessary
3540 * file capabilities are set.
3542 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3547 static int lxc_map_ids_exec_wrapper(void *args
)
3549 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
3553 static struct id_map
*find_mapped_hostid_entry(const struct list_head
*idmap
,
3554 unsigned id
, enum idtype idtype
);
3556 int lxc_map_ids(struct list_head
*idmap
, pid_t pid
)
3563 char cmd_output
[PATH_MAX
];
3566 int ret
= 0, gidmap
= 0, uidmap
= 0;
3567 char mapbuf
[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3568 INTTYPE_TO_STRLEN(pid_t
) + STRLITERALLEN(" ") +
3569 LXC_IDMAPLEN
] = {0};
3570 bool had_entry
= false, maps_host_root
= false, use_shadow
= false;
3572 hostuid
= geteuid();
3573 hostgid
= getegid();
3576 * Check whether caller wants to map host root.
3577 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3578 * host root into the child userns as you would be able to write fscaps
3579 * that would be valid in the ancestor userns. Mapping host root should
3580 * rarely be the case but LXC is being clever in a bunch of cases.
3582 if (find_mapped_hostid_entry(idmap
, 0, ID_TYPE_UID
))
3583 maps_host_root
= true;
3585 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3586 * ranges, then insist that root also reserve ranges in subuid. This
3587 * will protected it by preventing another user from being handed the
3590 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
3591 if (uidmap
== -ENOENT
)
3592 WARN("newuidmap binary is missing");
3594 WARN("newuidmap is lacking necessary privileges");
3596 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
3597 if (gidmap
== -ENOENT
)
3598 WARN("newgidmap binary is missing");
3600 WARN("newgidmap is lacking necessary privileges");
3602 if (maps_host_root
) {
3603 INFO("Caller maps host root. Writing mapping directly");
3604 } else if (uidmap
> 0 && gidmap
> 0) {
3605 DEBUG("Functional newuidmap and newgidmap binary found");
3608 /* In case unprivileged users run application containers via
3609 * execute() or a start*() there are valid cases where they may
3610 * only want to map their own {g,u}id. Let's not block them from
3611 * doing so by requiring geteuid() == 0.
3613 DEBUG("No newuidmap and newgidmap binary found. Trying to "
3614 "write directly with euid %d", hostuid
);
3617 /* Check if we really need to use newuidmap and newgidmap.
3618 * If the user is only remapping their own {g,u}id, we don't need it.
3620 if (use_shadow
&& list_len(map
, idmap
, head
) == 2) {
3622 list_for_each_entry(map
, idmap
, head
) {
3623 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3624 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3626 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3627 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3634 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3635 type
++, u_or_g
= 'g') {
3639 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3641 list_for_each_entry(map
, idmap
, head
) {
3642 if (map
->idtype
!= type
)
3647 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3648 fill
= strnprintf(pos
, left
, "%s%lu %lu %lu%s",
3649 use_shadow
? " " : "", map
->nsid
,
3650 map
->hostid
, map
->range
,
3651 use_shadow
? "" : "\n");
3653 * The kernel only takes <= 4k for writes to
3654 * /proc/<pid>/{g,u}id_map
3657 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
3664 /* Try to catch the output of new{g,u}idmap to make debugging
3668 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3669 lxc_map_ids_exec_wrapper
,
3672 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
3673 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3675 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3677 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
3678 TRACE("Wrote mapping \"%s\"", mapbuf
);
3681 memset(mapbuf
, 0, sizeof(mapbuf
));
3688 * Return the host uid/gid to which the container root is mapped in val.
3689 * Return true if id was found, false otherwise.
3691 static id_t
get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
)
3696 if (idtype
== ID_TYPE_UID
)
3697 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3699 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3701 list_for_each_entry (map
, &conf
->id_map
, head
) {
3702 if (map
->idtype
!= idtype
)
3704 if (map
->nsid
!= nsid
)
3709 if (idtype
== ID_TYPE_UID
)
3710 return LXC_INVALID_UID
;
3712 return LXC_INVALID_GID
;
3715 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
3719 list_for_each_entry(map
, &conf
->id_map
, head
) {
3720 if (map
->idtype
!= idtype
)
3723 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3724 return (id
- map
->hostid
) + map
->nsid
;
3730 int find_unmapped_nsid(const struct lxc_conf
*conf
, enum idtype idtype
)
3733 unsigned int freeid
= 0;
3736 list_for_each_entry(map
, &conf
->id_map
, head
) {
3737 if (map
->idtype
!= idtype
)
3740 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3741 freeid
= map
->nsid
+ map
->range
;
3750 * Mount a proc under @rootfs if proc self points to a pid other than
3751 * my own. This is needed to have a known-good proc mount for setting
3752 * up LSMs both at container startup and attach.
3754 * NOTE: not to be called from inside the container namespace!
3756 static int lxc_transient_proc(struct lxc_rootfs
*rootfs
)
3758 __do_close
int fd_proc
= -EBADF
;
3759 int link_to_pid
, link_len
, pid_self
, ret
;
3760 char link
[INTTYPE_TO_STRLEN(pid_t
) + 1];
3762 link_len
= readlinkat(rootfs
->dfd_mnt
, "proc/self", link
, sizeof(link
));
3764 ret
= mkdirat(rootfs
->dfd_mnt
, "proc", 0000);
3765 if (ret
< 0 && errno
!= EEXIST
)
3766 return log_error_errno(-errno
, errno
, "Failed to create %d(proc)", rootfs
->dfd_mnt
);
3769 } else if ((size_t)link_len
>= sizeof(link
)) {
3770 return log_error_errno(-EIO
, EIO
, "Truncated link target");
3772 link
[link_len
] = '\0';
3774 pid_self
= lxc_raw_getpid();
3775 INFO("Caller's PID is %d; /proc/self points to %s", pid_self
, link
);
3777 ret
= lxc_safe_int(link
, &link_to_pid
);
3779 return log_error_errno(-ret
, ret
, "Failed to parse %s", link
);
3781 /* Correct procfs is already mounted. */
3782 if (link_to_pid
== pid_self
)
3783 return log_trace(0, "Correct procfs instance mounted");
3785 fd_proc
= open_at(rootfs
->dfd_mnt
, "proc", PROTECT_OPATH_DIRECTORY
,
3786 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
3788 return log_error_errno(-errno
, errno
, "Failed to open transient procfs mountpoint");
3790 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/proc/self/fd/%d", fd_proc
);
3792 return ret_errno(EIO
);
3794 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
3796 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs
->buf
);
3799 /* rootfs is NULL */
3800 if (!rootfs
->path
) {
3801 ret
= mount("proc", rootfs
->buf
, "proc", 0, NULL
);
3803 ret
= safe_mount_beneath_at(rootfs
->dfd_mnt
, "none", "proc", "proc", 0, NULL
);
3805 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc", rootfs
->path
? rootfs
->mount
: "");
3807 return ret_errno(EIO
);
3809 ret
= safe_mount("proc", rootfs
->buf
, "proc", 0, NULL
, rootfs
->mount
);
3813 return log_error_errno(-1, errno
, "Failed to mount temporary procfs");
3815 INFO("Created transient procfs mount");
3819 /* NOTE: Must not be called from inside the container namespace! */
3820 static int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3824 mounted
= lxc_transient_proc(&conf
->rootfs
);
3825 if (mounted
== -1) {
3826 /* continue only if there is no rootfs */
3827 if (conf
->rootfs
.path
)
3828 return log_error_errno(-EPERM
, EPERM
, "Failed to create transient procfs mount");
3829 } else if (mounted
== 1) {
3830 conf
->transient_procfs_mnt
= true;
3836 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3838 if (lxc_conf
->transient_procfs_mnt
) {
3839 (void)umount2("/proc", MNT_DETACH
);
3840 lxc_conf
->transient_procfs_mnt
= false;
3844 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
3845 static void turn_into_dependent_mounts(const struct lxc_rootfs
*rootfs
)
3847 __do_free
char *line
= NULL
;
3848 __do_fclose
FILE *f
= NULL
;
3849 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3854 mntinfo_fd
= open_at(rootfs
->dfd_host
, "proc/self/mountinfo", PROTECT_OPEN
,
3855 (PROTECT_LOOKUP_BENEATH_XDEV
& ~RESOLVE_NO_SYMLINKS
), 0);
3856 if (mntinfo_fd
< 0) {
3857 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs
->dfd_host
);
3861 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3863 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3865 if (errno
!= ENOSYS
) {
3866 SYSERROR("Failed to create temporary in-memory file");
3870 memfd
= lxc_make_tmpfile(template, true);
3872 WARN("Failed to create temporary file");
3877 copied
= fd_to_fd(mntinfo_fd
, memfd
);
3879 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3883 ret
= lseek(memfd
, 0, SEEK_SET
);
3885 SYSERROR("Failed to reset file descriptor offset");
3889 f
= fdopen(memfd
, "re");
3891 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3896 * After a successful fdopen() memfd will be closed when calling
3897 * fclose(f). Calling close(memfd) afterwards is undefined.
3901 while (getline(&line
, &len
, f
) != -1) {
3902 char *opts
, *target
;
3904 target
= get_field(line
, 4);
3908 opts
= get_field(target
, 2);
3912 null_endofword(opts
);
3913 if (!strstr(opts
, "shared"))
3916 null_endofword(target
);
3917 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3919 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3923 TRACE("Turned all mount table entries into dependent mount");
3926 /* This does the work of remounting / if it is shared, calling the container
3927 * pre-mount hooks, and mounting the rootfs.
3929 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3930 const char *lxcpath
)
3934 conf
->rootfs
.dfd_host
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
3935 if (conf
->rootfs
.dfd_host
< 0)
3936 return log_error_errno(-errno
, errno
, "Failed to open \"/\"");
3938 turn_into_dependent_mounts(&conf
->rootfs
);
3940 if (conf
->rootfs_setup
) {
3941 const char *path
= conf
->rootfs
.mount
;
3944 * The rootfs was set up in another namespace. bind-mount it to
3945 * give us a mount in our own ns so we can pivot_root to it
3947 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3949 return log_error(-1, "Failed to bind mount container / onto itself");
3951 conf
->rootfs
.dfd_mnt
= openat(-EBADF
, path
, O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOCTTY
);
3952 if (conf
->rootfs
.dfd_mnt
< 0)
3953 return log_error_errno(-errno
, errno
, "Failed to open file descriptor for container rootfs");
3955 return log_trace(0, "Bind mounted container / onto itself");
3958 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3960 return log_error(-1, "Failed to run pre-mount hooks");
3962 ret
= lxc_mount_rootfs(&conf
->rootfs
);
3964 return log_error(-1, "Failed to setup rootfs for");
3966 conf
->rootfs_setup
= true;
3970 static bool verify_start_hooks(struct lxc_conf
*conf
)
3972 char path
[PATH_MAX
];
3973 struct string_entry
*hook
;
3975 list_for_each_entry(hook
, &conf
->hooks
[LXCHOOK_START
], head
) {
3977 char *hookname
= hook
->val
;
3979 ret
= strnprintf(path
, sizeof(path
), "%s%s",
3980 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3985 ret
= access(path
, X_OK
);
3987 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
3995 static int lxc_setup_boot_id(void)
3998 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3999 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
4002 if (access(boot_id_path
, F_OK
))
4005 memset(&n
, 0, sizeof(n
));
4006 if (lxc_id128_randomize(&n
)) {
4007 SYSERROR("Failed to generate random data for uuid");
4011 ret
= lxc_id128_write(mock_boot_id_path
, n
);
4013 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
4017 ret
= chmod(mock_boot_id_path
, 0444);
4019 SYSERROR("Failed to chown %s", mock_boot_id_path
);
4020 (void)unlink(mock_boot_id_path
);
4024 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
4026 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
4028 (void)unlink(mock_boot_id_path
);
4032 ret
= mount(NULL
, boot_id_path
, NULL
,
4033 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
4037 SYSERROR("Failed to remount %s read-only", boot_id_path
);
4038 (void)unlink(mock_boot_id_path
);
4045 static int lxc_setup_keyring(struct lsm_ops
*lsm_ops
, const struct lxc_conf
*conf
)
4047 key_serial_t keyring
;
4050 if (conf
->lsm_se_keyring_context
)
4051 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_keyring_context
);
4052 else if (conf
->lsm_se_context
)
4053 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_context
);
4055 return syserror("Failed to set keyring context");
4058 * Try to allocate a new session keyring for the container to prevent
4059 * information leaks.
4061 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
4062 prctl_arg(0), prctl_arg(0), prctl_arg(0));
4066 DEBUG("The keyctl() syscall is not supported or blocked");
4071 DEBUG("Failed to access kernel keyring. Continuing...");
4074 SYSWARN("Failed to create kernel keyring");
4082 static int lxc_rootfs_prepare_child(struct lxc_handler
*handler
)
4084 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
4085 int dfd_idmapped
= -EBADF
;
4088 if (list_empty(&handler
->conf
->id_map
))
4091 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
4094 if (handler
->conf
->rootfs_setup
)
4097 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1], &dfd_idmapped
, NULL
, 0);
4099 return syserror("Failed to receive idmapped mount fd");
4101 rootfs
->dfd_idmapped
= dfd_idmapped
;
4102 TRACE("Received detached idmapped mount %d", rootfs
->dfd_idmapped
);
4106 int lxc_idmapped_mounts_parent(struct lxc_handler
*handler
)
4111 __do_close
int fd_from
= -EBADF
, fd_userns
= -EBADF
;
4112 struct lxc_mount_attr attr
= {};
4113 struct lxc_mount_options opts
= {};
4116 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4117 &fd_from
, &fd_userns
,
4118 &opts
, sizeof(opts
));
4120 return syserror("Failed to receive idmapped mount file descriptors from child");
4122 if (fd_from
< 0 || fd_userns
< 0)
4123 return log_trace(0, "Finished receiving idmapped mount file descriptors from child");
4125 attr
.attr_set
= MOUNT_ATTR_IDMAP
;
4126 attr
.userns_fd
= fd_userns
;
4127 ret
= mount_setattr(fd_from
, "",
4129 (opts
.bind_recursively
? AT_RECURSIVE
: 0),
4130 &attr
, sizeof(attr
));
4132 return syserror("Failed to idmap detached %smount %d to %d",
4133 opts
.bind_recursively
? "recursive " : "",
4134 fd_from
, fd_userns
);
4136 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[1],
4140 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
4141 opts
.bind_recursively
? "recursive " : "",
4142 fd_from
, fd_userns
);
4144 TRACE("Parent idmapped detached %smount %d to user namespace %d",
4145 opts
.bind_recursively
? "recursive " : "", fd_from
, fd_userns
);
4150 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
4152 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*info_new
= &(struct lxc_tty_info
){};
4153 int sock
= handler
->data_sock
[1];
4154 struct lxc_conf
*conf
= handler
->conf
;
4155 struct lxc_tty_info
*tty_info
= &conf
->ttys
;
4156 size_t ttys_max
= tty_info
->max
;
4157 struct lxc_terminal_info
*terminal_info
;
4163 info_new
->tty
= malloc(sizeof(*(info_new
->tty
)) * ttys_max
);
4165 return ret_errno(ENOMEM
);
4167 for (size_t i
= 0; i
< ttys_max
; i
++) {
4168 terminal_info
= &info_new
->tty
[i
];
4169 terminal_info
->busy
= -1;
4170 terminal_info
->pty_nr
= -1;
4171 terminal_info
->ptx
= -EBADF
;
4172 terminal_info
->pty
= -EBADF
;
4175 for (size_t i
= 0; i
< ttys_max
; i
++) {
4176 int ptx
= -EBADF
, pty
= -EBADF
;
4178 ret
= lxc_abstract_unix_recv_two_fds(sock
, &ptx
, &pty
);
4180 return syserror("Failed to receive %zu ttys from child", ttys_max
);
4182 terminal_info
= &info_new
->tty
[i
];
4183 terminal_info
->ptx
= ptx
;
4184 terminal_info
->pty
= pty
;
4185 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4186 terminal_info
->ptx
, terminal_info
->pty
);
4189 tty_info
->tty
= move_ptr(info_new
->tty
);
4190 TRACE("Received %zu ttys from child", ttys_max
);
4194 static int lxc_send_console_to_parent(struct lxc_handler
*handler
)
4196 struct lxc_terminal
*console
= &handler
->conf
->console
;
4199 if (!wants_console(console
))
4202 /* We've already allocated a console from the host's devpts instance. */
4203 if (console
->pty
< 0)
4206 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
4207 console
->ptx
, console
->pty
,
4209 sizeof(struct lxc_terminal
));
4211 return syserror("Fail to send console to parent");
4213 TRACE("Sent console to parent");
4217 static int lxc_recv_console_from_child(struct lxc_handler
*handler
)
4219 __do_close
int fd_ptx
= -EBADF
, fd_pty
= -EBADF
;
4220 struct lxc_terminal
*console
= &handler
->conf
->console
;
4223 if (!wants_console(console
))
4226 /* We've already allocated a console from the host's devpts instance. */
4227 if (console
->pty
>= 0)
4230 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4233 sizeof(struct lxc_terminal
));
4235 return syserror("Fail to receive console from child");
4237 console
->ptx
= move_fd(fd_ptx
);
4238 console
->pty
= move_fd(fd_pty
);
4240 TRACE("Received console from child");
4244 int lxc_sync_fds_parent(struct lxc_handler
*handler
)
4248 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[1]);
4250 return syserror_ret(ret
, "Failed to receive seccomp notify fd from child");
4252 ret
= lxc_recv_devpts_from_child(handler
);
4254 return syserror_ret(ret
, "Failed to receive devpts fd from child");
4256 /* Read tty fds allocated by child. */
4257 ret
= lxc_recv_ttys_from_child(handler
);
4259 return syserror_ret(ret
, "Failed to receive tty info from child process");
4261 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4262 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
4264 return syserror_ret(ret
, "Failed to receive names and ifindices for network devices from child");
4267 ret
= lxc_recv_console_from_child(handler
);
4269 return syserror_ret(ret
, "Failed to receive console from child");
4271 TRACE("Finished syncing file descriptors with child");
4275 int lxc_sync_fds_child(struct lxc_handler
*handler
)
4279 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[0]);
4281 return syserror_ret(ret
, "Failed to send seccomp notify fd to parent");
4283 ret
= lxc_send_devpts_to_parent(handler
);
4285 return syserror_ret(ret
, "Failed to send seccomp devpts fd to parent");
4287 ret
= lxc_send_ttys_to_parent(handler
);
4289 return syserror_ret(ret
, "Failed to send tty file descriptors to parent");
4291 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4292 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
4294 return syserror_ret(ret
, "Failed to send network device names and ifindices to parent");
4297 ret
= lxc_send_console_to_parent(handler
);
4299 return syserror_ret(ret
, "Failed to send console to parent");
4301 TRACE("Finished syncing file descriptors with parent");
4305 static int setup_capabilities(struct lxc_conf
*conf
)
4309 if (conf
->caps
.keep
)
4310 ret
= capabilities_allow(conf
);
4312 ret
= capabilities_deny(conf
);
4314 return syserror_ret(ret
, "Failed to %s capabilities", conf
->caps
.keep
? "allow" : "deny");
4319 int lxc_setup(struct lxc_handler
*handler
)
4322 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
4323 struct lxc_conf
*lxc_conf
= handler
->conf
;
4325 ret
= lxc_rootfs_prepare_child(handler
);
4327 return syserror("Failed to prepare rootfs");
4329 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
4331 return log_error(-1, "Failed to setup rootfs");
4333 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
4334 ret
= setup_utsname(lxc_conf
->utsname
);
4336 return log_error(-1, "Failed to setup the utsname %s", name
);
4339 if (!lxc_conf
->keyring_disable_session
) {
4340 ret
= lxc_setup_keyring(handler
->lsm_ops
, lxc_conf
);
4342 return log_error(-1, "Failed to setup container keyring");
4345 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4346 ret
= lxc_network_recv_from_parent(handler
);
4348 return log_error(-1, "Failed to receive veth names from parent");
4350 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
);
4352 return log_error(-1, "Failed to setup network");
4355 if (lxc_conf
->autodev
> 0) {
4356 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
4358 return log_error(-1, "Failed to mount \"/dev\"");
4361 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4362 * need to wait until other stuff has finished.
4364 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
);
4366 return log_error(-1, "Failed to setup first automatic mounts");
4368 ret
= setup_mount_fstab(&lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
4370 return log_error(-1, "Failed to setup mounts");
4372 if (!list_empty(&lxc_conf
->mount_entries
)) {
4373 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
, name
, lxcpath
);
4375 return log_error(-1, "Failed to setup mount entries");
4378 if (!lxc_sync_wake_parent(handler
, START_SYNC_IDMAPPED_MOUNTS
))
4381 ret
= lxc_idmapped_mounts_child(handler
);
4383 return syserror("Failed to attached detached idmapped mounts");
4385 lxc_conf
->rootfs
.dfd_dev
= open_at(lxc_conf
->rootfs
.dfd_mnt
, "dev",
4386 PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
4387 if (lxc_conf
->rootfs
.dfd_dev
< 0 && errno
!= ENOENT
)
4388 return log_error_errno(-errno
, errno
, "Failed to open \"/dev\"");
4390 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4391 * mounted. It is guaranteed to be mounted now either through
4392 * automatically or via fstab entries.
4394 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
);
4396 return log_error(-1, "Failed to setup remaining automatic mounts");
4398 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
4400 return log_error(-1, "Failed to run mount hooks");
4402 if (lxc_rootfs_overmounted(&lxc_conf
->rootfs
))
4403 return log_error(-1, "Rootfs overmounted");
4405 if (lxc_conf
->autodev
> 0) {
4406 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
4408 return log_error(-1, "Failed to run autodev hooks");
4410 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
4412 return log_error(-1, "Failed to populate \"/dev\"");
4415 /* Make sure any start hooks are in the container */
4416 if (!verify_start_hooks(lxc_conf
))
4417 return log_error(-1, "Failed to verify start hooks");
4419 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
4421 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
4423 ret
= lxc_setup_devpts_child(handler
);
4425 return log_error(-1, "Failed to prepare new devpts instance");
4427 ret
= lxc_finish_devpts_child(handler
);
4429 return log_error(-1, "Failed to finish devpts setup");
4431 ret
= lxc_setup_console(handler
, &lxc_conf
->rootfs
, &lxc_conf
->console
,
4432 lxc_conf
->ttys
.dir
);
4434 return log_error(-1, "Failed to setup console");
4436 ret
= lxc_create_ttys(handler
);
4438 return log_error(-1, "Failed to create ttys");
4440 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
4442 return log_error(-1, "Failed to setup \"/dev\" symlinks");
4444 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
4446 return log_error(-1, "Failed to pivot root into rootfs");
4448 /* Setting the boot-id is best-effort for now. */
4449 if (lxc_conf
->autodev
> 0)
4450 (void)lxc_setup_boot_id();
4452 ret
= setup_personality(lxc_conf
->personality
);
4454 return syserror("Failed to set personality");
4456 /* Set sysctl value to a path under /proc/sys as determined from the
4457 * key. For e.g. net.ipv4.ip_forward translated to
4458 * /proc/sys/net/ipv4/ip_forward.
4460 ret
= setup_sysctl_parameters(lxc_conf
);
4462 return log_error(-1, "Failed to setup sysctl parameters");
4464 ret
= setup_capabilities(lxc_conf
);
4466 return log_error(-1, "Failed to setup capabilities");
4468 put_lxc_rootfs(&handler
->conf
->rootfs
, true);
4469 NOTICE("The container \"%s\" is set up", name
);
4474 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
4478 struct string_entry
*entry
;
4480 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
4481 if (strequal(hookname
, lxchook_names
[which
]))
4485 if (which
>= NUM_LXC_HOOKS
)
4488 list_for_each_entry(entry
, &conf
->hooks
[which
], head
) {
4490 char *hook
= entry
->val
;
4492 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
4501 int lxc_clear_config_caps(struct lxc_conf
*c
)
4503 struct cap_entry
*cap
, *ncap
;
4505 list_for_each_entry_safe(cap
, ncap
, &c
->caps
.list
, head
) {
4506 list_del(&cap
->head
);
4507 free(cap
->cap_name
);
4511 c
->caps
.keep
= false;
4512 INIT_LIST_HEAD(&c
->caps
.list
);
4516 static int lxc_free_idmap(struct list_head
*id_map
)
4518 struct id_map
*map
, *nmap
;
4520 list_for_each_entry_safe(map
, nmap
, id_map
, head
) {
4521 list_del(&map
->head
);
4525 INIT_LIST_HEAD(id_map
);
4529 static int __lxc_free_idmap(struct list_head
*id_map
)
4531 lxc_free_idmap(id_map
);
4534 define_cleanup_function(struct list_head
*, __lxc_free_idmap
);
4536 int lxc_clear_idmaps(struct lxc_conf
*c
)
4538 return lxc_free_idmap(&c
->id_map
);
4541 int lxc_clear_namespace(struct lxc_conf
*c
)
4543 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
4544 free_disarm(c
->ns_share
[i
]);
4549 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
4551 const char *k
= key
;
4553 char *global_token
, *namespaced_token
;
4554 size_t namespaced_token_len
;
4555 struct list_head
*list
;
4556 struct lxc_cgroup
*cgroup
, *ncgroup
;
4558 if (version
== CGROUP2_SUPER_MAGIC
) {
4559 global_token
= "lxc.cgroup2";
4560 namespaced_token
= "lxc.cgroup2.";
4561 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
4563 } else if (version
== CGROUP_SUPER_MAGIC
) {
4564 global_token
= "lxc.cgroup";
4565 namespaced_token
= "lxc.cgroup.";
4566 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
4569 return ret_errno(EINVAL
);
4572 if (strequal(key
, global_token
))
4574 else if (strnequal(key
, namespaced_token
, namespaced_token_len
))
4575 k
+= namespaced_token_len
;
4577 return ret_errno(EINVAL
);
4579 list_for_each_entry_safe(cgroup
, ncgroup
, list
, head
) {
4580 if (!all
&& !strequal(cgroup
->subsystem
, k
))
4583 list_del(&cgroup
->head
);
4584 free(cgroup
->subsystem
);
4585 free(cgroup
->value
);
4590 INIT_LIST_HEAD(list
);
4595 static inline void lxc_clear_cgroups_devices(struct lxc_conf
*conf
)
4597 lxc_clear_cgroup2_devices(&conf
->bpf_devices
);
4600 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
4602 const char *k
= NULL
;
4604 struct lxc_limit
*lim
, *nlim
;
4606 if (strequal(key
, "lxc.limit") || strequal(key
, "lxc.prlimit"))
4608 else if (strnequal(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
4609 k
= key
+ STRLITERALLEN("lxc.limit.");
4610 else if (strnequal(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
4611 k
= key
+ STRLITERALLEN("lxc.prlimit.");
4613 return ret_errno(EINVAL
);
4615 list_for_each_entry_safe(lim
, nlim
, &c
->limits
, head
) {
4616 if (!all
&& !strequal(lim
->resource
, k
))
4619 list_del(&lim
->head
);
4620 free_disarm(lim
->resource
);
4625 INIT_LIST_HEAD(&c
->limits
);
4630 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
4632 const char *k
= NULL
;
4634 struct lxc_sysctl
*sysctl
, *nsysctl
;
4636 if (strequal(key
, "lxc.sysctl"))
4638 else if (strnequal(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
4639 k
= key
+ STRLITERALLEN("lxc.sysctl.");
4643 list_for_each_entry_safe(sysctl
, nsysctl
, &c
->sysctls
, head
) {
4644 if (!all
&& !strequal(sysctl
->key
, k
))
4647 list_del(&sysctl
->head
);
4649 free(sysctl
->value
);
4654 INIT_LIST_HEAD(&c
->sysctls
);
4659 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
4661 const char *k
= NULL
;
4663 struct lxc_proc
*proc
, *nproc
;
4665 if (strequal(key
, "lxc.proc"))
4667 else if (strnequal(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
4668 k
= key
+ STRLITERALLEN("lxc.proc.");
4672 list_for_each_entry_safe(proc
, nproc
, &c
->procs
, head
) {
4673 if (!all
&& !strequal(proc
->filename
, k
))
4676 list_del(&proc
->head
);
4677 free(proc
->filename
);
4683 INIT_LIST_HEAD(&c
->procs
);
4688 int lxc_clear_groups(struct lxc_conf
*c
)
4690 struct string_entry
*entry
, *nentry
;
4692 list_for_each_entry_safe(entry
, nentry
, &c
->groups
, head
) {
4693 list_del(&entry
->head
);
4698 INIT_LIST_HEAD(&c
->groups
);
4702 int lxc_clear_environment(struct lxc_conf
*c
)
4704 struct environment_entry
*env
, *nenv
;
4706 list_for_each_entry_safe(env
, nenv
, &c
->environment
, head
) {
4707 list_del(&env
->head
);
4713 INIT_LIST_HEAD(&c
->environment
);
4717 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4719 struct string_entry
*entry
, *nentry
;
4721 list_for_each_entry_safe(entry
, nentry
, &c
->mount_entries
, head
) {
4722 list_del(&entry
->head
);
4727 INIT_LIST_HEAD(&c
->mount_entries
);
4731 int lxc_clear_automounts(struct lxc_conf
*c
)
4737 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4739 const char *k
= NULL
;
4740 bool all
= false, done
= false;
4741 struct string_entry
*entry
, *nentry
;
4743 if (strequal(key
, "lxc.hook"))
4745 else if (strnequal(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
4746 k
= key
+ STRLITERALLEN("lxc.hook.");
4750 for (int i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4751 if (all
|| strequal(k
, lxchook_names
[i
])) {
4752 list_for_each_entry_safe(entry
, nentry
, &c
->hooks
[i
], head
) {
4753 list_del(&entry
->head
);
4757 INIT_LIST_HEAD(&c
->hooks
[i
]);
4763 return log_error(-1, "Invalid hook key: %s", key
);
4768 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4770 struct string_entry
*entry
, *nentry
;
4772 list_for_each_entry_safe(entry
, nentry
, &c
->lsm_aa_raw
, head
) {
4773 list_del(&entry
->head
);
4778 INIT_LIST_HEAD(&c
->lsm_aa_raw
);
4782 void lxc_conf_free(struct lxc_conf
*conf
)
4787 if (current_config
== conf
)
4788 current_config
= NULL
;
4789 lxc_terminal_conf_free(&conf
->console
);
4790 free(conf
->rootfs
.mount
);
4791 free(conf
->rootfs
.bdev_type
);
4792 free(conf
->rootfs
.path
);
4793 put_lxc_rootfs(&conf
->rootfs
, true);
4794 free(conf
->logfile
);
4795 if (conf
->logfd
!= -1)
4797 free(conf
->utsname
);
4798 free(conf
->ttys
.dir
);
4799 free(conf
->ttys
.tty_names
);
4802 free(conf
->execute_cmd
);
4803 free(conf
->init_cmd
);
4804 free(conf
->init_groups
.list
);
4805 free(conf
->init_cwd
);
4806 free(conf
->unexpanded_config
);
4808 lxc_free_networks(conf
);
4809 free(conf
->lsm_aa_profile
);
4810 free(conf
->lsm_aa_profile_computed
);
4811 free(conf
->lsm_se_context
);
4812 free(conf
->lsm_se_keyring_context
);
4813 lxc_seccomp_free(&conf
->seccomp
);
4814 lxc_clear_config_caps(conf
);
4815 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4816 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4817 lxc_clear_cgroups_devices(conf
);
4818 lxc_clear_hooks(conf
, "lxc.hook");
4819 lxc_clear_mount_entries(conf
);
4820 lxc_clear_idmaps(conf
);
4821 lxc_clear_groups(conf
);
4822 lxc_clear_environment(conf
);
4823 lxc_clear_limits(conf
, "lxc.prlimit");
4824 lxc_clear_sysctls(conf
, "lxc.sysctl");
4825 lxc_clear_procs(conf
, "lxc.proc");
4826 lxc_clear_apparmor_raw(conf
);
4827 lxc_clear_namespace(conf
);
4828 free(conf
->cgroup_meta
.dir
);
4829 free(conf
->cgroup_meta
.monitor_dir
);
4830 free(conf
->cgroup_meta
.monitor_pivot_dir
);
4831 free(conf
->cgroup_meta
.container_dir
);
4832 free(conf
->cgroup_meta
.namespace_dir
);
4833 free(conf
->cgroup_meta
.controllers
);
4834 free(conf
->shmount
.path_host
);
4835 free(conf
->shmount
.path_cont
);
4839 struct userns_fn_data
{
4841 const char *fn_name
;
4846 static int run_userns_fn(void *data
)
4848 struct userns_fn_data
*d
= data
;
4852 close_prot_errno_disarm(d
->p
[1]);
4855 * Wait for parent to finish establishing a new mapping in the user
4856 * namespace we are executing in.
4858 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4859 close_prot_errno_disarm(d
->p
[0]);
4864 TRACE("Calling function \"%s\"", d
->fn_name
);
4866 /* Call function to run. */
4867 return d
->fn(d
->arg
);
4870 static struct id_map
*mapped_nsid_add(const struct lxc_conf
*conf
, unsigned id
,
4873 const struct id_map
*map
;
4874 struct id_map
*retmap
;
4876 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4880 retmap
= zalloc(sizeof(*retmap
));
4884 memcpy(retmap
, map
, sizeof(*retmap
));
4888 static struct id_map
*find_mapped_hostid_entry(const struct list_head
*idmap
,
4889 unsigned id
, enum idtype idtype
)
4891 struct id_map
*retmap
= NULL
;
4894 list_for_each_entry(map
, idmap
, head
) {
4895 if (map
->idtype
!= idtype
)
4898 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4907 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4908 * existing one or establish a new one.
4910 static struct id_map
*mapped_hostid_add(const struct lxc_conf
*conf
, uid_t id
,
4913 __do_free
struct id_map
*entry
= NULL
;
4915 struct id_map
*tmp
= NULL
;
4917 entry
= zalloc(sizeof(*entry
));
4921 /* Reuse existing mapping. */
4922 tmp
= find_mapped_hostid_entry(&conf
->id_map
, id
, type
);
4924 memcpy(entry
, tmp
, sizeof(*entry
));
4926 /* Find new mapping. */
4927 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4928 if (hostid_mapped
< 0)
4929 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
4931 entry
->idtype
= type
;
4932 entry
->nsid
= hostid_mapped
;
4933 entry
->hostid
= (unsigned long)id
;
4937 return move_ptr(entry
);
4940 static int get_minimal_idmap(const struct lxc_conf
*conf
, uid_t
*resuid
,
4941 gid_t
*resgid
, struct list_head
*head_ret
)
4943 __do_free
struct id_map
*container_root_uid
= NULL
,
4944 *container_root_gid
= NULL
,
4945 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4947 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4948 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4950 /* Find container root mappings. */
4951 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4952 if (!container_root_uid
)
4953 return sysdebug("Failed to find mapping for namespace uid %d", 0);
4955 if (euid
>= container_root_uid
->hostid
&&
4956 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4957 host_uid_map
= move_ptr(container_root_uid
);
4959 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4960 if (!container_root_gid
)
4961 return sysdebug("Failed to find mapping for namespace gid %d", 0);
4963 if (egid
>= container_root_gid
->hostid
&&
4964 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4965 host_gid_map
= move_ptr(container_root_gid
);
4967 /* Check whether the {g,u}id of the user has a mapping. */
4969 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4971 return sysdebug("Failed to find mapping for uid %d", euid
);
4974 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4976 return sysdebug("Failed to find mapping for gid %d", egid
);
4978 /* idmap will now keep track of that memory. */
4979 list_add_tail(&host_uid_map
->head
, head_ret
);
4980 move_ptr(host_uid_map
);
4982 if (container_root_uid
) {
4983 /* idmap will now keep track of that memory. */
4984 list_add_tail(&container_root_uid
->head
, head_ret
);
4985 move_ptr(container_root_uid
);
4988 /* idmap will now keep track of that memory. */
4989 list_add_tail(&host_gid_map
->head
, head_ret
);
4990 move_ptr(host_gid_map
);
4992 if (container_root_gid
) {
4993 /* idmap will now keep track of that memory. */
4994 list_add_tail(&container_root_gid
->head
, head_ret
);
4995 move_ptr(container_root_gid
);
4998 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid
, nsgid
);
5009 * Run a function in a new user namespace.
5010 * The caller's euid/egid will be mapped if it is not already.
5011 * Afaict, userns_exec_1() is only used to operate based on privileges for the
5012 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
5013 * This means we require only to establish a mapping from:
5014 * - the container root {g,u}id as seen from the host > user's host {g,u}id
5015 * - the container root -> some sub{g,u}id
5016 * The former we add, if the user did not specify a mapping. The latter we
5017 * retrieve from the container's configured {g,u}id mappings as it must have been
5018 * there to start the container in the first place.
5020 int userns_exec_1(const struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
5021 const char *fn_name
)
5023 LIST_HEAD(minimal_idmap
);
5024 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &minimal_idmap
;
5025 int ret
= -1, status
= -1;
5027 struct userns_fn_data d
= {
5038 ret
= get_minimal_idmap(conf
, NULL
, NULL
, idmap
);
5040 return ret_errno(ENOENT
);
5042 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
5046 d
.p
[0] = pipe_fds
[0];
5047 d
.p
[1] = pipe_fds
[1];
5049 /* Clone child in new user namespace. */
5050 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5052 ERROR("Failed to clone process in new user namespace");
5056 close_prot_errno_disarm(pipe_fds
[0]);
5058 if (lxc_log_trace()) {
5061 list_for_each_entry(map
, idmap
, head
)
5062 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5063 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5066 /* Set up {g,u}id mapping for user namespace of child process. */
5067 ret
= lxc_map_ids(idmap
, pid
);
5069 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5073 /* Tell child to proceed. */
5074 if (lxc_write_nointr(pipe_fds
[1], &c
, 1) != 1) {
5075 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5080 close_prot_errno_disarm(pipe_fds
[0]);
5081 close_prot_errno_disarm(pipe_fds
[1]);
5083 /* Wait for child to finish. */
5085 status
= wait_for_pid(pid
);
5093 int userns_exec_minimal(const struct lxc_conf
*conf
,
5094 int (*fn_parent
)(void *), void *fn_parent_data
,
5095 int (*fn_child
)(void *), void *fn_child_data
)
5097 LIST_HEAD(minimal_idmap
);
5098 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &minimal_idmap
;
5099 uid_t resuid
= LXC_INVALID_UID
;
5100 gid_t resgid
= LXC_INVALID_GID
;
5106 if (!conf
|| !fn_child
)
5107 return ret_errno(EINVAL
);
5109 ret
= get_minimal_idmap(conf
, &resuid
, &resgid
, idmap
);
5111 return ret_errno(ENOENT
);
5113 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5119 SYSERROR("Failed to create new process");
5124 close_prot_errno_disarm(sock_fds
[1]);
5126 ret
= unshare(CLONE_NEWUSER
);
5128 SYSERROR("Failed to unshare new user namespace");
5129 _exit(EXIT_FAILURE
);
5132 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5134 _exit(EXIT_FAILURE
);
5136 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5138 _exit(EXIT_FAILURE
);
5140 close_prot_errno_disarm(sock_fds
[0]);
5142 if (!lxc_drop_groups() && errno
!= EPERM
)
5143 _exit(EXIT_FAILURE
);
5145 ret
= setresgid(resgid
, resgid
, resgid
);
5147 SYSERROR("Failed to setresgid(%d, %d, %d)",
5148 resgid
, resgid
, resgid
);
5149 _exit(EXIT_FAILURE
);
5152 ret
= setresuid(resuid
, resuid
, resuid
);
5154 SYSERROR("Failed to setresuid(%d, %d, %d)",
5155 resuid
, resuid
, resuid
);
5156 _exit(EXIT_FAILURE
);
5159 ret
= fn_child(fn_child_data
);
5161 SYSERROR("Running function in new user namespace failed");
5162 _exit(EXIT_FAILURE
);
5165 _exit(EXIT_SUCCESS
);
5168 close_prot_errno_disarm(sock_fds
[0]);
5170 if (lxc_log_trace()) {
5173 list_for_each_entry(map
, idmap
, head
)
5174 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5175 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5178 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
5180 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
5184 /* Set up {g,u}id mapping for user namespace of child process. */
5185 ret
= lxc_map_ids(idmap
, pid
);
5187 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5191 /* Tell child to proceed. */
5192 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
5194 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5198 if (fn_parent
&& fn_parent(fn_parent_data
)) {
5199 SYSERROR("Running parent function failed");
5200 _exit(EXIT_FAILURE
);
5204 close_prot_errno_disarm(sock_fds
[0]);
5205 close_prot_errno_disarm(sock_fds
[1]);
5207 /* Wait for child to finish. */
5211 return wait_for_pid(pid
);
5214 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
5215 const char *fn_name
)
5217 LIST_HEAD(full_idmap
);
5220 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
5221 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
5226 struct userns_fn_data d
;
5231 ret
= pipe2(p
, O_CLOEXEC
);
5236 d
.fn_name
= fn_name
;
5241 /* Clone child in new user namespace. */
5242 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5244 ERROR("Failed to clone process in new user namespace");
5254 /* Find container root. */
5255 list_for_each_entry(map
, &conf
->id_map
, head
) {
5256 __do_free
struct id_map
*dup_map
= NULL
;
5258 dup_map
= memdup(map
, sizeof(struct id_map
));
5262 list_add_tail(&dup_map
->head
, &full_idmap
);
5265 if (map
->idtype
== ID_TYPE_UID
)
5266 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
5269 if (map
->idtype
== ID_TYPE_GID
)
5270 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
5276 if (map
->idtype
== ID_TYPE_UID
)
5277 if (container_root_uid
== NULL
)
5278 container_root_uid
= map
;
5280 if (map
->idtype
== ID_TYPE_GID
)
5281 if (container_root_gid
== NULL
)
5282 container_root_gid
= map
;
5285 if (!container_root_uid
|| !container_root_gid
) {
5286 ERROR("No mapping for container root found");
5290 /* Check whether the {g,u}id of the user has a mapping. */
5292 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
5294 host_uid_map
= container_root_uid
;
5297 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
5299 host_gid_map
= container_root_gid
;
5301 if (!host_uid_map
) {
5302 DEBUG("Failed to find mapping for uid %d", euid
);
5306 if (!host_gid_map
) {
5307 DEBUG("Failed to find mapping for gid %d", egid
);
5311 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
5312 /* idmap will now keep track of that memory. */
5313 list_add_tail(&host_uid_map
->head
, &full_idmap
);
5314 move_ptr(host_uid_map
);
5317 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
5318 /* idmap will now keep track of that memory. */
5319 list_add_tail(&host_gid_map
->head
, &full_idmap
);
5320 move_ptr(host_gid_map
);
5323 if (lxc_log_trace()) {
5324 list_for_each_entry(map
, &full_idmap
, head
) {
5325 TRACE("establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5326 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
5327 map
->nsid
, map
->hostid
, map
->range
);
5331 /* Set up {g,u}id mapping for user namespace of child process. */
5332 ret
= lxc_map_ids(&full_idmap
, pid
);
5334 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
5338 /* Tell child to proceed. */
5339 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
5340 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5349 /* Wait for child to finish. */
5351 ret
= wait_for_pid(pid
);
5353 __lxc_free_idmap(&full_idmap
);
5355 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
5357 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
5363 static int add_idmap_entry(struct list_head
*idmap_list
, enum idtype idtype
,
5364 unsigned long nsid
, unsigned long hostid
,
5365 unsigned long range
)
5367 __do_free
struct id_map
*new_idmap
= NULL
;
5369 new_idmap
= zalloc(sizeof(*new_idmap
));
5371 return ret_errno(ENOMEM
);
5373 new_idmap
->idtype
= idtype
;
5374 new_idmap
->hostid
= hostid
;
5375 new_idmap
->nsid
= nsid
;
5376 new_idmap
->range
= range
;
5378 list_add_tail(&new_idmap
->head
, idmap_list
);
5379 move_ptr(new_idmap
);
5381 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5382 idtype
== ID_TYPE_UID
? 'u' : 'g', nsid
, hostid
, range
);
5386 int userns_exec_mapped_root(const char *path
, int path_fd
,
5387 const struct lxc_conf
*conf
)
5389 LIST_HEAD(idmap_list
);
5390 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &idmap_list
;
5391 __do_close
int fd
= -EBADF
;
5392 int target_fd
= -EBADF
;
5397 uid_t container_host_uid
, hostuid
;
5398 gid_t container_host_gid
, hostgid
;
5401 if (!conf
|| (!path
&& path_fd
< 0))
5402 return ret_errno(EINVAL
);
5407 container_host_uid
= get_mapped_rootid(conf
, ID_TYPE_UID
);
5408 if (!uid_valid(container_host_uid
))
5409 return log_error(-1, "No uid mapping for container root");
5411 container_host_gid
= get_mapped_rootid(conf
, ID_TYPE_GID
);
5412 if (!gid_valid(container_host_gid
))
5413 return log_error(-1, "No gid mapping for container root");
5416 fd
= open(path
, O_CLOEXEC
| O_NOCTTY
);
5418 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", path
);
5421 target_fd
= path_fd
;
5424 hostuid
= geteuid();
5425 /* We are root so chown directly. */
5427 ret
= fchown(target_fd
, container_host_uid
, container_host_gid
);
5429 return log_error_errno(-errno
, errno
,
5430 "Failed to fchown(%d(%s), %d, %d)",
5431 target_fd
, path
, container_host_uid
,
5432 container_host_gid
);
5433 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd
, path
,
5434 container_host_uid
, container_host_gid
);
5437 /* The container's root host id matches */
5438 if (container_host_uid
== hostuid
)
5439 return log_info(0, "Container root id is mapped to our uid");
5441 /* Get the current ids of our target. */
5442 ret
= fstat(target_fd
, &st
);
5444 return log_error_errno(-errno
, errno
, "Failed to stat \"%s\"", path
);
5446 hostgid
= getegid();
5447 if (st
.st_uid
== hostuid
&& mapped_hostid(st
.st_gid
, conf
, ID_TYPE_GID
) < 0) {
5448 ret
= fchown(target_fd
, -1, hostgid
);
5450 return log_error_errno(-errno
, errno
,
5451 "Failed to fchown(%d(%s), -1, %d)",
5452 target_fd
, path
, hostgid
);
5453 TRACE("Chowned %d(%s) to -1:%d", target_fd
, path
, hostgid
);
5456 /* "u:0:rootuid:1" */
5457 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, 0, container_host_uid
, 1);
5459 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5461 /* "u:hostuid:hostuid:1" */
5462 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, hostuid
, hostuid
, 1);
5464 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5466 /* "g:0:rootgid:1" */
5467 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, 0, container_host_gid
, 1);
5469 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5471 /* "g:hostgid:hostgid:1" */
5472 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, hostgid
, hostgid
, 1);
5474 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5476 if (hostgid
!= st
.st_gid
) {
5477 /* "g:pathgid:rootgid+pathgid:1" */
5478 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, st
.st_gid
,
5479 container_host_gid
+ (gid_t
)st
.st_gid
, 1);
5481 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5484 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5490 SYSERROR("Failed to create new process");
5495 close_prot_errno_disarm(sock_fds
[1]);
5497 ret
= unshare(CLONE_NEWUSER
);
5499 SYSERROR("Failed to unshare new user namespace");
5500 _exit(EXIT_FAILURE
);
5503 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5505 _exit(EXIT_FAILURE
);
5507 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5509 _exit(EXIT_FAILURE
);
5511 close_prot_errno_disarm(sock_fds
[0]);
5513 if (!lxc_drop_groups() && errno
!= EPERM
)
5514 _exit(EXIT_FAILURE
);
5516 ret
= setresgid(0, 0, 0);
5518 SYSERROR("Failed to setresgid(0, 0, 0)");
5519 _exit(EXIT_FAILURE
);
5522 ret
= setresuid(0, 0, 0);
5524 SYSERROR("Failed to setresuid(0, 0, 0)");
5525 _exit(EXIT_FAILURE
);
5528 ret
= fchown(target_fd
, 0, st
.st_gid
);
5530 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5531 _exit(EXIT_FAILURE
);
5534 TRACE("Chowned %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5535 _exit(EXIT_SUCCESS
);
5538 close_prot_errno_disarm(sock_fds
[0]);
5540 if (lxc_log_trace()) {
5543 list_for_each_entry(map
, idmap
, head
)
5544 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5545 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5548 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
5550 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
5554 /* Set up {g,u}id mapping for user namespace of child process. */
5555 ret
= lxc_map_ids(idmap
, pid
);
5557 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5561 /* Tell child to proceed. */
5562 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
5564 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5569 close_prot_errno_disarm(sock_fds
[0]);
5570 close_prot_errno_disarm(sock_fds
[1]);
5572 /* Wait for child to finish. */
5574 return log_error(-1, "Failed to create child process");
5576 if (!wait_exited(pid
))
5582 /* not thread-safe, do not use from api without first forking */
5583 static char *getuname(void)
5585 __do_free
char *buf
= NULL
;
5586 struct passwd pwent
;
5587 struct passwd
*pwentp
= NULL
;
5591 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
5595 buf
= zalloc(bufsize
);
5599 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
5602 WARN("Could not find matched password record.");
5604 return log_error(NULL
, "Failed to get password record - %u", geteuid());
5607 return strdup(pwent
.pw_name
);
5610 /* not thread-safe, do not use from api without first forking */
5611 static char *getgname(void)
5613 __do_free
char *buf
= NULL
;
5615 struct group
*grentp
= NULL
;
5619 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
5623 buf
= zalloc(bufsize
);
5627 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
5630 WARN("Could not find matched group record");
5632 return log_error(NULL
, "Failed to get group record - %u", getegid());
5635 return strdup(grent
.gr_name
);
5638 /* not thread-safe, do not use from api without first forking */
5639 void suggest_default_idmap(void)
5641 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
5642 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
5643 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
5654 subuid_f
= fopen(subuidfile
, "re");
5656 ERROR("Your system is not configured with subuids");
5660 while (getline(&line
, &len
, subuid_f
) != -1) {
5662 size_t no_newline
= 0;
5664 p
= strchr(line
, ':');
5672 if (!strequal(line
, uname
))
5675 p2
= strchr(p
, ':');
5682 no_newline
= strcspn(p2
, "\n");
5683 p2
[no_newline
] = '\0';
5685 if (lxc_safe_uint(p
, &uid
) < 0)
5686 WARN("Could not parse UID");
5687 if (lxc_safe_uint(p2
, &urange
) < 0)
5688 WARN("Could not parse UID range");
5691 subgid_f
= fopen(subgidfile
, "re");
5693 ERROR("Your system is not configured with subgids");
5697 while (getline(&line
, &len
, subgid_f
) != -1) {
5699 size_t no_newline
= 0;
5701 p
= strchr(line
, ':');
5709 if (!strequal(line
, uname
))
5712 p2
= strchr(p
, ':');
5719 no_newline
= strcspn(p2
, "\n");
5720 p2
[no_newline
] = '\0';
5722 if (lxc_safe_uint(p
, &gid
) < 0)
5723 WARN("Could not parse GID");
5724 if (lxc_safe_uint(p2
, &grange
) < 0)
5725 WARN("Could not parse GID range");
5728 if (!urange
|| !grange
) {
5729 ERROR("You do not have subuids or subgids allocated");
5730 ERROR("Unprivileged containers require subuids and subgids");
5734 ERROR("You must either run as root, or define uid mappings");
5735 ERROR("To pass uid mappings to lxc-create, you could create");
5736 ERROR("~/.config/lxc/default.conf:");
5737 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
5738 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
5739 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
5742 int lxc_set_environment(const struct lxc_conf
*conf
)
5744 struct environment_entry
*env
;
5746 list_for_each_entry(env
, &conf
->environment
, head
) {
5749 ret
= setenv(env
->key
, env
->val
, 1);
5751 return syserror("Failed to set environment variable: %s=%s",
5752 env
->key
, env
->val
);
5753 TRACE("Set environment variable: %s=%s", env
->key
, env
->val
);