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"
53 #include "open_utils.h"
55 #include "process_utils.h"
58 #include "storage/storage.h"
59 #include "storage/overlay.h"
61 #include "syscall_wrappers.h"
67 #include <sys/mkdev.h>
71 #include <sys/statvfs.h>
81 #include <sys/capability.h>
89 #include "lxcmntent.h"
94 #if !HAVE_PRLIMIT && HAVE_PRLIMIT64
103 #include "strchrnul.h"
106 lxc_log_define(conf
, lxc
);
109 * The lxc_conf of the container currently being worked on in an API call.
110 * This is used in the error calls.
112 thread_local
struct lxc_conf
*current_config
;
114 char *lxchook_names
[NUM_LXC_HOOKS
] = {
145 static struct mount_opt mount_opt
[] = {
146 { "atime", 1, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
147 { "dev", 1, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
148 { "diratime", 1, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
149 { "exec", 1, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
150 { "noatime", 0, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
151 { "nodev", 0, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
152 { "nodiratime", 0, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
153 { "noexec", 0, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
154 { "norelatime", 1, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
155 { "nostrictatime", 1, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
156 { "nosuid", 0, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
157 { "relatime", 0, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
158 { "ro", 0, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
159 { "rw", 1, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
160 { "strictatime", 0, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
161 { "suid", 1, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
163 { "bind", 0, false, 0, MS_BIND
},
164 { "defaults", 0, false, 0, 0 },
165 { "rbind", 0, true, 0, MS_BIND
| MS_REC
},
167 { "sync", 0, false, ~0, MS_SYNCHRONOUS
},
168 { "async", 1, false, ~0, MS_SYNCHRONOUS
},
169 { "dirsync", 0, false, ~0, MS_DIRSYNC
},
170 { "lazytime", 0, false, ~0, MS_LAZYTIME
},
171 { "mand", 0, false, ~0, MS_MANDLOCK
},
172 { "nomand", 1, false, ~0, MS_MANDLOCK
},
173 { "remount", 0, false, ~0, MS_REMOUNT
},
175 { NULL
, 0, false, ~0, ~0 },
178 static struct mount_opt propagation_opt
[] = {
179 { "private", 0, false, MS_PRIVATE
, MS_PRIVATE
},
180 { "shared", 0, false, MS_SHARED
, MS_SHARED
},
181 { "slave", 0, false, MS_SLAVE
, MS_SLAVE
},
182 { "unbindable", 0, false, MS_UNBINDABLE
, MS_UNBINDABLE
},
183 { "rprivate", 0, true, MS_PRIVATE
, MS_PRIVATE
| MS_REC
},
184 { "rshared", 0, true, MS_SHARED
, MS_SHARED
| MS_REC
},
185 { "rslave", 0, true, MS_SLAVE
, MS_SLAVE
| MS_REC
},
186 { "runbindable", 0, true, MS_UNBINDABLE
, MS_UNBINDABLE
| MS_REC
},
187 { NULL
, 0, false, 0, 0 },
190 static struct caps_opt caps_opt
[] = {
192 { "chown", CAP_CHOWN
},
193 { "dac_override", CAP_DAC_OVERRIDE
},
194 { "dac_read_search", CAP_DAC_READ_SEARCH
},
195 { "fowner", CAP_FOWNER
},
196 { "fsetid", CAP_FSETID
},
197 { "kill", CAP_KILL
},
198 { "setgid", CAP_SETGID
},
199 { "setuid", CAP_SETUID
},
200 { "setpcap", CAP_SETPCAP
},
201 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
202 { "net_bind_service", CAP_NET_BIND_SERVICE
},
203 { "net_broadcast", CAP_NET_BROADCAST
},
204 { "net_admin", CAP_NET_ADMIN
},
205 { "net_raw", CAP_NET_RAW
},
206 { "ipc_lock", CAP_IPC_LOCK
},
207 { "ipc_owner", CAP_IPC_OWNER
},
208 { "sys_module", CAP_SYS_MODULE
},
209 { "sys_rawio", CAP_SYS_RAWIO
},
210 { "sys_chroot", CAP_SYS_CHROOT
},
211 { "sys_ptrace", CAP_SYS_PTRACE
},
212 { "sys_pacct", CAP_SYS_PACCT
},
213 { "sys_admin", CAP_SYS_ADMIN
},
214 { "sys_boot", CAP_SYS_BOOT
},
215 { "sys_nice", CAP_SYS_NICE
},
216 { "sys_resource", CAP_SYS_RESOURCE
},
217 { "sys_time", CAP_SYS_TIME
},
218 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
219 { "mknod", CAP_MKNOD
},
220 { "lease", CAP_LEASE
},
221 { "audit_write", CAP_AUDIT_WRITE
},
222 { "audit_control", CAP_AUDIT_CONTROL
},
223 { "setfcap", CAP_SETFCAP
},
224 { "mac_override", CAP_MAC_OVERRIDE
},
225 { "mac_admin", CAP_MAC_ADMIN
},
226 { "syslog", CAP_SYSLOG
},
227 { "wake_alarm", CAP_WAKE_ALARM
},
228 { "block_suspend", CAP_BLOCK_SUSPEND
},
229 { "audit_read", CAP_AUDIT_READ
},
230 { "perfmon", CAP_PERFMON
},
232 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE
},
236 static struct limit_opt limit_opt
[] = {
241 { "core", RLIMIT_CORE
},
244 { "cpu", RLIMIT_CPU
},
247 { "data", RLIMIT_DATA
},
250 { "fsize", RLIMIT_FSIZE
},
253 { "locks", RLIMIT_LOCKS
},
255 #ifdef RLIMIT_MEMLOCK
256 { "memlock", RLIMIT_MEMLOCK
},
258 #ifdef RLIMIT_MSGQUEUE
259 { "msgqueue", RLIMIT_MSGQUEUE
},
262 { "nice", RLIMIT_NICE
},
265 { "nofile", RLIMIT_NOFILE
},
268 { "nproc", RLIMIT_NPROC
},
271 { "rss", RLIMIT_RSS
},
274 { "rtprio", RLIMIT_RTPRIO
},
277 { "rttime", RLIMIT_RTTIME
},
279 #ifdef RLIMIT_SIGPENDING
280 { "sigpending", RLIMIT_SIGPENDING
},
283 { "stack", RLIMIT_STACK
},
287 static int run_buffer(char *buffer
)
289 __do_free
char *output
= NULL
;
290 __do_lxc_pclose
struct lxc_popen_FILE
*f
= NULL
;
293 f
= lxc_popen(buffer
);
295 return log_error_errno(-1, errno
, "Failed to popen() %s", buffer
);
297 output
= zalloc(LXC_LOG_BUFFER_SIZE
);
299 return log_error_errno(-1, ENOMEM
, "Failed to allocate memory for %s", buffer
);
303 return log_error_errno(-1, errno
, "Failed to retrieve underlying file descriptor");
305 for (int i
= 0; i
< 10; i
++) {
308 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
309 if (bytes_read
> 0) {
310 output
[bytes_read
] = '\0';
311 DEBUG("Script %s produced output: %s", buffer
, output
);
318 ret
= lxc_pclose(move_ptr(f
));
320 return log_error_errno(-1, errno
, "Script exited with error");
321 else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0)
322 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret
));
323 else if (WIFSIGNALED(ret
))
324 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret
));
329 int run_script_argv(const char *name
, unsigned int hook_version
,
330 const char *section
, const char *script
,
331 const char *hookname
, char **argv
)
333 __do_free
char *buffer
= NULL
;
337 if (hook_version
== 0)
338 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
339 script
, name
, section
);
341 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
343 for (i
= 0; argv
&& argv
[i
]; i
++)
344 size
+= strlen(argv
[i
]) + 1;
346 size
+= STRLITERALLEN("exec");
348 size
+= strlen(script
);
354 if (hook_version
== 0) {
355 size
+= strlen(hookname
);
358 size
+= strlen(name
);
361 size
+= strlen(section
);
368 buffer
= zalloc(size
);
372 if (hook_version
== 0)
373 buf_pos
= strnprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
375 buf_pos
= strnprintf(buffer
, size
, "exec %s", script
);
377 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
379 if (hook_version
== 1) {
380 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
382 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname
);
384 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
386 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
388 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section
);
389 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
391 if (strequal(section
, "net")) {
394 if (!argv
|| !argv
[0])
397 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
399 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_TYPE=%s", argv
[0]);
400 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
402 parent
= argv
[1] ? argv
[1] : "";
404 if (strequal(argv
[0], "macvlan")) {
405 ret
= setenv("LXC_NET_PARENT", parent
, 1);
407 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
408 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
409 } else if (strequal(argv
[0], "phys")) {
410 ret
= setenv("LXC_NET_PARENT", parent
, 1);
412 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
413 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
414 } else if (strequal(argv
[0], "veth")) {
415 char *peer
= argv
[2] ? argv
[2] : "";
417 ret
= setenv("LXC_NET_PEER", peer
, 1);
419 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PEER=%s", peer
);
420 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
422 ret
= setenv("LXC_NET_PARENT", parent
, 1);
424 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
425 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
430 for (i
= 0; argv
&& argv
[i
]; i
++) {
431 size_t len
= size
- buf_pos
;
433 ret
= strnprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
435 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
439 return run_buffer(buffer
);
442 int run_script(const char *name
, const char *section
, const char *script
, ...)
444 __do_free
char *buffer
= NULL
;
450 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
451 script
, name
, section
);
453 va_start(ap
, script
);
454 while ((p
= va_arg(ap
, char *)))
455 size
+= strlen(p
) + 1;
458 size
+= STRLITERALLEN("exec");
459 size
+= strlen(script
);
460 size
+= strlen(name
);
461 size
+= strlen(section
);
467 buffer
= must_realloc(NULL
, size
);
468 ret
= strnprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
472 va_start(ap
, script
);
473 while ((p
= va_arg(ap
, char *))) {
474 int len
= size
- ret
;
476 rc
= strnprintf(buffer
+ ret
, len
, " %s", p
);
485 return run_buffer(buffer
);
488 int lxc_storage_prepare(struct lxc_conf
*conf
)
491 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
494 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
496 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
498 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
499 if (rootfs
->dfd_mnt
< 0)
505 ret
= access(rootfs
->mount
, F_OK
);
507 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
510 rootfs
->storage
= storage_init(conf
);
511 if (!rootfs
->storage
)
512 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
513 rootfs
->path
, rootfs
->mount
,
514 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
519 void lxc_storage_put(struct lxc_conf
*conf
)
521 storage_put(conf
->rootfs
.storage
);
522 conf
->rootfs
.storage
= NULL
;
525 /* lxc_rootfs_prepare
526 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
527 * the duration of the container run, to prevent the container from marking
528 * the underlying fs readonly on shutdown. unlink the file immediately so
529 * no name pollution is happens.
530 * don't unlink on NFS to avoid random named stale handles.
532 int lxc_rootfs_init(struct lxc_conf
*conf
, bool userns
)
534 __do_close
int dfd_path
= -EBADF
, fd_pin
= -EBADF
;
538 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
540 ret
= lxc_storage_prepare(conf
);
542 return syserror_set(-EINVAL
, "Failed to prepare rootfs storage");
544 if (!is_empty_string(rootfs
->mnt_opts
.userns_path
)) {
546 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supported with separate rootfs for container");
548 if (rootfs
->bdev_type
&& !strequal(rootfs
->bdev_type
, "dir"))
549 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supports the \"dir\" storage driver");
553 return log_trace(0, "Not pinning because container does not have a rootfs");
556 return log_trace(0, "Not pinning because container runs in user namespace");
558 if (rootfs
->bdev_type
) {
559 if (strequal(rootfs
->bdev_type
, "overlay") ||
560 strequal(rootfs
->bdev_type
, "overlayfs"))
561 return log_trace_errno(0, EINVAL
, "Not pinning on stacking filesystem");
563 if (strequal(rootfs
->bdev_type
, "zfs"))
564 return log_trace_errno(0, EINVAL
, "Not pinning on ZFS filesystem");
567 dfd_path
= open_at(-EBADF
, rootfs
->path
, PROTECT_OPATH_FILE
, 0, 0);
569 return syserror("Failed to open \"%s\"", rootfs
->path
);
571 ret
= fstat(dfd_path
, &st
);
573 return log_trace_errno(-errno
, errno
, "Failed to retrieve file status");
575 if (!S_ISDIR(st
.st_mode
))
576 return log_trace_errno(0, ENOTDIR
, "Not pinning because file descriptor is not a directory");
578 fd_pin
= open_at(dfd_path
, ".lxc_keep",
579 PROTECT_OPEN
| O_CREAT
,
580 PROTECT_LOOKUP_BENEATH
,
584 return log_trace_errno(0, EROFS
, "Not pinning on read-only filesystem");
585 return syserror("Failed to pin rootfs");
588 TRACE("Pinned rootfs %d(.lxc_keep)", fd_pin
);
590 ret
= fstatfs(fd_pin
, &stfs
);
592 SYSWARN("Failed to retrieve filesystem status");
596 if (stfs
.f_type
== NFS_SUPER_MAGIC
) {
597 DEBUG("Not unlinking pinned file on NFS");
601 if (unlinkat(dfd_path
, ".lxc_keep", 0))
602 SYSTRACE("Failed to unlink rootfs pinning file %d(.lxc_keep)", dfd_path
);
604 TRACE("Unlinked pinned file %d(.lxc_keep)", dfd_path
);
607 rootfs
->fd_path_pin
= move_fd(fd_pin
);
611 int lxc_rootfs_prepare_parent(struct lxc_handler
*handler
)
613 __do_close
int dfd_idmapped
= -EBADF
, fd_userns
= -EBADF
;
614 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
615 struct lxc_storage
*storage
= rootfs
->storage
;
616 const struct lxc_mount_options
*mnt_opts
= &rootfs
->mnt_opts
;
618 const char *path_source
;
620 if (list_empty(&handler
->conf
->id_map
))
623 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
626 if (handler
->conf
->rootfs_setup
)
629 if (rootfs_is_blockdev(handler
->conf
))
630 return syserror_set(-EOPNOTSUPP
, "Idmapped mounts on block-backed storage not yet supported");
632 if (!can_use_bind_mounts())
633 return syserror_set(-EOPNOTSUPP
, "Kernel does not support the new mount api");
635 if (strequal(rootfs
->mnt_opts
.userns_path
, "container"))
636 fd_userns
= dup_cloexec(handler
->nsfd
[LXC_NS_USER
]);
638 fd_userns
= open_at(-EBADF
, rootfs
->mnt_opts
.userns_path
,
639 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
641 return syserror("Failed to open user namespace");
643 path_source
= lxc_storage_get_path(storage
->src
, storage
->type
);
645 dfd_idmapped
= create_detached_idmapped_mount(path_source
, fd_userns
, true,
646 mnt_opts
->attr
.attr_set
,
647 mnt_opts
->attr
.attr_clr
);
648 if (dfd_idmapped
< 0)
649 return syserror("Failed to create detached idmapped mount");
651 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &dfd_idmapped
, 1, NULL
, 0);
653 return syserror("Failed to send detached idmapped mount fd");
655 TRACE("Created detached idmapped mount %d", dfd_idmapped
);
659 static int add_shmount_to_list(struct lxc_conf
*conf
)
661 char new_mount
[PATH_MAX
];
662 /* Offset for the leading '/' since the path_cont
663 * is absolute inside the container.
665 int offset
= 1, ret
= -1;
667 ret
= strnprintf(new_mount
, sizeof(new_mount
),
668 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
669 conf
->shmount
.path_cont
+ offset
);
673 return add_elem_to_mount_list(new_mount
, conf
);
676 static int lxc_mount_auto_mounts(struct lxc_handler
*handler
, int flags
)
683 const char *destination
;
687 bool requires_cap_net_admin
;
688 } default_mounts
[] = {
689 /* Read-only bind-mounting... In older kernels, doing that
690 * required to do one MS_BIND mount and then
691 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
692 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
693 * onwards. However, this apparently does not work on kernel
694 * 3.8. Unfortunately, on that very same kernel, doing the same
695 * trick as above doesn't seem to work either, there one needs
696 * to ALSO specify MS_BIND for the remount, otherwise the
697 * entire fs is remounted read-only or the mount fails because
698 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
699 * kernels as low as 2.6.32...
701 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
702 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
703 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
, true, },
704 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
, false },
705 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
706 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
, true },
707 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
, false },
708 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
709 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
710 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
, false },
711 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
, false },
712 /* /proc/sys is used as a temporary staging directory for the read-write sysfs mount and unmounted after binding net */
713 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/proc/sys", "sysfs", MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
, false },
714 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
|MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
, false },
715 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/proc/sys/devices/virtual/net", "%r/sys/devices/virtual/net", NULL
, MS_BIND
, NULL
, false },
716 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/proc/sys", NULL
, NULL
, 0, NULL
, false },
717 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
, false }
719 struct lxc_conf
*conf
= handler
->conf
;
720 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
721 bool has_cap_net_admin
;
723 if (flags
& LXC_AUTO_PROC_MASK
) {
726 * Only unmount procfs if we have a separate rootfs so
727 * we can still access it in safe_mount() below.
729 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc",
730 rootfs
->path
? rootfs
->mount
: "");
732 return ret_errno(EIO
);
734 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
736 SYSDEBUG("Tried to ensure procfs is unmounted");
739 ret
= mkdirat(rootfs
->dfd_mnt
, "proc" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
740 if (ret
< 0 && errno
!= EEXIST
)
741 return syserror("Failed to create procfs mountpoint under %d", rootfs
->dfd_mnt
);
743 TRACE("Created procfs mountpoint under %d", rootfs
->dfd_mnt
);
746 if (flags
& LXC_AUTO_SYS_MASK
) {
749 * Only unmount sysfs if we have a separate rootfs so
750 * we can still access it in safe_mount() below.
752 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/sys",
753 rootfs
->path
? rootfs
->mount
: "");
755 return ret_errno(EIO
);
757 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
759 SYSDEBUG("Tried to ensure sysfs is unmounted");
762 ret
= mkdirat(rootfs
->dfd_mnt
, "sys" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
763 if (ret
< 0 && errno
!= EEXIST
)
764 return syserror("Failed to create sysfs mountpoint under %d", rootfs
->dfd_mnt
);
766 TRACE("Created sysfs mountpoint under %d", rootfs
->dfd_mnt
);
769 has_cap_net_admin
= lxc_wants_cap(CAP_NET_ADMIN
, conf
);
770 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
771 __do_free
char *destination
= NULL
, *source
= NULL
;
772 unsigned long mflags
= default_mounts
[i
].flags
;
774 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
777 if (default_mounts
[i
].source
) {
778 /* will act like strdup if %r is not present */
779 source
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].source
);
781 return syserror_set(-ENOMEM
, "Failed to create source path");
784 if (!has_cap_net_admin
&& default_mounts
[i
].requires_cap_net_admin
) {
785 TRACE("Container does not have CAP_NET_ADMIN. Skipping \"%s\" mount", default_mounts
[i
].source
?: "(null)");
789 if (!default_mounts
[i
].destination
) {
790 ret
= umount2(source
, MNT_DETACH
);
792 return log_error_errno(-1, errno
,
793 "Failed to unmount \"%s\"",
795 TRACE("Unmounted automount \"%s\"", source
);
799 /* will act like strdup if %r is not present */
800 destination
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].destination
);
802 return syserror_set(-ENOMEM
, "Failed to create target path");
804 ret
= safe_mount(source
, destination
,
805 default_mounts
[i
].fstype
,
807 default_mounts
[i
].options
,
808 rootfs
->path
? rootfs
->mount
: NULL
);
811 return syserror("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
813 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source
, destination
);
817 if (mflags
& MS_REMOUNT
)
818 TRACE("Remounted automount \"%s\" on \"%s\" %s with flags %lu", source
, destination
, (mflags
& MS_RDONLY
) ? "read-only" : "read-write", mflags
);
820 TRACE("Mounted automount \"%s\" on \"%s\" %s with flags %lu", source
, destination
, (mflags
& MS_RDONLY
) ? "read-only" : "read-write", mflags
);
823 if (flags
& LXC_AUTO_CGROUP_MASK
) {
826 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
827 /* If the type of cgroup mount was not specified, it depends on
828 * the container's capabilities as to what makes sense: if we
829 * have CAP_SYS_ADMIN, the read-only part can be remounted
830 * read-write anyway, so we may as well default to read-write;
831 * then the admin will not be given a false sense of security.
832 * (And if they really want mixed r/o r/w, then they can
833 * explicitly specify :mixed.) OTOH, if the container lacks
834 * CAP_SYS_ADMIN, do only default to :mixed, because then the
835 * container can't remount it read-write.
837 if ((cg_flags
== LXC_AUTO_CGROUP_NOSPEC
) || (cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
)) {
838 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
839 cg_flags
= has_cap(CAP_SYS_ADMIN
, conf
)
841 : LXC_AUTO_CGROUP_MIXED
;
843 cg_flags
= has_cap(CAP_SYS_ADMIN
, conf
)
844 ? LXC_AUTO_CGROUP_FULL_RW
845 : LXC_AUTO_CGROUP_FULL_MIXED
;
848 if (flags
& LXC_AUTO_CGROUP_FORCE
)
849 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
851 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
, handler
, cg_flags
))
852 return log_error_errno(-1, errno
, "Failed to mount \"/sys/fs/cgroup\"");
855 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
856 ret
= add_shmount_to_list(conf
);
858 return log_error(-1, "Failed to add shmount entry to container config");
864 static int setup_utsname(struct utsname
*utsname
)
871 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
873 return log_error_errno(-1, errno
, "Failed to set the hostname to \"%s\"",
876 INFO("Set hostname to \"%s\"", utsname
->nodename
);
881 struct dev_symlinks
{
886 static const struct dev_symlinks dev_symlinks
[] = {
887 { "/proc/self/fd", "fd" },
888 { "/proc/self/fd/0", "stdin" },
889 { "/proc/self/fd/1", "stdout" },
890 { "/proc/self/fd/2", "stderr" },
893 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
895 for (size_t i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
898 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
901 * Stat the path first. If we don't get an error accept it as
902 * is and don't try to create it
904 ret
= fstatat(rootfs
->dfd_dev
, d
->name
, &s
, 0);
908 ret
= symlinkat(d
->oldpath
, rootfs
->dfd_dev
, d
->name
);
912 WARN("Failed to create \"%s\" on read-only filesystem", d
->name
);
917 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", d
->name
);
925 /* Build a space-separate list of ptys to pass to systemd. */
926 static bool append_ttyname(struct lxc_tty_info
*ttys
, char *tty_name
)
928 char *tty_names
, *buf
;
934 size
= strlen(tty_name
) + 1;
936 size
+= strlen(ttys
->tty_names
) + 1;
938 buf
= realloc(ttys
->tty_names
, size
);
944 (void)strlcat(buf
, " ", size
);
947 (void)strlcat(buf
, tty_name
, size
);
948 ttys
->tty_names
= tty_names
;
952 static int open_ttymnt_at(int dfd
, const char *path
)
956 fd
= open_at(dfd
, path
,
957 PROTECT_OPEN
| O_CREAT
| O_EXCL
,
958 PROTECT_LOOKUP_BENEATH
,
961 if (errno
!= ENXIO
&& errno
!= EEXIST
)
962 return syserror("Failed to create \"%d/\%s\"", dfd
, path
);
964 SYSINFO("Failed to create \"%d/\%s\"", dfd
, path
);
965 fd
= open_at(dfd
, path
,
967 PROTECT_LOOKUP_BENEATH
,
974 static int lxc_setup_ttys(struct lxc_conf
*conf
)
977 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
978 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
979 char *ttydir
= ttys
->dir
;
981 if (!conf
->rootfs
.path
)
984 for (size_t i
= 0; i
< ttys
->max
; i
++) {
985 __do_close
int fd_to
= -EBADF
;
986 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
989 char *tty_name
, *tty_path
;
991 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
992 "/dev/%s/tty%zu", ttydir
, i
+ 1);
994 return ret_errno(-EIO
);
996 tty_path
= &rootfs
->buf
[STRLITERALLEN("/dev/")];
997 tty_name
= tty_path
+ strlen(ttydir
) + 1;
999 /* create bind-mount target */
1000 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, tty_path
);
1002 return log_error_errno(-errno
, errno
,
1003 "Failed to create tty mount target %d(%s)",
1004 rootfs
->dfd_dev
, tty_path
);
1006 ret
= unlinkat(rootfs
->dfd_dev
, tty_name
, 0);
1007 if (ret
< 0 && errno
!= ENOENT
)
1008 return log_error_errno(-errno
, errno
,
1009 "Failed to unlink %d(%s)",
1010 rootfs
->dfd_dev
, tty_name
);
1012 if (can_use_mount_api())
1013 ret
= fd_bind_mount(tty
->pty
, "",
1015 PROTECT_LOOKUP_BENEATH_XDEV
,
1018 PROTECT_LOOKUP_BENEATH_XDEV
,
1024 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1026 return log_error_errno(-errno
, errno
,
1027 "Failed to bind mount \"%s\" onto \"%s\"",
1028 tty
->name
, rootfs
->buf
);
1029 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1031 ret
= symlinkat(tty_path
, rootfs
->dfd_dev
, tty_name
);
1033 return log_error_errno(-errno
, errno
,
1034 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
1035 rootfs
->dfd_dev
, tty_name
,
1036 rootfs
->dfd_dev
, tty_path
);
1038 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "tty%zu", i
+ 1);
1040 return ret_errno(-EIO
);
1042 /* If we populated /dev, then we need to create /dev/tty<idx>. */
1043 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, rootfs
->buf
);
1045 return log_error_errno(-errno
, errno
,
1046 "Failed to create tty mount target %d(%s)",
1047 rootfs
->dfd_dev
, rootfs
->buf
);
1049 if (can_use_mount_api())
1050 ret
= fd_bind_mount(tty
->pty
, "",
1052 PROTECT_LOOKUP_BENEATH_XDEV
,
1055 PROTECT_LOOKUP_BENEATH
,
1061 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1063 return log_error_errno(-errno
, errno
,
1064 "Failed to bind mount \"%s\" onto \"%s\"",
1065 tty
->name
, rootfs
->buf
);
1066 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1069 if (!append_ttyname(&conf
->ttys
, tty
->name
))
1070 return log_error(-1, "Error setting up container_ttys string");
1073 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
1077 define_cleanup_function(struct lxc_tty_info
*, lxc_delete_tty
);
1079 static int lxc_allocate_ttys(struct lxc_conf
*conf
)
1081 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*ttys
= &conf
->ttys
;
1084 /* no tty in the configuration */
1088 ttys
->tty
= zalloc(sizeof(struct lxc_terminal_info
) * ttys
->max
);
1092 for (size_t i
= 0; i
< conf
->ttys
.max
; i
++) {
1093 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1095 ret
= lxc_devpts_terminal(conf
->devpts_fd
, &tty
->ptx
,
1096 &tty
->pty
, &tty
->pty_nr
, false);
1099 return syserror_set(-ENOTTY
, "Failed to create tty %zu", i
);
1101 ret
= strnprintf(tty
->name
, sizeof(tty
->name
), "pts/%d", tty
->pty_nr
);
1103 return syserror("Failed to create tty %zu", i
);
1105 DEBUG("Created tty with ptx fd %d and pty fd %d and index %d",
1106 tty
->ptx
, tty
->pty
, tty
->pty_nr
);
1110 INFO("Finished creating %zu tty devices", ttys
->max
);
1115 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1117 if (!ttys
|| !ttys
->tty
)
1120 for (size_t i
= 0; i
< ttys
->max
; i
++) {
1121 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1122 close_prot_errno_disarm(tty
->ptx
);
1123 close_prot_errno_disarm(tty
->pty
);
1126 free_disarm(ttys
->tty
);
1129 static int __lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1132 struct lxc_conf
*conf
= handler
->conf
;
1133 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1134 int sock
= handler
->data_sock
[0];
1139 for (size_t i
= 0; i
< ttys
->max
; i
++) {
1141 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1143 ttyfds
[0] = tty
->ptx
;
1144 ttyfds
[1] = tty
->pty
;
1146 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1150 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1151 tty
->name
, tty
->ptx
, tty
->pty
);
1155 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1157 TRACE("Sent %zu ttys to parent", ttys
->max
);
1162 static int lxc_create_ttys(struct lxc_handler
*handler
)
1165 struct lxc_conf
*conf
= handler
->conf
;
1167 ret
= lxc_allocate_ttys(conf
);
1169 ERROR("Failed to allocate ttys");
1173 if (!conf
->is_execute
) {
1174 ret
= lxc_setup_ttys(conf
);
1176 ERROR("Failed to setup ttys");
1181 if (conf
->ttys
.tty_names
) {
1182 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1184 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1187 TRACE("Set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1193 lxc_delete_tty(&conf
->ttys
);
1198 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1202 ret
= __lxc_send_ttys_to_parent(handler
);
1203 lxc_delete_tty(&handler
->conf
->ttys
);
1207 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1208 * error, log it but don't fail yet.
1210 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1211 int autodevtmpfssize
, const char *lxcpath
)
1213 __do_close
int fd_fs
= -EBADF
;
1214 const char *path
= rootfs
->path
? rootfs
->mount
: NULL
;
1215 size_t tmpfs_size
= (autodevtmpfssize
!= 0) ? autodevtmpfssize
: 500000;
1218 char mount_options
[128];
1220 INFO("Preparing \"/dev\"");
1222 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1223 ret
= mkdirat(rootfs
->dfd_mnt
, "dev" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1224 if (ret
< 0 && errno
!= EEXIST
) {
1225 SYSERROR("Failed to create \"/dev\" directory");
1230 if (can_use_mount_api()) {
1231 fd_fs
= fs_prepare("tmpfs", -EBADF
, "", 0, 0);
1233 return log_error_errno(-errno
, errno
, "Failed to prepare filesystem context for tmpfs");
1235 sprintf(mount_options
, "%zu", tmpfs_size
);
1237 ret
= fs_set_property(fd_fs
, "mode", "0755");
1239 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1241 ret
= fs_set_property(fd_fs
, "size", mount_options
);
1243 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1245 ret
= fs_attach(fd_fs
, rootfs
->dfd_mnt
, "dev",
1246 PROTECT_OPATH_DIRECTORY
,
1247 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1249 __do_free
char *fallback_path
= NULL
;
1251 sprintf(mount_options
, "size=%zu,mode=755", tmpfs_size
);
1252 DEBUG("Using mount options: %s", mount_options
);
1255 fallback_path
= must_make_path(path
, "/dev", NULL
);
1256 ret
= safe_mount("none", fallback_path
, "tmpfs", 0, mount_options
, path
);
1258 ret
= safe_mount("none", "dev", "tmpfs", 0, mount_options
, NULL
);
1262 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1266 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1267 * If not, then create it and exit if that fails...
1269 ret
= mkdirat(rootfs
->dfd_mnt
, "dev/pts", S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1270 if (ret
< 0 && errno
!= EEXIST
) {
1271 SYSERROR("Failed to create directory \"dev/pts\"");
1279 (void)umask(cur_mask
);
1281 INFO("Prepared \"/dev\"");
1285 struct lxc_device_node
{
1292 static const struct lxc_device_node lxc_devices
[] = {
1293 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1294 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1295 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1296 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1297 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1298 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1305 LXC_DEVNODE_PARTIAL
,
1309 static int lxc_fill_autodev(struct lxc_rootfs
*rootfs
)
1313 int use_mknod
= LXC_DEVNODE_MKNOD
;
1315 if (rootfs
->dfd_dev
< 0)
1316 return log_info(0, "No /dev directory found, skipping setup");
1318 INFO("Populating \"/dev\"");
1320 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1321 for (size_t i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1322 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1324 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1325 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, device
->mode
, makedev(device
->maj
, device
->min
));
1326 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1327 DEBUG("Created device node \"%s\"", device
->name
);
1328 } else if (ret
< 0) {
1330 return log_error_errno(-1, errno
, "Failed to create device node \"%s\"", device
->name
);
1332 use_mknod
= LXC_DEVNODE_BIND
;
1335 /* Device nodes are fully useable. */
1336 if (use_mknod
== LXC_DEVNODE_OPEN
)
1339 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1340 __do_close
int fd
= -EBADF
;
1342 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1343 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1345 fd
= open_at(rootfs
->dfd_dev
, device
->name
, PROTECT_OPEN
, PROTECT_LOOKUP_BENEATH
, 0);
1347 /* Device nodes are fully useable. */
1348 use_mknod
= LXC_DEVNODE_OPEN
;
1352 SYSTRACE("Failed to open \"%s\" device", device
->name
);
1353 /* Device nodes are only partially useable. */
1354 use_mknod
= LXC_DEVNODE_PARTIAL
;
1358 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1359 /* If we are dealing with partially functional device
1360 * nodes the prio mknod() call will have created the
1361 * device node so we can use it as a bind-mount target.
1363 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, S_IFREG
| 0000, 0);
1364 if (ret
< 0 && errno
!= EEXIST
)
1365 return log_error_errno(-1, errno
, "Failed to create file \"%s\"", device
->name
);
1368 /* Fallback to bind-mounting the device from the host. */
1369 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "dev/%s", device
->name
);
1371 return ret_errno(EIO
);
1373 if (can_use_mount_api()) {
1374 ret
= fd_bind_mount(rootfs
->dfd_host
, rootfs
->buf
,
1376 PROTECT_LOOKUP_BENEATH_XDEV
,
1377 rootfs
->dfd_dev
, device
->name
,
1379 PROTECT_LOOKUP_BENEATH
,
1385 char path
[PATH_MAX
];
1387 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/dev/%s", device
->name
);
1389 return ret_errno(EIO
);
1391 ret
= strnprintf(path
, sizeof(path
), "%s/dev/%s", get_rootfs_mnt(rootfs
), device
->name
);
1393 return log_error(-1, "Failed to create device path for %s", device
->name
);
1395 ret
= safe_mount(rootfs
->buf
, path
, 0, MS_BIND
, NULL
, get_rootfs_mnt(rootfs
));
1397 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1399 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1402 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs
->dfd_host
, rootfs
->buf
, rootfs
->dfd_dev
, device
->name
);
1406 INFO("Populated \"/dev\"");
1410 static int lxc_mount_rootfs(struct lxc_rootfs
*rootfs
)
1414 if (!rootfs
->path
) {
1415 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1417 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
1419 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1420 if (rootfs
->dfd_mnt
< 0)
1423 return log_trace(0, "Container doesn't use separate rootfs. Opened host's rootfs");
1426 ret
= access(rootfs
->mount
, F_OK
);
1428 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1431 ret
= rootfs
->storage
->ops
->mount(rootfs
->storage
);
1433 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1434 rootfs
->path
, rootfs
->mount
,
1435 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
1437 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1438 rootfs
->path
, rootfs
->mount
,
1439 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
1441 rootfs
->dfd_mnt
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1442 if (rootfs
->dfd_mnt
< 0)
1445 return log_trace(0, "Container uses separate rootfs. Opened container's rootfs");
1448 static bool lxc_rootfs_overmounted(struct lxc_rootfs
*rootfs
)
1450 __do_close
int fd_rootfs
= -EBADF
;
1453 fd_rootfs
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1455 fd_rootfs
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1459 if (!same_file_lax(rootfs
->dfd_mnt
, fd_rootfs
))
1460 return syswarn_ret(true, "Rootfs seems to have changed after setting up mounts");
1465 static int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1467 __do_free
char *nroot
= NULL
;
1469 char *root
= rootfs
->mount
;
1471 nroot
= realpath(root
, NULL
);
1473 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1479 /* We could use here MS_MOVE, but in userns this mount is locked and
1482 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1484 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1486 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1488 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1490 /* The following code cleans up inherited mounts which are not required
1493 * The mountinfo file shows not all mounts, if a few points have been
1494 * unmounted between read operations from the mountinfo. So we need to
1495 * read mountinfo a few times.
1497 * This loop can be skipped if a container uses userns, because all
1498 * inherited mounts are locked and we should live with all this trash.
1501 __do_fclose
FILE *f
= NULL
;
1502 __do_free
char *line
= NULL
;
1503 char *slider1
, *slider2
;
1507 f
= fopen("./proc/self/mountinfo", "re");
1509 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1511 while (getline(&line
, &len
, f
) > 0) {
1512 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1513 slider1
= strchr(slider1
+ 1, ' ');
1518 slider2
= strchr(slider1
+ 1, ' ');
1525 if (strequal(slider1
+ 1, "/"))
1528 if (strequal(slider1
+ 1, "/proc"))
1531 ret
= umount2(slider1
, MNT_DETACH
);
1540 /* This also can be skipped if a container uses userns. */
1541 (void)umount2("./proc", MNT_DETACH
);
1543 /* It is weird, but chdir("..") moves us in a new root */
1546 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1550 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1555 /* (The following explanation is copied verbatim from the kernel.)
1557 * pivot_root Semantics:
1558 * Moves the root file system of the current process to the directory put_old,
1559 * makes new_root as the new root file system of the current process, and sets
1560 * root/cwd of all processes which had them on the current root to new_root.
1563 * The new_root and put_old must be directories, and must not be on the
1564 * same file system as the current process root. The put_old must be
1565 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1566 * pointed to by put_old must yield the same directory as new_root. No other
1567 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1569 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1570 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1571 * in this situation.
1574 * - we don't move root/cwd if they are not at the root (reason: if something
1575 * cared enough to change them, it's probably wrong to force them elsewhere)
1576 * - it's okay to pick a root that isn't the root of a file system, e.g.
1577 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1578 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1581 static int lxc_pivot_root(const struct lxc_rootfs
*rootfs
)
1583 __do_close
int fd_oldroot
= -EBADF
;
1586 fd_oldroot
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1588 return log_error_errno(-1, errno
, "Failed to open old root directory");
1590 /* change into new root fs */
1591 ret
= fchdir(rootfs
->dfd_mnt
);
1593 return log_error_errno(-errno
, errno
, "Failed to change into new root directory \"%s\"", rootfs
->mount
);
1595 /* pivot_root into our new root fs */
1596 ret
= pivot_root(".", ".");
1598 return log_error_errno(-errno
, errno
, "Failed to pivot into new root directory \"%s\"", rootfs
->mount
);
1600 /* At this point the old-root is mounted on top of our new-root. To
1601 * unmounted it we must not be chdir'd into it, so escape back to
1604 ret
= fchdir(fd_oldroot
);
1606 return log_error_errno(-errno
, errno
, "Failed to enter old root directory");
1609 * Unprivileged containers will have had all their mounts turned into
1610 * dependent mounts when the container was created. But for privileged
1611 * containers we need to turn the old root mount tree into a dependent
1612 * mount tree to prevent propagating mounts and umounts into the host
1615 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1617 return log_error_errno(-errno
, errno
, "Failed to recursively turn old root mount tree into dependent mount");
1619 ret
= umount2(".", MNT_DETACH
);
1621 return log_error_errno(-errno
, errno
, "Failed to detach old root directory");
1623 ret
= fchdir(rootfs
->dfd_mnt
);
1625 return log_error_errno(-errno
, errno
, "Failed to re-enter new root directory \"%s\"", rootfs
->mount
);
1628 * Finally, we turn the rootfs into a shared mount. Note, that this
1629 * doesn't reestablish mount propagation with the hosts mount
1630 * namespace. Instead we'll create a new peer group.
1632 * We're doing this because most workloads do rely on the rootfs being
1633 * a shared mount. For example, systemd daemon like sytemd-udevd run in
1634 * their own mount namespace. Their mount namespace has been made a
1635 * dependent mount (MS_SLAVE) with the host rootfs as it's dominating
1636 * mount. This means new mounts on the host propagate into the
1637 * respective services.
1639 * This is broken if we leave the container's rootfs a dependent mount.
1640 * In which case both the container's rootfs and the service's rootfs
1641 * will be dependent mounts with the host's rootfs as their dominating
1642 * mount. So if you were to mount over the rootfs from the host it
1643 * would not just propagate into the container's mount namespace it
1644 * would also propagate into the service. That's nonsense semantics for
1645 * nearly all relevant use-cases. Instead, establish the container's
1646 * rootfs as a separate peer group mirroring the behavior on the host.
1648 ret
= mount("", ".", "", MS_SHARED
| MS_REC
, NULL
);
1650 return log_error_errno(-errno
, errno
, "Failed to turn new root mount tree into shared mount tree");
1652 TRACE("Changed into new rootfs \"%s\"", rootfs
->mount
);
1656 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1659 return log_debug(0, "Container does not have a rootfs");
1661 if (detect_ramfs_rootfs())
1662 return lxc_chroot(rootfs
);
1664 return lxc_pivot_root(rootfs
);
1667 static const struct id_map
*find_mapped_nsid_entry(const struct lxc_conf
*conf
,
1672 struct id_map
*retmap
= NULL
;
1674 /* Shortcut for container's root mappings. */
1676 if (idtype
== ID_TYPE_UID
)
1677 return conf
->root_nsuid_map
;
1679 if (idtype
== ID_TYPE_GID
)
1680 return conf
->root_nsgid_map
;
1683 list_for_each_entry(map
, &conf
->id_map
, head
) {
1684 if (map
->idtype
!= idtype
)
1687 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1696 static int lxc_recv_devpts_from_child(struct lxc_handler
*handler
)
1700 if (handler
->conf
->pty_max
<= 0)
1703 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1],
1704 &handler
->conf
->devpts_fd
,
1705 &handler
->conf
->devpts_fd
,
1706 sizeof(handler
->conf
->devpts_fd
));
1708 return log_error_errno(-1, errno
, "Failed to receive devpts fd from child");
1710 TRACE("Received devpts file descriptor %d from child", handler
->conf
->devpts_fd
);
1714 static int lxc_setup_devpts_child(struct lxc_handler
*handler
)
1716 __do_close
int devpts_fd
= -EBADF
, fd_fs
= -EBADF
;
1717 struct lxc_conf
*conf
= handler
->conf
;
1718 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1719 size_t pty_max
= conf
->pty_max
;
1722 pty_max
+= conf
->ttys
.max
;
1724 return log_debug(0, "No new devpts instance will be mounted since no pts devices are required");
1726 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
1727 "/proc/self/fd/%d/pts", rootfs
->dfd_dev
);
1729 return syserror("Failed to create path");
1731 (void)umount2(rootfs
->buf
, MNT_DETACH
);
1733 /* Create mountpoint for devpts instance. */
1734 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1735 if (ret
< 0 && errno
!= EEXIST
)
1736 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1738 if (can_use_mount_api()) {
1739 fd_fs
= fs_prepare("devpts", -EBADF
, "", 0, 0);
1741 return syserror("Failed to prepare filesystem context for devpts");
1743 ret
= fs_set_property(fd_fs
, "source", "devpts");
1745 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs
);
1747 ret
= fs_set_property(fd_fs
, "gid", "5");
1749 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs
);
1751 ret
= fs_set_flag(fd_fs
, "newinstance");
1753 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs
);
1755 ret
= fs_set_property(fd_fs
, "ptmxmode", "0666");
1757 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs
);
1759 ret
= fs_set_property(fd_fs
, "mode", "0620");
1761 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs
);
1763 ret
= fs_set_property(fd_fs
, "max", fdstr(pty_max
));
1765 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf
->pty_max
, fd_fs
);
1767 ret
= fsconfig(fd_fs
, FSCONFIG_CMD_CREATE
, NULL
, NULL
, 0);
1769 return syserror("Failed to finalize filesystem context %d", fd_fs
);
1771 devpts_fd
= fsmount(fd_fs
, FSMOUNT_CLOEXEC
, MOUNT_ATTR_NOSUID
| MOUNT_ATTR_NOEXEC
);
1773 return syserror("Failed to create new mount for filesystem context %d", fd_fs
);
1774 TRACE("Created detached devpts mount %d", devpts_fd
);
1776 ret
= move_mount(devpts_fd
, "", rootfs
->dfd_dev
, "pts", MOVE_MOUNT_F_EMPTY_PATH
);
1778 return syserror("Failed to attach devpts mount %d to %d/pts", conf
->devpts_fd
, rootfs
->dfd_dev
);
1780 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd
, rootfs
->dfd_dev
);
1783 char devpts_mntopts
[256];
1784 char *mntopt_sets
[5];
1785 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1788 * Fallback codepath in case the new mount API can't be used to
1789 * create detached mounts.
1792 ret
= strnprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1793 default_devpts_mntopts
, pty_max
);
1797 /* Create mountpoint for devpts instance. */
1798 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1799 if (ret
< 0 && errno
!= EEXIST
)
1800 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1803 mntopt_sets
[0] = devpts_mntopts
;
1805 /* !gid=5 && max= */
1806 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1808 /* gid=5 && !max= */
1809 mntopt_sets
[2] = default_devpts_mntopts
;
1811 /* !gid=5 && !max= */
1812 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1815 mntopt_sets
[4] = NULL
;
1817 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1818 /* mount new devpts instance */
1819 ret
= mount_at(rootfs
->dfd_dev
, "", 0,
1820 rootfs
->dfd_dev
, "pts", PROTECT_LOOKUP_BENEATH
,
1821 "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1826 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1828 devpts_fd
= open_at(rootfs
->dfd_dev
, "pts", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1829 if (devpts_fd
< 0) {
1831 TRACE("Failed to create detached devpts mount");
1834 DEBUG("Mounted new devpts instance with options \"%s\"", *opts
);
1837 handler
->conf
->devpts_fd
= move_fd(devpts_fd
);
1840 * In order to allocate terminal devices the devpts filesystem will
1841 * have to be attached to the filesystem at least ones in the new mount
1842 * api. The reason is lengthy but the gist is that until the new mount
1843 * has been attached to the filesystem it is a detached mount with an
1844 * anonymous mount mamespace attached to it for which the kernel
1845 * refuses certain operations.
1846 * We end up here if the user has requested to allocate tty devices
1847 * while not requestig pty devices be made available to the container.
1848 * We only need the devpts_fd to allocate tty devices.
1850 if (conf
->pty_max
<= 0)
1853 /* Remove any pre-existing /dev/ptmx file. */
1854 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1856 if (errno
!= ENOENT
)
1857 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1859 DEBUG("Removed existing \"/dev/ptmx\" file");
1862 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1863 ret
= mknodat(rootfs
->dfd_dev
, "ptmx", S_IFREG
| 0000, 0);
1864 if (ret
< 0 && errno
!= EEXIST
)
1865 return log_error_errno(-1, errno
, "Failed to create \"/dev/ptmx\" file as bind mount target");
1866 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
1868 /* Main option: use a bind-mount to please AppArmor */
1869 ret
= mount_at(rootfs
->dfd_dev
, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1870 rootfs
->dfd_dev
, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1871 NULL
, MS_BIND
, NULL
);
1873 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1875 /* Fallthrough and try to create a symlink. */
1876 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1878 /* Remove the placeholder /dev/ptmx file we created above. */
1879 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1881 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1883 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1884 ret
= symlinkat("/dev/pts/ptmx", rootfs
->dfd_dev
, "dev/ptmx");
1886 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1888 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1892 static int lxc_finish_devpts_child(struct lxc_handler
*handler
)
1894 struct lxc_conf
*conf
= handler
->conf
;
1895 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1898 if (conf
->pty_max
> 0)
1902 * We end up here if the user has requested to allocate tty devices
1903 * while not requestig pty devices be made available to the container.
1904 * This means we can unmount the devpts instance. We only need the
1905 * devpts_fd to allocate tty devices.
1907 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
1908 "/proc/self/fd/%d/pts", rootfs
->dfd_dev
);
1910 return syserror("Failed to create path");
1912 close_prot_errno_disarm(conf
->devpts_fd
);
1913 (void)umount2(rootfs
->buf
, MNT_DETACH
);
1917 static int lxc_send_devpts_to_parent(struct lxc_handler
*handler
)
1921 if (handler
->conf
->pty_max
<= 0)
1922 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1924 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->conf
->devpts_fd
, 1, NULL
, 0);
1926 SYSERROR("Failed to send devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1928 TRACE("Sent devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1930 close_prot_errno_disarm(handler
->conf
->devpts_fd
);
1935 static int setup_personality(personality_t persona
)
1939 if (persona
== LXC_ARCH_UNCHANGED
)
1940 return log_debug(0, "Retaining original personality");
1942 ret
= lxc_personality(persona
);
1944 return syserror("Failed to set personality to \"0lx%lx\"", persona
);
1946 INFO("Set personality to \"0lx%lx\"", persona
);
1950 static int bind_mount_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1951 struct lxc_terminal
*console
, int fd_to
)
1953 __do_close
int fd_pty
= -EBADF
;
1955 if (is_empty_string(console
->name
))
1956 return ret_errno(EINVAL
);
1959 * When the pty fd stashed in console->pty has been retrieved via the
1960 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1961 * allocating new pty devices we can't reopen it through openat2() or
1962 * created a detached mount through open_tree() from it. This means we
1963 * would need to mount using the path stased in console->name which is
1964 * unsafe. We could be mounting a device that isn't identical to the
1965 * one we've already safely opened and stashed in console->pty.
1966 * So, what we do is we open an O_PATH file descriptor for
1967 * console->name and verify that the opened fd and the fd we stashed in
1968 * console->pty refer to the same device. If they do we can go on and
1969 * created a detached mount based on the newly opened O_PATH file
1970 * descriptor and then safely mount.
1972 fd_pty
= open_at_same(console
->pty
, fd_devpts
, fdstr(console
->pty_nr
),
1973 PROTECT_OPATH_FILE
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1975 return syserror("Failed to open \"%s\"", console
->name
);
1978 * Note, there are intentionally no open or lookup restrictions since
1979 * we're operating directly on the fd.
1981 if (can_use_mount_api())
1982 return fd_bind_mount(fd_pty
, "", 0, 0, fd_to
, "", 0, 0, 0, 0, 0, false);
1984 return mount_fd(fd_pty
, fd_to
, "none", MS_BIND
, 0);
1987 static int lxc_setup_dev_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1988 struct lxc_terminal
*console
)
1990 __do_close
int fd_console
= -EBADF
;
1994 * When we are asked to setup a console we remove any previous
1995 * /dev/console bind-mounts.
1997 if (exists_file_at(rootfs
->dfd_dev
, "console")) {
1998 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
2000 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
2004 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
2006 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
2008 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
2012 * For unprivileged containers autodev or automounts will already have
2013 * taken care of creating /dev/console.
2015 fd_console
= open_at(rootfs
->dfd_dev
,
2017 PROTECT_OPEN
| O_CREAT
,
2018 PROTECT_LOOKUP_BENEATH
,
2021 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
2023 ret
= fchmod(console
->pty
, 0620);
2025 return syserror("Failed to change console mode");
2027 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_console
);
2029 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2030 console
->pty
, console
->name
, fd_console
);
2032 TRACE("Setup console \"%s\"", console
->name
);
2036 static int lxc_setup_ttydir_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
2037 struct lxc_terminal
*console
,
2040 __do_close
int fd_ttydir
= -EBADF
, fd_dev_console
= -EBADF
,
2041 fd_reg_console
= -EBADF
, fd_reg_ttydir_console
= -EBADF
;
2044 /* create dev/<ttydir> */
2045 ret
= mkdirat(rootfs
->dfd_dev
, ttydir
, 0755);
2046 if (ret
< 0 && errno
!= EEXIST
)
2047 return syserror("Failed to create \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
2049 fd_ttydir
= open_at(rootfs
->dfd_dev
,
2051 PROTECT_OPATH_DIRECTORY
,
2052 PROTECT_LOOKUP_BENEATH
,
2055 return syserror("Failed to open \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
2057 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/console", ttydir
);
2061 /* create dev/<ttydir>/console */
2062 fd_reg_ttydir_console
= open_at(fd_ttydir
,
2064 PROTECT_OPEN
| O_CREAT
,
2065 PROTECT_LOOKUP_BENEATH
,
2067 if (fd_reg_ttydir_console
< 0)
2068 return syserror("Failed to create \"%d/console\"", fd_ttydir
);
2070 if (file_exists(rootfs
->buf
)) {
2071 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
2073 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
2077 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
2079 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
2081 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
2084 /* create dev/console */
2085 fd_reg_console
= open_at(rootfs
->dfd_dev
,
2087 PROTECT_OPEN
| O_CREAT
,
2088 PROTECT_LOOKUP_BENEATH
,
2090 if (fd_reg_console
< 0)
2091 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
2093 ret
= fchmod(console
->pty
, 0620);
2095 return syserror("Failed to change console mode");
2097 /* bind mount console to '/dev/<ttydir>/console' */
2098 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_reg_ttydir_console
);
2100 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2101 console
->pty
, console
->name
, fd_reg_ttydir_console
);
2103 fd_dev_console
= open_at_same(console
->pty
,
2107 PROTECT_LOOKUP_BENEATH_XDEV
,
2109 if (fd_dev_console
< 0)
2110 return syserror("Failed to open \"%d/console\"", fd_ttydir
);
2112 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
2113 if (can_use_mount_api())
2114 ret
= fd_bind_mount(fd_dev_console
,
2117 PROTECT_LOOKUP_BENEATH_XDEV
,
2121 PROTECT_LOOKUP_BENEATH
,
2127 ret
= mount_fd(fd_dev_console
, fd_reg_console
, "none", MS_BIND
, 0);
2129 return syserror("Failed to mount \"%d\" on \"%d\"",
2130 fd_dev_console
, fd_reg_console
);
2132 TRACE("Setup console \"%s\"", console
->name
);
2136 static int lxc_setup_console(const struct lxc_handler
*handler
,
2137 struct lxc_rootfs
*rootfs
,
2138 struct lxc_terminal
*console
, char *ttydir
)
2140 __do_close
int fd_devpts_host
= -EBADF
;
2141 int fd_devpts
= handler
->conf
->devpts_fd
;
2144 if (!wants_console(console
))
2145 return log_trace(0, "Skipping console setup");
2147 if (console
->pty
< 0) {
2149 * Allocate a console from the container's devpts instance. We
2150 * have checked on the host that we have enough pty devices
2153 ret
= lxc_devpts_terminal(handler
->conf
->devpts_fd
, &console
->ptx
,
2154 &console
->pty
, &console
->pty_nr
, false);
2156 return syserror("Failed to allocate console from container's devpts instance");
2158 ret
= strnprintf(console
->name
, sizeof(console
->name
),
2159 "/dev/pts/%d", console
->pty_nr
);
2161 return syserror("Failed to create console path");
2164 * We're using a console from the host's devpts instance. Open
2165 * it again so we can later verify that the console we're
2166 * supposed to use is still the same as the one we opened on
2169 fd_devpts_host
= open_at(rootfs
->dfd_host
,
2171 PROTECT_OPATH_DIRECTORY
,
2172 PROTECT_LOOKUP_BENEATH_XDEV
,
2174 if (fd_devpts_host
< 0)
2175 return syserror("Failed to open host devpts");
2177 fd_devpts
= fd_devpts_host
;
2181 ret
= lxc_setup_ttydir_console(fd_devpts
, rootfs
, console
, ttydir
);
2183 ret
= lxc_setup_dev_console(fd_devpts
, rootfs
, console
);
2185 return syserror("Failed to setup console");
2188 * Some init's such as busybox will set sane tty settings on stdin,
2189 * stdout, stderr which it thinks is the console. We already set them
2190 * the way we wanted on the real terminal, and we want init to do its
2191 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2192 * make sure that that pty is stdin,stdout,stderr.
2194 if (console
->pty
>= 0) {
2195 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
2196 ret
= set_stdfds(console
->pty
);
2198 ret
= lxc_terminal_set_stdfds(console
->pty
);
2200 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console
->pty
);
2203 * If the console has been allocated from the host's devpts
2204 * we're done and we don't need to send fds to the parent.
2206 if (fd_devpts_host
>= 0)
2207 lxc_terminal_delete(console
);
2213 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
2217 /* If '=' is contained in opt, the option must go into data. */
2218 if (!strchr(opt
, '=')) {
2220 * If opt is found in mount_opt, set or clear flags.
2221 * Otherwise append it to data.
2223 size_t opt_len
= strlen(opt
);
2224 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2225 size_t mo_name_len
= strlen(mo
->name
);
2227 if (opt_len
== mo_name_len
&& strnequal(opt
, mo
->name
, mo_name_len
)) {
2229 *flags
&= ~mo
->legacy_flag
;
2231 *flags
|= mo
->legacy_flag
;
2237 if (strlen(*data
)) {
2238 ret
= strlcat(*data
, ",", size
);
2240 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
2243 ret
= strlcat(*data
, opt
, size
);
2245 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
2250 int parse_mntopts_legacy(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
2252 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2253 char *mntopt_cur
= NULL
;
2256 if (*mntdata
|| *mntflags
)
2257 return ret_errno(EINVAL
);
2262 mntopts_dup
= strdup(mntopts
);
2264 return ret_errno(ENOMEM
);
2266 size
= strlen(mntopts_dup
) + 1;
2267 mntopts_new
= zalloc(size
);
2269 return ret_errno(ENOMEM
);
2271 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
2272 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
2273 return ret_errno(EINVAL
);
2276 *mntdata
= move_ptr(mntopts_new
);
2281 static int parse_vfs_attr(struct lxc_mount_options
*opts
, char *opt
, size_t size
)
2284 * If opt is found in mount_opt, set or clear flags.
2285 * Otherwise append it to data.
2287 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2288 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2291 /* This is a recursive bind-mount. */
2292 if (strequal(mo
->name
, "rbind")) {
2293 opts
->bind_recursively
= 1;
2295 opts
->mnt_flags
|= mo
->legacy_flag
; /* MS_BIND | MS_REC */
2299 /* This is a bind-mount. */
2300 if (strequal(mo
->name
, "bind")) {
2302 opts
->mnt_flags
|= mo
->legacy_flag
; /* MS_BIND */
2306 if (mo
->flag
== (__u64
)~0)
2307 return log_info(0, "Ignoring %s mount option", mo
->name
);
2310 opts
->attr
.attr_clr
|= mo
->flag
;
2311 opts
->mnt_flags
&= ~mo
->legacy_flag
;
2312 TRACE("Lowering %s", mo
->name
);
2314 opts
->attr
.attr_set
|= mo
->flag
;
2315 opts
->mnt_flags
|= mo
->legacy_flag
;
2316 TRACE("Raising %s", mo
->name
);
2322 for (struct mount_opt
*mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
2323 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2326 if (strequal(mo
->name
, "rslave") ||
2327 strequal(mo
->name
, "rshared") ||
2328 strequal(mo
->name
, "runbindable") ||
2329 strequal(mo
->name
, "rprivate"))
2330 opts
->propagate_recursively
= 1;
2332 opts
->attr
.propagation
= mo
->flag
;
2333 opts
->prop_flags
|= mo
->legacy_flag
;
2340 int parse_mount_attrs(struct lxc_mount_options
*opts
, const char *mntopts
)
2342 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2343 char *end
= NULL
, *mntopt_cur
= NULL
;
2348 return ret_errno(EINVAL
);
2353 mntopts_dup
= strdup(mntopts
);
2355 return ret_errno(ENOMEM
);
2357 size
= strlen(mntopts_dup
) + 1;
2358 mntopts_new
= zalloc(size
);
2360 return ret_errno(ENOMEM
);
2362 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",") {
2363 /* This is a filesystem specific option. */
2364 if (strchr(mntopt_cur
, '=')) {
2366 end
= stpcpy(mntopts_new
, mntopt_cur
);
2368 end
= stpcpy(end
, ",");
2369 end
= stpcpy(end
, mntopt_cur
);
2375 /* This is a generic vfs option. */
2376 ret
= parse_vfs_attr(opts
, mntopt_cur
, size
);
2378 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur
);
2382 opts
->data
= move_ptr(mntopts_new
);
2387 static void null_endofword(char *word
)
2389 while (*word
&& *word
!= ' ' && *word
!= '\t')
2394 /* skip @nfields spaces in @src */
2395 static char *get_field(char *src
, int nfields
)
2400 for (i
= 0; i
< nfields
; i
++) {
2401 while (*p
&& *p
!= ' ' && *p
!= '\t')
2413 static int mount_entry(const char *fsname
, const char *target
,
2414 const char *fstype
, unsigned long mountflags
,
2415 unsigned long pflags
, const char *data
, bool optional
,
2416 bool dev
, bool relative
, const char *rootfs
)
2419 char srcbuf
[PATH_MAX
];
2420 const char *srcpath
= fsname
;
2426 ret
= strnprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2428 return log_error_errno(-1, errno
, "source path is too long");
2432 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2436 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2437 srcpath
? srcpath
: "(null)", target
);
2439 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2440 srcpath
? srcpath
: "(null)", target
);
2443 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2445 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2446 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2449 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2450 unsigned long required_flags
= 0;
2452 if (sb
.f_flag
& MS_NOSUID
)
2453 required_flags
|= MS_NOSUID
;
2455 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2456 required_flags
|= MS_NODEV
;
2458 if (sb
.f_flag
& MS_RDONLY
)
2459 required_flags
|= MS_RDONLY
;
2461 if (sb
.f_flag
& MS_NOEXEC
)
2462 required_flags
|= MS_NOEXEC
;
2464 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2465 srcpath
, sb
.f_flag
, required_flags
);
2467 /* If this was a bind mount request, and required_flags
2468 * does not have any flags which are not already in
2469 * mountflags, then skip the remount.
2471 if (!(mountflags
& MS_REMOUNT
) &&
2472 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
2473 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
2477 mountflags
|= required_flags
;
2481 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2484 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2485 srcpath
? srcpath
: "(null)",
2488 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2489 srcpath
? srcpath
: "(null)",
2498 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2501 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2503 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2505 DEBUG("Changed mount propagation for \"%s\"", target
);
2508 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2509 srcpath
? srcpath
: "(null)", target
, fstype
);
2514 const char *lxc_mount_options_info
[LXC_MOUNT_MAX
] = {
2522 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2523 int parse_lxc_mount_attrs(struct lxc_mount_options
*opts
, char *mnt_opts
)
2525 for (size_t i
= LXC_MOUNT_CREATE_DIR
; i
< LXC_MOUNT_MAX
; i
++) {
2526 __do_close
int fd_userns
= -EBADF
;
2527 const char *opt_name
= lxc_mount_options_info
[i
];
2529 char *idmap_path
, *opt
, *opt_next
;
2531 opt
= strstr(mnt_opts
, opt_name
);
2536 case LXC_MOUNT_CREATE_DIR
:
2537 opts
->create_dir
= 1;
2539 case LXC_MOUNT_CREATE_FILE
:
2540 opts
->create_file
= 1;
2542 case LXC_MOUNT_OPTIONAL
:
2545 case LXC_MOUNT_RELATIVE
:
2548 case LXC_MOUNT_IDMAP
:
2550 opt_next
+= STRLITERALLEN("idmap=");
2551 idmap_path
= strchrnul(opt_next
, ',');
2552 len
= idmap_path
- opt_next
+ 1;
2554 if (len
>= sizeof(opts
->userns_path
))
2555 return syserror_set(-EIO
, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2557 strlcpy(opts
->userns_path
, opt_next
, len
);
2559 if (is_empty_string(opts
->userns_path
))
2560 return syserror_set(-EINVAL
, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2562 if (!strequal(opts
->userns_path
, "container")) {
2563 fd_userns
= open(opts
->userns_path
, O_RDONLY
| O_NOCTTY
| O_CLOEXEC
);
2565 return syserror("Failed to open user namespace %s", opts
->userns_path
);
2568 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns
, opts
->userns_path
);
2571 return syserror_set(-EINVAL
, "Unknown LXC specific mount option");
2574 opt_next
= strchr(opt
, ',');
2576 *opt
= '\0'; /* no more mntopts, so just chop it here */
2578 memmove(opt
, opt_next
+ 1, strlen(opt_next
+ 1) + 1);
2584 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2586 const struct lxc_rootfs
*rootfs
,
2587 const char *lxc_name
, const char *lxc_path
)
2589 __do_free
char *p1
= NULL
;
2593 if (strnequal(mntent
->mnt_type
, "overlay", 7)) {
2594 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2599 if (hasmntopt(mntent
, "create=dir")) {
2600 ret
= mkdir_p(path
, 0755);
2601 if (ret
< 0 && errno
!= EEXIST
)
2602 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2605 if (!hasmntopt(mntent
, "create=file"))
2608 ret
= access(path
, F_OK
);
2618 ret
= mkdir_p(p2
, 0755);
2619 if (ret
< 0 && errno
!= EEXIST
)
2620 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2622 ret
= mknod(path
, S_IFREG
| 0000, 0);
2623 if (ret
< 0 && errno
!= EEXIST
)
2629 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2630 * without a rootfs. */
2631 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2633 const struct lxc_rootfs
*rootfs
,
2634 const char *lxc_name
,
2635 const char *lxc_path
)
2637 __do_free
char *mntdata
= NULL
;
2638 char *rootfs_path
= NULL
;
2640 bool dev
, optional
, relative
;
2641 struct lxc_mount_options opts
= {};
2643 optional
= hasmntopt(mntent
, "optional") != NULL
;
2644 dev
= hasmntopt(mntent
, "dev") != NULL
;
2645 relative
= hasmntopt(mntent
, "relative") != NULL
;
2647 if (rootfs
&& rootfs
->path
)
2648 rootfs_path
= rootfs
->mount
;
2650 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2659 ret
= parse_lxc_mount_attrs(&opts
, mntent
->mnt_opts
);
2664 * Idmapped mount entries will be setup by the parent for us. Note that
2665 * we rely on mount_entry_create_dir_file() above to have already
2666 * created the target path for us. So the parent can just open the
2667 * target and send us the target fd.
2670 if (!is_empty_string(opts
.userns_path
))
2671 return systrace_ret(0, "Skipping idmapped mount entry");
2673 ret
= parse_mount_attrs(&opts
, mntent
->mnt_opts
);
2677 ret
= mount_entry(mntent
->mnt_fsname
,
2691 static inline int mount_entry_on_systemfs(struct lxc_rootfs
*rootfs
,
2692 struct mntent
*mntent
)
2696 /* For containers created without a rootfs all mounts are treated as
2697 * absolute paths starting at / on the host.
2699 if (mntent
->mnt_dir
[0] != '/')
2700 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/%s", mntent
->mnt_dir
);
2702 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s", mntent
->mnt_dir
);
2706 return mount_entry_on_generic(mntent
, rootfs
->buf
, NULL
, NULL
, NULL
);
2709 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2710 struct lxc_rootfs
*rootfs
,
2711 const char *lxc_name
,
2712 const char *lxc_path
)
2716 const char *lxcpath
;
2719 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2723 /* If rootfs->path is a blockdev path, allow container fstab to use
2724 * <lxcpath>/<name>/rootfs" as the target prefix.
2726 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s/rootfs", lxcpath
, lxc_name
);
2730 aux
= strstr(mntent
->mnt_dir
, rootfs
->buf
);
2732 offset
= strlen(rootfs
->buf
);
2737 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2739 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2740 offset
= strlen(rootfs
->path
);
2743 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, aux
+ offset
);
2747 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2750 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2751 struct lxc_rootfs
*rootfs
,
2752 const char *lxc_name
,
2753 const char *lxc_path
)
2757 /* relative to root mount point */
2758 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2762 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2765 static int mount_file_entries(struct lxc_rootfs
*rootfs
, FILE *file
,
2766 const char *lxc_name
, const char *lxc_path
)
2769 struct mntent mntent
;
2771 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2775 ret
= mount_entry_on_systemfs(rootfs
, &mntent
);
2776 else if (mntent
.mnt_dir
[0] != '/')
2777 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2778 lxc_name
, lxc_path
);
2780 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2781 lxc_name
, lxc_path
);
2786 if (!feof(file
) || ferror(file
))
2787 return log_error(-1, "Failed to parse mount entries");
2792 static inline void __auto_endmntent__(FILE **f
)
2798 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2800 static int setup_mount_fstab(struct lxc_rootfs
*rootfs
, const char *fstab
,
2801 const char *lxc_name
, const char *lxc_path
)
2803 __do_endmntent
FILE *f
= NULL
;
2809 f
= setmntent(fstab
, "re");
2811 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2813 ret
= mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2815 ERROR("Failed to set up mount entries");
2821 * In order for nested containers to be able to mount /proc and /sys they need
2822 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2824 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2825 * apparmor rule to deny access to them. This is mostly for convenience: The
2826 * container's root user can mount them anyway and thus has access to the two
2827 * file systems. But a non-root user in the container should not be allowed to
2828 * access them as a side effect without explicitly allowing it.
2830 static const char nesting_helpers
[] =
2831 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2832 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2834 FILE *make_anonymous_mount_file(const struct list_head
*mount_entries
,
2835 bool include_nesting_helpers
)
2837 __do_close
int fd
= -EBADF
;
2840 struct string_entry
*entry
;
2842 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2844 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2846 if (errno
!= ENOSYS
)
2849 fd
= lxc_make_tmpfile(template, true);
2851 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2853 TRACE("Created temporary mount file");
2856 list_for_each_entry(entry
, mount_entries
, head
) {
2859 len
= strlen(entry
->val
);
2861 ret
= lxc_write_nointr(fd
, entry
->val
, len
);
2862 if (ret
< 0 || (size_t)ret
!= len
)
2865 ret
= lxc_write_nointr(fd
, "\n", 1);
2870 if (include_nesting_helpers
) {
2871 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2872 STRARRAYLEN(nesting_helpers
));
2873 if (ret
!= STRARRAYLEN(nesting_helpers
))
2877 ret
= lseek(fd
, 0, SEEK_SET
);
2881 f
= fdopen(fd
, "re+");
2883 move_fd(fd
); /* Transfer ownership of fd. */
2887 static int setup_mount_entries(const struct lxc_conf
*conf
,
2888 struct lxc_rootfs
*rootfs
,
2889 const char *lxc_name
, const char *lxc_path
)
2891 __do_fclose
FILE *f
= NULL
;
2893 f
= make_anonymous_mount_file(&conf
->mount_entries
, conf
->lsm_aa_allow_nesting
);
2897 return mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2900 static int __lxc_idmapped_mounts_child(struct lxc_handler
*handler
, FILE *f
)
2902 struct lxc_conf
*conf
= handler
->conf
;
2903 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
2907 struct mntent mntent
;
2909 while (getmntent_r(f
, &mntent
, buf
, sizeof(buf
))) {
2910 __do_close
int fd_from
= -EBADF
, fd_to
= -EBADF
,
2912 __do_free
char *__data
= NULL
;
2913 int cur_mnt_seq
= -1;
2914 struct lxc_mount_options opts
= {};
2916 const char *source_relative
, *target_relative
;
2917 struct mount_attr attr
= {};
2919 ret
= parse_lxc_mount_attrs(&opts
, mntent
.mnt_opts
);
2921 return syserror("Failed to parse LXC specific mount options");
2924 ret
= parse_mount_attrs(&opts
, mntent
.mnt_opts
);
2926 return syserror("Failed to parse mount options");
2928 /* No idmapped mount entry so skip it. */
2929 if (is_empty_string(opts
.userns_path
))
2932 if (!can_use_bind_mounts())
2933 return syserror_set(-EINVAL
, "Kernel does not support idmapped mounts");
2936 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2938 /* We don't support new filesystem mounts yet. */
2939 if (!is_empty_string(mntent
.mnt_type
) &&
2940 !strequal(mntent
.mnt_type
, "none"))
2941 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2943 /* Someone specified additional mount options for a bind-mount. */
2944 if (!is_empty_string(opts
.data
))
2945 return syserror_set(-EINVAL
, "Bind mounts don't support non-generic mount options");
2948 * The source path is supposed to be taken relative to the
2949 * container's rootfs mount or - if the container does not have
2950 * a separate rootfs - to the host's /.
2952 source_relative
= deabs(mntent
.mnt_fsname
);
2953 if (opts
.relative
|| !rootfs
->path
)
2954 dfd_from
= rootfs
->dfd_mnt
;
2956 dfd_from
= rootfs
->dfd_host
;
2957 fd_from
= open_tree(dfd_from
, source_relative
,
2958 OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
|
2959 (opts
.bind_recursively
? AT_RECURSIVE
: 0));
2961 return syserror("Failed to create detached %smount of %d/%s",
2962 opts
.bind_recursively
? "recursive " : "",
2963 dfd_from
, source_relative
);
2965 if (strequal(opts
.userns_path
, "container"))
2966 fd_userns
= openat(dfd_from
, "proc/self/ns/user", O_RDONLY
| O_CLOEXEC
);
2968 fd_userns
= open_at(-EBADF
, opts
.userns_path
,
2969 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
2970 if (fd_userns
< 0) {
2971 if (opts
.optional
) {
2972 TRACE("Skipping optional idmapped mount");
2976 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
2977 opts
.userns_path
, opts
.bind_recursively
? "recursive " : "",
2978 dfd_from
, source_relative
);
2981 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
2983 &opts
, sizeof(opts
));
2985 if (opts
.optional
) {
2986 TRACE("Skipping optional idmapped mount");
2990 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
2991 fd_from
, opts
.bind_recursively
? "recursive " : "",
2992 dfd_from
, source_relative
, fd_userns
,
2996 ret
= lxc_abstract_unix_rcv_credential(handler
->data_sock
[0],
2998 sizeof(cur_mnt_seq
));
3000 if (opts
.optional
) {
3001 TRACE("Skipping optional idmapped mount");
3005 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
3006 opts
.bind_recursively
? "recursive " : "",
3007 dfd_from
, source_relative
, fd_userns
);
3010 if (mnt_seq
!= cur_mnt_seq
)
3011 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
3012 mnt_seq
, cur_mnt_seq
);
3015 /* Set regular mount options. */
3017 attr
.propagation
= 0;
3018 ret
= mount_setattr(fd_from
,
3021 (opts
.bind_recursively
? AT_RECURSIVE
: 0),
3025 if (opts
.optional
) {
3026 TRACE("Skipping optional idmapped mount");
3030 return syserror("Failed to set %smount options on detached %d/%s",
3031 opts
.bind_recursively
? "recursive " : "",
3032 dfd_from
, source_relative
);
3035 /* Set propagation mount options. */
3036 if (opts
.attr
.propagation
) {
3037 attr
= (struct mount_attr
) {
3038 .propagation
= opts
.attr
.propagation
,
3041 ret
= mount_setattr(fd_from
,
3044 (opts
.propagate_recursively
? AT_RECURSIVE
: 0),
3048 if (opts
.optional
) {
3049 TRACE("Skipping optional idmapped mount");
3053 return syserror("Failed to set %spropagation mount options on detached %d/%s",
3054 opts
.bind_recursively
? "recursive " : "",
3055 dfd_from
, source_relative
);
3061 * In contrast to the legacy mount codepath we will simplify
3062 * our lifes and just always treat the target mountpoint to be
3063 * relative to the container's rootfs mountpoint or - if the
3064 * container does not have a separate rootfs - to the host's /.
3067 target_relative
= deabs(mntent
.mnt_dir
);
3069 dfd_from
= rootfs
->dfd_mnt
;
3071 dfd_from
= rootfs
->dfd_host
;
3072 fd_to
= open_at(dfd_from
, target_relative
, PROTECT_OPATH_FILE
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
3074 if (opts
.optional
) {
3075 TRACE("Skipping optional idmapped mount");
3079 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
3080 dfd_from
, target_relative
,
3081 opts
.bind_recursively
? "recursive " : "",
3082 fd_userns
, dfd_from
, source_relative
);
3085 ret
= move_detached_mount(fd_from
, fd_to
, "", 0, 0);
3087 if (opts
.optional
) {
3088 TRACE("Skipping optional idmapped mount");
3092 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3093 opts
.bind_recursively
? "recursive " : "",
3094 fd_userns
, dfd_from
, source_relative
, dfd_from
, target_relative
);
3097 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3098 opts
.bind_recursively
? "recursive " : "", fd_userns
, dfd_from
,
3099 source_relative
, dfd_from
, target_relative
);
3102 if (!feof(f
) || ferror(f
))
3103 return syserror_set(-EINVAL
, "Failed to parse mount entries");
3108 static int lxc_idmapped_mounts_child(struct lxc_handler
*handler
)
3110 __do_fclose
FILE *f_entries
= NULL
;
3112 struct lxc_conf
*conf
= handler
->conf
;
3113 const char *fstab
= conf
->fstab
;
3116 f_entries
= make_anonymous_mount_file(&conf
->mount_entries
,
3117 conf
->lsm_aa_allow_nesting
);
3119 SYSERROR("Failed to create anonymous mount file");
3123 ret
= __lxc_idmapped_mounts_child(handler
, f_entries
);
3125 SYSERROR("Failed to setup idmapped mount entries");
3129 TRACE("Finished setting up idmapped mounts");
3132 __do_endmntent
FILE *f_fstab
= NULL
;
3134 f_fstab
= setmntent(fstab
, "re");
3136 SYSERROR("Failed to open fstab format file \"%s\"", fstab
);
3140 ret
= __lxc_idmapped_mounts_child(handler
, f_fstab
);
3142 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3146 TRACE("Finished setting up idmapped mounts specified in fstab");
3152 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[0], NULL
, 0);
3154 return syserror("Failed to inform parent that we are done setting up mounts");
3159 int parse_cap(const char *cap_name
, __u32
*cap
)
3161 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
3166 if (strequal(cap_name
, "none"))
3169 for (size_t i
= 0; i
< end
; i
++) {
3170 if (!strequal(cap_name
, caps_opt
[i
].name
))
3173 *cap
= caps_opt
[i
].value
;
3178 * Try to see if it's numeric, so the user may specify
3179 * capabilities that the running kernel knows about but we
3182 ret
= lxc_safe_uint(cap_name
, &res
);
3186 ret
= lxc_caps_last_cap(&last_cap
);
3190 if ((__u32
)res
> last_cap
)
3197 bool has_cap(__u32 cap
, struct lxc_conf
*conf
)
3199 bool cap_in_list
= false;
3200 struct cap_entry
*cap_entry
;
3202 list_for_each_entry(cap_entry
, &conf
->caps
.list
, head
) {
3203 if (cap_entry
->cap
!= cap
)
3209 /* The capability is kept. */
3210 if (conf
->caps
.keep
)
3213 /* The capability is not dropped. */
3214 return !cap_in_list
;
3217 static int capabilities_deny(struct lxc_conf
*conf
)
3219 struct cap_entry
*cap
;
3221 list_for_each_entry(cap
, &conf
->caps
.list
, head
) {
3224 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(cap
->cap
), prctl_arg(0),
3225 prctl_arg(0), prctl_arg(0));
3227 return syserror("Failed to remove %s capability", cap
->cap_name
);
3229 DEBUG("Dropped %s (%d) capability", cap
->cap_name
, cap
->cap
);
3232 DEBUG("Capabilities have been setup");
3236 static int capabilities_allow(struct lxc_conf
*conf
)
3238 __do_free __u32
*keep_bits
= NULL
;
3240 struct cap_entry
*cap
;
3241 __u32 last_cap
, nr_u32
;
3243 ret
= lxc_caps_last_cap(&last_cap
);
3244 if (ret
|| last_cap
> 200)
3245 return ret_errno(EINVAL
);
3247 TRACE("Found %d capabilities", last_cap
);
3249 nr_u32
= BITS_TO_LONGS(last_cap
);
3250 keep_bits
= zalloc(nr_u32
* sizeof(__u32
));
3252 return ret_errno(ENOMEM
);
3254 list_for_each_entry(cap
, &conf
->caps
.list
, head
) {
3255 if (cap
->cap
> last_cap
)
3258 set_bit(cap
->cap
, keep_bits
);
3259 DEBUG("Keeping %s (%d) capability", cap
->cap_name
, cap
->cap
);
3262 for (__u32 cap_bit
= 0; cap_bit
<= last_cap
; cap_bit
++) {
3263 if (is_set(cap_bit
, keep_bits
))
3266 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(cap_bit
), prctl_arg(0),
3267 prctl_arg(0), prctl_arg(0));
3269 return syserror("Failed to remove capability %d", cap_bit
);
3271 TRACE("Dropped capability %d", cap_bit
);
3274 DEBUG("Capabilities have been setup");
3278 static int parse_resource(const char *res
)
3284 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
3285 if (strequal(res
, limit_opt
[i
].name
))
3286 return limit_opt
[i
].value
;
3288 /* Try to see if it's numeric, so the user may specify
3289 * resources that the running kernel knows about but
3292 ret
= lxc_safe_int(res
, &resid
);
3299 int setup_resource_limits(struct lxc_conf
*conf
, pid_t pid
)
3302 struct lxc_limit
*lim
;
3304 if (list_empty(&conf
->limits
))
3307 list_for_each_entry(lim
, &conf
->limits
, head
) {
3308 resid
= parse_resource(lim
->resource
);
3310 return log_error(-1, "Unknown resource %s", lim
->resource
);
3312 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
3313 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
3314 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
3316 TRACE("Setup \"%s\" limit", lim
->resource
);
3318 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
3322 TRACE("Setup resource limits");
3326 int setup_sysctl_parameters(struct lxc_conf
*conf
)
3328 __do_free
char *tmp
= NULL
;
3330 char filename
[PATH_MAX
] = {0};
3331 struct lxc_sysctl
*sysctl
, *nsysctl
;
3333 if (list_empty(&conf
->sysctls
))
3336 list_for_each_entry_safe(sysctl
, nsysctl
, &conf
->sysctls
, head
) {
3337 tmp
= lxc_string_replace(".", "/", sysctl
->key
);
3339 return log_error(-1, "Failed to replace key %s", sysctl
->key
);
3341 ret
= strnprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
3343 return log_error(-1, "Error setting up sysctl parameters path");
3345 ret
= lxc_write_to_file(filename
, sysctl
->value
,
3346 strlen(sysctl
->value
), false, 0666);
3348 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
3349 sysctl
->key
, sysctl
->value
);
3351 TRACE("Setting %s to %s", filename
, sysctl
->value
);
3354 TRACE("Setup /proc/sys settings");
3358 int setup_proc_filesystem(struct lxc_conf
*conf
, pid_t pid
)
3360 __do_free
char *tmp
= NULL
;
3362 char filename
[PATH_MAX
] = {0};
3363 struct lxc_proc
*proc
;
3365 if (list_empty(&conf
->procs
))
3368 list_for_each_entry(proc
, &conf
->procs
, head
) {
3369 tmp
= lxc_string_replace(".", "/", proc
->filename
);
3371 return log_error(-1, "Failed to replace key %s", proc
->filename
);
3373 ret
= strnprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
3375 return log_error(-1, "Error setting up proc filesystem path");
3377 ret
= lxc_write_to_file(filename
, proc
->value
,
3378 strlen(proc
->value
), false, 0666);
3380 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s",
3381 proc
->filename
, proc
->value
);
3383 TRACE("Setting %s to %s", filename
, proc
->value
);
3386 TRACE("Setup /proc/%d settings", pid
);
3390 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
3392 struct lxc_conf
*lxc_conf_init(void)
3395 struct lxc_conf
*new;
3397 new = zalloc(sizeof(*new));
3401 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
3402 new->personality
= LXC_ARCH_UNCHANGED
;
3404 new->console
.buffer_size
= 0;
3405 new->console
.log_path
= NULL
;
3406 new->console
.log_fd
= -1;
3407 new->console
.log_size
= 0;
3408 new->console
.path
= NULL
;
3409 new->console
.peer
= -1;
3410 new->console
.proxy
.busy
= -1;
3411 new->console
.proxy
.ptx
= -1;
3412 new->console
.proxy
.pty
= -1;
3413 new->console
.ptx
= -EBADF
;
3414 new->console
.pty
= -EBADF
;
3415 new->console
.pty_nr
= -1;
3416 new->console
.name
[0] = '\0';
3417 new->devpts_fd
= -EBADF
;
3418 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
3419 new->maincmd_fd
= -1;
3420 new->monitor_signal_pdeath
= SIGKILL
;
3422 new->rootfs
.mount
= strdup(default_rootfs_mount
);
3423 if (!new->rootfs
.mount
) {
3427 new->rootfs
.managed
= true;
3428 new->rootfs
.dfd_mnt
= -EBADF
;
3429 new->rootfs
.dfd_dev
= -EBADF
;
3430 new->rootfs
.dfd_host
= -EBADF
;
3431 new->rootfs
.fd_path_pin
= -EBADF
;
3432 new->rootfs
.dfd_idmapped
= -EBADF
;
3434 INIT_LIST_HEAD(&new->cgroup
);
3435 INIT_LIST_HEAD(&new->cgroup2
);
3436 /* Block ("allowlist") all devices by default. */
3437 new->bpf_devices
.list_type
= LXC_BPF_DEVICE_CGROUP_ALLOWLIST
;
3438 INIT_LIST_HEAD(&(new->bpf_devices
).devices
);
3439 INIT_LIST_HEAD(&new->mount_entries
);
3440 INIT_LIST_HEAD(&new->caps
.list
);
3441 INIT_LIST_HEAD(&new->id_map
);
3442 new->root_nsuid_map
= NULL
;
3443 new->root_nsgid_map
= NULL
;
3444 INIT_LIST_HEAD(&new->environment
);
3445 INIT_LIST_HEAD(&new->limits
);
3446 INIT_LIST_HEAD(&new->sysctls
);
3447 INIT_LIST_HEAD(&new->procs
);
3448 new->hooks_version
= 0;
3449 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
3450 INIT_LIST_HEAD(&new->hooks
[i
]);
3451 INIT_LIST_HEAD(&new->groups
);
3452 INIT_LIST_HEAD(&new->state_clients
);
3453 new->lsm_aa_profile
= NULL
;
3454 INIT_LIST_HEAD(&new->lsm_aa_raw
);
3455 new->lsm_se_context
= NULL
;
3456 new->lsm_se_keyring_context
= NULL
;
3457 new->keyring_disable_session
= false;
3458 new->transient_procfs_mnt
= false;
3459 new->shmount
.path_host
= NULL
;
3460 new->shmount
.path_cont
= NULL
;
3461 new->sched_core
= false;
3462 new->sched_core_cookie
= INVALID_SCHED_CORE_COOKIE
;
3464 /* if running in a new user namespace, init and COMMAND
3465 * default to running as UID/GID 0 when using lxc-execute */
3468 memset(&new->init_groups
, 0, sizeof(lxc_groups_t
));
3469 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
3470 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
3471 memset(&new->timens
, 0, sizeof(struct timens_offsets
));
3472 seccomp_conf_init(new);
3474 INIT_LIST_HEAD(&new->netdevs
);
3479 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
3482 __do_close
int fd
= -EBADF
;
3484 char path
[PATH_MAX
];
3486 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
3487 __do_close
int setgroups_fd
= -EBADF
;
3489 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/setgroups", pid
);
3493 setgroups_fd
= open(path
, O_WRONLY
);
3494 if (setgroups_fd
< 0 && errno
!= ENOENT
)
3495 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3497 if (setgroups_fd
>= 0) {
3498 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
3499 STRLITERALLEN("deny\n"));
3500 if (ret
!= STRLITERALLEN("deny\n"))
3501 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
3502 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
3506 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/%cid_map", pid
,
3507 idtype
== ID_TYPE_UID
? 'u' : 'g');
3511 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
3513 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3515 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
3516 if (ret
< 0 || (size_t)ret
!= buf_size
)
3517 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
3518 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
3523 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3525 * @return 1 if functional binary was found
3526 * @return 0 if binary exists but is lacking privilege
3527 * @return -ENOENT if binary does not exist
3528 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
3530 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
3532 __do_free
char *path
= NULL
;
3536 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
3537 return ret_errno(EINVAL
);
3539 path
= on_path(binary
, NULL
);
3541 return ret_errno(ENOENT
);
3543 ret
= stat(path
, &st
);
3547 /* Check if the binary is setuid. */
3548 if (st
.st_mode
& S_ISUID
)
3549 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
3551 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
3552 /* Check if it has the CAP_SETUID capability. */
3553 if ((cap
& CAP_SETUID
) &&
3554 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
3555 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
3556 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3558 /* Check if it has the CAP_SETGID capability. */
3559 if ((cap
& CAP_SETGID
) &&
3560 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
3561 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
3562 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3567 * If we cannot check for file capabilities we need to give the benefit
3568 * of the doubt. Otherwise we might fail even though all the necessary
3569 * file capabilities are set.
3571 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3576 static int lxc_map_ids_exec_wrapper(void *args
)
3578 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
3582 static struct id_map
*find_mapped_hostid_entry(const struct list_head
*idmap
,
3583 unsigned id
, enum idtype idtype
);
3585 int lxc_map_ids(struct list_head
*idmap
, pid_t pid
)
3592 char cmd_output
[PATH_MAX
];
3595 int ret
= 0, gidmap
= 0, uidmap
= 0;
3596 char mapbuf
[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3597 INTTYPE_TO_STRLEN(pid_t
) + STRLITERALLEN(" ") +
3598 LXC_IDMAPLEN
] = {0};
3599 bool had_entry
= false, maps_host_root
= false, use_shadow
= false;
3601 hostuid
= geteuid();
3602 hostgid
= getegid();
3605 * Check whether caller wants to map host root.
3606 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3607 * host root into the child userns as you would be able to write fscaps
3608 * that would be valid in the ancestor userns. Mapping host root should
3609 * rarely be the case but LXC is being clever in a bunch of cases.
3611 if (find_mapped_hostid_entry(idmap
, 0, ID_TYPE_UID
))
3612 maps_host_root
= true;
3614 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3615 * ranges, then insist that root also reserve ranges in subuid. This
3616 * will protected it by preventing another user from being handed the
3619 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
3620 if (uidmap
== -ENOENT
)
3621 WARN("newuidmap binary is missing");
3623 WARN("newuidmap is lacking necessary privileges");
3625 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
3626 if (gidmap
== -ENOENT
)
3627 WARN("newgidmap binary is missing");
3629 WARN("newgidmap is lacking necessary privileges");
3631 if (maps_host_root
) {
3632 INFO("Caller maps host root. Writing mapping directly");
3633 } else if (uidmap
> 0 && gidmap
> 0) {
3634 DEBUG("Functional newuidmap and newgidmap binary found");
3637 /* In case unprivileged users run application containers via
3638 * execute() or a start*() there are valid cases where they may
3639 * only want to map their own {g,u}id. Let's not block them from
3640 * doing so by requiring geteuid() == 0.
3642 DEBUG("No newuidmap and newgidmap binary found. Trying to "
3643 "write directly with euid %d", hostuid
);
3646 /* Check if we really need to use newuidmap and newgidmap.
3647 * If the user is only remapping their own {g,u}id, we don't need it.
3649 if (use_shadow
&& list_len(map
, idmap
, head
) == 2) {
3651 list_for_each_entry(map
, idmap
, head
) {
3652 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3653 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3655 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3656 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3663 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3664 type
++, u_or_g
= 'g') {
3668 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3670 list_for_each_entry(map
, idmap
, head
) {
3671 if (map
->idtype
!= type
)
3676 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3677 fill
= strnprintf(pos
, left
, "%s%lu %lu %lu%s",
3678 use_shadow
? " " : "", map
->nsid
,
3679 map
->hostid
, map
->range
,
3680 use_shadow
? "" : "\n");
3682 * The kernel only takes <= 4k for writes to
3683 * /proc/<pid>/{g,u}id_map
3686 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
3693 /* Try to catch the output of new{g,u}idmap to make debugging
3697 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3698 lxc_map_ids_exec_wrapper
,
3701 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
3702 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3704 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3706 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
3707 TRACE("Wrote mapping \"%s\"", mapbuf
);
3710 memset(mapbuf
, 0, sizeof(mapbuf
));
3717 * Return the host uid/gid to which the container root is mapped in val.
3718 * Return true if id was found, false otherwise.
3720 static id_t
get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
)
3725 if (idtype
== ID_TYPE_UID
)
3726 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3728 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3730 list_for_each_entry (map
, &conf
->id_map
, head
) {
3731 if (map
->idtype
!= idtype
)
3733 if (map
->nsid
!= nsid
)
3738 if (idtype
== ID_TYPE_UID
)
3739 return LXC_INVALID_UID
;
3741 return LXC_INVALID_GID
;
3744 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
3748 list_for_each_entry(map
, &conf
->id_map
, head
) {
3749 if (map
->idtype
!= idtype
)
3752 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3753 return (id
- map
->hostid
) + map
->nsid
;
3759 int find_unmapped_nsid(const struct lxc_conf
*conf
, enum idtype idtype
)
3762 unsigned int freeid
= 0;
3765 list_for_each_entry(map
, &conf
->id_map
, head
) {
3766 if (map
->idtype
!= idtype
)
3769 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3770 freeid
= map
->nsid
+ map
->range
;
3779 * Mount a proc under @rootfs if proc self points to a pid other than
3780 * my own. This is needed to have a known-good proc mount for setting
3781 * up LSMs both at container startup and attach.
3783 * NOTE: not to be called from inside the container namespace!
3785 static int lxc_transient_proc(struct lxc_rootfs
*rootfs
)
3787 __do_close
int fd_proc
= -EBADF
;
3788 int link_to_pid
, link_len
, pid_self
, ret
;
3789 char link
[INTTYPE_TO_STRLEN(pid_t
) + 1];
3791 link_len
= readlinkat(rootfs
->dfd_mnt
, "proc/self", link
, sizeof(link
));
3793 ret
= mkdirat(rootfs
->dfd_mnt
, "proc", 0000);
3794 if (ret
< 0 && errno
!= EEXIST
)
3795 return log_error_errno(-errno
, errno
, "Failed to create %d(proc)", rootfs
->dfd_mnt
);
3798 } else if ((size_t)link_len
>= sizeof(link
)) {
3799 return log_error_errno(-EIO
, EIO
, "Truncated link target");
3801 link
[link_len
] = '\0';
3803 pid_self
= lxc_raw_getpid();
3804 INFO("Caller's PID is %d; /proc/self points to %s", pid_self
, link
);
3806 ret
= lxc_safe_int(link
, &link_to_pid
);
3808 return log_error_errno(-ret
, ret
, "Failed to parse %s", link
);
3810 /* Correct procfs is already mounted. */
3811 if (link_to_pid
== pid_self
)
3812 return log_trace(0, "Correct procfs instance mounted");
3814 fd_proc
= open_at(rootfs
->dfd_mnt
, "proc", PROTECT_OPATH_DIRECTORY
,
3815 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
3817 return log_error_errno(-errno
, errno
, "Failed to open transient procfs mountpoint");
3819 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/proc/self/fd/%d", fd_proc
);
3821 return ret_errno(EIO
);
3823 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
3825 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs
->buf
);
3828 /* rootfs is NULL */
3829 if (!rootfs
->path
) {
3830 ret
= mount("proc", rootfs
->buf
, "proc", 0, NULL
);
3832 ret
= safe_mount_beneath_at(rootfs
->dfd_mnt
, "none", "proc", "proc", 0, NULL
);
3834 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc", rootfs
->path
? rootfs
->mount
: "");
3836 return ret_errno(EIO
);
3838 ret
= safe_mount("proc", rootfs
->buf
, "proc", 0, NULL
, rootfs
->mount
);
3842 return log_error_errno(-1, errno
, "Failed to mount temporary procfs");
3844 INFO("Created transient procfs mount");
3848 /* NOTE: Must not be called from inside the container namespace! */
3849 static int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3853 mounted
= lxc_transient_proc(&conf
->rootfs
);
3854 if (mounted
== -1) {
3855 /* continue only if there is no rootfs */
3856 if (conf
->rootfs
.path
)
3857 return log_error_errno(-EPERM
, EPERM
, "Failed to create transient procfs mount");
3858 } else if (mounted
== 1) {
3859 conf
->transient_procfs_mnt
= true;
3865 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3867 if (lxc_conf
->transient_procfs_mnt
) {
3868 (void)umount2("/proc", MNT_DETACH
);
3869 lxc_conf
->transient_procfs_mnt
= false;
3873 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
3874 static void turn_into_dependent_mounts(const struct lxc_rootfs
*rootfs
)
3876 __do_free
char *line
= NULL
;
3877 __do_fclose
FILE *f
= NULL
;
3878 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3883 mntinfo_fd
= open_at(rootfs
->dfd_host
, "proc/self/mountinfo", PROTECT_OPEN
,
3884 (PROTECT_LOOKUP_BENEATH_XDEV
& ~RESOLVE_NO_SYMLINKS
), 0);
3885 if (mntinfo_fd
< 0) {
3886 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs
->dfd_host
);
3890 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3892 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3894 if (errno
!= ENOSYS
) {
3895 SYSERROR("Failed to create temporary in-memory file");
3899 memfd
= lxc_make_tmpfile(template, true);
3901 WARN("Failed to create temporary file");
3906 copied
= fd_to_fd(mntinfo_fd
, memfd
);
3908 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3912 ret
= lseek(memfd
, 0, SEEK_SET
);
3914 SYSERROR("Failed to reset file descriptor offset");
3918 f
= fdopen(memfd
, "re");
3920 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3925 * After a successful fdopen() memfd will be closed when calling
3926 * fclose(f). Calling close(memfd) afterwards is undefined.
3930 while (getline(&line
, &len
, f
) != -1) {
3931 char *opts
, *target
;
3933 target
= get_field(line
, 4);
3937 opts
= get_field(target
, 2);
3941 null_endofword(opts
);
3942 if (!strstr(opts
, "shared"))
3945 null_endofword(target
);
3946 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3948 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3952 TRACE("Turned all mount table entries into dependent mount");
3955 /* This does the work of remounting / if it is shared, calling the container
3956 * pre-mount hooks, and mounting the rootfs.
3958 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3959 const char *lxcpath
)
3963 conf
->rootfs
.dfd_host
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
3964 if (conf
->rootfs
.dfd_host
< 0)
3965 return log_error_errno(-errno
, errno
, "Failed to open \"/\"");
3967 turn_into_dependent_mounts(&conf
->rootfs
);
3969 if (conf
->rootfs_setup
) {
3970 const char *path
= conf
->rootfs
.mount
;
3973 * The rootfs was set up in another namespace. bind-mount it to
3974 * give us a mount in our own ns so we can pivot_root to it
3976 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3978 return log_error(-1, "Failed to bind mount container / onto itself");
3980 conf
->rootfs
.dfd_mnt
= openat(-EBADF
, path
, O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOCTTY
);
3981 if (conf
->rootfs
.dfd_mnt
< 0)
3982 return log_error_errno(-errno
, errno
, "Failed to open file descriptor for container rootfs");
3984 return log_trace(0, "Bind mounted container / onto itself");
3987 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3989 return log_error(-1, "Failed to run pre-mount hooks");
3991 ret
= lxc_mount_rootfs(&conf
->rootfs
);
3993 return log_error(-1, "Failed to setup rootfs for");
3995 conf
->rootfs_setup
= true;
3999 static bool verify_start_hooks(struct lxc_conf
*conf
)
4001 char path
[PATH_MAX
];
4002 struct string_entry
*hook
;
4004 list_for_each_entry(hook
, &conf
->hooks
[LXCHOOK_START
], head
) {
4006 char *hookname
= hook
->val
;
4008 ret
= strnprintf(path
, sizeof(path
), "%s%s",
4009 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
4014 ret
= access(path
, X_OK
);
4016 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
4024 static int lxc_setup_boot_id(void)
4027 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
4028 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
4031 if (access(boot_id_path
, F_OK
))
4034 memset(&n
, 0, sizeof(n
));
4035 if (lxc_id128_randomize(&n
)) {
4036 SYSERROR("Failed to generate random data for uuid");
4040 ret
= lxc_id128_write(mock_boot_id_path
, n
);
4042 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
4046 ret
= chmod(mock_boot_id_path
, 0444);
4048 SYSERROR("Failed to chown %s", mock_boot_id_path
);
4049 (void)unlink(mock_boot_id_path
);
4053 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
4055 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
4057 (void)unlink(mock_boot_id_path
);
4061 ret
= mount(NULL
, boot_id_path
, NULL
,
4062 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
4066 SYSERROR("Failed to remount %s read-only", boot_id_path
);
4067 (void)unlink(mock_boot_id_path
);
4074 static int lxc_setup_keyring(struct lsm_ops
*lsm_ops
, const struct lxc_conf
*conf
)
4076 key_serial_t keyring
;
4079 if (conf
->lsm_se_keyring_context
)
4080 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_keyring_context
);
4081 else if (conf
->lsm_se_context
)
4082 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_context
);
4084 return syserror("Failed to set keyring context");
4087 * Try to allocate a new session keyring for the container to prevent
4088 * information leaks.
4090 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
4091 prctl_arg(0), prctl_arg(0), prctl_arg(0));
4095 DEBUG("The keyctl() syscall is not supported or blocked");
4100 DEBUG("Failed to access kernel keyring. Continuing...");
4103 SYSWARN("Failed to create kernel keyring");
4111 static int lxc_rootfs_prepare_child(struct lxc_handler
*handler
)
4113 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
4114 int dfd_idmapped
= -EBADF
;
4117 if (list_empty(&handler
->conf
->id_map
))
4120 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
4123 if (handler
->conf
->rootfs_setup
)
4126 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1], &dfd_idmapped
, NULL
, 0);
4128 return syserror("Failed to receive idmapped mount fd");
4130 rootfs
->dfd_idmapped
= dfd_idmapped
;
4131 TRACE("Received detached idmapped mount %d", rootfs
->dfd_idmapped
);
4135 int lxc_idmapped_mounts_parent(struct lxc_handler
*handler
)
4140 __do_close
int fd_from
= -EBADF
, fd_userns
= -EBADF
;
4141 struct mount_attr attr
= {};
4142 struct lxc_mount_options opts
= {};
4145 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4146 &fd_from
, &fd_userns
,
4147 &opts
, sizeof(opts
));
4149 return syserror("Failed to receive idmapped mount file descriptors from child");
4151 if (fd_from
< 0 || fd_userns
< 0)
4152 return log_trace(0, "Finished receiving idmapped mount file descriptors (%d | %d) from child", fd_from
, fd_userns
);
4154 attr
.attr_set
= MOUNT_ATTR_IDMAP
;
4155 attr
.userns_fd
= fd_userns
;
4156 ret
= mount_setattr(fd_from
, "",
4158 (opts
.bind_recursively
? AT_RECURSIVE
: 0),
4159 &attr
, sizeof(attr
));
4161 return syserror("Failed to idmap detached %smount %d to %d",
4162 opts
.bind_recursively
? "recursive " : "",
4163 fd_from
, fd_userns
);
4165 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[1],
4169 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
4170 opts
.bind_recursively
? "recursive " : "",
4171 fd_from
, fd_userns
);
4173 TRACE("Parent idmapped detached %smount %d to user namespace %d",
4174 opts
.bind_recursively
? "recursive " : "", fd_from
, fd_userns
);
4179 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
4181 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*info_new
= &(struct lxc_tty_info
){};
4182 int sock
= handler
->data_sock
[1];
4183 struct lxc_conf
*conf
= handler
->conf
;
4184 struct lxc_tty_info
*tty_info
= &conf
->ttys
;
4185 size_t ttys_max
= tty_info
->max
;
4186 struct lxc_terminal_info
*terminal_info
;
4192 info_new
->tty
= malloc(sizeof(*(info_new
->tty
)) * ttys_max
);
4194 return ret_errno(ENOMEM
);
4196 for (size_t i
= 0; i
< ttys_max
; i
++) {
4197 terminal_info
= &info_new
->tty
[i
];
4198 terminal_info
->busy
= -1;
4199 terminal_info
->pty_nr
= -1;
4200 terminal_info
->ptx
= -EBADF
;
4201 terminal_info
->pty
= -EBADF
;
4204 for (size_t i
= 0; i
< ttys_max
; i
++) {
4205 int ptx
= -EBADF
, pty
= -EBADF
;
4207 ret
= lxc_abstract_unix_recv_two_fds(sock
, &ptx
, &pty
);
4209 return syserror("Failed to receive %zu ttys from child", ttys_max
);
4211 terminal_info
= &info_new
->tty
[i
];
4212 terminal_info
->ptx
= ptx
;
4213 terminal_info
->pty
= pty
;
4214 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4215 terminal_info
->ptx
, terminal_info
->pty
);
4218 tty_info
->tty
= move_ptr(info_new
->tty
);
4219 TRACE("Received %zu ttys from child", ttys_max
);
4223 static int lxc_send_console_to_parent(struct lxc_handler
*handler
)
4225 struct lxc_terminal
*console
= &handler
->conf
->console
;
4228 if (!wants_console(console
))
4231 /* We've already allocated a console from the host's devpts instance. */
4232 if (console
->pty
< 0)
4235 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
4236 console
->ptx
, console
->pty
,
4238 sizeof(struct lxc_terminal
));
4240 return syserror("Fail to send console to parent");
4242 TRACE("Sent console to parent");
4246 static int lxc_recv_console_from_child(struct lxc_handler
*handler
)
4248 __do_close
int fd_ptx
= -EBADF
, fd_pty
= -EBADF
;
4249 struct lxc_terminal
*console
= &handler
->conf
->console
;
4252 if (!wants_console(console
))
4255 /* We've already allocated a console from the host's devpts instance. */
4256 if (console
->pty
>= 0)
4259 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4262 sizeof(struct lxc_terminal
));
4264 return syserror("Fail to receive console from child");
4266 console
->ptx
= move_fd(fd_ptx
);
4267 console
->pty
= move_fd(fd_pty
);
4269 TRACE("Received console from child");
4273 int lxc_sync_fds_parent(struct lxc_handler
*handler
)
4277 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[1]);
4279 return syserror_ret(ret
, "Failed to receive seccomp notify fd from child");
4281 ret
= lxc_recv_devpts_from_child(handler
);
4283 return syserror_ret(ret
, "Failed to receive devpts fd from child");
4285 /* Read tty fds allocated by child. */
4286 ret
= lxc_recv_ttys_from_child(handler
);
4288 return syserror_ret(ret
, "Failed to receive tty info from child process");
4290 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4291 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
4293 return syserror_ret(ret
, "Failed to receive names and ifindices for network devices from child");
4296 ret
= lxc_recv_console_from_child(handler
);
4298 return syserror_ret(ret
, "Failed to receive console from child");
4300 TRACE("Finished syncing file descriptors with child");
4304 int lxc_sync_fds_child(struct lxc_handler
*handler
)
4308 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[0]);
4310 return syserror_ret(ret
, "Failed to send seccomp notify fd to parent");
4312 ret
= lxc_send_devpts_to_parent(handler
);
4314 return syserror_ret(ret
, "Failed to send seccomp devpts fd to parent");
4316 ret
= lxc_send_ttys_to_parent(handler
);
4318 return syserror_ret(ret
, "Failed to send tty file descriptors to parent");
4320 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4321 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
4323 return syserror_ret(ret
, "Failed to send network device names and ifindices to parent");
4326 ret
= lxc_send_console_to_parent(handler
);
4328 return syserror_ret(ret
, "Failed to send console to parent");
4330 TRACE("Finished syncing file descriptors with parent");
4334 static int setup_capabilities(struct lxc_conf
*conf
)
4338 if (conf
->caps
.keep
)
4339 ret
= capabilities_allow(conf
);
4341 ret
= capabilities_deny(conf
);
4343 return syserror_ret(ret
, "Failed to %s capabilities", conf
->caps
.keep
? "allow" : "deny");
4348 static int make_shmount_dependent_mount(const struct lxc_conf
*conf
)
4350 if (!(conf
->auto_mounts
& LXC_AUTO_SHMOUNTS_MASK
))
4353 return mount(NULL
, conf
->shmount
.path_cont
, NULL
, MS_REC
| MS_SLAVE
, 0);
4356 int lxc_setup(struct lxc_handler
*handler
)
4359 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
4360 struct lxc_conf
*lxc_conf
= handler
->conf
;
4362 ret
= lxc_rootfs_prepare_child(handler
);
4364 return syserror("Failed to prepare rootfs");
4366 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
4368 return log_error(-1, "Failed to setup rootfs");
4370 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
4371 ret
= setup_utsname(lxc_conf
->utsname
);
4373 return log_error(-1, "Failed to setup the utsname %s", name
);
4376 if (!lxc_conf
->keyring_disable_session
) {
4377 ret
= lxc_setup_keyring(handler
->lsm_ops
, lxc_conf
);
4379 return log_error(-1, "Failed to setup container keyring");
4382 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4383 ret
= lxc_network_recv_from_parent(handler
);
4385 return log_error(-1, "Failed to receive veth names from parent");
4387 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
);
4389 return log_error(-1, "Failed to setup network");
4392 if (lxc_conf
->autodev
> 0) {
4393 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
4395 return log_error(-1, "Failed to mount \"/dev\"");
4398 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4399 * need to wait until other stuff has finished.
4401 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
);
4403 return log_error(-1, "Failed to setup first automatic mounts");
4405 ret
= setup_mount_fstab(&lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
4407 return log_error(-1, "Failed to setup mounts");
4409 if (!list_empty(&lxc_conf
->mount_entries
)) {
4410 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
, name
, lxcpath
);
4412 return log_error(-1, "Failed to setup mount entries");
4415 if (!lxc_sync_wake_parent(handler
, START_SYNC_IDMAPPED_MOUNTS
))
4418 ret
= lxc_idmapped_mounts_child(handler
);
4420 return syserror("Failed to attached detached idmapped mounts");
4422 lxc_conf
->rootfs
.dfd_dev
= open_at(lxc_conf
->rootfs
.dfd_mnt
, "dev",
4423 PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
4424 if (lxc_conf
->rootfs
.dfd_dev
< 0 && errno
!= ENOENT
)
4425 return log_error_errno(-errno
, errno
, "Failed to open \"/dev\"");
4427 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4428 * mounted. It is guaranteed to be mounted now either through
4429 * automatically or via fstab entries.
4431 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
);
4433 return log_error(-1, "Failed to setup remaining automatic mounts");
4435 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
4437 return log_error(-1, "Failed to run mount hooks");
4439 if (lxc_rootfs_overmounted(&lxc_conf
->rootfs
))
4440 return log_error(-1, "Rootfs overmounted");
4442 if (lxc_conf
->autodev
> 0) {
4443 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
4445 return log_error(-1, "Failed to run autodev hooks");
4447 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
4449 return log_error(-1, "Failed to populate \"/dev\"");
4452 /* Make sure any start hooks are in the container */
4453 if (!verify_start_hooks(lxc_conf
))
4454 return log_error(-1, "Failed to verify start hooks");
4456 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
4458 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
4460 ret
= lxc_setup_devpts_child(handler
);
4462 return log_error(-1, "Failed to prepare new devpts instance");
4464 ret
= lxc_finish_devpts_child(handler
);
4466 return log_error(-1, "Failed to finish devpts setup");
4468 ret
= lxc_setup_console(handler
, &lxc_conf
->rootfs
, &lxc_conf
->console
,
4469 lxc_conf
->ttys
.dir
);
4471 return log_error(-1, "Failed to setup console");
4473 ret
= lxc_create_ttys(handler
);
4475 return log_error(-1, "Failed to create ttys");
4477 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
4479 return log_error(-1, "Failed to setup \"/dev\" symlinks");
4481 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
4483 return log_error(-1, "Failed to pivot root into rootfs");
4485 ret
= make_shmount_dependent_mount(lxc_conf
);
4487 return log_error(-1, "Failed to turn mount tunnel \"%s\" into dependent mount",
4488 lxc_conf
->shmount
.path_cont
);
4490 /* Setting the boot-id is best-effort for now. */
4491 if (lxc_conf
->autodev
> 0)
4492 (void)lxc_setup_boot_id();
4494 ret
= setup_personality(lxc_conf
->personality
);
4496 return syserror("Failed to set personality");
4498 /* Set sysctl value to a path under /proc/sys as determined from the
4499 * key. For e.g. net.ipv4.ip_forward translated to
4500 * /proc/sys/net/ipv4/ip_forward.
4502 ret
= setup_sysctl_parameters(lxc_conf
);
4504 return log_error(-1, "Failed to setup sysctl parameters");
4506 ret
= setup_capabilities(lxc_conf
);
4508 return log_error(-1, "Failed to setup capabilities");
4510 put_lxc_rootfs(&handler
->conf
->rootfs
, true);
4511 NOTICE("The container \"%s\" is set up", name
);
4516 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
4520 struct string_entry
*entry
;
4522 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
4523 if (strequal(hookname
, lxchook_names
[which
]))
4527 if (which
>= NUM_LXC_HOOKS
)
4530 list_for_each_entry(entry
, &conf
->hooks
[which
], head
) {
4532 char *hook
= entry
->val
;
4534 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
4543 int lxc_clear_config_caps(struct lxc_conf
*c
)
4545 struct cap_entry
*cap
, *ncap
;
4547 list_for_each_entry_safe(cap
, ncap
, &c
->caps
.list
, head
) {
4548 list_del(&cap
->head
);
4549 free(cap
->cap_name
);
4553 c
->caps
.keep
= false;
4554 INIT_LIST_HEAD(&c
->caps
.list
);
4558 static int lxc_free_idmap(struct list_head
*id_map
)
4560 struct id_map
*map
, *nmap
;
4562 list_for_each_entry_safe(map
, nmap
, id_map
, head
) {
4563 list_del(&map
->head
);
4567 INIT_LIST_HEAD(id_map
);
4571 static int __lxc_free_idmap(struct list_head
*id_map
)
4573 lxc_free_idmap(id_map
);
4576 define_cleanup_function(struct list_head
*, __lxc_free_idmap
);
4578 int lxc_clear_idmaps(struct lxc_conf
*c
)
4580 return lxc_free_idmap(&c
->id_map
);
4583 int lxc_clear_namespace(struct lxc_conf
*c
)
4585 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
4586 free_disarm(c
->ns_share
[i
]);
4591 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
4593 const char *k
= key
;
4595 char *global_token
, *namespaced_token
;
4596 size_t namespaced_token_len
;
4597 struct list_head
*list
;
4598 struct lxc_cgroup
*cgroup
, *ncgroup
;
4600 if (version
== CGROUP2_SUPER_MAGIC
) {
4601 global_token
= "lxc.cgroup2";
4602 namespaced_token
= "lxc.cgroup2.";
4603 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
4605 } else if (version
== CGROUP_SUPER_MAGIC
) {
4606 global_token
= "lxc.cgroup";
4607 namespaced_token
= "lxc.cgroup.";
4608 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
4611 return ret_errno(EINVAL
);
4614 if (strequal(key
, global_token
))
4616 else if (strnequal(key
, namespaced_token
, namespaced_token_len
))
4617 k
+= namespaced_token_len
;
4619 return ret_errno(EINVAL
);
4621 list_for_each_entry_safe(cgroup
, ncgroup
, list
, head
) {
4622 if (!all
&& !strequal(cgroup
->subsystem
, k
))
4625 list_del(&cgroup
->head
);
4626 free(cgroup
->subsystem
);
4627 free(cgroup
->value
);
4632 INIT_LIST_HEAD(list
);
4637 static inline void lxc_clear_cgroups_devices(struct lxc_conf
*conf
)
4639 lxc_clear_cgroup2_devices(&conf
->bpf_devices
);
4642 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
4644 const char *k
= NULL
;
4646 struct lxc_limit
*lim
, *nlim
;
4648 if (strequal(key
, "lxc.limit") || strequal(key
, "lxc.prlimit"))
4650 else if (strnequal(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
4651 k
= key
+ STRLITERALLEN("lxc.limit.");
4652 else if (strnequal(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
4653 k
= key
+ STRLITERALLEN("lxc.prlimit.");
4655 return ret_errno(EINVAL
);
4657 list_for_each_entry_safe(lim
, nlim
, &c
->limits
, head
) {
4658 if (!all
&& !strequal(lim
->resource
, k
))
4661 list_del(&lim
->head
);
4662 free_disarm(lim
->resource
);
4667 INIT_LIST_HEAD(&c
->limits
);
4672 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
4674 const char *k
= NULL
;
4676 struct lxc_sysctl
*sysctl
, *nsysctl
;
4678 if (strequal(key
, "lxc.sysctl"))
4680 else if (strnequal(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
4681 k
= key
+ STRLITERALLEN("lxc.sysctl.");
4685 list_for_each_entry_safe(sysctl
, nsysctl
, &c
->sysctls
, head
) {
4686 if (!all
&& !strequal(sysctl
->key
, k
))
4689 list_del(&sysctl
->head
);
4691 free(sysctl
->value
);
4696 INIT_LIST_HEAD(&c
->sysctls
);
4701 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
4703 const char *k
= NULL
;
4705 struct lxc_proc
*proc
, *nproc
;
4707 if (strequal(key
, "lxc.proc"))
4709 else if (strnequal(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
4710 k
= key
+ STRLITERALLEN("lxc.proc.");
4714 list_for_each_entry_safe(proc
, nproc
, &c
->procs
, head
) {
4715 if (!all
&& !strequal(proc
->filename
, k
))
4718 list_del(&proc
->head
);
4719 free(proc
->filename
);
4725 INIT_LIST_HEAD(&c
->procs
);
4730 int lxc_clear_groups(struct lxc_conf
*c
)
4732 struct string_entry
*entry
, *nentry
;
4734 list_for_each_entry_safe(entry
, nentry
, &c
->groups
, head
) {
4735 list_del(&entry
->head
);
4740 INIT_LIST_HEAD(&c
->groups
);
4744 int lxc_clear_environment(struct lxc_conf
*c
)
4746 struct environment_entry
*env
, *nenv
;
4748 list_for_each_entry_safe(env
, nenv
, &c
->environment
, head
) {
4749 list_del(&env
->head
);
4755 INIT_LIST_HEAD(&c
->environment
);
4759 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4761 struct string_entry
*entry
, *nentry
;
4763 list_for_each_entry_safe(entry
, nentry
, &c
->mount_entries
, head
) {
4764 list_del(&entry
->head
);
4769 INIT_LIST_HEAD(&c
->mount_entries
);
4773 int lxc_clear_automounts(struct lxc_conf
*c
)
4779 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4781 const char *k
= NULL
;
4782 bool all
= false, done
= false;
4783 struct string_entry
*entry
, *nentry
;
4785 if (strequal(key
, "lxc.hook"))
4787 else if (strnequal(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
4788 k
= key
+ STRLITERALLEN("lxc.hook.");
4792 for (int i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4793 if (all
|| strequal(k
, lxchook_names
[i
])) {
4794 list_for_each_entry_safe(entry
, nentry
, &c
->hooks
[i
], head
) {
4795 list_del(&entry
->head
);
4799 INIT_LIST_HEAD(&c
->hooks
[i
]);
4805 return log_error(-1, "Invalid hook key: %s", key
);
4810 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4812 struct string_entry
*entry
, *nentry
;
4814 list_for_each_entry_safe(entry
, nentry
, &c
->lsm_aa_raw
, head
) {
4815 list_del(&entry
->head
);
4820 INIT_LIST_HEAD(&c
->lsm_aa_raw
);
4824 void lxc_conf_free(struct lxc_conf
*conf
)
4829 if (current_config
== conf
)
4830 current_config
= NULL
;
4831 lxc_terminal_conf_free(&conf
->console
);
4832 free(conf
->rootfs
.mount
);
4833 free(conf
->rootfs
.bdev_type
);
4834 free(conf
->rootfs
.path
);
4835 put_lxc_rootfs(&conf
->rootfs
, true);
4836 free(conf
->logfile
);
4837 if (conf
->logfd
!= -1)
4839 free(conf
->utsname
);
4840 free(conf
->ttys
.dir
);
4841 free(conf
->ttys
.tty_names
);
4844 free(conf
->execute_cmd
);
4845 free(conf
->init_cmd
);
4846 free(conf
->init_groups
.list
);
4847 free(conf
->init_cwd
);
4848 free(conf
->unexpanded_config
);
4850 lxc_free_networks(conf
);
4851 free(conf
->lsm_aa_profile
);
4852 free(conf
->lsm_aa_profile_computed
);
4853 free(conf
->lsm_se_context
);
4854 free(conf
->lsm_se_keyring_context
);
4855 lxc_seccomp_free(&conf
->seccomp
);
4856 lxc_clear_config_caps(conf
);
4857 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4858 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4859 lxc_clear_cgroups_devices(conf
);
4860 lxc_clear_hooks(conf
, "lxc.hook");
4861 lxc_clear_mount_entries(conf
);
4862 lxc_clear_idmaps(conf
);
4863 lxc_clear_groups(conf
);
4864 lxc_clear_environment(conf
);
4865 lxc_clear_limits(conf
, "lxc.prlimit");
4866 lxc_clear_sysctls(conf
, "lxc.sysctl");
4867 lxc_clear_procs(conf
, "lxc.proc");
4868 lxc_clear_apparmor_raw(conf
);
4869 lxc_clear_namespace(conf
);
4870 free(conf
->cgroup_meta
.dir
);
4871 free(conf
->cgroup_meta
.monitor_dir
);
4872 free(conf
->cgroup_meta
.monitor_pivot_dir
);
4873 free(conf
->cgroup_meta
.container_dir
);
4874 free(conf
->cgroup_meta
.namespace_dir
);
4875 free(conf
->cgroup_meta
.controllers
);
4876 free(conf
->cgroup_meta
.systemd_scope
);
4877 free(conf
->shmount
.path_host
);
4878 free(conf
->shmount
.path_cont
);
4882 struct userns_fn_data
{
4884 const char *fn_name
;
4889 static int run_userns_fn(void *data
)
4891 struct userns_fn_data
*d
= data
;
4895 close_prot_errno_disarm(d
->p
[1]);
4898 * Wait for parent to finish establishing a new mapping in the user
4899 * namespace we are executing in.
4901 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4902 close_prot_errno_disarm(d
->p
[0]);
4907 TRACE("Calling function \"%s\"", d
->fn_name
);
4909 /* Call function to run. */
4910 return d
->fn(d
->arg
);
4913 static struct id_map
*mapped_nsid_add(const struct lxc_conf
*conf
, unsigned id
,
4916 const struct id_map
*map
;
4917 struct id_map
*retmap
;
4919 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4923 retmap
= zalloc(sizeof(*retmap
));
4927 memcpy(retmap
, map
, sizeof(*retmap
));
4931 static struct id_map
*find_mapped_hostid_entry(const struct list_head
*idmap
,
4932 unsigned id
, enum idtype idtype
)
4934 struct id_map
*retmap
= NULL
;
4937 list_for_each_entry(map
, idmap
, head
) {
4938 if (map
->idtype
!= idtype
)
4941 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4950 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4951 * existing one or establish a new one.
4953 static struct id_map
*mapped_hostid_add(const struct lxc_conf
*conf
, uid_t id
,
4956 __do_free
struct id_map
*entry
= NULL
;
4958 struct id_map
*tmp
= NULL
;
4960 entry
= zalloc(sizeof(*entry
));
4964 /* Reuse existing mapping. */
4965 tmp
= find_mapped_hostid_entry(&conf
->id_map
, id
, type
);
4967 memcpy(entry
, tmp
, sizeof(*entry
));
4969 /* Find new mapping. */
4970 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4971 if (hostid_mapped
< 0)
4972 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
4974 entry
->idtype
= type
;
4975 entry
->nsid
= hostid_mapped
;
4976 entry
->hostid
= (unsigned long)id
;
4980 return move_ptr(entry
);
4983 static int get_minimal_idmap(const struct lxc_conf
*conf
, uid_t
*resuid
,
4984 gid_t
*resgid
, struct list_head
*head_ret
)
4986 __do_free
struct id_map
*container_root_uid
= NULL
,
4987 *container_root_gid
= NULL
,
4988 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4990 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4991 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4993 /* Find container root mappings. */
4994 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4995 if (!container_root_uid
)
4996 return sysdebug("Failed to find mapping for namespace uid %d", 0);
4998 if (euid
>= container_root_uid
->hostid
&&
4999 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
5000 host_uid_map
= move_ptr(container_root_uid
);
5002 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
5003 if (!container_root_gid
)
5004 return sysdebug("Failed to find mapping for namespace gid %d", 0);
5006 if (egid
>= container_root_gid
->hostid
&&
5007 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
5008 host_gid_map
= move_ptr(container_root_gid
);
5010 /* Check whether the {g,u}id of the user has a mapping. */
5012 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
5014 return sysdebug("Failed to find mapping for uid %d", euid
);
5017 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
5019 return sysdebug("Failed to find mapping for gid %d", egid
);
5021 /* idmap will now keep track of that memory. */
5022 list_add_tail(&host_uid_map
->head
, head_ret
);
5023 move_ptr(host_uid_map
);
5025 if (container_root_uid
) {
5026 /* idmap will now keep track of that memory. */
5027 list_add_tail(&container_root_uid
->head
, head_ret
);
5028 move_ptr(container_root_uid
);
5031 /* idmap will now keep track of that memory. */
5032 list_add_tail(&host_gid_map
->head
, head_ret
);
5033 move_ptr(host_gid_map
);
5035 if (container_root_gid
) {
5036 /* idmap will now keep track of that memory. */
5037 list_add_tail(&container_root_gid
->head
, head_ret
);
5038 move_ptr(container_root_gid
);
5041 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid
, nsgid
);
5052 * Run a function in a new user namespace.
5053 * The caller's euid/egid will be mapped if it is not already.
5054 * Afaict, userns_exec_1() is only used to operate based on privileges for the
5055 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
5056 * This means we require only to establish a mapping from:
5057 * - the container root {g,u}id as seen from the host > user's host {g,u}id
5058 * - the container root -> some sub{g,u}id
5059 * The former we add, if the user did not specify a mapping. The latter we
5060 * retrieve from the container's configured {g,u}id mappings as it must have been
5061 * there to start the container in the first place.
5063 int userns_exec_1(const struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
5064 const char *fn_name
)
5066 LIST_HEAD(minimal_idmap
);
5067 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &minimal_idmap
;
5068 int ret
= -1, status
= -1;
5070 struct userns_fn_data d
= {
5081 ret
= get_minimal_idmap(conf
, NULL
, NULL
, idmap
);
5083 return ret_errno(ENOENT
);
5085 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
5089 d
.p
[0] = pipe_fds
[0];
5090 d
.p
[1] = pipe_fds
[1];
5092 /* Clone child in new user namespace. */
5093 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5095 ERROR("Failed to clone process in new user namespace");
5099 close_prot_errno_disarm(pipe_fds
[0]);
5101 if (lxc_log_trace()) {
5104 list_for_each_entry(map
, idmap
, head
)
5105 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5106 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5109 /* Set up {g,u}id mapping for user namespace of child process. */
5110 ret
= lxc_map_ids(idmap
, pid
);
5112 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5116 /* Tell child to proceed. */
5117 if (lxc_write_nointr(pipe_fds
[1], &c
, 1) != 1) {
5118 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5123 close_prot_errno_disarm(pipe_fds
[0]);
5124 close_prot_errno_disarm(pipe_fds
[1]);
5126 /* Wait for child to finish. */
5128 status
= wait_for_pid(pid
);
5136 int userns_exec_minimal(const struct lxc_conf
*conf
,
5137 int (*fn_parent
)(void *), void *fn_parent_data
,
5138 int (*fn_child
)(void *), void *fn_child_data
)
5140 LIST_HEAD(minimal_idmap
);
5141 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &minimal_idmap
;
5142 uid_t resuid
= LXC_INVALID_UID
;
5143 gid_t resgid
= LXC_INVALID_GID
;
5149 if (!conf
|| !fn_child
)
5150 return ret_errno(EINVAL
);
5152 ret
= get_minimal_idmap(conf
, &resuid
, &resgid
, idmap
);
5154 return ret_errno(ENOENT
);
5156 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5162 SYSERROR("Failed to create new process");
5167 close_prot_errno_disarm(sock_fds
[1]);
5169 ret
= unshare(CLONE_NEWUSER
);
5171 SYSERROR("Failed to unshare new user namespace");
5172 _exit(EXIT_FAILURE
);
5175 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5177 _exit(EXIT_FAILURE
);
5179 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5181 _exit(EXIT_FAILURE
);
5183 close_prot_errno_disarm(sock_fds
[0]);
5185 if (!lxc_drop_groups() && errno
!= EPERM
)
5186 _exit(EXIT_FAILURE
);
5188 ret
= setresgid(resgid
, resgid
, resgid
);
5190 SYSERROR("Failed to setresgid(%d, %d, %d)",
5191 resgid
, resgid
, resgid
);
5192 _exit(EXIT_FAILURE
);
5195 ret
= setresuid(resuid
, resuid
, resuid
);
5197 SYSERROR("Failed to setresuid(%d, %d, %d)",
5198 resuid
, resuid
, resuid
);
5199 _exit(EXIT_FAILURE
);
5202 ret
= fn_child(fn_child_data
);
5204 SYSERROR("Running function in new user namespace failed");
5205 _exit(EXIT_FAILURE
);
5208 _exit(EXIT_SUCCESS
);
5211 close_prot_errno_disarm(sock_fds
[0]);
5213 if (lxc_log_trace()) {
5216 list_for_each_entry(map
, idmap
, head
)
5217 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5218 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5221 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
5223 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
5227 /* Set up {g,u}id mapping for user namespace of child process. */
5228 ret
= lxc_map_ids(idmap
, pid
);
5230 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5234 /* Tell child to proceed. */
5235 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
5237 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5241 if (fn_parent
&& fn_parent(fn_parent_data
)) {
5242 SYSERROR("Running parent function failed");
5243 _exit(EXIT_FAILURE
);
5247 close_prot_errno_disarm(sock_fds
[0]);
5248 close_prot_errno_disarm(sock_fds
[1]);
5250 /* Wait for child to finish. */
5254 return wait_for_pid(pid
);
5257 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
5258 const char *fn_name
)
5260 LIST_HEAD(full_idmap
);
5263 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
5264 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
5269 struct userns_fn_data d
;
5274 ret
= pipe2(p
, O_CLOEXEC
);
5279 d
.fn_name
= fn_name
;
5284 /* Clone child in new user namespace. */
5285 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5287 ERROR("Failed to clone process in new user namespace");
5297 /* Find container root. */
5298 list_for_each_entry(map
, &conf
->id_map
, head
) {
5299 __do_free
struct id_map
*dup_map
= NULL
;
5301 dup_map
= memdup(map
, sizeof(struct id_map
));
5305 list_add_tail(&dup_map
->head
, &full_idmap
);
5308 if (map
->idtype
== ID_TYPE_UID
)
5309 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
5312 if (map
->idtype
== ID_TYPE_GID
)
5313 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
5319 if (map
->idtype
== ID_TYPE_UID
)
5320 if (container_root_uid
== NULL
)
5321 container_root_uid
= map
;
5323 if (map
->idtype
== ID_TYPE_GID
)
5324 if (container_root_gid
== NULL
)
5325 container_root_gid
= map
;
5328 if (!container_root_uid
|| !container_root_gid
) {
5329 ERROR("No mapping for container root found");
5333 /* Check whether the {g,u}id of the user has a mapping. */
5335 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
5337 host_uid_map
= container_root_uid
;
5340 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
5342 host_gid_map
= container_root_gid
;
5344 if (!host_uid_map
) {
5345 DEBUG("Failed to find mapping for uid %d", euid
);
5349 if (!host_gid_map
) {
5350 DEBUG("Failed to find mapping for gid %d", egid
);
5354 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
5355 /* idmap will now keep track of that memory. */
5356 list_add_tail(&host_uid_map
->head
, &full_idmap
);
5357 move_ptr(host_uid_map
);
5360 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
5361 /* idmap will now keep track of that memory. */
5362 list_add_tail(&host_gid_map
->head
, &full_idmap
);
5363 move_ptr(host_gid_map
);
5366 if (lxc_log_trace()) {
5367 list_for_each_entry(map
, &full_idmap
, head
) {
5368 TRACE("establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5369 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
5370 map
->nsid
, map
->hostid
, map
->range
);
5374 /* Set up {g,u}id mapping for user namespace of child process. */
5375 ret
= lxc_map_ids(&full_idmap
, pid
);
5377 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
5381 /* Tell child to proceed. */
5382 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
5383 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5392 /* Wait for child to finish. */
5394 ret
= wait_for_pid(pid
);
5396 __lxc_free_idmap(&full_idmap
);
5398 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
5400 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
5406 static int add_idmap_entry(struct list_head
*idmap_list
, enum idtype idtype
,
5407 unsigned long nsid
, unsigned long hostid
,
5408 unsigned long range
)
5410 __do_free
struct id_map
*new_idmap
= NULL
;
5412 new_idmap
= zalloc(sizeof(*new_idmap
));
5414 return ret_errno(ENOMEM
);
5416 new_idmap
->idtype
= idtype
;
5417 new_idmap
->hostid
= hostid
;
5418 new_idmap
->nsid
= nsid
;
5419 new_idmap
->range
= range
;
5421 list_add_tail(&new_idmap
->head
, idmap_list
);
5422 move_ptr(new_idmap
);
5424 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5425 idtype
== ID_TYPE_UID
? 'u' : 'g', nsid
, hostid
, range
);
5429 int userns_exec_mapped_root(const char *path
, int path_fd
,
5430 const struct lxc_conf
*conf
)
5432 LIST_HEAD(idmap_list
);
5433 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &idmap_list
;
5434 __do_close
int fd
= -EBADF
;
5435 int target_fd
= -EBADF
;
5440 uid_t container_host_uid
, hostuid
;
5441 gid_t container_host_gid
, hostgid
;
5444 if (!conf
|| (!path
&& path_fd
< 0))
5445 return ret_errno(EINVAL
);
5450 container_host_uid
= get_mapped_rootid(conf
, ID_TYPE_UID
);
5451 if (!uid_valid(container_host_uid
))
5452 return log_error(-1, "No uid mapping for container root");
5454 container_host_gid
= get_mapped_rootid(conf
, ID_TYPE_GID
);
5455 if (!gid_valid(container_host_gid
))
5456 return log_error(-1, "No gid mapping for container root");
5459 fd
= open(path
, O_CLOEXEC
| O_NOCTTY
);
5461 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", path
);
5464 target_fd
= path_fd
;
5467 hostuid
= geteuid();
5468 /* We are root so chown directly. */
5470 ret
= fchown(target_fd
, container_host_uid
, container_host_gid
);
5472 return log_error_errno(-errno
, errno
,
5473 "Failed to fchown(%d(%s), %d, %d)",
5474 target_fd
, path
, container_host_uid
,
5475 container_host_gid
);
5476 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd
, path
,
5477 container_host_uid
, container_host_gid
);
5480 /* The container's root host id matches */
5481 if (container_host_uid
== hostuid
)
5482 return log_info(0, "Container root id is mapped to our uid");
5484 /* Get the current ids of our target. */
5485 ret
= fstat(target_fd
, &st
);
5487 return log_error_errno(-errno
, errno
, "Failed to stat \"%s\"", path
);
5489 hostgid
= getegid();
5490 if (st
.st_uid
== hostuid
&& mapped_hostid(st
.st_gid
, conf
, ID_TYPE_GID
) < 0) {
5491 ret
= fchown(target_fd
, -1, hostgid
);
5493 return log_error_errno(-errno
, errno
,
5494 "Failed to fchown(%d(%s), -1, %d)",
5495 target_fd
, path
, hostgid
);
5496 TRACE("Chowned %d(%s) to -1:%d", target_fd
, path
, hostgid
);
5499 /* "u:0:rootuid:1" */
5500 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, 0, container_host_uid
, 1);
5502 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5504 /* "u:hostuid:hostuid:1" */
5505 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, hostuid
, hostuid
, 1);
5507 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5509 /* "g:0:rootgid:1" */
5510 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, 0, container_host_gid
, 1);
5512 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5514 /* "g:hostgid:hostgid:1" */
5515 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, hostgid
, hostgid
, 1);
5517 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5519 if (hostgid
!= st
.st_gid
) {
5520 /* "g:pathgid:rootgid+pathgid:1" */
5521 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, st
.st_gid
,
5522 container_host_gid
+ (gid_t
)st
.st_gid
, 1);
5524 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5527 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5533 SYSERROR("Failed to create new process");
5538 close_prot_errno_disarm(sock_fds
[1]);
5540 ret
= unshare(CLONE_NEWUSER
);
5542 SYSERROR("Failed to unshare new user namespace");
5543 _exit(EXIT_FAILURE
);
5546 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5548 _exit(EXIT_FAILURE
);
5550 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5552 _exit(EXIT_FAILURE
);
5554 close_prot_errno_disarm(sock_fds
[0]);
5556 if (!lxc_drop_groups() && errno
!= EPERM
)
5557 _exit(EXIT_FAILURE
);
5559 ret
= setresgid(0, 0, 0);
5561 SYSERROR("Failed to setresgid(0, 0, 0)");
5562 _exit(EXIT_FAILURE
);
5565 ret
= setresuid(0, 0, 0);
5567 SYSERROR("Failed to setresuid(0, 0, 0)");
5568 _exit(EXIT_FAILURE
);
5571 ret
= fchown(target_fd
, 0, st
.st_gid
);
5573 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5574 _exit(EXIT_FAILURE
);
5577 TRACE("Chowned %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5578 _exit(EXIT_SUCCESS
);
5581 close_prot_errno_disarm(sock_fds
[0]);
5583 if (lxc_log_trace()) {
5586 list_for_each_entry(map
, idmap
, head
)
5587 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5588 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5591 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
5593 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
5597 /* Set up {g,u}id mapping for user namespace of child process. */
5598 ret
= lxc_map_ids(idmap
, pid
);
5600 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5604 /* Tell child to proceed. */
5605 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
5607 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5612 close_prot_errno_disarm(sock_fds
[0]);
5613 close_prot_errno_disarm(sock_fds
[1]);
5615 /* Wait for child to finish. */
5617 return log_error(-1, "Failed to create child process");
5619 if (!wait_exited(pid
))
5625 /* not thread-safe, do not use from api without first forking */
5626 static char *getuname(void)
5628 __do_free
char *buf
= NULL
;
5629 struct passwd pwent
;
5630 struct passwd
*pwentp
= NULL
;
5634 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
5638 buf
= zalloc(bufsize
);
5642 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
5645 WARN("Could not find matched password record.");
5647 return log_error(NULL
, "Failed to get password record - %u", geteuid());
5650 return strdup(pwent
.pw_name
);
5653 /* not thread-safe, do not use from api without first forking */
5654 static char *getgname(void)
5656 __do_free
char *buf
= NULL
;
5658 struct group
*grentp
= NULL
;
5662 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
5666 buf
= zalloc(bufsize
);
5670 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
5673 WARN("Could not find matched group record");
5675 return log_error(NULL
, "Failed to get group record - %u", getegid());
5678 return strdup(grent
.gr_name
);
5681 /* not thread-safe, do not use from api without first forking */
5682 void suggest_default_idmap(void)
5684 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
5685 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
5686 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
5697 subuid_f
= fopen(subuidfile
, "re");
5699 ERROR("Your system is not configured with subuids");
5703 while (getline(&line
, &len
, subuid_f
) != -1) {
5705 size_t no_newline
= 0;
5707 p
= strchr(line
, ':');
5715 if (!strequal(line
, uname
))
5718 p2
= strchr(p
, ':');
5725 no_newline
= strcspn(p2
, "\n");
5726 p2
[no_newline
] = '\0';
5728 if (lxc_safe_uint(p
, &uid
) < 0)
5729 WARN("Could not parse UID");
5730 if (lxc_safe_uint(p2
, &urange
) < 0)
5731 WARN("Could not parse UID range");
5734 subgid_f
= fopen(subgidfile
, "re");
5736 ERROR("Your system is not configured with subgids");
5740 while (getline(&line
, &len
, subgid_f
) != -1) {
5742 size_t no_newline
= 0;
5744 p
= strchr(line
, ':');
5752 if (!strequal(line
, uname
))
5755 p2
= strchr(p
, ':');
5762 no_newline
= strcspn(p2
, "\n");
5763 p2
[no_newline
] = '\0';
5765 if (lxc_safe_uint(p
, &gid
) < 0)
5766 WARN("Could not parse GID");
5767 if (lxc_safe_uint(p2
, &grange
) < 0)
5768 WARN("Could not parse GID range");
5771 if (!urange
|| !grange
) {
5772 ERROR("You do not have subuids or subgids allocated");
5773 ERROR("Unprivileged containers require subuids and subgids");
5777 ERROR("You must either run as root, or define uid mappings");
5778 ERROR("To pass uid mappings to lxc-create, you could create");
5779 ERROR("~/.config/lxc/default.conf:");
5780 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
5781 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
5782 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
5785 int lxc_set_environment(const struct lxc_conf
*conf
)
5787 struct environment_entry
*env
;
5789 list_for_each_entry(env
, &conf
->environment
, head
) {
5792 ret
= setenv(env
->key
, env
->val
, 1);
5794 return syserror("Failed to set environment variable: %s=%s",
5795 env
->key
, env
->val
);
5796 TRACE("Set environment variable: %s=%s", env
->key
, env
->val
);