1 /* SPDX-License-Identifier: LGPL-2.1+ */
12 #include <linux/loop.h>
14 #include <netinet/in.h>
22 #include <sys/mount.h>
23 #include <sys/param.h>
24 #include <sys/prctl.h>
25 #include <sys/sendfile.h>
26 #include <sys/socket.h>
28 #include <sys/syscall.h>
29 #include <sys/sysmacros.h>
30 #include <sys/types.h>
31 #include <sys/utsname.h>
39 #include "cgroups/cgroup.h"
42 #include "confile_utils.h"
47 #include "lxcseccomp.h"
49 #include "memory_utils.h"
50 #include "mount_utils.h"
51 #include "namespace.h"
54 #include "process_utils.h"
57 #include "storage/storage.h"
58 #include "storage/overlay.h"
60 #include "syscall_wrappers.h"
66 #include <sys/mkdev.h>
70 #include <sys/statvfs.h>
80 #include <sys/capability.h>
88 #include "lxcmntent.h"
93 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
102 #include "strchrnul.h"
105 lxc_log_define(conf
, lxc
);
108 * The lxc_conf of the container currently being worked on in an API call.
109 * This is used in the error calls.
111 thread_local
struct lxc_conf
*current_config
;
113 char *lxchook_names
[NUM_LXC_HOOKS
] = {
144 static struct mount_opt mount_opt
[] = {
145 { "atime", 1, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
146 { "dev", 1, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
147 { "diratime", 1, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
148 { "exec", 1, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
149 { "noatime", 0, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
150 { "nodev", 0, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
151 { "nodiratime", 0, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
152 { "noexec", 0, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
153 { "norelatime", 1, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
154 { "nostrictatime", 1, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
155 { "nosuid", 0, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
156 { "relatime", 0, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
157 { "ro", 0, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
158 { "rw", 1, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
159 { "strictatime", 0, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
160 { "suid", 1, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
162 { "bind", 0, false, 0, MS_BIND
},
163 { "defaults", 0, false, 0, 0 },
164 { "rbind", 0, true, 0, MS_BIND
| MS_REC
},
166 { "sync", 0, false, ~0, MS_SYNCHRONOUS
},
167 { "async", 1, false, ~0, MS_SYNCHRONOUS
},
168 { "dirsync", 0, false, ~0, MS_DIRSYNC
},
169 { "lazytime", 0, false, ~0, MS_LAZYTIME
},
170 { "mand", 0, false, ~0, MS_MANDLOCK
},
171 { "nomand", 1, false, ~0, MS_MANDLOCK
},
172 { "remount", 0, false, ~0, MS_REMOUNT
},
174 { NULL
, 0, false, ~0, ~0 },
177 static struct mount_opt propagation_opt
[] = {
178 { "private", 0, false, MS_PRIVATE
, MS_PRIVATE
},
179 { "shared", 0, false, MS_SHARED
, MS_SHARED
},
180 { "slave", 0, false, MS_SLAVE
, MS_SLAVE
},
181 { "unbindable", 0, false, MS_UNBINDABLE
, MS_UNBINDABLE
},
182 { "rprivate", 0, true, MS_PRIVATE
, MS_PRIVATE
| MS_REC
},
183 { "rshared", 0, true, MS_SHARED
, MS_SHARED
| MS_REC
},
184 { "rslave", 0, true, MS_SLAVE
, MS_SLAVE
| MS_REC
},
185 { "runbindable", 0, true, MS_UNBINDABLE
, MS_UNBINDABLE
| MS_REC
},
186 { NULL
, 0, false, 0, 0 },
189 static struct caps_opt caps_opt
[] = {
191 { "chown", CAP_CHOWN
},
192 { "dac_override", CAP_DAC_OVERRIDE
},
193 { "dac_read_search", CAP_DAC_READ_SEARCH
},
194 { "fowner", CAP_FOWNER
},
195 { "fsetid", CAP_FSETID
},
196 { "kill", CAP_KILL
},
197 { "setgid", CAP_SETGID
},
198 { "setuid", CAP_SETUID
},
199 { "setpcap", CAP_SETPCAP
},
200 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
201 { "net_bind_service", CAP_NET_BIND_SERVICE
},
202 { "net_broadcast", CAP_NET_BROADCAST
},
203 { "net_admin", CAP_NET_ADMIN
},
204 { "net_raw", CAP_NET_RAW
},
205 { "ipc_lock", CAP_IPC_LOCK
},
206 { "ipc_owner", CAP_IPC_OWNER
},
207 { "sys_module", CAP_SYS_MODULE
},
208 { "sys_rawio", CAP_SYS_RAWIO
},
209 { "sys_chroot", CAP_SYS_CHROOT
},
210 { "sys_ptrace", CAP_SYS_PTRACE
},
211 { "sys_pacct", CAP_SYS_PACCT
},
212 { "sys_admin", CAP_SYS_ADMIN
},
213 { "sys_boot", CAP_SYS_BOOT
},
214 { "sys_nice", CAP_SYS_NICE
},
215 { "sys_resource", CAP_SYS_RESOURCE
},
216 { "sys_time", CAP_SYS_TIME
},
217 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
218 { "mknod", CAP_MKNOD
},
219 { "lease", CAP_LEASE
},
220 { "audit_write", CAP_AUDIT_WRITE
},
221 { "audit_control", CAP_AUDIT_CONTROL
},
222 { "setfcap", CAP_SETFCAP
},
223 { "mac_override", CAP_MAC_OVERRIDE
},
224 { "mac_admin", CAP_MAC_ADMIN
},
225 { "syslog", CAP_SYSLOG
},
226 { "wake_alarm", CAP_WAKE_ALARM
},
227 { "block_suspend", CAP_BLOCK_SUSPEND
},
228 { "audit_read", CAP_AUDIT_READ
},
229 { "perfmon", CAP_PERFMON
},
231 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE
},
235 static struct limit_opt limit_opt
[] = {
240 { "core", RLIMIT_CORE
},
243 { "cpu", RLIMIT_CPU
},
246 { "data", RLIMIT_DATA
},
249 { "fsize", RLIMIT_FSIZE
},
252 { "locks", RLIMIT_LOCKS
},
254 #ifdef RLIMIT_MEMLOCK
255 { "memlock", RLIMIT_MEMLOCK
},
257 #ifdef RLIMIT_MSGQUEUE
258 { "msgqueue", RLIMIT_MSGQUEUE
},
261 { "nice", RLIMIT_NICE
},
264 { "nofile", RLIMIT_NOFILE
},
267 { "nproc", RLIMIT_NPROC
},
270 { "rss", RLIMIT_RSS
},
273 { "rtprio", RLIMIT_RTPRIO
},
276 { "rttime", RLIMIT_RTTIME
},
278 #ifdef RLIMIT_SIGPENDING
279 { "sigpending", RLIMIT_SIGPENDING
},
282 { "stack", RLIMIT_STACK
},
286 static int run_buffer(char *buffer
)
288 __do_free
char *output
= NULL
;
289 __do_lxc_pclose
struct lxc_popen_FILE
*f
= NULL
;
292 f
= lxc_popen(buffer
);
294 return log_error_errno(-1, errno
, "Failed to popen() %s", buffer
);
296 output
= zalloc(LXC_LOG_BUFFER_SIZE
);
298 return log_error_errno(-1, ENOMEM
, "Failed to allocate memory for %s", buffer
);
302 return log_error_errno(-1, errno
, "Failed to retrieve underlying file descriptor");
304 for (int i
= 0; i
< 10; i
++) {
307 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
308 if (bytes_read
> 0) {
309 output
[bytes_read
] = '\0';
310 DEBUG("Script %s produced output: %s", buffer
, output
);
317 ret
= lxc_pclose(move_ptr(f
));
319 return log_error_errno(-1, errno
, "Script exited with error");
320 else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0)
321 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret
));
322 else if (WIFSIGNALED(ret
))
323 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret
));
328 int run_script_argv(const char *name
, unsigned int hook_version
,
329 const char *section
, const char *script
,
330 const char *hookname
, char **argv
)
332 __do_free
char *buffer
= NULL
;
336 if (hook_version
== 0)
337 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
338 script
, name
, section
);
340 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
342 for (i
= 0; argv
&& argv
[i
]; i
++)
343 size
+= strlen(argv
[i
]) + 1;
345 size
+= STRLITERALLEN("exec");
347 size
+= strlen(script
);
353 if (hook_version
== 0) {
354 size
+= strlen(hookname
);
357 size
+= strlen(name
);
360 size
+= strlen(section
);
367 buffer
= zalloc(size
);
371 if (hook_version
== 0)
372 buf_pos
= strnprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
374 buf_pos
= strnprintf(buffer
, size
, "exec %s", script
);
376 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
378 if (hook_version
== 1) {
379 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
381 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname
);
383 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
385 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
387 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section
);
388 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
390 if (strequal(section
, "net")) {
393 if (!argv
|| !argv
[0])
396 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
398 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_TYPE=%s", argv
[0]);
399 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
401 parent
= argv
[1] ? argv
[1] : "";
403 if (strequal(argv
[0], "macvlan")) {
404 ret
= setenv("LXC_NET_PARENT", parent
, 1);
406 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
407 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
408 } else if (strequal(argv
[0], "phys")) {
409 ret
= setenv("LXC_NET_PARENT", parent
, 1);
411 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
412 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
413 } else if (strequal(argv
[0], "veth")) {
414 char *peer
= argv
[2] ? argv
[2] : "";
416 ret
= setenv("LXC_NET_PEER", peer
, 1);
418 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PEER=%s", peer
);
419 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
421 ret
= setenv("LXC_NET_PARENT", parent
, 1);
423 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
424 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
429 for (i
= 0; argv
&& argv
[i
]; i
++) {
430 size_t len
= size
- buf_pos
;
432 ret
= strnprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
434 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
438 return run_buffer(buffer
);
441 int run_script(const char *name
, const char *section
, const char *script
, ...)
443 __do_free
char *buffer
= NULL
;
449 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
450 script
, name
, section
);
452 va_start(ap
, script
);
453 while ((p
= va_arg(ap
, char *)))
454 size
+= strlen(p
) + 1;
457 size
+= STRLITERALLEN("exec");
458 size
+= strlen(script
);
459 size
+= strlen(name
);
460 size
+= strlen(section
);
466 buffer
= must_realloc(NULL
, size
);
467 ret
= strnprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
471 va_start(ap
, script
);
472 while ((p
= va_arg(ap
, char *))) {
473 int len
= size
- ret
;
475 rc
= strnprintf(buffer
+ ret
, len
, " %s", p
);
484 return run_buffer(buffer
);
487 int lxc_storage_prepare(struct lxc_conf
*conf
)
490 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
493 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
495 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
497 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
498 if (rootfs
->dfd_mnt
< 0)
504 ret
= access(rootfs
->mount
, F_OK
);
506 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
509 rootfs
->storage
= storage_init(conf
);
510 if (!rootfs
->storage
)
511 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
512 rootfs
->path
, rootfs
->mount
,
513 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
518 void lxc_storage_put(struct lxc_conf
*conf
)
520 storage_put(conf
->rootfs
.storage
);
521 conf
->rootfs
.storage
= NULL
;
524 /* lxc_rootfs_prepare
525 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
526 * the duration of the container run, to prevent the container from marking
527 * the underlying fs readonly on shutdown. unlink the file immediately so
528 * no name pollution is happens.
529 * don't unlink on NFS to avoid random named stale handles.
531 int lxc_rootfs_init(struct lxc_conf
*conf
, bool userns
)
533 __do_close
int dfd_path
= -EBADF
, fd_pin
= -EBADF
;
537 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
539 ret
= lxc_storage_prepare(conf
);
541 return syserror_set(-EINVAL
, "Failed to prepare rootfs storage");
543 if (!is_empty_string(rootfs
->mnt_opts
.userns_path
)) {
545 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supported with separate rootfs for container");
547 if (rootfs
->bdev_type
&& !strequal(rootfs
->bdev_type
, "dir"))
548 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supports the \"dir\" storage driver");
552 return log_trace(0, "Not pinning because container does not have a rootfs");
555 return log_trace(0, "Not pinning because container runs in user namespace");
557 if (rootfs
->bdev_type
) {
558 if (strequal(rootfs
->bdev_type
, "overlay") ||
559 strequal(rootfs
->bdev_type
, "overlayfs"))
560 return log_trace_errno(0, EINVAL
, "Not pinning on stacking filesystem");
562 if (strequal(rootfs
->bdev_type
, "zfs"))
563 return log_trace_errno(0, EINVAL
, "Not pinning on ZFS filesystem");
566 dfd_path
= open_at(-EBADF
, rootfs
->path
, PROTECT_OPATH_FILE
, 0, 0);
568 return syserror("Failed to open \"%s\"", rootfs
->path
);
570 ret
= fstat(dfd_path
, &st
);
572 return log_trace_errno(-errno
, errno
, "Failed to retrieve file status");
574 if (!S_ISDIR(st
.st_mode
))
575 return log_trace_errno(0, ENOTDIR
, "Not pinning because file descriptor is not a directory");
577 fd_pin
= open_at(dfd_path
, ".lxc_keep",
578 PROTECT_OPEN
| O_CREAT
,
579 PROTECT_LOOKUP_BENEATH
,
583 return log_trace_errno(0, EROFS
, "Not pinning on read-only filesystem");
584 return syserror("Failed to pin rootfs");
587 TRACE("Pinned rootfs %d(.lxc_keep)", fd_pin
);
589 ret
= fstatfs(fd_pin
, &stfs
);
591 SYSWARN("Failed to retrieve filesystem status");
595 if (stfs
.f_type
== NFS_SUPER_MAGIC
) {
596 DEBUG("Not unlinking pinned file on NFS");
600 if (unlinkat(dfd_path
, ".lxc_keep", 0))
601 SYSTRACE("Failed to unlink rootfs pinning file %d(.lxc_keep)", dfd_path
);
603 TRACE("Unlinked pinned file %d(.lxc_keep)", dfd_path
);
606 rootfs
->fd_path_pin
= move_fd(fd_pin
);
610 int lxc_rootfs_prepare_parent(struct lxc_handler
*handler
)
612 __do_close
int dfd_idmapped
= -EBADF
, fd_userns
= -EBADF
;
613 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
614 struct lxc_storage
*storage
= rootfs
->storage
;
615 const struct lxc_mount_options
*mnt_opts
= &rootfs
->mnt_opts
;
617 const char *path_source
;
619 if (list_empty(&handler
->conf
->id_map
))
622 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
625 if (handler
->conf
->rootfs_setup
)
628 if (rootfs_is_blockdev(handler
->conf
))
629 return syserror_set(-EOPNOTSUPP
, "Idmapped mounts on block-backed storage not yet supported");
631 if (!can_use_bind_mounts())
632 return syserror_set(-EOPNOTSUPP
, "Kernel does not support the new mount api");
634 if (strequal(rootfs
->mnt_opts
.userns_path
, "container"))
635 fd_userns
= dup_cloexec(handler
->nsfd
[LXC_NS_USER
]);
637 fd_userns
= open_at(-EBADF
, rootfs
->mnt_opts
.userns_path
,
638 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
640 return syserror("Failed to open user namespace");
642 path_source
= lxc_storage_get_path(storage
->src
, storage
->type
);
644 dfd_idmapped
= create_detached_idmapped_mount(path_source
, fd_userns
, true,
645 mnt_opts
->attr
.attr_set
,
646 mnt_opts
->attr
.attr_clr
);
647 if (dfd_idmapped
< 0)
648 return syserror("Failed to create detached idmapped mount");
650 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &dfd_idmapped
, 1, NULL
, 0);
652 return syserror("Failed to send detached idmapped mount fd");
654 TRACE("Created detached idmapped mount %d", dfd_idmapped
);
658 static int add_shmount_to_list(struct lxc_conf
*conf
)
660 char new_mount
[PATH_MAX
];
661 /* Offset for the leading '/' since the path_cont
662 * is absolute inside the container.
664 int offset
= 1, ret
= -1;
666 ret
= strnprintf(new_mount
, sizeof(new_mount
),
667 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
668 conf
->shmount
.path_cont
+ offset
);
672 return add_elem_to_mount_list(new_mount
, conf
);
675 static int lxc_mount_auto_mounts(struct lxc_handler
*handler
, int flags
)
682 const char *destination
;
686 bool requires_cap_net_admin
;
687 } default_mounts
[] = {
688 /* Read-only bind-mounting... In older kernels, doing that
689 * required to do one MS_BIND mount and then
690 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
691 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
692 * onwards. However, this apparently does not work on kernel
693 * 3.8. Unfortunately, on that very same kernel, doing the same
694 * trick as above doesn't seem to work either, there one needs
695 * to ALSO specify MS_BIND for the remount, otherwise the
696 * entire fs is remounted read-only or the mount fails because
697 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
698 * kernels as low as 2.6.32...
700 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
701 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
702 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
, true, },
703 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
, false },
704 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
705 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
, true },
706 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
, false },
707 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
, false },
708 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
, false },
709 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
, false },
710 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
, false },
711 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
|MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
, false },
712 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys/devices/virtual/net", "%r/sys/devices/virtual/net", NULL
, MS_BIND
, NULL
, false },
713 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys/devices/virtual/net", NULL
, MS_REMOUNT
|MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
, false },
714 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
, false }
716 struct lxc_conf
*conf
= handler
->conf
;
717 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
718 bool has_cap_net_admin
;
720 if (flags
& LXC_AUTO_PROC_MASK
) {
723 * Only unmount procfs if we have a separate rootfs so
724 * we can still access it in safe_mount() below.
726 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc",
727 rootfs
->path
? rootfs
->mount
: "");
729 return ret_errno(EIO
);
731 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
733 SYSDEBUG("Tried to ensure procfs is unmounted");
736 ret
= mkdirat(rootfs
->dfd_mnt
, "proc" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
737 if (ret
< 0 && errno
!= EEXIST
)
738 return syserror("Failed to create procfs mountpoint under %d", rootfs
->dfd_mnt
);
740 TRACE("Created procfs mountpoint under %d", rootfs
->dfd_mnt
);
743 if (flags
& LXC_AUTO_SYS_MASK
) {
746 * Only unmount sysfs if we have a separate rootfs so
747 * we can still access it in safe_mount() below.
749 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/sys",
750 rootfs
->path
? rootfs
->mount
: "");
752 return ret_errno(EIO
);
754 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
756 SYSDEBUG("Tried to ensure sysfs is unmounted");
759 ret
= mkdirat(rootfs
->dfd_mnt
, "sys" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
760 if (ret
< 0 && errno
!= EEXIST
)
761 return syserror("Failed to create sysfs mountpoint under %d", rootfs
->dfd_mnt
);
763 TRACE("Created sysfs mountpoint under %d", rootfs
->dfd_mnt
);
766 has_cap_net_admin
= lxc_wants_cap(CAP_NET_ADMIN
, conf
);
767 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
768 __do_free
char *destination
= NULL
, *source
= NULL
;
769 unsigned long mflags
= default_mounts
[i
].flags
;
771 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
774 if (default_mounts
[i
].source
) {
775 /* will act like strdup if %r is not present */
776 source
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].source
);
778 return syserror_set(-ENOMEM
, "Failed to create source path");
781 if (!default_mounts
[i
].destination
)
782 return syserror_set(-EINVAL
, "BUG: auto mounts destination %d was NULL", i
);
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 /* will act like strdup if %r is not present */
790 destination
= lxc_string_replace("%r", rootfs
->path
? rootfs
->mount
: "", default_mounts
[i
].destination
);
792 return syserror_set(-ENOMEM
, "Failed to create target path");
794 ret
= safe_mount(source
, destination
,
795 default_mounts
[i
].fstype
,
797 default_mounts
[i
].options
,
798 rootfs
->path
? rootfs
->mount
: NULL
);
801 return syserror("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
803 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source
, destination
);
807 if (mflags
& MS_REMOUNT
)
808 TRACE("Remounted automount \"%s\" on \"%s\" %s with flags %lu", source
, destination
, (mflags
& MS_RDONLY
) ? "read-only" : "read-write", mflags
);
810 TRACE("Mounted automount \"%s\" on \"%s\" %s with flags %lu", source
, destination
, (mflags
& MS_RDONLY
) ? "read-only" : "read-write", mflags
);
813 if (flags
& LXC_AUTO_CGROUP_MASK
) {
816 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
817 /* If the type of cgroup mount was not specified, it depends on
818 * the container's capabilities as to what makes sense: if we
819 * have CAP_SYS_ADMIN, the read-only part can be remounted
820 * read-write anyway, so we may as well default to read-write;
821 * then the admin will not be given a false sense of security.
822 * (And if they really want mixed r/o r/w, then they can
823 * explicitly specify :mixed.) OTOH, if the container lacks
824 * CAP_SYS_ADMIN, do only default to :mixed, because then the
825 * container can't remount it read-write.
827 if ((cg_flags
== LXC_AUTO_CGROUP_NOSPEC
) || (cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
)) {
828 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
829 cg_flags
= has_cap(CAP_SYS_ADMIN
, conf
)
831 : LXC_AUTO_CGROUP_MIXED
;
833 cg_flags
= has_cap(CAP_SYS_ADMIN
, conf
)
834 ? LXC_AUTO_CGROUP_FULL_RW
835 : LXC_AUTO_CGROUP_FULL_MIXED
;
838 if (flags
& LXC_AUTO_CGROUP_FORCE
)
839 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
841 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
, handler
, cg_flags
))
842 return log_error_errno(-1, errno
, "Failed to mount \"/sys/fs/cgroup\"");
845 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
846 ret
= add_shmount_to_list(conf
);
848 return log_error(-1, "Failed to add shmount entry to container config");
854 static int setup_utsname(struct utsname
*utsname
)
861 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
863 return log_error_errno(-1, errno
, "Failed to set the hostname to \"%s\"",
866 INFO("Set hostname to \"%s\"", utsname
->nodename
);
871 struct dev_symlinks
{
876 static const struct dev_symlinks dev_symlinks
[] = {
877 { "/proc/self/fd", "fd" },
878 { "/proc/self/fd/0", "stdin" },
879 { "/proc/self/fd/1", "stdout" },
880 { "/proc/self/fd/2", "stderr" },
883 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
885 for (size_t i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
888 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
891 * Stat the path first. If we don't get an error accept it as
892 * is and don't try to create it
894 ret
= fstatat(rootfs
->dfd_dev
, d
->name
, &s
, 0);
898 ret
= symlinkat(d
->oldpath
, rootfs
->dfd_dev
, d
->name
);
902 WARN("Failed to create \"%s\" on read-only filesystem", d
->name
);
907 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", d
->name
);
915 /* Build a space-separate list of ptys to pass to systemd. */
916 static bool append_ttyname(char **pp
, char *name
)
922 *pp
= zalloc(strlen(name
) + strlen("container_ttys=") + 1);
926 sprintf(*pp
, "container_ttys=%s", name
);
930 size
= strlen(*pp
) + strlen(name
) + 2;
931 p
= realloc(*pp
, size
);
936 (void)strlcat(p
, " ", size
);
937 (void)strlcat(p
, name
, size
);
942 static int open_ttymnt_at(int dfd
, const char *path
)
946 fd
= open_at(dfd
, path
,
947 PROTECT_OPEN
| O_CREAT
| O_EXCL
,
948 PROTECT_LOOKUP_BENEATH
,
951 if (!IN_SET(errno
, ENXIO
, EEXIST
))
952 return syserror("Failed to create \"%d/\%s\"", dfd
, path
);
954 SYSINFO("Failed to create \"%d/\%s\"", dfd
, path
);
955 fd
= open_at(dfd
, path
,
957 PROTECT_LOOKUP_BENEATH
,
964 static int lxc_setup_ttys(struct lxc_conf
*conf
)
967 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
968 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
969 char *ttydir
= ttys
->dir
;
971 if (!conf
->rootfs
.path
)
974 for (size_t i
= 0; i
< ttys
->max
; i
++) {
975 __do_close
int fd_to
= -EBADF
;
976 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
979 char *tty_name
, *tty_path
;
981 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
982 "/dev/%s/tty%zu", ttydir
, i
+ 1);
984 return ret_errno(-EIO
);
986 tty_path
= &rootfs
->buf
[STRLITERALLEN("/dev/")];
987 tty_name
= tty_path
+ strlen(ttydir
) + 1;
989 /* create bind-mount target */
990 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, tty_path
);
992 return log_error_errno(-errno
, errno
,
993 "Failed to create tty mount target %d(%s)",
994 rootfs
->dfd_dev
, tty_path
);
996 ret
= unlinkat(rootfs
->dfd_dev
, tty_name
, 0);
997 if (ret
< 0 && errno
!= ENOENT
)
998 return log_error_errno(-errno
, errno
,
999 "Failed to unlink %d(%s)",
1000 rootfs
->dfd_dev
, tty_name
);
1002 if (can_use_mount_api())
1003 ret
= fd_bind_mount(tty
->pty
, "",
1005 PROTECT_LOOKUP_BENEATH_XDEV
,
1008 PROTECT_LOOKUP_BENEATH_XDEV
,
1014 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1016 return log_error_errno(-errno
, errno
,
1017 "Failed to bind mount \"%s\" onto \"%s\"",
1018 tty
->name
, rootfs
->buf
);
1019 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1021 ret
= symlinkat(tty_path
, rootfs
->dfd_dev
, tty_name
);
1023 return log_error_errno(-errno
, errno
,
1024 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
1025 rootfs
->dfd_dev
, tty_name
,
1026 rootfs
->dfd_dev
, tty_path
);
1028 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "tty%zu", i
+ 1);
1030 return ret_errno(-EIO
);
1032 /* If we populated /dev, then we need to create /dev/tty<idx>. */
1033 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, rootfs
->buf
);
1035 return log_error_errno(-errno
, errno
,
1036 "Failed to create tty mount target %d(%s)",
1037 rootfs
->dfd_dev
, rootfs
->buf
);
1039 if (can_use_mount_api())
1040 ret
= fd_bind_mount(tty
->pty
, "",
1042 PROTECT_LOOKUP_BENEATH_XDEV
,
1045 PROTECT_LOOKUP_BENEATH
,
1051 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1053 return log_error_errno(-errno
, errno
,
1054 "Failed to bind mount \"%s\" onto \"%s\"",
1055 tty
->name
, rootfs
->buf
);
1056 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1059 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
))
1060 return log_error(-1, "Error setting up container_ttys string");
1063 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
1067 define_cleanup_function(struct lxc_tty_info
*, lxc_delete_tty
);
1069 static int lxc_allocate_ttys(struct lxc_conf
*conf
)
1071 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*ttys
= &conf
->ttys
;
1074 /* no tty in the configuration */
1078 ttys
->tty
= zalloc(sizeof(struct lxc_terminal_info
) * ttys
->max
);
1082 for (size_t i
= 0; i
< conf
->ttys
.max
; i
++) {
1084 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1086 ret
= lxc_devpts_terminal(conf
->devpts_fd
, &tty
->ptx
,
1087 &tty
->pty
, &pty_nr
, false);
1090 return syserror_set(-ENOTTY
, "Failed to create tty %zu", i
);
1092 DEBUG("Created tty with ptx fd %d and pty fd %d and index %d",
1093 tty
->ptx
, tty
->pty
, pty_nr
);
1097 INFO("Finished creating %zu tty devices", ttys
->max
);
1102 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1104 if (!ttys
|| !ttys
->tty
)
1107 for (size_t i
= 0; i
< ttys
->max
; i
++) {
1108 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1109 close_prot_errno_disarm(tty
->ptx
);
1110 close_prot_errno_disarm(tty
->pty
);
1113 free_disarm(ttys
->tty
);
1116 static int __lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1119 struct lxc_conf
*conf
= handler
->conf
;
1120 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1121 int sock
= handler
->data_sock
[0];
1126 for (size_t i
= 0; i
< ttys
->max
; i
++) {
1128 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1130 ttyfds
[0] = tty
->ptx
;
1131 ttyfds
[1] = tty
->pty
;
1133 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1137 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1138 tty
->name
, tty
->ptx
, tty
->pty
);
1142 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1144 TRACE("Sent %zu ttys to parent", ttys
->max
);
1149 static int lxc_create_ttys(struct lxc_handler
*handler
)
1152 struct lxc_conf
*conf
= handler
->conf
;
1154 ret
= lxc_allocate_ttys(conf
);
1156 ERROR("Failed to allocate ttys");
1160 if (!conf
->is_execute
) {
1161 ret
= lxc_setup_ttys(conf
);
1163 ERROR("Failed to setup ttys");
1168 if (conf
->ttys
.tty_names
) {
1169 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1171 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1179 lxc_delete_tty(&conf
->ttys
);
1184 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1188 ret
= __lxc_send_ttys_to_parent(handler
);
1189 lxc_delete_tty(&handler
->conf
->ttys
);
1193 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1194 * error, log it but don't fail yet.
1196 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1197 int autodevtmpfssize
, const char *lxcpath
)
1199 __do_close
int fd_fs
= -EBADF
;
1200 const char *path
= rootfs
->path
? rootfs
->mount
: NULL
;
1201 size_t tmpfs_size
= (autodevtmpfssize
!= 0) ? autodevtmpfssize
: 500000;
1204 char mount_options
[128];
1206 INFO("Preparing \"/dev\"");
1208 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1209 ret
= mkdirat(rootfs
->dfd_mnt
, "dev" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1210 if (ret
< 0 && errno
!= EEXIST
) {
1211 SYSERROR("Failed to create \"/dev\" directory");
1216 if (can_use_mount_api()) {
1217 fd_fs
= fs_prepare("tmpfs", -EBADF
, "", 0, 0);
1219 return log_error_errno(-errno
, errno
, "Failed to prepare filesystem context for tmpfs");
1221 sprintf(mount_options
, "%zu", tmpfs_size
);
1223 ret
= fs_set_property(fd_fs
, "mode", "0755");
1225 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1227 ret
= fs_set_property(fd_fs
, "size", mount_options
);
1229 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1231 ret
= fs_attach(fd_fs
, rootfs
->dfd_mnt
, "dev",
1232 PROTECT_OPATH_DIRECTORY
,
1233 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1235 __do_free
char *fallback_path
= NULL
;
1237 sprintf(mount_options
, "size=%zu,mode=755", tmpfs_size
);
1238 DEBUG("Using mount options: %s", mount_options
);
1241 fallback_path
= must_make_path(path
, "/dev", NULL
);
1242 ret
= safe_mount("none", fallback_path
, "tmpfs", 0, mount_options
, path
);
1244 ret
= safe_mount("none", "dev", "tmpfs", 0, mount_options
, NULL
);
1248 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1252 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1253 * If not, then create it and exit if that fails...
1255 ret
= mkdirat(rootfs
->dfd_mnt
, "dev/pts", S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1256 if (ret
< 0 && errno
!= EEXIST
) {
1257 SYSERROR("Failed to create directory \"dev/pts\"");
1265 (void)umask(cur_mask
);
1267 INFO("Prepared \"/dev\"");
1271 struct lxc_device_node
{
1278 static const struct lxc_device_node lxc_devices
[] = {
1279 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1280 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1281 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1282 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1283 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1284 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1291 LXC_DEVNODE_PARTIAL
,
1295 static int lxc_fill_autodev(struct lxc_rootfs
*rootfs
)
1299 int use_mknod
= LXC_DEVNODE_MKNOD
;
1301 if (rootfs
->dfd_dev
< 0)
1302 return log_info(0, "No /dev directory found, skipping setup");
1304 INFO("Populating \"/dev\"");
1306 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1307 for (size_t i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1308 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1310 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1311 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, device
->mode
, makedev(device
->maj
, device
->min
));
1312 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1313 DEBUG("Created device node \"%s\"", device
->name
);
1314 } else if (ret
< 0) {
1316 return log_error_errno(-1, errno
, "Failed to create device node \"%s\"", device
->name
);
1318 use_mknod
= LXC_DEVNODE_BIND
;
1321 /* Device nodes are fully useable. */
1322 if (use_mknod
== LXC_DEVNODE_OPEN
)
1325 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1326 __do_close
int fd
= -EBADF
;
1328 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1329 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1331 fd
= open_at(rootfs
->dfd_dev
, device
->name
, PROTECT_OPEN
, PROTECT_LOOKUP_BENEATH
, 0);
1333 /* Device nodes are fully useable. */
1334 use_mknod
= LXC_DEVNODE_OPEN
;
1338 SYSTRACE("Failed to open \"%s\" device", device
->name
);
1339 /* Device nodes are only partially useable. */
1340 use_mknod
= LXC_DEVNODE_PARTIAL
;
1344 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1345 /* If we are dealing with partially functional device
1346 * nodes the prio mknod() call will have created the
1347 * device node so we can use it as a bind-mount target.
1349 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, S_IFREG
| 0000, 0);
1350 if (ret
< 0 && errno
!= EEXIST
)
1351 return log_error_errno(-1, errno
, "Failed to create file \"%s\"", device
->name
);
1354 /* Fallback to bind-mounting the device from the host. */
1355 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "dev/%s", device
->name
);
1357 return ret_errno(EIO
);
1359 if (can_use_mount_api()) {
1360 ret
= fd_bind_mount(rootfs
->dfd_host
, rootfs
->buf
,
1362 PROTECT_LOOKUP_BENEATH_XDEV
,
1363 rootfs
->dfd_dev
, device
->name
,
1365 PROTECT_LOOKUP_BENEATH
,
1371 char path
[PATH_MAX
];
1373 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/dev/%s", device
->name
);
1375 return ret_errno(EIO
);
1377 ret
= strnprintf(path
, sizeof(path
), "%s/dev/%s", get_rootfs_mnt(rootfs
), device
->name
);
1379 return log_error(-1, "Failed to create device path for %s", device
->name
);
1381 ret
= safe_mount(rootfs
->buf
, path
, 0, MS_BIND
, NULL
, get_rootfs_mnt(rootfs
));
1383 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1385 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1388 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs
->dfd_host
, rootfs
->buf
, rootfs
->dfd_dev
, device
->name
);
1392 INFO("Populated \"/dev\"");
1396 static int lxc_mount_rootfs(struct lxc_rootfs
*rootfs
)
1400 if (!rootfs
->path
) {
1401 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1403 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
1405 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1406 if (rootfs
->dfd_mnt
< 0)
1409 return log_trace(0, "Container doesn't use separate rootfs. Opened host's rootfs");
1412 ret
= access(rootfs
->mount
, F_OK
);
1414 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1417 ret
= rootfs
->storage
->ops
->mount(rootfs
->storage
);
1419 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1420 rootfs
->path
, rootfs
->mount
,
1421 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
1423 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1424 rootfs
->path
, rootfs
->mount
,
1425 rootfs
->mnt_opts
.raw_options
? rootfs
->mnt_opts
.raw_options
: "(null)");
1427 rootfs
->dfd_mnt
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1428 if (rootfs
->dfd_mnt
< 0)
1431 return log_trace(0, "Container uses separate rootfs. Opened container's rootfs");
1434 static bool lxc_rootfs_overmounted(struct lxc_rootfs
*rootfs
)
1436 __do_close
int fd_rootfs
= -EBADF
;
1439 fd_rootfs
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1441 fd_rootfs
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1445 if (!same_file_lax(rootfs
->dfd_mnt
, fd_rootfs
))
1446 return syswarn_ret(true, "Rootfs seems to have changed after setting up mounts");
1451 static int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1453 __do_free
char *nroot
= NULL
;
1455 char *root
= rootfs
->mount
;
1457 nroot
= realpath(root
, NULL
);
1459 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1465 /* We could use here MS_MOVE, but in userns this mount is locked and
1468 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1470 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1472 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1474 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1476 /* The following code cleans up inherited mounts which are not required
1479 * The mountinfo file shows not all mounts, if a few points have been
1480 * unmounted between read operations from the mountinfo. So we need to
1481 * read mountinfo a few times.
1483 * This loop can be skipped if a container uses userns, because all
1484 * inherited mounts are locked and we should live with all this trash.
1487 __do_fclose
FILE *f
= NULL
;
1488 __do_free
char *line
= NULL
;
1489 char *slider1
, *slider2
;
1493 f
= fopen("./proc/self/mountinfo", "re");
1495 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1497 while (getline(&line
, &len
, f
) > 0) {
1498 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1499 slider1
= strchr(slider1
+ 1, ' ');
1504 slider2
= strchr(slider1
+ 1, ' ');
1511 if (strequal(slider1
+ 1, "/"))
1514 if (strequal(slider1
+ 1, "/proc"))
1517 ret
= umount2(slider1
, MNT_DETACH
);
1526 /* This also can be skipped if a container uses userns. */
1527 (void)umount2("./proc", MNT_DETACH
);
1529 /* It is weird, but chdir("..") moves us in a new root */
1532 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1536 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1541 /* (The following explanation is copied verbatim from the kernel.)
1543 * pivot_root Semantics:
1544 * Moves the root file system of the current process to the directory put_old,
1545 * makes new_root as the new root file system of the current process, and sets
1546 * root/cwd of all processes which had them on the current root to new_root.
1549 * The new_root and put_old must be directories, and must not be on the
1550 * same file system as the current process root. The put_old must be
1551 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1552 * pointed to by put_old must yield the same directory as new_root. No other
1553 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1555 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1556 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1557 * in this situation.
1560 * - we don't move root/cwd if they are not at the root (reason: if something
1561 * cared enough to change them, it's probably wrong to force them elsewhere)
1562 * - it's okay to pick a root that isn't the root of a file system, e.g.
1563 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1564 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1567 static int lxc_pivot_root(const struct lxc_rootfs
*rootfs
)
1569 __do_close
int fd_oldroot
= -EBADF
;
1572 fd_oldroot
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1574 return log_error_errno(-1, errno
, "Failed to open old root directory");
1576 /* change into new root fs */
1577 ret
= fchdir(rootfs
->dfd_mnt
);
1579 return log_error_errno(-errno
, errno
, "Failed to change into new root directory \"%s\"", rootfs
->mount
);
1581 /* pivot_root into our new root fs */
1582 ret
= pivot_root(".", ".");
1584 return log_error_errno(-errno
, errno
, "Failed to pivot into new root directory \"%s\"", rootfs
->mount
);
1586 /* At this point the old-root is mounted on top of our new-root. To
1587 * unmounted it we must not be chdir'd into it, so escape back to
1590 ret
= fchdir(fd_oldroot
);
1592 return log_error_errno(-errno
, errno
, "Failed to enter old root directory");
1595 * Make fd_oldroot a depedent mount to make sure our umounts don't
1596 * propagate to the host.
1598 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1600 return log_error_errno(-errno
, errno
, "Failed to recursively turn old root mount tree into dependent mount");
1602 ret
= umount2(".", MNT_DETACH
);
1604 return log_error_errno(-errno
, errno
, "Failed to detach old root directory");
1606 ret
= fchdir(rootfs
->dfd_mnt
);
1608 return log_error_errno(-errno
, errno
, "Failed to re-enter new root directory \"%s\"", rootfs
->mount
);
1610 TRACE("Changed into new rootfs \"%s\"", rootfs
->mount
);
1614 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1617 return log_debug(0, "Container does not have a rootfs");
1619 if (detect_ramfs_rootfs())
1620 return lxc_chroot(rootfs
);
1622 return lxc_pivot_root(rootfs
);
1625 static const struct id_map
*find_mapped_nsid_entry(const struct lxc_conf
*conf
,
1630 struct id_map
*retmap
= NULL
;
1632 /* Shortcut for container's root mappings. */
1634 if (idtype
== ID_TYPE_UID
)
1635 return conf
->root_nsuid_map
;
1637 if (idtype
== ID_TYPE_GID
)
1638 return conf
->root_nsgid_map
;
1641 list_for_each_entry(map
, &conf
->id_map
, head
) {
1642 if (map
->idtype
!= idtype
)
1645 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1654 static int lxc_recv_devpts_from_child(struct lxc_handler
*handler
)
1658 if (handler
->conf
->pty_max
<= 0)
1661 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1],
1662 &handler
->conf
->devpts_fd
,
1663 &handler
->conf
->devpts_fd
,
1664 sizeof(handler
->conf
->devpts_fd
));
1666 return log_error_errno(-1, errno
, "Failed to receive devpts fd from child");
1668 TRACE("Received devpts file descriptor %d from child", handler
->conf
->devpts_fd
);
1672 static int lxc_setup_devpts_child(struct lxc_handler
*handler
)
1674 __do_close
int devpts_fd
= -EBADF
, fd_fs
= -EBADF
;
1675 struct lxc_conf
*conf
= handler
->conf
;
1676 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1677 size_t pty_max
= conf
->pty_max
;
1680 pty_max
+= conf
->ttys
.max
;
1682 return log_debug(0, "No new devpts instance will be mounted since no pts devices are required");
1684 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
1685 "/proc/self/fd/%d/pts", rootfs
->dfd_dev
);
1687 return syserror("Failed to create path");
1689 (void)umount2(rootfs
->buf
, MNT_DETACH
);
1691 /* Create mountpoint for devpts instance. */
1692 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1693 if (ret
< 0 && errno
!= EEXIST
)
1694 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1696 if (can_use_mount_api()) {
1697 fd_fs
= fs_prepare("devpts", -EBADF
, "", 0, 0);
1699 return syserror("Failed to prepare filesystem context for devpts");
1701 ret
= fs_set_property(fd_fs
, "source", "devpts");
1703 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs
);
1705 ret
= fs_set_property(fd_fs
, "gid", "5");
1707 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs
);
1709 ret
= fs_set_flag(fd_fs
, "newinstance");
1711 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs
);
1713 ret
= fs_set_property(fd_fs
, "ptmxmode", "0666");
1715 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs
);
1717 ret
= fs_set_property(fd_fs
, "mode", "0620");
1719 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs
);
1721 ret
= fs_set_property(fd_fs
, "max", fdstr(pty_max
));
1723 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf
->pty_max
, fd_fs
);
1725 ret
= fsconfig(fd_fs
, FSCONFIG_CMD_CREATE
, NULL
, NULL
, 0);
1727 return syserror("Failed to finalize filesystem context %d", fd_fs
);
1729 devpts_fd
= fsmount(fd_fs
, FSMOUNT_CLOEXEC
, MOUNT_ATTR_NOSUID
| MOUNT_ATTR_NOEXEC
);
1731 return syserror("Failed to create new mount for filesystem context %d", fd_fs
);
1732 TRACE("Created detached devpts mount %d", devpts_fd
);
1734 ret
= move_mount(devpts_fd
, "", rootfs
->dfd_dev
, "pts", MOVE_MOUNT_F_EMPTY_PATH
);
1736 return syserror("Failed to attach devpts mount %d to %d/pts", conf
->devpts_fd
, rootfs
->dfd_dev
);
1738 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd
, rootfs
->dfd_dev
);
1741 char devpts_mntopts
[256];
1742 char *mntopt_sets
[5];
1743 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1746 * Fallback codepath in case the new mount API can't be used to
1747 * create detached mounts.
1750 ret
= strnprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1751 default_devpts_mntopts
, pty_max
);
1755 /* Create mountpoint for devpts instance. */
1756 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1757 if (ret
< 0 && errno
!= EEXIST
)
1758 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1761 mntopt_sets
[0] = devpts_mntopts
;
1763 /* !gid=5 && max= */
1764 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1766 /* gid=5 && !max= */
1767 mntopt_sets
[2] = default_devpts_mntopts
;
1769 /* !gid=5 && !max= */
1770 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1773 mntopt_sets
[4] = NULL
;
1775 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1776 /* mount new devpts instance */
1777 ret
= mount_at(rootfs
->dfd_dev
, "", 0,
1778 rootfs
->dfd_dev
, "pts", PROTECT_LOOKUP_BENEATH
,
1779 "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1784 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1786 devpts_fd
= open_at(rootfs
->dfd_dev
, "pts", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1787 if (devpts_fd
< 0) {
1789 TRACE("Failed to create detached devpts mount");
1792 DEBUG("Mounted new devpts instance with options \"%s\"", *opts
);
1795 handler
->conf
->devpts_fd
= move_fd(devpts_fd
);
1798 * In order to allocate terminal devices the devpts filesystem will
1799 * have to be attached to the filesystem at least ones in the new mount
1800 * api. The reason is lengthy but the gist is that until the new mount
1801 * has been attached to the filesystem it is a detached mount with an
1802 * anonymous mount mamespace attached to it for which the kernel
1803 * refuses certain operations.
1804 * We end up here if the user has requested to allocate tty devices
1805 * while not requestig pty devices be made available to the container.
1806 * We only need the devpts_fd to allocate tty devices.
1808 if (conf
->pty_max
<= 0)
1811 /* Remove any pre-existing /dev/ptmx file. */
1812 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1814 if (errno
!= ENOENT
)
1815 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1817 DEBUG("Removed existing \"/dev/ptmx\" file");
1820 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1821 ret
= mknodat(rootfs
->dfd_dev
, "ptmx", S_IFREG
| 0000, 0);
1822 if (ret
< 0 && errno
!= EEXIST
)
1823 return log_error_errno(-1, errno
, "Failed to create \"/dev/ptmx\" file as bind mount target");
1824 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
1826 /* Main option: use a bind-mount to please AppArmor */
1827 ret
= mount_at(rootfs
->dfd_dev
, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1828 rootfs
->dfd_dev
, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1829 NULL
, MS_BIND
, NULL
);
1831 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1833 /* Fallthrough and try to create a symlink. */
1834 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1836 /* Remove the placeholder /dev/ptmx file we created above. */
1837 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1839 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1841 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1842 ret
= symlinkat("/dev/pts/ptmx", rootfs
->dfd_dev
, "dev/ptmx");
1844 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1846 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1850 static int lxc_finish_devpts_child(struct lxc_handler
*handler
)
1852 struct lxc_conf
*conf
= handler
->conf
;
1853 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1856 if (conf
->pty_max
> 0)
1860 * We end up here if the user has requested to allocate tty devices
1861 * while not requestig pty devices be made available to the container.
1862 * This means we can unmount the devpts instance. We only need the
1863 * devpts_fd to allocate tty devices.
1865 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
1866 "/proc/self/fd/%d/pts", rootfs
->dfd_dev
);
1868 return syserror("Failed to create path");
1870 close_prot_errno_disarm(conf
->devpts_fd
);
1871 (void)umount2(rootfs
->buf
, MNT_DETACH
);
1875 static int lxc_send_devpts_to_parent(struct lxc_handler
*handler
)
1879 if (handler
->conf
->pty_max
<= 0)
1880 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1882 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->conf
->devpts_fd
, 1, NULL
, 0);
1884 SYSERROR("Failed to send devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1886 TRACE("Sent devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1888 close_prot_errno_disarm(handler
->conf
->devpts_fd
);
1893 static int setup_personality(personality_t persona
)
1897 if (persona
== LXC_ARCH_UNCHANGED
)
1898 return log_debug(0, "Retaining original personality");
1900 ret
= lxc_personality(persona
);
1902 return syserror("Failed to set personality to \"0lx%lx\"", persona
);
1904 INFO("Set personality to \"0lx%lx\"", persona
);
1908 static int bind_mount_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1909 struct lxc_terminal
*console
, int fd_to
)
1911 __do_close
int fd_pty
= -EBADF
;
1913 if (is_empty_string(console
->name
))
1914 return ret_errno(EINVAL
);
1917 * When the pty fd stashed in console->pty has been retrieved via the
1918 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1919 * allocating new pty devices we can't reopen it through openat2() or
1920 * created a detached mount through open_tree() from it. This means we
1921 * would need to mount using the path stased in console->name which is
1922 * unsafe. We could be mounting a device that isn't identical to the
1923 * one we've already safely opened and stashed in console->pty.
1924 * So, what we do is we open an O_PATH file descriptor for
1925 * console->name and verify that the opened fd and the fd we stashed in
1926 * console->pty refer to the same device. If they do we can go on and
1927 * created a detached mount based on the newly opened O_PATH file
1928 * descriptor and then safely mount.
1930 fd_pty
= open_at_same(console
->pty
, fd_devpts
, fdstr(console
->pty_nr
),
1931 PROTECT_OPATH_FILE
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1933 return syserror("Failed to open \"%s\"", console
->name
);
1936 * Note, there are intentionally no open or lookup restrictions since
1937 * we're operating directly on the fd.
1939 if (can_use_mount_api())
1940 return fd_bind_mount(fd_pty
, "", 0, 0, fd_to
, "", 0, 0, 0, 0, 0, false);
1942 return mount_fd(fd_pty
, fd_to
, "none", MS_BIND
, 0);
1945 static int lxc_setup_dev_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1946 struct lxc_terminal
*console
)
1948 __do_close
int fd_console
= -EBADF
;
1952 * When we are asked to setup a console we remove any previous
1953 * /dev/console bind-mounts.
1955 if (exists_file_at(rootfs
->dfd_dev
, "console")) {
1956 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1958 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
1962 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
1964 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
1966 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
1970 * For unprivileged containers autodev or automounts will already have
1971 * taken care of creating /dev/console.
1973 fd_console
= open_at(rootfs
->dfd_dev
,
1975 PROTECT_OPEN
| O_CREAT
,
1976 PROTECT_LOOKUP_BENEATH
,
1979 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
1981 ret
= fchmod(console
->pty
, 0620);
1983 return syserror("Failed to change console mode");
1985 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_console
);
1987 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1988 console
->pty
, console
->name
, fd_console
);
1990 TRACE("Setup console \"%s\"", console
->name
);
1994 static int lxc_setup_ttydir_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1995 struct lxc_terminal
*console
,
1998 __do_close
int fd_ttydir
= -EBADF
, fd_dev_console
= -EBADF
,
1999 fd_reg_console
= -EBADF
, fd_reg_ttydir_console
= -EBADF
;
2002 /* create dev/<ttydir> */
2003 ret
= mkdirat(rootfs
->dfd_dev
, ttydir
, 0755);
2004 if (ret
< 0 && errno
!= EEXIST
)
2005 return syserror("Failed to create \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
2007 fd_ttydir
= open_at(rootfs
->dfd_dev
,
2009 PROTECT_OPATH_DIRECTORY
,
2010 PROTECT_LOOKUP_BENEATH
,
2013 return syserror("Failed to open \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
2015 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/console", ttydir
);
2019 /* create dev/<ttydir>/console */
2020 fd_reg_ttydir_console
= open_at(fd_ttydir
,
2022 PROTECT_OPEN
| O_CREAT
,
2023 PROTECT_LOOKUP_BENEATH
,
2025 if (fd_reg_ttydir_console
< 0)
2026 return syserror("Failed to create \"%d/console\"", fd_ttydir
);
2028 if (file_exists(rootfs
->buf
)) {
2029 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
2031 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
2035 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
2037 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
2039 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
2042 /* create dev/console */
2043 fd_reg_console
= open_at(rootfs
->dfd_dev
,
2045 PROTECT_OPEN
| O_CREAT
,
2046 PROTECT_LOOKUP_BENEATH
,
2048 if (fd_reg_console
< 0)
2049 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
2051 ret
= fchmod(console
->pty
, 0620);
2053 return syserror("Failed to change console mode");
2055 /* bind mount console to '/dev/<ttydir>/console' */
2056 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_reg_ttydir_console
);
2058 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2059 console
->pty
, console
->name
, fd_reg_ttydir_console
);
2061 fd_dev_console
= open_at_same(console
->pty
,
2065 PROTECT_LOOKUP_BENEATH_XDEV
,
2067 if (fd_dev_console
< 0)
2068 return syserror("Failed to open \"%d/console\"", fd_ttydir
);
2070 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
2071 if (can_use_mount_api())
2072 ret
= fd_bind_mount(fd_dev_console
,
2075 PROTECT_LOOKUP_BENEATH_XDEV
,
2079 PROTECT_LOOKUP_BENEATH
,
2085 ret
= mount_fd(fd_dev_console
, fd_reg_console
, "none", MS_BIND
, 0);
2087 return syserror("Failed to mount \"%d\" on \"%d\"",
2088 fd_dev_console
, fd_reg_console
);
2090 TRACE("Setup console \"%s\"", console
->name
);
2094 static int lxc_setup_console(const struct lxc_handler
*handler
,
2095 struct lxc_rootfs
*rootfs
,
2096 struct lxc_terminal
*console
, char *ttydir
)
2098 __do_close
int fd_devpts_host
= -EBADF
;
2099 int fd_devpts
= handler
->conf
->devpts_fd
;
2102 if (!wants_console(console
))
2103 return log_trace(0, "Skipping console setup");
2105 if (console
->pty
< 0) {
2107 * Allocate a console from the container's devpts instance. We
2108 * have checked on the host that we have enough pty devices
2111 ret
= lxc_devpts_terminal(handler
->conf
->devpts_fd
, &console
->ptx
,
2112 &console
->pty
, &console
->pty_nr
, false);
2114 return syserror("Failed to allocate console from container's devpts instance");
2116 ret
= strnprintf(console
->name
, sizeof(console
->name
),
2117 "/dev/pts/%d", console
->pty_nr
);
2119 return syserror("Failed to create console path");
2122 * We're using a console from the host's devpts instance. Open
2123 * it again so we can later verify that the console we're
2124 * supposed to use is still the same as the one we opened on
2127 fd_devpts_host
= open_at(rootfs
->dfd_host
,
2129 PROTECT_OPATH_DIRECTORY
,
2130 PROTECT_LOOKUP_BENEATH_XDEV
,
2132 if (fd_devpts_host
< 0)
2133 return syserror("Failed to open host devpts");
2135 fd_devpts
= fd_devpts_host
;
2139 ret
= lxc_setup_ttydir_console(fd_devpts
, rootfs
, console
, ttydir
);
2141 ret
= lxc_setup_dev_console(fd_devpts
, rootfs
, console
);
2143 return syserror("Failed to setup console");
2146 * Some init's such as busybox will set sane tty settings on stdin,
2147 * stdout, stderr which it thinks is the console. We already set them
2148 * the way we wanted on the real terminal, and we want init to do its
2149 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2150 * make sure that that pty is stdin,stdout,stderr.
2152 if (console
->pty
>= 0) {
2153 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
2154 ret
= set_stdfds(console
->pty
);
2156 ret
= lxc_terminal_set_stdfds(console
->pty
);
2158 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console
->pty
);
2161 * If the console has been allocated from the host's devpts
2162 * we're done and we don't need to send fds to the parent.
2164 if (fd_devpts_host
>= 0)
2165 lxc_terminal_delete(console
);
2171 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
2175 /* If '=' is contained in opt, the option must go into data. */
2176 if (!strchr(opt
, '=')) {
2178 * If opt is found in mount_opt, set or clear flags.
2179 * Otherwise append it to data.
2181 size_t opt_len
= strlen(opt
);
2182 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2183 size_t mo_name_len
= strlen(mo
->name
);
2185 if (opt_len
== mo_name_len
&& strnequal(opt
, mo
->name
, mo_name_len
)) {
2187 *flags
&= ~mo
->legacy_flag
;
2189 *flags
|= mo
->legacy_flag
;
2195 if (strlen(*data
)) {
2196 ret
= strlcat(*data
, ",", size
);
2198 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
2201 ret
= strlcat(*data
, opt
, size
);
2203 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
2208 int parse_mntopts_legacy(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
2210 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2211 char *mntopt_cur
= NULL
;
2214 if (*mntdata
|| *mntflags
)
2215 return ret_errno(EINVAL
);
2220 mntopts_dup
= strdup(mntopts
);
2222 return ret_errno(ENOMEM
);
2224 size
= strlen(mntopts_dup
) + 1;
2225 mntopts_new
= zalloc(size
);
2227 return ret_errno(ENOMEM
);
2229 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
2230 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
2231 return ret_errno(EINVAL
);
2234 *mntdata
= move_ptr(mntopts_new
);
2239 static int parse_vfs_attr(struct lxc_mount_options
*opts
, char *opt
, size_t size
)
2242 * If opt is found in mount_opt, set or clear flags.
2243 * Otherwise append it to data.
2245 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2246 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2249 /* This is a recursive bind-mount. */
2250 if (strequal(mo
->name
, "rbind")) {
2251 opts
->bind_recursively
= 1;
2253 opts
->mnt_flags
|= mo
->legacy_flag
; /* MS_BIND | MS_REC */
2257 /* This is a bind-mount. */
2258 if (strequal(mo
->name
, "bind")) {
2260 opts
->mnt_flags
|= mo
->legacy_flag
; /* MS_BIND */
2264 if (mo
->flag
== (__u64
)~0)
2265 return log_info(0, "Ignoring %s mount option", mo
->name
);
2268 opts
->attr
.attr_clr
|= mo
->flag
;
2269 opts
->mnt_flags
&= ~mo
->legacy_flag
;
2270 TRACE("Lowering %s", mo
->name
);
2272 opts
->attr
.attr_set
|= mo
->flag
;
2273 opts
->mnt_flags
|= mo
->legacy_flag
;
2274 TRACE("Raising %s", mo
->name
);
2280 for (struct mount_opt
*mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
2281 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2284 if (strequal(mo
->name
, "rslave") ||
2285 strequal(mo
->name
, "rshared") ||
2286 strequal(mo
->name
, "runbindable") ||
2287 strequal(mo
->name
, "rprivate"))
2288 opts
->propagate_recursively
= 1;
2290 opts
->attr
.propagation
= mo
->flag
;
2291 opts
->prop_flags
|= mo
->legacy_flag
;
2298 int parse_mount_attrs(struct lxc_mount_options
*opts
, const char *mntopts
)
2300 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2301 char *end
= NULL
, *mntopt_cur
= NULL
;
2306 return ret_errno(EINVAL
);
2311 mntopts_dup
= strdup(mntopts
);
2313 return ret_errno(ENOMEM
);
2315 size
= strlen(mntopts_dup
) + 1;
2316 mntopts_new
= zalloc(size
);
2318 return ret_errno(ENOMEM
);
2320 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",") {
2321 /* This is a filesystem specific option. */
2322 if (strchr(mntopt_cur
, '=')) {
2324 end
= stpcpy(mntopts_new
, mntopt_cur
);
2326 end
= stpcpy(end
, ",");
2327 end
= stpcpy(end
, mntopt_cur
);
2333 /* This is a generic vfs option. */
2334 ret
= parse_vfs_attr(opts
, mntopt_cur
, size
);
2336 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur
);
2340 opts
->data
= move_ptr(mntopts_new
);
2345 static void null_endofword(char *word
)
2347 while (*word
&& *word
!= ' ' && *word
!= '\t')
2352 /* skip @nfields spaces in @src */
2353 static char *get_field(char *src
, int nfields
)
2358 for (i
= 0; i
< nfields
; i
++) {
2359 while (*p
&& *p
!= ' ' && *p
!= '\t')
2371 static int mount_entry(const char *fsname
, const char *target
,
2372 const char *fstype
, unsigned long mountflags
,
2373 unsigned long pflags
, const char *data
, bool optional
,
2374 bool dev
, bool relative
, const char *rootfs
)
2377 char srcbuf
[PATH_MAX
];
2378 const char *srcpath
= fsname
;
2384 ret
= strnprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2386 return log_error_errno(-1, errno
, "source path is too long");
2390 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2394 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2395 srcpath
? srcpath
: "(null)", target
);
2397 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2398 srcpath
? srcpath
: "(null)", target
);
2401 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2403 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2404 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2407 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2408 unsigned long required_flags
= 0;
2410 if (sb
.f_flag
& MS_NOSUID
)
2411 required_flags
|= MS_NOSUID
;
2413 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2414 required_flags
|= MS_NODEV
;
2416 if (sb
.f_flag
& MS_RDONLY
)
2417 required_flags
|= MS_RDONLY
;
2419 if (sb
.f_flag
& MS_NOEXEC
)
2420 required_flags
|= MS_NOEXEC
;
2422 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2423 srcpath
, sb
.f_flag
, required_flags
);
2425 /* If this was a bind mount request, and required_flags
2426 * does not have any flags which are not already in
2427 * mountflags, then skip the remount.
2429 if (!(mountflags
& MS_REMOUNT
) &&
2430 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
2431 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
2435 mountflags
|= required_flags
;
2439 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2442 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2443 srcpath
? srcpath
: "(null)",
2446 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2447 srcpath
? srcpath
: "(null)",
2456 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2459 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2461 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2463 DEBUG("Changed mount propagation for \"%s\"", target
);
2466 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2467 srcpath
? srcpath
: "(null)", target
, fstype
);
2472 const char *lxc_mount_options_info
[LXC_MOUNT_MAX
] = {
2480 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2481 int parse_lxc_mount_attrs(struct lxc_mount_options
*opts
, char *mnt_opts
)
2483 for (size_t i
= LXC_MOUNT_CREATE_DIR
; i
< LXC_MOUNT_MAX
; i
++) {
2484 __do_close
int fd_userns
= -EBADF
;
2485 const char *opt_name
= lxc_mount_options_info
[i
];
2487 char *idmap_path
, *opt
, *opt_next
;
2489 opt
= strstr(mnt_opts
, opt_name
);
2494 case LXC_MOUNT_CREATE_DIR
:
2495 opts
->create_dir
= 1;
2497 case LXC_MOUNT_CREATE_FILE
:
2498 opts
->create_file
= 1;
2500 case LXC_MOUNT_OPTIONAL
:
2503 case LXC_MOUNT_RELATIVE
:
2506 case LXC_MOUNT_IDMAP
:
2508 opt_next
+= STRLITERALLEN("idmap=");
2509 idmap_path
= strchrnul(opt_next
, ',');
2510 len
= idmap_path
- opt_next
+ 1;
2512 if (len
>= sizeof(opts
->userns_path
))
2513 return syserror_set(-EIO
, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2515 strlcpy(opts
->userns_path
, opt_next
, len
);
2517 if (is_empty_string(opts
->userns_path
))
2518 return syserror_set(-EINVAL
, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2520 if (!strequal(opts
->userns_path
, "container")) {
2521 fd_userns
= open(opts
->userns_path
, O_RDONLY
| O_NOCTTY
| O_CLOEXEC
);
2523 return syserror("Failed to open user namespace %s", opts
->userns_path
);
2526 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns
, opts
->userns_path
);
2529 return syserror_set(-EINVAL
, "Unknown LXC specific mount option");
2532 opt_next
= strchr(opt
, ',');
2534 *opt
= '\0'; /* no more mntopts, so just chop it here */
2536 memmove(opt
, opt_next
+ 1, strlen(opt_next
+ 1) + 1);
2542 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2544 const struct lxc_rootfs
*rootfs
,
2545 const char *lxc_name
, const char *lxc_path
)
2547 __do_free
char *p1
= NULL
;
2551 if (strnequal(mntent
->mnt_type
, "overlay", 7)) {
2552 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2557 if (hasmntopt(mntent
, "create=dir")) {
2558 ret
= mkdir_p(path
, 0755);
2559 if (ret
< 0 && errno
!= EEXIST
)
2560 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2563 if (!hasmntopt(mntent
, "create=file"))
2566 ret
= access(path
, F_OK
);
2576 ret
= mkdir_p(p2
, 0755);
2577 if (ret
< 0 && errno
!= EEXIST
)
2578 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2580 ret
= mknod(path
, S_IFREG
| 0000, 0);
2581 if (ret
< 0 && errno
!= EEXIST
)
2587 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2588 * without a rootfs. */
2589 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2591 const struct lxc_rootfs
*rootfs
,
2592 const char *lxc_name
,
2593 const char *lxc_path
)
2595 __do_free
char *mntdata
= NULL
;
2596 char *rootfs_path
= NULL
;
2598 bool dev
, optional
, relative
;
2599 struct lxc_mount_options opts
= {};
2601 optional
= hasmntopt(mntent
, "optional") != NULL
;
2602 dev
= hasmntopt(mntent
, "dev") != NULL
;
2603 relative
= hasmntopt(mntent
, "relative") != NULL
;
2605 if (rootfs
&& rootfs
->path
)
2606 rootfs_path
= rootfs
->mount
;
2608 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2617 ret
= parse_lxc_mount_attrs(&opts
, mntent
->mnt_opts
);
2622 * Idmapped mount entries will be setup by the parent for us. Note that
2623 * we rely on mount_entry_create_dir_file() above to have already
2624 * created the target path for us. So the parent can just open the
2625 * target and send us the target fd.
2628 if (!is_empty_string(opts
.userns_path
))
2629 return systrace_ret(0, "Skipping idmapped mount entry");
2631 ret
= parse_mount_attrs(&opts
, mntent
->mnt_opts
);
2635 ret
= mount_entry(mntent
->mnt_fsname
,
2649 static inline int mount_entry_on_systemfs(struct lxc_rootfs
*rootfs
,
2650 struct mntent
*mntent
)
2654 /* For containers created without a rootfs all mounts are treated as
2655 * absolute paths starting at / on the host.
2657 if (mntent
->mnt_dir
[0] != '/')
2658 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/%s", mntent
->mnt_dir
);
2660 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s", mntent
->mnt_dir
);
2664 return mount_entry_on_generic(mntent
, rootfs
->buf
, NULL
, NULL
, NULL
);
2667 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2668 struct lxc_rootfs
*rootfs
,
2669 const char *lxc_name
,
2670 const char *lxc_path
)
2674 const char *lxcpath
;
2677 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2681 /* If rootfs->path is a blockdev path, allow container fstab to use
2682 * <lxcpath>/<name>/rootfs" as the target prefix.
2684 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s/rootfs", lxcpath
, lxc_name
);
2688 aux
= strstr(mntent
->mnt_dir
, rootfs
->buf
);
2690 offset
= strlen(rootfs
->buf
);
2695 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2697 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2698 offset
= strlen(rootfs
->path
);
2701 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, aux
+ offset
);
2705 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2708 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2709 struct lxc_rootfs
*rootfs
,
2710 const char *lxc_name
,
2711 const char *lxc_path
)
2715 /* relative to root mount point */
2716 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2720 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2723 static int mount_file_entries(struct lxc_rootfs
*rootfs
, FILE *file
,
2724 const char *lxc_name
, const char *lxc_path
)
2727 struct mntent mntent
;
2729 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2733 ret
= mount_entry_on_systemfs(rootfs
, &mntent
);
2734 else if (mntent
.mnt_dir
[0] != '/')
2735 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2736 lxc_name
, lxc_path
);
2738 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2739 lxc_name
, lxc_path
);
2744 if (!feof(file
) || ferror(file
))
2745 return log_error(-1, "Failed to parse mount entries");
2750 static inline void __auto_endmntent__(FILE **f
)
2756 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2758 static int setup_mount_fstab(struct lxc_rootfs
*rootfs
, const char *fstab
,
2759 const char *lxc_name
, const char *lxc_path
)
2761 __do_endmntent
FILE *f
= NULL
;
2767 f
= setmntent(fstab
, "re");
2769 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2771 ret
= mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2773 ERROR("Failed to set up mount entries");
2779 * In order for nested containers to be able to mount /proc and /sys they need
2780 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2782 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2783 * apparmor rule to deny access to them. This is mostly for convenience: The
2784 * container's root user can mount them anyway and thus has access to the two
2785 * file systems. But a non-root user in the container should not be allowed to
2786 * access them as a side effect without explicitly allowing it.
2788 static const char nesting_helpers
[] =
2789 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2790 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2792 FILE *make_anonymous_mount_file(const struct list_head
*mount_entries
,
2793 bool include_nesting_helpers
)
2795 __do_close
int fd
= -EBADF
;
2798 struct string_entry
*entry
;
2800 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2802 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2804 if (errno
!= ENOSYS
)
2807 fd
= lxc_make_tmpfile(template, true);
2809 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2811 TRACE("Created temporary mount file");
2814 list_for_each_entry(entry
, mount_entries
, head
) {
2817 len
= strlen(entry
->val
);
2819 ret
= lxc_write_nointr(fd
, entry
->val
, len
);
2820 if (ret
< 0 || (size_t)ret
!= len
)
2823 ret
= lxc_write_nointr(fd
, "\n", 1);
2828 if (include_nesting_helpers
) {
2829 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2830 STRARRAYLEN(nesting_helpers
));
2831 if (ret
!= STRARRAYLEN(nesting_helpers
))
2835 ret
= lseek(fd
, 0, SEEK_SET
);
2839 f
= fdopen(fd
, "re+");
2841 move_fd(fd
); /* Transfer ownership of fd. */
2845 static int setup_mount_entries(const struct lxc_conf
*conf
,
2846 struct lxc_rootfs
*rootfs
,
2847 const char *lxc_name
, const char *lxc_path
)
2849 __do_fclose
FILE *f
= NULL
;
2851 f
= make_anonymous_mount_file(&conf
->mount_entries
, conf
->lsm_aa_allow_nesting
);
2855 return mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2858 static int __lxc_idmapped_mounts_child(struct lxc_handler
*handler
, FILE *f
)
2860 struct lxc_conf
*conf
= handler
->conf
;
2861 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
2865 struct mntent mntent
;
2867 while (getmntent_r(f
, &mntent
, buf
, sizeof(buf
))) {
2868 __do_close
int fd_from
= -EBADF
, fd_to
= -EBADF
,
2870 __do_free
char *__data
= NULL
;
2871 int cur_mnt_seq
= -1;
2872 struct lxc_mount_options opts
= {};
2874 const char *source_relative
, *target_relative
;
2875 struct lxc_mount_attr attr
= {};
2877 ret
= parse_lxc_mount_attrs(&opts
, mntent
.mnt_opts
);
2879 return syserror("Failed to parse LXC specific mount options");
2882 ret
= parse_mount_attrs(&opts
, mntent
.mnt_opts
);
2884 return syserror("Failed to parse mount options");
2886 /* No idmapped mount entry so skip it. */
2887 if (is_empty_string(opts
.userns_path
))
2890 if (!can_use_bind_mounts())
2891 return syserror_set(-EINVAL
, "Kernel does not support idmapped mounts");
2894 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2896 /* We don't support new filesystem mounts yet. */
2897 if (!is_empty_string(mntent
.mnt_type
) &&
2898 !strequal(mntent
.mnt_type
, "none"))
2899 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2901 /* Someone specified additional mount options for a bind-mount. */
2902 if (!is_empty_string(opts
.data
))
2903 return syserror_set(-EINVAL
, "Bind mounts don't support non-generic mount options");
2906 * The source path is supposed to be taken relative to the
2907 * container's rootfs mount or - if the container does not have
2908 * a separate rootfs - to the host's /.
2910 source_relative
= deabs(mntent
.mnt_fsname
);
2911 if (opts
.relative
|| !rootfs
->path
)
2912 dfd_from
= rootfs
->dfd_mnt
;
2914 dfd_from
= rootfs
->dfd_host
;
2915 fd_from
= open_tree(dfd_from
, source_relative
,
2916 OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
|
2917 (opts
.bind_recursively
? AT_RECURSIVE
: 0));
2919 return syserror("Failed to create detached %smount of %d/%s",
2920 opts
.bind_recursively
? "recursive " : "",
2921 dfd_from
, source_relative
);
2923 if (strequal(opts
.userns_path
, "container"))
2924 fd_userns
= openat(dfd_from
, "proc/self/ns/user", O_RDONLY
| O_CLOEXEC
);
2926 fd_userns
= open_at(-EBADF
, opts
.userns_path
,
2927 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
2928 if (fd_userns
< 0) {
2929 if (opts
.optional
) {
2930 TRACE("Skipping optional idmapped mount");
2934 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
2935 opts
.userns_path
, opts
.bind_recursively
? "recursive " : "",
2936 dfd_from
, source_relative
);
2939 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
2941 &opts
, sizeof(opts
));
2943 if (opts
.optional
) {
2944 TRACE("Skipping optional idmapped mount");
2948 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
2949 fd_from
, opts
.bind_recursively
? "recursive " : "",
2950 dfd_from
, source_relative
, fd_userns
,
2954 ret
= lxc_abstract_unix_rcv_credential(handler
->data_sock
[0],
2956 sizeof(cur_mnt_seq
));
2958 if (opts
.optional
) {
2959 TRACE("Skipping optional idmapped mount");
2963 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2964 opts
.bind_recursively
? "recursive " : "",
2965 dfd_from
, source_relative
, fd_userns
);
2968 if (mnt_seq
!= cur_mnt_seq
)
2969 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
2970 mnt_seq
, cur_mnt_seq
);
2973 /* Set regular mount options. */
2975 attr
.propagation
= 0;
2976 ret
= mount_setattr(fd_from
,
2979 (opts
.bind_recursively
? AT_RECURSIVE
: 0),
2983 if (opts
.optional
) {
2984 TRACE("Skipping optional idmapped mount");
2988 return syserror("Failed to set %smount options on detached %d/%s",
2989 opts
.bind_recursively
? "recursive " : "",
2990 dfd_from
, source_relative
);
2993 /* Set propagation mount options. */
2994 if (opts
.attr
.propagation
) {
2995 attr
= (struct lxc_mount_attr
) {
2996 .propagation
= opts
.attr
.propagation
,
2999 ret
= mount_setattr(fd_from
,
3002 (opts
.propagate_recursively
? AT_RECURSIVE
: 0),
3006 if (opts
.optional
) {
3007 TRACE("Skipping optional idmapped mount");
3011 return syserror("Failed to set %spropagation mount options on detached %d/%s",
3012 opts
.bind_recursively
? "recursive " : "",
3013 dfd_from
, source_relative
);
3019 * In contrast to the legacy mount codepath we will simplify
3020 * our lifes and just always treat the target mountpoint to be
3021 * relative to the container's rootfs mountpoint or - if the
3022 * container does not have a separate rootfs - to the host's /.
3025 target_relative
= deabs(mntent
.mnt_dir
);
3027 dfd_from
= rootfs
->dfd_mnt
;
3029 dfd_from
= rootfs
->dfd_host
;
3030 fd_to
= open_at(dfd_from
, target_relative
, PROTECT_OPATH_FILE
, PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
, 0);
3032 if (opts
.optional
) {
3033 TRACE("Skipping optional idmapped mount");
3037 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
3038 dfd_from
, target_relative
,
3039 opts
.bind_recursively
? "recursive " : "",
3040 fd_userns
, dfd_from
, source_relative
);
3043 ret
= move_detached_mount(fd_from
, fd_to
, "", 0, 0);
3045 if (opts
.optional
) {
3046 TRACE("Skipping optional idmapped mount");
3050 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3051 opts
.bind_recursively
? "recursive " : "",
3052 fd_userns
, dfd_from
, source_relative
, dfd_from
, target_relative
);
3055 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3056 opts
.bind_recursively
? "recursive " : "", fd_userns
, dfd_from
,
3057 source_relative
, dfd_from
, target_relative
);
3060 if (!feof(f
) || ferror(f
))
3061 return syserror_set(-EINVAL
, "Failed to parse mount entries");
3066 static int lxc_idmapped_mounts_child(struct lxc_handler
*handler
)
3068 __do_fclose
FILE *f_entries
= NULL
;
3070 struct lxc_conf
*conf
= handler
->conf
;
3071 const char *fstab
= conf
->fstab
;
3074 f_entries
= make_anonymous_mount_file(&conf
->mount_entries
,
3075 conf
->lsm_aa_allow_nesting
);
3077 SYSERROR("Failed to create anonymous mount file");
3081 ret
= __lxc_idmapped_mounts_child(handler
, f_entries
);
3083 SYSERROR("Failed to setup idmapped mount entries");
3087 TRACE("Finished setting up idmapped mounts");
3090 __do_endmntent
FILE *f_fstab
= NULL
;
3092 f_fstab
= setmntent(fstab
, "re");
3094 SYSERROR("Failed to open fstab format file \"%s\"", fstab
);
3098 ret
= __lxc_idmapped_mounts_child(handler
, f_fstab
);
3100 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3104 TRACE("Finished setting up idmapped mounts specified in fstab");
3110 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[0], NULL
, 0);
3112 return syserror("Failed to inform parent that we are done setting up mounts");
3117 int parse_cap(const char *cap_name
, __u32
*cap
)
3119 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
3124 if (strequal(cap_name
, "none"))
3127 for (size_t i
= 0; i
< end
; i
++) {
3128 if (!strequal(cap_name
, caps_opt
[i
].name
))
3131 *cap
= caps_opt
[i
].value
;
3136 * Try to see if it's numeric, so the user may specify
3137 * capabilities that the running kernel knows about but we
3140 ret
= lxc_safe_uint(cap_name
, &res
);
3144 ret
= lxc_caps_last_cap(&last_cap
);
3148 if ((__u32
)res
> last_cap
)
3155 bool has_cap(__u32 cap
, struct lxc_conf
*conf
)
3157 bool cap_in_list
= false;
3158 struct cap_entry
*cap_entry
;
3160 list_for_each_entry(cap_entry
, &conf
->caps
.list
, head
) {
3161 if (cap_entry
->cap
!= cap
)
3167 /* The capability is kept. */
3168 if (conf
->caps
.keep
)
3171 /* The capability is not dropped. */
3172 return !cap_in_list
;
3175 static int capabilities_deny(struct lxc_conf
*conf
)
3177 struct cap_entry
*cap
;
3179 list_for_each_entry(cap
, &conf
->caps
.list
, head
) {
3182 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(cap
->cap
), prctl_arg(0),
3183 prctl_arg(0), prctl_arg(0));
3185 return syserror("Failed to remove %s capability", cap
->cap_name
);
3187 DEBUG("Dropped %s (%d) capability", cap
->cap_name
, cap
->cap
);
3190 DEBUG("Capabilities have been setup");
3194 static int capabilities_allow(struct lxc_conf
*conf
)
3196 __do_free __u32
*keep_bits
= NULL
;
3198 struct cap_entry
*cap
;
3199 __u32 last_cap
, nr_u32
;
3201 ret
= lxc_caps_last_cap(&last_cap
);
3202 if (ret
|| last_cap
> 200)
3203 return ret_errno(EINVAL
);
3205 TRACE("Found %d capabilities", last_cap
);
3207 nr_u32
= BITS_TO_LONGS(last_cap
);
3208 keep_bits
= zalloc(nr_u32
* sizeof(__u32
));
3210 return ret_errno(ENOMEM
);
3212 list_for_each_entry(cap
, &conf
->caps
.list
, head
) {
3213 if (cap
->cap
> last_cap
)
3216 set_bit(cap
->cap
, keep_bits
);
3217 DEBUG("Keeping %s (%d) capability", cap
->cap_name
, cap
->cap
);
3220 for (__u32 cap_bit
= 0; cap_bit
<= last_cap
; cap_bit
++) {
3221 if (is_set(cap_bit
, keep_bits
))
3224 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(cap_bit
), prctl_arg(0),
3225 prctl_arg(0), prctl_arg(0));
3227 return syserror("Failed to remove capability %d", cap_bit
);
3229 TRACE("Dropped capability %d", cap_bit
);
3232 DEBUG("Capabilities have been setup");
3236 static int parse_resource(const char *res
)
3242 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
3243 if (strequal(res
, limit_opt
[i
].name
))
3244 return limit_opt
[i
].value
;
3246 /* Try to see if it's numeric, so the user may specify
3247 * resources that the running kernel knows about but
3250 ret
= lxc_safe_int(res
, &resid
);
3257 int setup_resource_limits(struct lxc_conf
*conf
, pid_t pid
)
3260 struct lxc_limit
*lim
;
3262 if (list_empty(&conf
->limits
))
3265 list_for_each_entry(lim
, &conf
->limits
, head
) {
3266 resid
= parse_resource(lim
->resource
);
3268 return log_error(-1, "Unknown resource %s", lim
->resource
);
3270 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
3271 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
3272 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
3274 TRACE("Setup \"%s\" limit", lim
->resource
);
3276 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
3280 TRACE("Setup resource limits");
3284 int setup_sysctl_parameters(struct lxc_conf
*conf
)
3286 __do_free
char *tmp
= NULL
;
3288 char filename
[PATH_MAX
] = {0};
3289 struct lxc_sysctl
*sysctl
, *nsysctl
;
3291 if (!list_empty(&conf
->sysctls
))
3294 list_for_each_entry_safe(sysctl
, nsysctl
, &conf
->sysctls
, head
) {
3295 tmp
= lxc_string_replace(".", "/", sysctl
->key
);
3297 return log_error(-1, "Failed to replace key %s", sysctl
->key
);
3299 ret
= strnprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
3301 return log_error(-1, "Error setting up sysctl parameters path");
3303 ret
= lxc_write_to_file(filename
, sysctl
->value
,
3304 strlen(sysctl
->value
), false, 0666);
3306 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
3307 sysctl
->key
, sysctl
->value
);
3313 int setup_proc_filesystem(struct lxc_conf
*conf
, pid_t pid
)
3315 __do_free
char *tmp
= NULL
;
3317 char filename
[PATH_MAX
] = {0};
3318 struct lxc_proc
*proc
;
3320 if (!list_empty(&conf
->procs
))
3323 list_for_each_entry(proc
, &conf
->procs
, head
) {
3324 tmp
= lxc_string_replace(".", "/", proc
->filename
);
3326 return log_error(-1, "Failed to replace key %s", proc
->filename
);
3328 ret
= strnprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
3330 return log_error(-1, "Error setting up proc filesystem path");
3332 ret
= lxc_write_to_file(filename
, proc
->value
,
3333 strlen(proc
->value
), false, 0666);
3335 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s",
3336 proc
->filename
, proc
->value
);
3339 TRACE("Setup /proc/%d settings", pid
);
3343 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
3345 struct lxc_conf
*lxc_conf_init(void)
3348 struct lxc_conf
*new;
3350 new = zalloc(sizeof(*new));
3354 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
3355 new->personality
= LXC_ARCH_UNCHANGED
;
3357 new->console
.buffer_size
= 0;
3358 new->console
.log_path
= NULL
;
3359 new->console
.log_fd
= -1;
3360 new->console
.log_size
= 0;
3361 new->console
.path
= NULL
;
3362 new->console
.peer
= -1;
3363 new->console
.proxy
.busy
= -1;
3364 new->console
.proxy
.ptx
= -1;
3365 new->console
.proxy
.pty
= -1;
3366 new->console
.ptx
= -EBADF
;
3367 new->console
.pty
= -EBADF
;
3368 new->console
.pty_nr
= -1;
3369 new->console
.name
[0] = '\0';
3370 new->devpts_fd
= -EBADF
;
3371 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
3372 new->maincmd_fd
= -1;
3373 new->monitor_signal_pdeath
= SIGKILL
;
3375 new->rootfs
.mount
= strdup(default_rootfs_mount
);
3376 if (!new->rootfs
.mount
) {
3380 new->rootfs
.managed
= true;
3381 new->rootfs
.dfd_mnt
= -EBADF
;
3382 new->rootfs
.dfd_dev
= -EBADF
;
3383 new->rootfs
.dfd_host
= -EBADF
;
3384 new->rootfs
.fd_path_pin
= -EBADF
;
3385 new->rootfs
.dfd_idmapped
= -EBADF
;
3387 INIT_LIST_HEAD(&new->cgroup
);
3388 INIT_LIST_HEAD(&new->cgroup2
);
3389 /* Block ("allowlist") all devices by default. */
3390 new->bpf_devices
.list_type
= LXC_BPF_DEVICE_CGROUP_ALLOWLIST
;
3391 INIT_LIST_HEAD(&(new->bpf_devices
).devices
);
3392 INIT_LIST_HEAD(&new->mount_entries
);
3393 INIT_LIST_HEAD(&new->caps
.list
);
3394 INIT_LIST_HEAD(&new->id_map
);
3395 new->root_nsuid_map
= NULL
;
3396 new->root_nsgid_map
= NULL
;
3397 INIT_LIST_HEAD(&new->environment
);
3398 INIT_LIST_HEAD(&new->limits
);
3399 INIT_LIST_HEAD(&new->sysctls
);
3400 INIT_LIST_HEAD(&new->procs
);
3401 new->hooks_version
= 0;
3402 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
3403 INIT_LIST_HEAD(&new->hooks
[i
]);
3404 INIT_LIST_HEAD(&new->groups
);
3405 INIT_LIST_HEAD(&new->state_clients
);
3406 new->lsm_aa_profile
= NULL
;
3407 INIT_LIST_HEAD(&new->lsm_aa_raw
);
3408 new->lsm_se_context
= NULL
;
3409 new->lsm_se_keyring_context
= NULL
;
3410 new->keyring_disable_session
= false;
3411 new->transient_procfs_mnt
= false;
3412 new->shmount
.path_host
= NULL
;
3413 new->shmount
.path_cont
= NULL
;
3414 new->sched_core
= false;
3415 new->sched_core_cookie
= INVALID_SCHED_CORE_COOKIE
;
3417 /* if running in a new user namespace, init and COMMAND
3418 * default to running as UID/GID 0 when using lxc-execute */
3421 memset(&new->init_groups
, 0, sizeof(lxc_groups_t
));
3422 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
3423 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
3424 memset(&new->timens
, 0, sizeof(struct timens_offsets
));
3425 seccomp_conf_init(new);
3427 INIT_LIST_HEAD(&new->netdevs
);
3432 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
3435 __do_close
int fd
= -EBADF
;
3437 char path
[PATH_MAX
];
3439 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
3440 __do_close
int setgroups_fd
= -EBADF
;
3442 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/setgroups", pid
);
3446 setgroups_fd
= open(path
, O_WRONLY
);
3447 if (setgroups_fd
< 0 && errno
!= ENOENT
)
3448 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3450 if (setgroups_fd
>= 0) {
3451 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
3452 STRLITERALLEN("deny\n"));
3453 if (ret
!= STRLITERALLEN("deny\n"))
3454 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
3455 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
3459 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/%cid_map", pid
,
3460 idtype
== ID_TYPE_UID
? 'u' : 'g');
3464 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
3466 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3468 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
3469 if (ret
< 0 || (size_t)ret
!= buf_size
)
3470 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
3471 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
3476 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3478 * @return 1 if functional binary was found
3479 * @return 0 if binary exists but is lacking privilege
3480 * @return -ENOENT if binary does not exist
3481 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
3483 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
3485 __do_free
char *path
= NULL
;
3489 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
3490 return ret_errno(EINVAL
);
3492 path
= on_path(binary
, NULL
);
3494 return ret_errno(ENOENT
);
3496 ret
= stat(path
, &st
);
3500 /* Check if the binary is setuid. */
3501 if (st
.st_mode
& S_ISUID
)
3502 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
3504 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
3505 /* Check if it has the CAP_SETUID capability. */
3506 if ((cap
& CAP_SETUID
) &&
3507 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
3508 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
3509 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3511 /* Check if it has the CAP_SETGID capability. */
3512 if ((cap
& CAP_SETGID
) &&
3513 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
3514 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
3515 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3520 * If we cannot check for file capabilities we need to give the benefit
3521 * of the doubt. Otherwise we might fail even though all the necessary
3522 * file capabilities are set.
3524 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3529 static int lxc_map_ids_exec_wrapper(void *args
)
3531 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
3535 static struct id_map
*find_mapped_hostid_entry(const struct list_head
*idmap
,
3536 unsigned id
, enum idtype idtype
);
3538 int lxc_map_ids(struct list_head
*idmap
, pid_t pid
)
3545 char cmd_output
[PATH_MAX
];
3548 int ret
= 0, gidmap
= 0, uidmap
= 0;
3549 char mapbuf
[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3550 INTTYPE_TO_STRLEN(pid_t
) + STRLITERALLEN(" ") +
3551 LXC_IDMAPLEN
] = {0};
3552 bool had_entry
= false, maps_host_root
= false, use_shadow
= false;
3554 hostuid
= geteuid();
3555 hostgid
= getegid();
3558 * Check whether caller wants to map host root.
3559 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3560 * host root into the child userns as you would be able to write fscaps
3561 * that would be valid in the ancestor userns. Mapping host root should
3562 * rarely be the case but LXC is being clever in a bunch of cases.
3564 if (find_mapped_hostid_entry(idmap
, 0, ID_TYPE_UID
))
3565 maps_host_root
= true;
3567 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3568 * ranges, then insist that root also reserve ranges in subuid. This
3569 * will protected it by preventing another user from being handed the
3572 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
3573 if (uidmap
== -ENOENT
)
3574 WARN("newuidmap binary is missing");
3576 WARN("newuidmap is lacking necessary privileges");
3578 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
3579 if (gidmap
== -ENOENT
)
3580 WARN("newgidmap binary is missing");
3582 WARN("newgidmap is lacking necessary privileges");
3584 if (maps_host_root
) {
3585 INFO("Caller maps host root. Writing mapping directly");
3586 } else if (uidmap
> 0 && gidmap
> 0) {
3587 DEBUG("Functional newuidmap and newgidmap binary found");
3590 /* In case unprivileged users run application containers via
3591 * execute() or a start*() there are valid cases where they may
3592 * only want to map their own {g,u}id. Let's not block them from
3593 * doing so by requiring geteuid() == 0.
3595 DEBUG("No newuidmap and newgidmap binary found. Trying to "
3596 "write directly with euid %d", hostuid
);
3599 /* Check if we really need to use newuidmap and newgidmap.
3600 * If the user is only remapping their own {g,u}id, we don't need it.
3602 if (use_shadow
&& list_len(map
, idmap
, head
) == 2) {
3604 list_for_each_entry(map
, idmap
, head
) {
3605 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3606 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3608 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3609 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3616 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3617 type
++, u_or_g
= 'g') {
3621 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3623 list_for_each_entry(map
, idmap
, head
) {
3624 if (map
->idtype
!= type
)
3629 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3630 fill
= strnprintf(pos
, left
, "%s%lu %lu %lu%s",
3631 use_shadow
? " " : "", map
->nsid
,
3632 map
->hostid
, map
->range
,
3633 use_shadow
? "" : "\n");
3635 * The kernel only takes <= 4k for writes to
3636 * /proc/<pid>/{g,u}id_map
3639 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
3646 /* Try to catch the output of new{g,u}idmap to make debugging
3650 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3651 lxc_map_ids_exec_wrapper
,
3654 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
3655 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3657 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3659 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
3660 TRACE("Wrote mapping \"%s\"", mapbuf
);
3663 memset(mapbuf
, 0, sizeof(mapbuf
));
3670 * Return the host uid/gid to which the container root is mapped in val.
3671 * Return true if id was found, false otherwise.
3673 static id_t
get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
)
3678 if (idtype
== ID_TYPE_UID
)
3679 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3681 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3683 list_for_each_entry (map
, &conf
->id_map
, head
) {
3684 if (map
->idtype
!= idtype
)
3686 if (map
->nsid
!= nsid
)
3691 if (idtype
== ID_TYPE_UID
)
3692 return LXC_INVALID_UID
;
3694 return LXC_INVALID_GID
;
3697 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
3701 list_for_each_entry(map
, &conf
->id_map
, head
) {
3702 if (map
->idtype
!= idtype
)
3705 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3706 return (id
- map
->hostid
) + map
->nsid
;
3712 int find_unmapped_nsid(const struct lxc_conf
*conf
, enum idtype idtype
)
3715 unsigned int freeid
= 0;
3718 list_for_each_entry(map
, &conf
->id_map
, head
) {
3719 if (map
->idtype
!= idtype
)
3722 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3723 freeid
= map
->nsid
+ map
->range
;
3732 * Mount a proc under @rootfs if proc self points to a pid other than
3733 * my own. This is needed to have a known-good proc mount for setting
3734 * up LSMs both at container startup and attach.
3736 * NOTE: not to be called from inside the container namespace!
3738 static int lxc_transient_proc(struct lxc_rootfs
*rootfs
)
3740 __do_close
int fd_proc
= -EBADF
;
3741 int link_to_pid
, link_len
, pid_self
, ret
;
3742 char link
[INTTYPE_TO_STRLEN(pid_t
) + 1];
3744 link_len
= readlinkat(rootfs
->dfd_mnt
, "proc/self", link
, sizeof(link
));
3746 ret
= mkdirat(rootfs
->dfd_mnt
, "proc", 0000);
3747 if (ret
< 0 && errno
!= EEXIST
)
3748 return log_error_errno(-errno
, errno
, "Failed to create %d(proc)", rootfs
->dfd_mnt
);
3751 } else if ((size_t)link_len
>= sizeof(link
)) {
3752 return log_error_errno(-EIO
, EIO
, "Truncated link target");
3754 link
[link_len
] = '\0';
3756 pid_self
= lxc_raw_getpid();
3757 INFO("Caller's PID is %d; /proc/self points to %s", pid_self
, link
);
3759 ret
= lxc_safe_int(link
, &link_to_pid
);
3761 return log_error_errno(-ret
, ret
, "Failed to parse %s", link
);
3763 /* Correct procfs is already mounted. */
3764 if (link_to_pid
== pid_self
)
3765 return log_trace(0, "Correct procfs instance mounted");
3767 fd_proc
= open_at(rootfs
->dfd_mnt
, "proc", PROTECT_OPATH_DIRECTORY
,
3768 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
3770 return log_error_errno(-errno
, errno
, "Failed to open transient procfs mountpoint");
3772 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/proc/self/fd/%d", fd_proc
);
3774 return ret_errno(EIO
);
3776 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
3778 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs
->buf
);
3781 /* rootfs is NULL */
3782 if (!rootfs
->path
) {
3783 ret
= mount("proc", rootfs
->buf
, "proc", 0, NULL
);
3785 ret
= safe_mount_beneath_at(rootfs
->dfd_mnt
, "none", "proc", "proc", 0, NULL
);
3787 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc", rootfs
->path
? rootfs
->mount
: "");
3789 return ret_errno(EIO
);
3791 ret
= safe_mount("proc", rootfs
->buf
, "proc", 0, NULL
, rootfs
->mount
);
3795 return log_error_errno(-1, errno
, "Failed to mount temporary procfs");
3797 INFO("Created transient procfs mount");
3801 /* NOTE: Must not be called from inside the container namespace! */
3802 static int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3806 mounted
= lxc_transient_proc(&conf
->rootfs
);
3807 if (mounted
== -1) {
3808 /* continue only if there is no rootfs */
3809 if (conf
->rootfs
.path
)
3810 return log_error_errno(-EPERM
, EPERM
, "Failed to create transient procfs mount");
3811 } else if (mounted
== 1) {
3812 conf
->transient_procfs_mnt
= true;
3818 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3820 if (lxc_conf
->transient_procfs_mnt
) {
3821 (void)umount2("/proc", MNT_DETACH
);
3822 lxc_conf
->transient_procfs_mnt
= false;
3826 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
3827 static void turn_into_dependent_mounts(const struct lxc_rootfs
*rootfs
)
3829 __do_free
char *line
= NULL
;
3830 __do_fclose
FILE *f
= NULL
;
3831 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3836 mntinfo_fd
= open_at(rootfs
->dfd_host
, "proc/self/mountinfo", PROTECT_OPEN
,
3837 (PROTECT_LOOKUP_BENEATH_XDEV
& ~RESOLVE_NO_SYMLINKS
), 0);
3838 if (mntinfo_fd
< 0) {
3839 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs
->dfd_host
);
3843 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3845 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3847 if (errno
!= ENOSYS
) {
3848 SYSERROR("Failed to create temporary in-memory file");
3852 memfd
= lxc_make_tmpfile(template, true);
3854 WARN("Failed to create temporary file");
3859 copied
= fd_to_fd(mntinfo_fd
, memfd
);
3861 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3865 ret
= lseek(memfd
, 0, SEEK_SET
);
3867 SYSERROR("Failed to reset file descriptor offset");
3871 f
= fdopen(memfd
, "re");
3873 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3878 * After a successful fdopen() memfd will be closed when calling
3879 * fclose(f). Calling close(memfd) afterwards is undefined.
3883 while (getline(&line
, &len
, f
) != -1) {
3884 char *opts
, *target
;
3886 target
= get_field(line
, 4);
3890 opts
= get_field(target
, 2);
3894 null_endofword(opts
);
3895 if (!strstr(opts
, "shared"))
3898 null_endofword(target
);
3899 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3901 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3905 TRACE("Turned all mount table entries into dependent mount");
3908 /* This does the work of remounting / if it is shared, calling the container
3909 * pre-mount hooks, and mounting the rootfs.
3911 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3912 const char *lxcpath
)
3916 conf
->rootfs
.dfd_host
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
3917 if (conf
->rootfs
.dfd_host
< 0)
3918 return log_error_errno(-errno
, errno
, "Failed to open \"/\"");
3920 turn_into_dependent_mounts(&conf
->rootfs
);
3922 if (conf
->rootfs_setup
) {
3923 const char *path
= conf
->rootfs
.mount
;
3926 * The rootfs was set up in another namespace. bind-mount it to
3927 * give us a mount in our own ns so we can pivot_root to it
3929 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3931 return log_error(-1, "Failed to bind mount container / onto itself");
3933 conf
->rootfs
.dfd_mnt
= openat(-EBADF
, path
, O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOCTTY
);
3934 if (conf
->rootfs
.dfd_mnt
< 0)
3935 return log_error_errno(-errno
, errno
, "Failed to open file descriptor for container rootfs");
3937 return log_trace(0, "Bind mounted container / onto itself");
3940 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3942 return log_error(-1, "Failed to run pre-mount hooks");
3944 ret
= lxc_mount_rootfs(&conf
->rootfs
);
3946 return log_error(-1, "Failed to setup rootfs for");
3948 conf
->rootfs_setup
= true;
3952 static bool verify_start_hooks(struct lxc_conf
*conf
)
3954 char path
[PATH_MAX
];
3955 struct string_entry
*hook
;
3957 list_for_each_entry(hook
, &conf
->hooks
[LXCHOOK_START
], head
) {
3959 char *hookname
= hook
->val
;
3961 ret
= strnprintf(path
, sizeof(path
), "%s%s",
3962 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3967 ret
= access(path
, X_OK
);
3969 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
3977 static int lxc_setup_boot_id(void)
3980 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3981 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
3984 if (access(boot_id_path
, F_OK
))
3987 memset(&n
, 0, sizeof(n
));
3988 if (lxc_id128_randomize(&n
)) {
3989 SYSERROR("Failed to generate random data for uuid");
3993 ret
= lxc_id128_write(mock_boot_id_path
, n
);
3995 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
3999 ret
= chmod(mock_boot_id_path
, 0444);
4001 SYSERROR("Failed to chown %s", mock_boot_id_path
);
4002 (void)unlink(mock_boot_id_path
);
4006 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
4008 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
4010 (void)unlink(mock_boot_id_path
);
4014 ret
= mount(NULL
, boot_id_path
, NULL
,
4015 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
4019 SYSERROR("Failed to remount %s read-only", boot_id_path
);
4020 (void)unlink(mock_boot_id_path
);
4027 static int lxc_setup_keyring(struct lsm_ops
*lsm_ops
, const struct lxc_conf
*conf
)
4029 key_serial_t keyring
;
4032 if (conf
->lsm_se_keyring_context
)
4033 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_keyring_context
);
4034 else if (conf
->lsm_se_context
)
4035 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_context
);
4037 return syserror("Failed to set keyring context");
4040 * Try to allocate a new session keyring for the container to prevent
4041 * information leaks.
4043 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
4044 prctl_arg(0), prctl_arg(0), prctl_arg(0));
4048 DEBUG("The keyctl() syscall is not supported or blocked");
4053 DEBUG("Failed to access kernel keyring. Continuing...");
4056 SYSWARN("Failed to create kernel keyring");
4064 static int lxc_rootfs_prepare_child(struct lxc_handler
*handler
)
4066 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
4067 int dfd_idmapped
= -EBADF
;
4070 if (list_empty(&handler
->conf
->id_map
))
4073 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
4076 if (handler
->conf
->rootfs_setup
)
4079 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1], &dfd_idmapped
, NULL
, 0);
4081 return syserror("Failed to receive idmapped mount fd");
4083 rootfs
->dfd_idmapped
= dfd_idmapped
;
4084 TRACE("Received detached idmapped mount %d", rootfs
->dfd_idmapped
);
4088 int lxc_idmapped_mounts_parent(struct lxc_handler
*handler
)
4093 __do_close
int fd_from
= -EBADF
, fd_userns
= -EBADF
;
4094 struct lxc_mount_attr attr
= {};
4095 struct lxc_mount_options opts
= {};
4098 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4099 &fd_from
, &fd_userns
,
4100 &opts
, sizeof(opts
));
4102 return syserror("Failed to receive idmapped mount file descriptors from child");
4104 if (fd_from
< 0 || fd_userns
< 0)
4105 return log_trace(0, "Finished receiving idmapped mount file descriptors from child");
4107 attr
.attr_set
= MOUNT_ATTR_IDMAP
;
4108 attr
.userns_fd
= fd_userns
;
4109 ret
= mount_setattr(fd_from
, "",
4111 (opts
.bind_recursively
? AT_RECURSIVE
: 0),
4112 &attr
, sizeof(attr
));
4114 return syserror("Failed to idmap detached %smount %d to %d",
4115 opts
.bind_recursively
? "recursive " : "",
4116 fd_from
, fd_userns
);
4118 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[1],
4122 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
4123 opts
.bind_recursively
? "recursive " : "",
4124 fd_from
, fd_userns
);
4126 TRACE("Parent idmapped detached %smount %d to user namespace %d",
4127 opts
.bind_recursively
? "recursive " : "", fd_from
, fd_userns
);
4132 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
4134 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*info_new
= &(struct lxc_tty_info
){};
4135 int sock
= handler
->data_sock
[1];
4136 struct lxc_conf
*conf
= handler
->conf
;
4137 struct lxc_tty_info
*tty_info
= &conf
->ttys
;
4138 size_t ttys_max
= tty_info
->max
;
4139 struct lxc_terminal_info
*terminal_info
;
4145 info_new
->tty
= malloc(sizeof(*(info_new
->tty
)) * ttys_max
);
4147 return ret_errno(ENOMEM
);
4149 for (size_t i
= 0; i
< ttys_max
; i
++) {
4150 terminal_info
= &info_new
->tty
[i
];
4151 terminal_info
->busy
= -1;
4152 terminal_info
->ptx
= -EBADF
;
4153 terminal_info
->pty
= -EBADF
;
4156 for (size_t i
= 0; i
< ttys_max
; i
++) {
4157 int ptx
= -EBADF
, pty
= -EBADF
;
4159 ret
= lxc_abstract_unix_recv_two_fds(sock
, &ptx
, &pty
);
4161 return syserror("Failed to receive %zu ttys from child", ttys_max
);
4163 terminal_info
= &info_new
->tty
[i
];
4164 terminal_info
->ptx
= ptx
;
4165 terminal_info
->pty
= pty
;
4166 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4167 terminal_info
->ptx
, terminal_info
->pty
);
4170 tty_info
->tty
= move_ptr(info_new
->tty
);
4171 TRACE("Received %zu ttys from child", ttys_max
);
4175 static int lxc_send_console_to_parent(struct lxc_handler
*handler
)
4177 struct lxc_terminal
*console
= &handler
->conf
->console
;
4180 if (!wants_console(console
))
4183 /* We've already allocated a console from the host's devpts instance. */
4184 if (console
->pty
< 0)
4187 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
4188 console
->ptx
, console
->pty
,
4190 sizeof(struct lxc_terminal
));
4192 return syserror("Fail to send console to parent");
4194 TRACE("Sent console to parent");
4198 static int lxc_recv_console_from_child(struct lxc_handler
*handler
)
4200 __do_close
int fd_ptx
= -EBADF
, fd_pty
= -EBADF
;
4201 struct lxc_terminal
*console
= &handler
->conf
->console
;
4204 if (!wants_console(console
))
4207 /* We've already allocated a console from the host's devpts instance. */
4208 if (console
->pty
>= 0)
4211 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4214 sizeof(struct lxc_terminal
));
4216 return syserror("Fail to receive console from child");
4218 console
->ptx
= move_fd(fd_ptx
);
4219 console
->pty
= move_fd(fd_pty
);
4221 TRACE("Received console from child");
4225 int lxc_sync_fds_parent(struct lxc_handler
*handler
)
4229 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[1]);
4231 return syserror_ret(ret
, "Failed to receive seccomp notify fd from child");
4233 ret
= lxc_recv_devpts_from_child(handler
);
4235 return syserror_ret(ret
, "Failed to receive devpts fd from child");
4237 /* Read tty fds allocated by child. */
4238 ret
= lxc_recv_ttys_from_child(handler
);
4240 return syserror_ret(ret
, "Failed to receive tty info from child process");
4242 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4243 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
4245 return syserror_ret(ret
, "Failed to receive names and ifindices for network devices from child");
4248 ret
= lxc_recv_console_from_child(handler
);
4250 return syserror_ret(ret
, "Failed to receive console from child");
4252 TRACE("Finished syncing file descriptors with child");
4256 int lxc_sync_fds_child(struct lxc_handler
*handler
)
4260 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[0]);
4262 return syserror_ret(ret
, "Failed to send seccomp notify fd to parent");
4264 ret
= lxc_send_devpts_to_parent(handler
);
4266 return syserror_ret(ret
, "Failed to send seccomp devpts fd to parent");
4268 ret
= lxc_send_ttys_to_parent(handler
);
4270 return syserror_ret(ret
, "Failed to send tty file descriptors to parent");
4272 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4273 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
4275 return syserror_ret(ret
, "Failed to send network device names and ifindices to parent");
4278 ret
= lxc_send_console_to_parent(handler
);
4280 return syserror_ret(ret
, "Failed to send console to parent");
4282 TRACE("Finished syncing file descriptors with parent");
4286 static int setup_capabilities(struct lxc_conf
*conf
)
4290 if (conf
->caps
.keep
)
4291 ret
= capabilities_allow(conf
);
4293 ret
= capabilities_deny(conf
);
4295 return syserror_ret(ret
, "Failed to %s capabilities", conf
->caps
.keep
? "allow" : "deny");
4300 int lxc_setup(struct lxc_handler
*handler
)
4303 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
4304 struct lxc_conf
*lxc_conf
= handler
->conf
;
4306 ret
= lxc_rootfs_prepare_child(handler
);
4308 return syserror("Failed to prepare rootfs");
4310 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
4312 return log_error(-1, "Failed to setup rootfs");
4314 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
4315 ret
= setup_utsname(lxc_conf
->utsname
);
4317 return log_error(-1, "Failed to setup the utsname %s", name
);
4320 if (!lxc_conf
->keyring_disable_session
) {
4321 ret
= lxc_setup_keyring(handler
->lsm_ops
, lxc_conf
);
4323 return log_error(-1, "Failed to setup container keyring");
4326 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4327 ret
= lxc_network_recv_from_parent(handler
);
4329 return log_error(-1, "Failed to receive veth names from parent");
4331 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
);
4333 return log_error(-1, "Failed to setup network");
4336 if (lxc_conf
->autodev
> 0) {
4337 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
4339 return log_error(-1, "Failed to mount \"/dev\"");
4342 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4343 * need to wait until other stuff has finished.
4345 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
);
4347 return log_error(-1, "Failed to setup first automatic mounts");
4349 ret
= setup_mount_fstab(&lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
4351 return log_error(-1, "Failed to setup mounts");
4353 if (!list_empty(&lxc_conf
->mount_entries
)) {
4354 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
, name
, lxcpath
);
4356 return log_error(-1, "Failed to setup mount entries");
4359 if (!lxc_sync_wake_parent(handler
, START_SYNC_IDMAPPED_MOUNTS
))
4362 ret
= lxc_idmapped_mounts_child(handler
);
4364 return syserror("Failed to attached detached idmapped mounts");
4366 lxc_conf
->rootfs
.dfd_dev
= open_at(lxc_conf
->rootfs
.dfd_mnt
, "dev",
4367 PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
4368 if (lxc_conf
->rootfs
.dfd_dev
< 0 && errno
!= ENOENT
)
4369 return log_error_errno(-errno
, errno
, "Failed to open \"/dev\"");
4371 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4372 * mounted. It is guaranteed to be mounted now either through
4373 * automatically or via fstab entries.
4375 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
);
4377 return log_error(-1, "Failed to setup remaining automatic mounts");
4379 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
4381 return log_error(-1, "Failed to run mount hooks");
4383 if (lxc_rootfs_overmounted(&lxc_conf
->rootfs
))
4384 return log_error(-1, "Rootfs overmounted");
4386 if (lxc_conf
->autodev
> 0) {
4387 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
4389 return log_error(-1, "Failed to run autodev hooks");
4391 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
4393 return log_error(-1, "Failed to populate \"/dev\"");
4396 /* Make sure any start hooks are in the container */
4397 if (!verify_start_hooks(lxc_conf
))
4398 return log_error(-1, "Failed to verify start hooks");
4400 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
4402 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
4404 ret
= lxc_setup_devpts_child(handler
);
4406 return log_error(-1, "Failed to prepare new devpts instance");
4408 ret
= lxc_finish_devpts_child(handler
);
4410 return log_error(-1, "Failed to finish devpts setup");
4412 ret
= lxc_setup_console(handler
, &lxc_conf
->rootfs
, &lxc_conf
->console
,
4413 lxc_conf
->ttys
.dir
);
4415 return log_error(-1, "Failed to setup console");
4417 ret
= lxc_create_ttys(handler
);
4419 return log_error(-1, "Failed to create ttys");
4421 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
4423 return log_error(-1, "Failed to setup \"/dev\" symlinks");
4425 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
4427 return log_error(-1, "Failed to pivot root into rootfs");
4429 /* Setting the boot-id is best-effort for now. */
4430 if (lxc_conf
->autodev
> 0)
4431 (void)lxc_setup_boot_id();
4433 ret
= setup_personality(lxc_conf
->personality
);
4435 return syserror("Failed to set personality");
4437 /* Set sysctl value to a path under /proc/sys as determined from the
4438 * key. For e.g. net.ipv4.ip_forward translated to
4439 * /proc/sys/net/ipv4/ip_forward.
4441 ret
= setup_sysctl_parameters(lxc_conf
);
4443 return log_error(-1, "Failed to setup sysctl parameters");
4445 ret
= setup_capabilities(lxc_conf
);
4447 return log_error(-1, "Failed to setup capabilities");
4449 put_lxc_rootfs(&handler
->conf
->rootfs
, true);
4450 NOTICE("The container \"%s\" is set up", name
);
4455 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
4459 struct string_entry
*entry
;
4461 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
4462 if (strequal(hookname
, lxchook_names
[which
]))
4466 if (which
>= NUM_LXC_HOOKS
)
4469 list_for_each_entry(entry
, &conf
->hooks
[which
], head
) {
4471 char *hook
= entry
->val
;
4473 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
4482 int lxc_clear_config_caps(struct lxc_conf
*c
)
4484 struct cap_entry
*cap
, *ncap
;
4486 list_for_each_entry_safe(cap
, ncap
, &c
->caps
.list
, head
) {
4487 list_del(&cap
->head
);
4488 free(cap
->cap_name
);
4492 c
->caps
.keep
= false;
4493 INIT_LIST_HEAD(&c
->caps
.list
);
4497 static int lxc_free_idmap(struct list_head
*id_map
)
4499 struct id_map
*map
, *nmap
;
4501 list_for_each_entry_safe(map
, nmap
, id_map
, head
) {
4502 list_del(&map
->head
);
4506 INIT_LIST_HEAD(id_map
);
4510 static int __lxc_free_idmap(struct list_head
*id_map
)
4512 lxc_free_idmap(id_map
);
4515 define_cleanup_function(struct list_head
*, __lxc_free_idmap
);
4517 int lxc_clear_idmaps(struct lxc_conf
*c
)
4519 return lxc_free_idmap(&c
->id_map
);
4522 int lxc_clear_namespace(struct lxc_conf
*c
)
4524 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
4525 free_disarm(c
->ns_share
[i
]);
4530 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
4532 const char *k
= key
;
4534 char *global_token
, *namespaced_token
;
4535 size_t namespaced_token_len
;
4536 struct list_head
*list
;
4537 struct lxc_cgroup
*cgroup
, *ncgroup
;
4539 if (version
== CGROUP2_SUPER_MAGIC
) {
4540 global_token
= "lxc.cgroup2";
4541 namespaced_token
= "lxc.cgroup2.";
4542 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
4544 } else if (version
== CGROUP_SUPER_MAGIC
) {
4545 global_token
= "lxc.cgroup";
4546 namespaced_token
= "lxc.cgroup.";
4547 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
4550 return ret_errno(EINVAL
);
4553 if (strequal(key
, global_token
))
4555 else if (strnequal(key
, namespaced_token
, namespaced_token_len
))
4556 k
+= namespaced_token_len
;
4558 return ret_errno(EINVAL
);
4560 list_for_each_entry_safe(cgroup
, ncgroup
, list
, head
) {
4561 if (!all
&& !strequal(cgroup
->subsystem
, k
))
4564 list_del(&cgroup
->head
);
4565 free(cgroup
->subsystem
);
4566 free(cgroup
->value
);
4571 INIT_LIST_HEAD(list
);
4576 static inline void lxc_clear_cgroups_devices(struct lxc_conf
*conf
)
4578 lxc_clear_cgroup2_devices(&conf
->bpf_devices
);
4581 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
4583 const char *k
= NULL
;
4585 struct lxc_limit
*lim
, *nlim
;
4587 if (strequal(key
, "lxc.limit") || strequal(key
, "lxc.prlimit"))
4589 else if (strnequal(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
4590 k
= key
+ STRLITERALLEN("lxc.limit.");
4591 else if (strnequal(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
4592 k
= key
+ STRLITERALLEN("lxc.prlimit.");
4594 return ret_errno(EINVAL
);
4596 list_for_each_entry_safe(lim
, nlim
, &c
->limits
, head
) {
4597 if (!all
&& !strequal(lim
->resource
, k
))
4600 list_del(&lim
->head
);
4601 free_disarm(lim
->resource
);
4606 INIT_LIST_HEAD(&c
->limits
);
4611 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
4613 const char *k
= NULL
;
4615 struct lxc_sysctl
*sysctl
, *nsysctl
;
4617 if (strequal(key
, "lxc.sysctl"))
4619 else if (strnequal(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
4620 k
= key
+ STRLITERALLEN("lxc.sysctl.");
4624 list_for_each_entry_safe(sysctl
, nsysctl
, &c
->sysctls
, head
) {
4625 if (!all
&& !strequal(sysctl
->key
, k
))
4628 list_del(&sysctl
->head
);
4630 free(sysctl
->value
);
4635 INIT_LIST_HEAD(&c
->sysctls
);
4640 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
4642 const char *k
= NULL
;
4644 struct lxc_proc
*proc
, *nproc
;
4646 if (strequal(key
, "lxc.proc"))
4648 else if (strnequal(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
4649 k
= key
+ STRLITERALLEN("lxc.proc.");
4653 list_for_each_entry_safe(proc
, nproc
, &c
->procs
, head
) {
4654 if (!all
&& !strequal(proc
->filename
, k
))
4657 list_del(&proc
->head
);
4658 free(proc
->filename
);
4664 INIT_LIST_HEAD(&c
->procs
);
4669 int lxc_clear_groups(struct lxc_conf
*c
)
4671 struct string_entry
*entry
, *nentry
;
4673 list_for_each_entry_safe(entry
, nentry
, &c
->groups
, head
) {
4674 list_del(&entry
->head
);
4679 INIT_LIST_HEAD(&c
->groups
);
4683 int lxc_clear_environment(struct lxc_conf
*c
)
4685 struct environment_entry
*env
, *nenv
;
4687 list_for_each_entry_safe(env
, nenv
, &c
->environment
, head
) {
4688 list_del(&env
->head
);
4694 INIT_LIST_HEAD(&c
->environment
);
4698 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4700 struct string_entry
*entry
, *nentry
;
4702 list_for_each_entry_safe(entry
, nentry
, &c
->mount_entries
, head
) {
4703 list_del(&entry
->head
);
4708 INIT_LIST_HEAD(&c
->mount_entries
);
4712 int lxc_clear_automounts(struct lxc_conf
*c
)
4718 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4720 const char *k
= NULL
;
4721 bool all
= false, done
= false;
4722 struct string_entry
*entry
, *nentry
;
4724 if (strequal(key
, "lxc.hook"))
4726 else if (strnequal(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
4727 k
= key
+ STRLITERALLEN("lxc.hook.");
4731 for (int i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4732 if (all
|| strequal(k
, lxchook_names
[i
])) {
4733 list_for_each_entry_safe(entry
, nentry
, &c
->hooks
[i
], head
) {
4734 list_del(&entry
->head
);
4738 INIT_LIST_HEAD(&c
->hooks
[i
]);
4744 return log_error(-1, "Invalid hook key: %s", key
);
4749 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4751 struct string_entry
*entry
, *nentry
;
4753 list_for_each_entry_safe(entry
, nentry
, &c
->lsm_aa_raw
, head
) {
4754 list_del(&entry
->head
);
4759 INIT_LIST_HEAD(&c
->lsm_aa_raw
);
4763 void lxc_conf_free(struct lxc_conf
*conf
)
4768 if (current_config
== conf
)
4769 current_config
= NULL
;
4770 lxc_terminal_conf_free(&conf
->console
);
4771 free(conf
->rootfs
.mount
);
4772 free(conf
->rootfs
.bdev_type
);
4773 free(conf
->rootfs
.path
);
4774 put_lxc_rootfs(&conf
->rootfs
, true);
4775 free(conf
->logfile
);
4776 if (conf
->logfd
!= -1)
4778 free(conf
->utsname
);
4779 free(conf
->ttys
.dir
);
4780 free(conf
->ttys
.tty_names
);
4783 free(conf
->execute_cmd
);
4784 free(conf
->init_cmd
);
4785 free(conf
->init_groups
.list
);
4786 free(conf
->init_cwd
);
4787 free(conf
->unexpanded_config
);
4789 lxc_free_networks(conf
);
4790 free(conf
->lsm_aa_profile
);
4791 free(conf
->lsm_aa_profile_computed
);
4792 free(conf
->lsm_se_context
);
4793 free(conf
->lsm_se_keyring_context
);
4794 lxc_seccomp_free(&conf
->seccomp
);
4795 lxc_clear_config_caps(conf
);
4796 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4797 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4798 lxc_clear_cgroups_devices(conf
);
4799 lxc_clear_hooks(conf
, "lxc.hook");
4800 lxc_clear_mount_entries(conf
);
4801 lxc_clear_idmaps(conf
);
4802 lxc_clear_groups(conf
);
4803 lxc_clear_environment(conf
);
4804 lxc_clear_limits(conf
, "lxc.prlimit");
4805 lxc_clear_sysctls(conf
, "lxc.sysctl");
4806 lxc_clear_procs(conf
, "lxc.proc");
4807 lxc_clear_apparmor_raw(conf
);
4808 lxc_clear_namespace(conf
);
4809 free(conf
->cgroup_meta
.dir
);
4810 free(conf
->cgroup_meta
.monitor_dir
);
4811 free(conf
->cgroup_meta
.monitor_pivot_dir
);
4812 free(conf
->cgroup_meta
.container_dir
);
4813 free(conf
->cgroup_meta
.namespace_dir
);
4814 free(conf
->cgroup_meta
.controllers
);
4815 free(conf
->shmount
.path_host
);
4816 free(conf
->shmount
.path_cont
);
4820 struct userns_fn_data
{
4822 const char *fn_name
;
4827 static int run_userns_fn(void *data
)
4829 struct userns_fn_data
*d
= data
;
4833 close_prot_errno_disarm(d
->p
[1]);
4836 * Wait for parent to finish establishing a new mapping in the user
4837 * namespace we are executing in.
4839 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4840 close_prot_errno_disarm(d
->p
[0]);
4845 TRACE("Calling function \"%s\"", d
->fn_name
);
4847 /* Call function to run. */
4848 return d
->fn(d
->arg
);
4851 static struct id_map
*mapped_nsid_add(const struct lxc_conf
*conf
, unsigned id
,
4854 const struct id_map
*map
;
4855 struct id_map
*retmap
;
4857 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4861 retmap
= zalloc(sizeof(*retmap
));
4865 memcpy(retmap
, map
, sizeof(*retmap
));
4869 static struct id_map
*find_mapped_hostid_entry(const struct list_head
*idmap
,
4870 unsigned id
, enum idtype idtype
)
4872 struct id_map
*retmap
= NULL
;
4875 list_for_each_entry(map
, idmap
, head
) {
4876 if (map
->idtype
!= idtype
)
4879 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4888 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4889 * existing one or establish a new one.
4891 static struct id_map
*mapped_hostid_add(const struct lxc_conf
*conf
, uid_t id
,
4894 __do_free
struct id_map
*entry
= NULL
;
4896 struct id_map
*tmp
= NULL
;
4898 entry
= zalloc(sizeof(*entry
));
4902 /* Reuse existing mapping. */
4903 tmp
= find_mapped_hostid_entry(&conf
->id_map
, id
, type
);
4905 memcpy(entry
, tmp
, sizeof(*entry
));
4907 /* Find new mapping. */
4908 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4909 if (hostid_mapped
< 0)
4910 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
4912 entry
->idtype
= type
;
4913 entry
->nsid
= hostid_mapped
;
4914 entry
->hostid
= (unsigned long)id
;
4918 return move_ptr(entry
);
4921 static int get_minimal_idmap(const struct lxc_conf
*conf
, uid_t
*resuid
,
4922 gid_t
*resgid
, struct list_head
*head_ret
)
4924 __do_free
struct id_map
*container_root_uid
= NULL
,
4925 *container_root_gid
= NULL
,
4926 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4928 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4929 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4931 /* Find container root mappings. */
4932 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4933 if (!container_root_uid
)
4934 return sysdebug("Failed to find mapping for namespace uid %d", 0);
4936 if (euid
>= container_root_uid
->hostid
&&
4937 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4938 host_uid_map
= move_ptr(container_root_uid
);
4940 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4941 if (!container_root_gid
)
4942 return sysdebug("Failed to find mapping for namespace gid %d", 0);
4944 if (egid
>= container_root_gid
->hostid
&&
4945 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4946 host_gid_map
= move_ptr(container_root_gid
);
4948 /* Check whether the {g,u}id of the user has a mapping. */
4950 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4952 return sysdebug("Failed to find mapping for uid %d", euid
);
4955 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4957 return sysdebug("Failed to find mapping for gid %d", egid
);
4959 /* idmap will now keep track of that memory. */
4960 list_add_tail(&host_uid_map
->head
, head_ret
);
4961 move_ptr(host_uid_map
);
4963 if (container_root_uid
) {
4964 /* idmap will now keep track of that memory. */
4965 list_add_tail(&container_root_uid
->head
, head_ret
);
4966 move_ptr(container_root_uid
);
4969 /* idmap will now keep track of that memory. */
4970 list_add_tail(&host_gid_map
->head
, head_ret
);
4971 move_ptr(host_gid_map
);
4973 if (container_root_gid
) {
4974 /* idmap will now keep track of that memory. */
4975 list_add_tail(&container_root_gid
->head
, head_ret
);
4976 move_ptr(container_root_gid
);
4979 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid
, nsgid
);
4990 * Run a function in a new user namespace.
4991 * The caller's euid/egid will be mapped if it is not already.
4992 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4993 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4994 * This means we require only to establish a mapping from:
4995 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4996 * - the container root -> some sub{g,u}id
4997 * The former we add, if the user did not specify a mapping. The latter we
4998 * retrieve from the container's configured {g,u}id mappings as it must have been
4999 * there to start the container in the first place.
5001 int userns_exec_1(const struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
5002 const char *fn_name
)
5004 LIST_HEAD(minimal_idmap
);
5005 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &minimal_idmap
;
5006 int ret
= -1, status
= -1;
5008 struct userns_fn_data d
= {
5019 ret
= get_minimal_idmap(conf
, NULL
, NULL
, idmap
);
5021 return ret_errno(ENOENT
);
5023 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
5027 d
.p
[0] = pipe_fds
[0];
5028 d
.p
[1] = pipe_fds
[1];
5030 /* Clone child in new user namespace. */
5031 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5033 ERROR("Failed to clone process in new user namespace");
5037 close_prot_errno_disarm(pipe_fds
[0]);
5039 if (lxc_log_trace()) {
5042 list_for_each_entry(map
, idmap
, head
)
5043 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5044 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5047 /* Set up {g,u}id mapping for user namespace of child process. */
5048 ret
= lxc_map_ids(idmap
, pid
);
5050 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5054 /* Tell child to proceed. */
5055 if (lxc_write_nointr(pipe_fds
[1], &c
, 1) != 1) {
5056 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5061 close_prot_errno_disarm(pipe_fds
[0]);
5062 close_prot_errno_disarm(pipe_fds
[1]);
5064 /* Wait for child to finish. */
5066 status
= wait_for_pid(pid
);
5074 int userns_exec_minimal(const struct lxc_conf
*conf
,
5075 int (*fn_parent
)(void *), void *fn_parent_data
,
5076 int (*fn_child
)(void *), void *fn_child_data
)
5078 LIST_HEAD(minimal_idmap
);
5079 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &minimal_idmap
;
5080 uid_t resuid
= LXC_INVALID_UID
;
5081 gid_t resgid
= LXC_INVALID_GID
;
5087 if (!conf
|| !fn_child
)
5088 return ret_errno(EINVAL
);
5090 ret
= get_minimal_idmap(conf
, &resuid
, &resgid
, idmap
);
5092 return ret_errno(ENOENT
);
5094 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5100 SYSERROR("Failed to create new process");
5105 close_prot_errno_disarm(sock_fds
[1]);
5107 ret
= unshare(CLONE_NEWUSER
);
5109 SYSERROR("Failed to unshare new user namespace");
5110 _exit(EXIT_FAILURE
);
5113 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5115 _exit(EXIT_FAILURE
);
5117 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5119 _exit(EXIT_FAILURE
);
5121 close_prot_errno_disarm(sock_fds
[0]);
5123 if (!lxc_drop_groups() && errno
!= EPERM
)
5124 _exit(EXIT_FAILURE
);
5126 ret
= setresgid(resgid
, resgid
, resgid
);
5128 SYSERROR("Failed to setresgid(%d, %d, %d)",
5129 resgid
, resgid
, resgid
);
5130 _exit(EXIT_FAILURE
);
5133 ret
= setresuid(resuid
, resuid
, resuid
);
5135 SYSERROR("Failed to setresuid(%d, %d, %d)",
5136 resuid
, resuid
, resuid
);
5137 _exit(EXIT_FAILURE
);
5140 ret
= fn_child(fn_child_data
);
5142 SYSERROR("Running function in new user namespace failed");
5143 _exit(EXIT_FAILURE
);
5146 _exit(EXIT_SUCCESS
);
5149 close_prot_errno_disarm(sock_fds
[0]);
5151 if (lxc_log_trace()) {
5154 list_for_each_entry(map
, idmap
, head
)
5155 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5156 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5159 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
5161 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
5165 /* Set up {g,u}id mapping for user namespace of child process. */
5166 ret
= lxc_map_ids(idmap
, pid
);
5168 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5172 /* Tell child to proceed. */
5173 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
5175 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5179 if (fn_parent
&& fn_parent(fn_parent_data
)) {
5180 SYSERROR("Running parent function failed");
5181 _exit(EXIT_FAILURE
);
5185 close_prot_errno_disarm(sock_fds
[0]);
5186 close_prot_errno_disarm(sock_fds
[1]);
5188 /* Wait for child to finish. */
5192 return wait_for_pid(pid
);
5195 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
5196 const char *fn_name
)
5198 LIST_HEAD(full_idmap
);
5201 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
5202 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
5207 struct userns_fn_data d
;
5212 ret
= pipe2(p
, O_CLOEXEC
);
5217 d
.fn_name
= fn_name
;
5222 /* Clone child in new user namespace. */
5223 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5225 ERROR("Failed to clone process in new user namespace");
5235 /* Find container root. */
5236 list_for_each_entry(map
, &conf
->id_map
, head
) {
5237 __do_free
struct id_map
*dup_map
= NULL
;
5239 dup_map
= memdup(map
, sizeof(struct id_map
));
5243 list_add_tail(&dup_map
->head
, &full_idmap
);
5246 if (map
->idtype
== ID_TYPE_UID
)
5247 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
5250 if (map
->idtype
== ID_TYPE_GID
)
5251 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
5257 if (map
->idtype
== ID_TYPE_UID
)
5258 if (container_root_uid
== NULL
)
5259 container_root_uid
= map
;
5261 if (map
->idtype
== ID_TYPE_GID
)
5262 if (container_root_gid
== NULL
)
5263 container_root_gid
= map
;
5266 if (!container_root_uid
|| !container_root_gid
) {
5267 ERROR("No mapping for container root found");
5271 /* Check whether the {g,u}id of the user has a mapping. */
5273 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
5275 host_uid_map
= container_root_uid
;
5278 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
5280 host_gid_map
= container_root_gid
;
5282 if (!host_uid_map
) {
5283 DEBUG("Failed to find mapping for uid %d", euid
);
5287 if (!host_gid_map
) {
5288 DEBUG("Failed to find mapping for gid %d", egid
);
5292 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
5293 /* idmap will now keep track of that memory. */
5294 list_add_tail(&host_uid_map
->head
, &full_idmap
);
5295 move_ptr(host_uid_map
);
5298 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
5299 /* idmap will now keep track of that memory. */
5300 list_add_tail(&host_gid_map
->head
, &full_idmap
);
5301 move_ptr(host_gid_map
);
5304 if (lxc_log_trace()) {
5305 list_for_each_entry(map
, &full_idmap
, head
) {
5306 TRACE("establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5307 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
5308 map
->nsid
, map
->hostid
, map
->range
);
5312 /* Set up {g,u}id mapping for user namespace of child process. */
5313 ret
= lxc_map_ids(&full_idmap
, pid
);
5315 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
5319 /* Tell child to proceed. */
5320 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
5321 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5330 /* Wait for child to finish. */
5332 ret
= wait_for_pid(pid
);
5334 __lxc_free_idmap(&full_idmap
);
5336 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
5338 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
5344 static int add_idmap_entry(struct list_head
*idmap_list
, enum idtype idtype
,
5345 unsigned long nsid
, unsigned long hostid
,
5346 unsigned long range
)
5348 __do_free
struct id_map
*new_idmap
= NULL
;
5350 new_idmap
= zalloc(sizeof(*new_idmap
));
5352 return ret_errno(ENOMEM
);
5354 new_idmap
->idtype
= idtype
;
5355 new_idmap
->hostid
= hostid
;
5356 new_idmap
->nsid
= nsid
;
5357 new_idmap
->range
= range
;
5359 list_add_tail(&new_idmap
->head
, idmap_list
);
5360 move_ptr(new_idmap
);
5362 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5363 idtype
== ID_TYPE_UID
? 'u' : 'g', nsid
, hostid
, range
);
5367 int userns_exec_mapped_root(const char *path
, int path_fd
,
5368 const struct lxc_conf
*conf
)
5370 LIST_HEAD(idmap_list
);
5371 call_cleaner(__lxc_free_idmap
) struct list_head
*idmap
= &idmap_list
;
5372 __do_close
int fd
= -EBADF
;
5373 int target_fd
= -EBADF
;
5378 uid_t container_host_uid
, hostuid
;
5379 gid_t container_host_gid
, hostgid
;
5382 if (!conf
|| (!path
&& path_fd
< 0))
5383 return ret_errno(EINVAL
);
5388 container_host_uid
= get_mapped_rootid(conf
, ID_TYPE_UID
);
5389 if (!uid_valid(container_host_uid
))
5390 return log_error(-1, "No uid mapping for container root");
5392 container_host_gid
= get_mapped_rootid(conf
, ID_TYPE_GID
);
5393 if (!gid_valid(container_host_gid
))
5394 return log_error(-1, "No gid mapping for container root");
5397 fd
= open(path
, O_CLOEXEC
| O_NOCTTY
);
5399 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", path
);
5402 target_fd
= path_fd
;
5405 hostuid
= geteuid();
5406 /* We are root so chown directly. */
5408 ret
= fchown(target_fd
, container_host_uid
, container_host_gid
);
5410 return log_error_errno(-errno
, errno
,
5411 "Failed to fchown(%d(%s), %d, %d)",
5412 target_fd
, path
, container_host_uid
,
5413 container_host_gid
);
5414 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd
, path
,
5415 container_host_uid
, container_host_gid
);
5418 /* The container's root host id matches */
5419 if (container_host_uid
== hostuid
)
5420 return log_info(0, "Container root id is mapped to our uid");
5422 /* Get the current ids of our target. */
5423 ret
= fstat(target_fd
, &st
);
5425 return log_error_errno(-errno
, errno
, "Failed to stat \"%s\"", path
);
5427 hostgid
= getegid();
5428 if (st
.st_uid
== hostuid
&& mapped_hostid(st
.st_gid
, conf
, ID_TYPE_GID
) < 0) {
5429 ret
= fchown(target_fd
, -1, hostgid
);
5431 return log_error_errno(-errno
, errno
,
5432 "Failed to fchown(%d(%s), -1, %d)",
5433 target_fd
, path
, hostgid
);
5434 TRACE("Chowned %d(%s) to -1:%d", target_fd
, path
, hostgid
);
5437 /* "u:0:rootuid:1" */
5438 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, 0, container_host_uid
, 1);
5440 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5442 /* "u:hostuid:hostuid:1" */
5443 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, hostuid
, hostuid
, 1);
5445 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5447 /* "g:0:rootgid:1" */
5448 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, 0, container_host_gid
, 1);
5450 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5452 /* "g:hostgid:hostgid:1" */
5453 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, hostgid
, hostgid
, 1);
5455 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5457 if (hostgid
!= st
.st_gid
) {
5458 /* "g:pathgid:rootgid+pathgid:1" */
5459 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, st
.st_gid
,
5460 container_host_gid
+ (gid_t
)st
.st_gid
, 1);
5462 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5465 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5471 SYSERROR("Failed to create new process");
5476 close_prot_errno_disarm(sock_fds
[1]);
5478 ret
= unshare(CLONE_NEWUSER
);
5480 SYSERROR("Failed to unshare new user namespace");
5481 _exit(EXIT_FAILURE
);
5484 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5486 _exit(EXIT_FAILURE
);
5488 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5490 _exit(EXIT_FAILURE
);
5492 close_prot_errno_disarm(sock_fds
[0]);
5494 if (!lxc_switch_uid_gid(0, 0))
5495 _exit(EXIT_FAILURE
);
5497 if (!lxc_drop_groups())
5498 _exit(EXIT_FAILURE
);
5500 ret
= fchown(target_fd
, 0, st
.st_gid
);
5502 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5503 _exit(EXIT_FAILURE
);
5506 TRACE("Chowned %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5507 _exit(EXIT_SUCCESS
);
5510 close_prot_errno_disarm(sock_fds
[0]);
5512 if (lxc_log_trace()) {
5515 list_for_each_entry(map
, idmap
, head
)
5516 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5517 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5520 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
5522 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
5526 /* Set up {g,u}id mapping for user namespace of child process. */
5527 ret
= lxc_map_ids(idmap
, pid
);
5529 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5533 /* Tell child to proceed. */
5534 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
5536 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5541 close_prot_errno_disarm(sock_fds
[0]);
5542 close_prot_errno_disarm(sock_fds
[1]);
5544 /* Wait for child to finish. */
5548 return wait_for_pid(pid
);
5551 /* not thread-safe, do not use from api without first forking */
5552 static char *getuname(void)
5554 __do_free
char *buf
= NULL
;
5555 struct passwd pwent
;
5556 struct passwd
*pwentp
= NULL
;
5560 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
5564 buf
= zalloc(bufsize
);
5568 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
5571 WARN("Could not find matched password record.");
5573 return log_error(NULL
, "Failed to get password record - %u", geteuid());
5576 return strdup(pwent
.pw_name
);
5579 /* not thread-safe, do not use from api without first forking */
5580 static char *getgname(void)
5582 __do_free
char *buf
= NULL
;
5584 struct group
*grentp
= NULL
;
5588 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
5592 buf
= zalloc(bufsize
);
5596 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
5599 WARN("Could not find matched group record");
5601 return log_error(NULL
, "Failed to get group record - %u", getegid());
5604 return strdup(grent
.gr_name
);
5607 /* not thread-safe, do not use from api without first forking */
5608 void suggest_default_idmap(void)
5610 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
5611 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
5612 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
5623 subuid_f
= fopen(subuidfile
, "re");
5625 ERROR("Your system is not configured with subuids");
5629 while (getline(&line
, &len
, subuid_f
) != -1) {
5631 size_t no_newline
= 0;
5633 p
= strchr(line
, ':');
5641 if (!strequal(line
, uname
))
5644 p2
= strchr(p
, ':');
5651 no_newline
= strcspn(p2
, "\n");
5652 p2
[no_newline
] = '\0';
5654 if (lxc_safe_uint(p
, &uid
) < 0)
5655 WARN("Could not parse UID");
5656 if (lxc_safe_uint(p2
, &urange
) < 0)
5657 WARN("Could not parse UID range");
5660 subgid_f
= fopen(subgidfile
, "re");
5662 ERROR("Your system is not configured with subgids");
5666 while (getline(&line
, &len
, subgid_f
) != -1) {
5668 size_t no_newline
= 0;
5670 p
= strchr(line
, ':');
5678 if (!strequal(line
, uname
))
5681 p2
= strchr(p
, ':');
5688 no_newline
= strcspn(p2
, "\n");
5689 p2
[no_newline
] = '\0';
5691 if (lxc_safe_uint(p
, &gid
) < 0)
5692 WARN("Could not parse GID");
5693 if (lxc_safe_uint(p2
, &grange
) < 0)
5694 WARN("Could not parse GID range");
5697 if (!urange
|| !grange
) {
5698 ERROR("You do not have subuids or subgids allocated");
5699 ERROR("Unprivileged containers require subuids and subgids");
5703 ERROR("You must either run as root, or define uid mappings");
5704 ERROR("To pass uid mappings to lxc-create, you could create");
5705 ERROR("~/.config/lxc/default.conf:");
5706 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
5707 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
5708 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
5711 int lxc_set_environment(const struct lxc_conf
*conf
)
5713 struct environment_entry
*env
;
5715 list_for_each_entry(env
, &conf
->environment
, head
) {
5718 ret
= setenv(env
->key
, env
->val
, 1);
5720 return syserror("Failed to set environment variable: %s=%s",
5721 env
->key
, env
->val
);
5722 TRACE("Set environment variable: %s=%s", env
->key
, env
->val
);