1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <linux/loop.h>
15 #include <netinet/in.h>
23 #include <sys/mount.h>
24 #include <sys/param.h>
25 #include <sys/prctl.h>
26 #include <sys/sendfile.h>
27 #include <sys/socket.h>
29 #include <sys/syscall.h>
30 #include <sys/sysmacros.h>
31 #include <sys/types.h>
32 #include <sys/utsname.h>
39 #include "cgroups/cgroup.h"
44 #include "confile_utils.h"
49 #include "lxcseccomp.h"
51 #include "memory_utils.h"
52 #include "mount_utils.h"
53 #include "namespace.h"
56 #include "process_utils.h"
59 #include "storage/storage.h"
60 #include "storage/overlay.h"
62 #include "syscall_wrappers.h"
68 #include <sys/mkdev.h>
72 #include <sys/statvfs.h>
78 #include <../include/openpty.h>
82 #include <sys/capability.h>
86 #include "include/strlcat.h"
90 #include <../include/lxcmntent.h>
95 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
96 #include <../include/prlimit.h>
100 #include "include/strlcpy.h"
103 #ifndef HAVE_STRCHRNUL
104 #include "include/strchrnul.h"
107 lxc_log_define(conf
, lxc
);
110 * The lxc_conf of the container currently being worked on in an API call.
111 * This is used in the error calls.
113 thread_local
struct lxc_conf
*current_config
;
115 char *lxchook_names
[NUM_LXC_HOOKS
] = {
146 static struct mount_opt mount_opt
[] = {
147 { "atime", 1, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
148 { "dev", 1, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
149 { "diratime", 1, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
150 { "exec", 1, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
151 { "noatime", 0, false, MOUNT_ATTR_NOATIME
, MS_NOATIME
},
152 { "nodev", 0, false, MOUNT_ATTR_NODEV
, MS_NODEV
},
153 { "nodiratime", 0, false, MOUNT_ATTR_NODIRATIME
, MS_NODIRATIME
},
154 { "noexec", 0, false, MOUNT_ATTR_NOEXEC
, MS_NOEXEC
},
155 { "norelatime", 1, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
156 { "nostrictatime", 1, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
157 { "nosuid", 0, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
158 { "relatime", 0, false, MOUNT_ATTR_RELATIME
, MS_RELATIME
},
159 { "ro", 0, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
160 { "rw", 1, false, MOUNT_ATTR_RDONLY
, MS_RDONLY
},
161 { "strictatime", 0, false, MOUNT_ATTR_STRICTATIME
, MS_STRICTATIME
},
162 { "suid", 1, false, MOUNT_ATTR_NOSUID
, MS_NOSUID
},
164 { "bind", 0, false, 0, MS_BIND
},
165 { "defaults", 0, false, 0, 0 },
166 { "rbind", 0, true, 0, MS_BIND
| MS_REC
},
168 { "sync", 0, false, ~0, MS_SYNCHRONOUS
},
169 { "async", 1, false, ~0, MS_SYNCHRONOUS
},
170 { "dirsync", 0, false, ~0, MS_DIRSYNC
},
171 { "lazytime", 0, false, ~0, MS_LAZYTIME
},
172 { "mand", 0, false, ~0, MS_MANDLOCK
},
173 { "nomand", 1, false, ~0, MS_MANDLOCK
},
174 { "remount", 0, false, ~0, MS_REMOUNT
},
176 { NULL
, 0, false, ~0, ~0 },
179 static struct mount_opt propagation_opt
[] = {
180 { "private", 0, false, MS_PRIVATE
, MS_PRIVATE
},
181 { "shared", 0, false, MS_SHARED
, MS_SHARED
},
182 { "slave", 0, false, MS_SLAVE
, MS_SLAVE
},
183 { "unbindable", 0, false, MS_UNBINDABLE
, MS_UNBINDABLE
},
184 { "rprivate", 0, true, MS_PRIVATE
, MS_PRIVATE
| MS_REC
},
185 { "rshared", 0, true, MS_SHARED
, MS_SHARED
| MS_REC
},
186 { "rslave", 0, true, MS_SLAVE
, MS_SLAVE
| MS_REC
},
187 { "runbindable", 0, true, MS_UNBINDABLE
, MS_UNBINDABLE
| MS_REC
},
191 static struct caps_opt caps_opt
[] = {
193 { "chown", CAP_CHOWN
},
194 { "dac_override", CAP_DAC_OVERRIDE
},
195 { "dac_read_search", CAP_DAC_READ_SEARCH
},
196 { "fowner", CAP_FOWNER
},
197 { "fsetid", CAP_FSETID
},
198 { "kill", CAP_KILL
},
199 { "setgid", CAP_SETGID
},
200 { "setuid", CAP_SETUID
},
201 { "setpcap", CAP_SETPCAP
},
202 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
203 { "net_bind_service", CAP_NET_BIND_SERVICE
},
204 { "net_broadcast", CAP_NET_BROADCAST
},
205 { "net_admin", CAP_NET_ADMIN
},
206 { "net_raw", CAP_NET_RAW
},
207 { "ipc_lock", CAP_IPC_LOCK
},
208 { "ipc_owner", CAP_IPC_OWNER
},
209 { "sys_module", CAP_SYS_MODULE
},
210 { "sys_rawio", CAP_SYS_RAWIO
},
211 { "sys_chroot", CAP_SYS_CHROOT
},
212 { "sys_ptrace", CAP_SYS_PTRACE
},
213 { "sys_pacct", CAP_SYS_PACCT
},
214 { "sys_admin", CAP_SYS_ADMIN
},
215 { "sys_boot", CAP_SYS_BOOT
},
216 { "sys_nice", CAP_SYS_NICE
},
217 { "sys_resource", CAP_SYS_RESOURCE
},
218 { "sys_time", CAP_SYS_TIME
},
219 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
220 { "mknod", CAP_MKNOD
},
221 { "lease", CAP_LEASE
},
222 { "audit_write", CAP_AUDIT_WRITE
},
223 { "audit_control", CAP_AUDIT_CONTROL
},
224 { "setfcap", CAP_SETFCAP
},
225 { "mac_override", CAP_MAC_OVERRIDE
},
226 { "mac_admin", CAP_MAC_ADMIN
},
227 { "syslog", CAP_SYSLOG
},
228 { "wake_alarm", CAP_WAKE_ALARM
},
229 { "block_suspend", CAP_BLOCK_SUSPEND
},
230 { "audit_read", CAP_AUDIT_READ
},
231 { "perfmon", CAP_PERFMON
},
233 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE
},
237 static struct limit_opt limit_opt
[] = {
242 { "core", RLIMIT_CORE
},
245 { "cpu", RLIMIT_CPU
},
248 { "data", RLIMIT_DATA
},
251 { "fsize", RLIMIT_FSIZE
},
254 { "locks", RLIMIT_LOCKS
},
256 #ifdef RLIMIT_MEMLOCK
257 { "memlock", RLIMIT_MEMLOCK
},
259 #ifdef RLIMIT_MSGQUEUE
260 { "msgqueue", RLIMIT_MSGQUEUE
},
263 { "nice", RLIMIT_NICE
},
266 { "nofile", RLIMIT_NOFILE
},
269 { "nproc", RLIMIT_NPROC
},
272 { "rss", RLIMIT_RSS
},
275 { "rtprio", RLIMIT_RTPRIO
},
278 { "rttime", RLIMIT_RTTIME
},
280 #ifdef RLIMIT_SIGPENDING
281 { "sigpending", RLIMIT_SIGPENDING
},
284 { "stack", RLIMIT_STACK
},
288 static int run_buffer(char *buffer
)
290 __do_free
char *output
= NULL
;
291 __do_lxc_pclose
struct lxc_popen_FILE
*f
= NULL
;
294 f
= lxc_popen(buffer
);
296 return log_error_errno(-1, errno
, "Failed to popen() %s", buffer
);
298 output
= zalloc(LXC_LOG_BUFFER_SIZE
);
300 return log_error_errno(-1, ENOMEM
, "Failed to allocate memory for %s", buffer
);
304 return log_error_errno(-1, errno
, "Failed to retrieve underlying file descriptor");
306 for (int i
= 0; i
< 10; i
++) {
309 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
310 if (bytes_read
> 0) {
311 output
[bytes_read
] = '\0';
312 DEBUG("Script %s produced output: %s", buffer
, output
);
319 ret
= lxc_pclose(move_ptr(f
));
321 return log_error_errno(-1, errno
, "Script exited with error");
322 else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0)
323 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret
));
324 else if (WIFSIGNALED(ret
))
325 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret
));
330 int run_script_argv(const char *name
, unsigned int hook_version
,
331 const char *section
, const char *script
,
332 const char *hookname
, char **argv
)
334 __do_free
char *buffer
= NULL
;
338 if (hook_version
== 0)
339 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
340 script
, name
, section
);
342 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
344 for (i
= 0; argv
&& argv
[i
]; i
++)
345 size
+= strlen(argv
[i
]) + 1;
347 size
+= STRLITERALLEN("exec");
349 size
+= strlen(script
);
355 if (hook_version
== 0) {
356 size
+= strlen(hookname
);
359 size
+= strlen(name
);
362 size
+= strlen(section
);
369 buffer
= zalloc(size
);
373 if (hook_version
== 0)
374 buf_pos
= strnprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
376 buf_pos
= strnprintf(buffer
, size
, "exec %s", script
);
378 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
380 if (hook_version
== 1) {
381 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
383 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname
);
385 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
387 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
389 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section
);
390 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
392 if (strequal(section
, "net")) {
395 if (!argv
|| !argv
[0])
398 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
400 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_TYPE=%s", argv
[0]);
401 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
403 parent
= argv
[1] ? argv
[1] : "";
405 if (strequal(argv
[0], "macvlan")) {
406 ret
= setenv("LXC_NET_PARENT", parent
, 1);
408 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
409 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
410 } else if (strequal(argv
[0], "phys")) {
411 ret
= setenv("LXC_NET_PARENT", parent
, 1);
413 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
414 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
415 } else if (strequal(argv
[0], "veth")) {
416 char *peer
= argv
[2] ? argv
[2] : "";
418 ret
= setenv("LXC_NET_PEER", peer
, 1);
420 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PEER=%s", peer
);
421 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
423 ret
= setenv("LXC_NET_PARENT", parent
, 1);
425 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
426 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
431 for (i
= 0; argv
&& argv
[i
]; i
++) {
432 size_t len
= size
- buf_pos
;
434 ret
= strnprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
436 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
440 return run_buffer(buffer
);
443 int run_script(const char *name
, const char *section
, const char *script
, ...)
445 __do_free
char *buffer
= NULL
;
451 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
452 script
, name
, section
);
454 va_start(ap
, script
);
455 while ((p
= va_arg(ap
, char *)))
456 size
+= strlen(p
) + 1;
459 size
+= STRLITERALLEN("exec");
460 size
+= strlen(script
);
461 size
+= strlen(name
);
462 size
+= strlen(section
);
468 buffer
= must_realloc(NULL
, size
);
469 ret
= strnprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
473 va_start(ap
, script
);
474 while ((p
= va_arg(ap
, char *))) {
475 int len
= size
- ret
;
477 rc
= strnprintf(buffer
+ ret
, len
, " %s", p
);
486 return run_buffer(buffer
);
489 int lxc_storage_prepare(struct lxc_conf
*conf
)
492 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
495 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
497 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
499 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
500 if (rootfs
->dfd_mnt
< 0)
506 ret
= access(rootfs
->mount
, F_OK
);
508 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
511 rootfs
->storage
= storage_init(conf
);
512 if (!rootfs
->storage
)
513 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
514 rootfs
->path
, rootfs
->mount
,
515 rootfs
->options
? rootfs
->options
: "(null)");
520 void lxc_storage_put(struct lxc_conf
*conf
)
522 storage_put(conf
->rootfs
.storage
);
523 conf
->rootfs
.storage
= NULL
;
526 /* lxc_rootfs_prepare
527 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
528 * the duration of the container run, to prevent the container from marking
529 * the underlying fs readonly on shutdown. unlink the file immediately so
530 * no name pollution is happens.
531 * don't unlink on NFS to avoid random named stale handles.
533 int lxc_rootfs_init(struct lxc_conf
*conf
, bool userns
)
535 __do_close
int dfd_path
= -EBADF
, fd_pin
= -EBADF
;
539 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
541 ret
= lxc_storage_prepare(conf
);
543 return syserror_set(-EINVAL
, "Failed to prepare rootfs storage");
545 if (!is_empty_string(rootfs
->mnt_opts
.userns_path
)) {
547 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supported with separate rootfs for container");
549 if (rootfs
->bdev_type
&& !strequal(rootfs
->bdev_type
, "dir"))
550 return syserror_set(-EINVAL
, "Idmapped rootfs currently only supports the \"dir\" storage driver");
554 return log_trace(0, "Not pinning because container does not have a rootfs");
557 return log_trace(0, "Not pinning because container runs in user namespace");
559 if (rootfs
->bdev_type
) {
560 if (strequal(rootfs
->bdev_type
, "overlay") ||
561 strequal(rootfs
->bdev_type
, "overlayfs"))
562 return log_trace_errno(0, EINVAL
, "Not pinning on stacking filesystem");
564 if (strequal(rootfs
->bdev_type
, "zfs"))
565 return log_trace_errno(0, EINVAL
, "Not pinning on ZFS filesystem");
568 dfd_path
= open_at(-EBADF
, rootfs
->path
, PROTECT_OPATH_FILE
, 0, 0);
570 return syserror("Failed to open \"%s\"", rootfs
->path
);
572 ret
= fstat(dfd_path
, &st
);
574 return log_trace_errno(-errno
, errno
, "Failed to retrieve file status");
576 if (!S_ISDIR(st
.st_mode
))
577 return log_trace_errno(0, ENOTDIR
, "Not pinning because file descriptor is not a directory");
579 fd_pin
= open_at(dfd_path
, ".lxc_keep",
580 PROTECT_OPEN
| O_CREAT
,
581 PROTECT_LOOKUP_BENEATH
,
584 if (errno
== EROFS
) {
585 return log_trace_errno(0, EROFS
, "Not pinning on read-only filesystem");
587 return syserror("Failed to pin rootfs");
590 TRACE("Pinned rootfs %d(.lxc_keep)", fd_pin
);
592 ret
= fstatfs(fd_pin
, &stfs
);
594 SYSWARN("Failed to retrieve filesystem status");
598 if (stfs
.f_type
== NFS_SUPER_MAGIC
) {
599 DEBUG("Not unlinking pinned file on NFS");
603 if (unlinkat(dfd_path
, ".lxc_keep", 0))
604 SYSTRACE("Failed to unlink rootfs pinning file %d(.lxc_keep)", dfd_path
);
606 TRACE("Unlinked pinned file %d(.lxc_keep)", dfd_path
);
609 rootfs
->fd_path_pin
= move_fd(fd_pin
);
613 int lxc_rootfs_prepare_parent(struct lxc_handler
*handler
)
615 __do_close
int dfd_idmapped
= -EBADF
, fd_userns
= -EBADF
;
616 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
617 struct lxc_storage
*storage
= rootfs
->storage
;
619 const char *path_source
;
621 if (lxc_list_empty(&handler
->conf
->id_map
))
624 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
627 if (handler
->conf
->rootfs_setup
)
630 if (rootfs_is_blockdev(handler
->conf
))
631 return syserror_set(-EOPNOTSUPP
, "Idmapped mounts on block-backed storage not yet supported");
633 if (!can_use_bind_mounts())
634 return syserror_set(-EOPNOTSUPP
, "Kernel does not support the new mount api");
636 if (strequal(rootfs
->mnt_opts
.userns_path
, "container"))
637 fd_userns
= dup_cloexec(handler
->nsfd
[LXC_NS_USER
]);
639 fd_userns
= open_at(-EBADF
, rootfs
->mnt_opts
.userns_path
,
640 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
642 return syserror("Failed to open user namespace");
644 path_source
= lxc_storage_get_path(storage
->src
, storage
->type
);
646 dfd_idmapped
= create_detached_idmapped_mount(path_source
, fd_userns
, true);
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 int has_sys_admin
= 0;
830 if (!lxc_list_empty(&conf
->keepcaps
))
831 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
833 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
835 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
836 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
838 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
841 if (flags
& LXC_AUTO_CGROUP_FORCE
)
842 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
844 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
, handler
, cg_flags
))
845 return log_error_errno(-1, errno
, "Failed to mount \"/sys/fs/cgroup\"");
848 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
849 ret
= add_shmount_to_list(conf
);
851 return log_error(-1, "Failed to add shmount entry to container config");
857 static int setup_utsname(struct utsname
*utsname
)
864 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
866 return log_error_errno(-1, errno
, "Failed to set the hostname to \"%s\"",
869 INFO("Set hostname to \"%s\"", utsname
->nodename
);
874 struct dev_symlinks
{
879 static const struct dev_symlinks dev_symlinks
[] = {
880 { "/proc/self/fd", "fd" },
881 { "/proc/self/fd/0", "stdin" },
882 { "/proc/self/fd/1", "stdout" },
883 { "/proc/self/fd/2", "stderr" },
886 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
888 for (int i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
891 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
894 * Stat the path first. If we don't get an error accept it as
895 * is and don't try to create it
897 ret
= fstatat(rootfs
->dfd_dev
, d
->name
, &s
, 0);
901 ret
= symlinkat(d
->oldpath
, rootfs
->dfd_dev
, d
->name
);
905 WARN("Failed to create \"%s\" on read-only filesystem", d
->name
);
910 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", d
->name
);
918 /* Build a space-separate list of ptys to pass to systemd. */
919 static bool append_ttyname(char **pp
, char *name
)
925 *pp
= zalloc(strlen(name
) + strlen("container_ttys=") + 1);
929 sprintf(*pp
, "container_ttys=%s", name
);
933 size
= strlen(*pp
) + strlen(name
) + 2;
934 p
= realloc(*pp
, size
);
939 (void)strlcat(p
, " ", size
);
940 (void)strlcat(p
, name
, size
);
945 static int open_ttymnt_at(int dfd
, const char *path
)
949 fd
= open_at(dfd
, path
, PROTECT_OPEN
| O_CREAT
| O_EXCL
,
950 PROTECT_LOOKUP_BENEATH
, 0);
951 if (fd
< 0 && (errno
== ENXIO
|| errno
== EEXIST
))
952 fd
= open_at(dfd
, path
, PROTECT_OPATH_FILE
,
953 PROTECT_LOOKUP_BENEATH
, 0);
958 static int lxc_setup_ttys(struct lxc_conf
*conf
)
961 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
962 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
963 char *ttydir
= ttys
->dir
;
965 if (!conf
->rootfs
.path
)
968 for (int i
= 0; i
< ttys
->max
; i
++) {
969 __do_close
int fd_to
= -EBADF
;
970 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
973 char *tty_name
, *tty_path
;
975 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
976 "/dev/%s/tty%d", ttydir
, i
+ 1);
978 return ret_errno(-EIO
);
980 tty_path
= &rootfs
->buf
[STRLITERALLEN("/dev/")];
981 tty_name
= tty_path
+ strlen(ttydir
) + 1;
983 /* create bind-mount target */
984 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, tty_path
);
986 return log_error_errno(-errno
, errno
,
987 "Failed to create tty mount target %d(%s)",
988 rootfs
->dfd_dev
, tty_path
);
990 ret
= unlinkat(rootfs
->dfd_dev
, tty_name
, 0);
991 if (ret
< 0 && errno
!= ENOENT
)
992 return log_error_errno(-errno
, errno
,
993 "Failed to unlink %d(%s)",
994 rootfs
->dfd_dev
, tty_name
);
996 if (can_use_mount_api())
997 ret
= fd_bind_mount(tty
->pty
, "",
999 PROTECT_LOOKUP_BENEATH_XDEV
,
1002 PROTECT_LOOKUP_BENEATH_XDEV
, 0,
1005 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1007 return log_error_errno(-errno
, errno
,
1008 "Failed to bind mount \"%s\" onto \"%s\"",
1009 tty
->name
, rootfs
->buf
);
1010 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1012 ret
= symlinkat(tty_path
, rootfs
->dfd_dev
, tty_name
);
1014 return log_error_errno(-errno
, errno
,
1015 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
1016 rootfs
->dfd_dev
, tty_name
,
1017 rootfs
->dfd_dev
, tty_path
);
1019 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "tty%d", i
+ 1);
1021 return ret_errno(-EIO
);
1023 /* If we populated /dev, then we need to create /dev/tty<idx>. */
1024 fd_to
= open_ttymnt_at(rootfs
->dfd_dev
, rootfs
->buf
);
1026 return log_error_errno(-errno
, errno
,
1027 "Failed to create tty mount target %d(%s)",
1028 rootfs
->dfd_dev
, rootfs
->buf
);
1030 if (can_use_mount_api())
1031 ret
= fd_bind_mount(tty
->pty
, "",
1033 PROTECT_LOOKUP_BENEATH_XDEV
,
1036 PROTECT_LOOKUP_BENEATH
, 0,
1039 ret
= mount_fd(tty
->pty
, fd_to
, "none", MS_BIND
, 0);
1041 return log_error_errno(-errno
, errno
,
1042 "Failed to bind mount \"%s\" onto \"%s\"",
1043 tty
->name
, rootfs
->buf
);
1044 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, rootfs
->buf
);
1047 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
))
1048 return log_error(-1, "Error setting up container_ttys string");
1051 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
1055 define_cleanup_function(struct lxc_tty_info
*, lxc_delete_tty
);
1057 static int lxc_allocate_ttys(struct lxc_conf
*conf
)
1059 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*ttys
= &conf
->ttys
;
1062 /* no tty in the configuration */
1066 ttys
->tty
= zalloc(sizeof(struct lxc_terminal_info
) * ttys
->max
);
1070 for (size_t i
= 0; i
< conf
->ttys
.max
; i
++) {
1072 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1074 ret
= lxc_devpts_terminal(conf
->devpts_fd
, &tty
->ptx
,
1075 &tty
->pty
, &pty_nr
, false);
1078 return syserror_set(-ENOTTY
, "Failed to create tty %zu", i
);
1080 DEBUG("Created tty with ptx fd %d and pty fd %d and index %d",
1081 tty
->ptx
, tty
->pty
, pty_nr
);
1085 INFO("Finished creating %zu tty devices", ttys
->max
);
1090 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1092 if (!ttys
|| !ttys
->tty
)
1095 for (int i
= 0; i
< ttys
->max
; i
++) {
1096 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1097 close_prot_errno_disarm(tty
->ptx
);
1098 close_prot_errno_disarm(tty
->pty
);
1101 free_disarm(ttys
->tty
);
1104 static int __lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1108 struct lxc_conf
*conf
= handler
->conf
;
1109 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1110 int sock
= handler
->data_sock
[0];
1115 for (i
= 0; i
< ttys
->max
; i
++) {
1117 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1119 ttyfds
[0] = tty
->ptx
;
1120 ttyfds
[1] = tty
->pty
;
1122 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1126 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1127 tty
->name
, tty
->ptx
, tty
->pty
);
1131 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1133 TRACE("Sent %zu ttys to parent", ttys
->max
);
1138 static int lxc_create_ttys(struct lxc_handler
*handler
)
1141 struct lxc_conf
*conf
= handler
->conf
;
1143 ret
= lxc_allocate_ttys(conf
);
1145 ERROR("Failed to allocate ttys");
1149 if (!conf
->is_execute
) {
1150 ret
= lxc_setup_ttys(conf
);
1152 ERROR("Failed to setup ttys");
1157 if (conf
->ttys
.tty_names
) {
1158 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1160 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1168 lxc_delete_tty(&conf
->ttys
);
1173 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1177 ret
= __lxc_send_ttys_to_parent(handler
);
1178 lxc_delete_tty(&handler
->conf
->ttys
);
1182 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1183 * error, log it but don't fail yet.
1185 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1186 int autodevtmpfssize
, const char *lxcpath
)
1188 __do_close
int fd_fs
= -EBADF
;
1189 const char *path
= rootfs
->path
? rootfs
->mount
: NULL
;
1190 size_t tmpfs_size
= (autodevtmpfssize
!= 0) ? autodevtmpfssize
: 500000;
1193 char mount_options
[128];
1195 INFO("Preparing \"/dev\"");
1197 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1198 ret
= mkdirat(rootfs
->dfd_mnt
, "dev" , S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1199 if (ret
< 0 && errno
!= EEXIST
) {
1200 SYSERROR("Failed to create \"/dev\" directory");
1205 if (can_use_mount_api()) {
1206 fd_fs
= fs_prepare("tmpfs", -EBADF
, "", 0, 0);
1208 return log_error_errno(-errno
, errno
, "Failed to prepare filesystem context for tmpfs");
1210 sprintf(mount_options
, "%zu", tmpfs_size
);
1212 ret
= fs_set_property(fd_fs
, "mode", "0755");
1214 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1216 ret
= fs_set_property(fd_fs
, "size", mount_options
);
1218 return log_error_errno(-errno
, errno
, "Failed to mount tmpfs onto %d(dev)", fd_fs
);
1220 ret
= fs_attach(fd_fs
, rootfs
->dfd_mnt
, "dev",
1221 PROTECT_OPATH_DIRECTORY
,
1222 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1224 __do_free
char *fallback_path
= NULL
;
1226 sprintf(mount_options
, "size=%zu,mode=755", tmpfs_size
);
1227 DEBUG("Using mount options: %s", mount_options
);
1230 fallback_path
= must_make_path(path
, "/dev", NULL
);
1231 ret
= safe_mount("none", fallback_path
, "tmpfs", 0, mount_options
, path
);
1233 ret
= safe_mount("none", "dev", "tmpfs", 0, mount_options
, NULL
);
1237 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1241 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1242 * If not, then create it and exit if that fails...
1244 ret
= mkdirat(rootfs
->dfd_mnt
, "dev/pts", S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1245 if (ret
< 0 && errno
!= EEXIST
) {
1246 SYSERROR("Failed to create directory \"dev/pts\"");
1254 (void)umask(cur_mask
);
1256 INFO("Prepared \"/dev\"");
1260 struct lxc_device_node
{
1267 static const struct lxc_device_node lxc_devices
[] = {
1268 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1269 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1270 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1271 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1272 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1273 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1280 LXC_DEVNODE_PARTIAL
,
1284 static int lxc_fill_autodev(struct lxc_rootfs
*rootfs
)
1288 int use_mknod
= LXC_DEVNODE_MKNOD
;
1290 if (rootfs
->dfd_dev
< 0)
1291 return log_info(0, "No /dev directory found, skipping setup");
1293 INFO("Populating \"/dev\"");
1295 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1296 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1297 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1299 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1300 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, device
->mode
, makedev(device
->maj
, device
->min
));
1301 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1302 DEBUG("Created device node \"%s\"", device
->name
);
1303 } else if (ret
< 0) {
1305 return log_error_errno(-1, errno
, "Failed to create device node \"%s\"", device
->name
);
1307 use_mknod
= LXC_DEVNODE_BIND
;
1310 /* Device nodes are fully useable. */
1311 if (use_mknod
== LXC_DEVNODE_OPEN
)
1314 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1315 __do_close
int fd
= -EBADF
;
1317 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1318 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1320 fd
= open_at(rootfs
->dfd_dev
, device
->name
, PROTECT_OPEN
, PROTECT_LOOKUP_BENEATH
, 0);
1322 /* Device nodes are fully useable. */
1323 use_mknod
= LXC_DEVNODE_OPEN
;
1327 SYSTRACE("Failed to open \"%s\" device", device
->name
);
1328 /* Device nodes are only partially useable. */
1329 use_mknod
= LXC_DEVNODE_PARTIAL
;
1333 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1334 /* If we are dealing with partially functional device
1335 * nodes the prio mknod() call will have created the
1336 * device node so we can use it as a bind-mount target.
1338 ret
= mknodat(rootfs
->dfd_dev
, device
->name
, S_IFREG
| 0000, 0);
1339 if (ret
< 0 && errno
!= EEXIST
)
1340 return log_error_errno(-1, errno
, "Failed to create file \"%s\"", device
->name
);
1343 /* Fallback to bind-mounting the device from the host. */
1344 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "dev/%s", device
->name
);
1346 return ret_errno(EIO
);
1348 if (can_use_mount_api()) {
1349 ret
= fd_bind_mount(rootfs
->dfd_host
, rootfs
->buf
,
1351 PROTECT_LOOKUP_BENEATH_XDEV
,
1352 rootfs
->dfd_dev
, device
->name
,
1354 PROTECT_LOOKUP_BENEATH
, 0, false);
1356 char path
[PATH_MAX
];
1358 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/dev/%s", device
->name
);
1360 return ret_errno(EIO
);
1362 ret
= strnprintf(path
, sizeof(path
), "%s/dev/%s", get_rootfs_mnt(rootfs
), device
->name
);
1364 return log_error(-1, "Failed to create device path for %s", device
->name
);
1366 ret
= safe_mount(rootfs
->buf
, path
, 0, MS_BIND
, NULL
, get_rootfs_mnt(rootfs
));
1368 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1370 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs
->buf
, path
);
1373 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs
->dfd_host
, rootfs
->buf
, rootfs
->dfd_dev
, device
->name
);
1377 INFO("Populated \"/dev\"");
1381 static int lxc_mount_rootfs(struct lxc_rootfs
*rootfs
)
1385 if (!rootfs
->path
) {
1386 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1388 return log_error_errno(-1, errno
, "Failed to recursively turn root mount tree into dependent mount");
1390 rootfs
->dfd_mnt
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1391 if (rootfs
->dfd_mnt
< 0)
1394 return log_trace(0, "Container doesn't use separate rootfs. Opened host's rootfs");
1397 ret
= access(rootfs
->mount
, F_OK
);
1399 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1402 ret
= rootfs
->storage
->ops
->mount(rootfs
->storage
);
1404 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1405 rootfs
->path
, rootfs
->mount
,
1406 rootfs
->options
? rootfs
->options
: "(null)");
1408 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1409 rootfs
->path
, rootfs
->mount
,
1410 rootfs
->options
? rootfs
->options
: "(null)");
1412 rootfs
->dfd_mnt
= open_at(-EBADF
, rootfs
->mount
, PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1413 if (rootfs
->dfd_mnt
< 0)
1416 return log_trace(0, "Container uses separate rootfs. Opened container's rootfs");
1419 static int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1421 __do_free
char *nroot
= NULL
;
1423 char *root
= rootfs
->mount
;
1425 nroot
= realpath(root
, NULL
);
1427 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1433 /* We could use here MS_MOVE, but in userns this mount is locked and
1436 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1438 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1440 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1442 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1444 /* The following code cleans up inherited mounts which are not required
1447 * The mountinfo file shows not all mounts, if a few points have been
1448 * unmounted between read operations from the mountinfo. So we need to
1449 * read mountinfo a few times.
1451 * This loop can be skipped if a container uses userns, because all
1452 * inherited mounts are locked and we should live with all this trash.
1455 __do_fclose
FILE *f
= NULL
;
1456 __do_free
char *line
= NULL
;
1457 char *slider1
, *slider2
;
1461 f
= fopen("./proc/self/mountinfo", "re");
1463 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1465 while (getline(&line
, &len
, f
) > 0) {
1466 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1467 slider1
= strchr(slider1
+ 1, ' ');
1472 slider2
= strchr(slider1
+ 1, ' ');
1479 if (strequal(slider1
+ 1, "/"))
1482 if (strequal(slider1
+ 1, "/proc"))
1485 ret
= umount2(slider1
, MNT_DETACH
);
1494 /* This also can be skipped if a container uses userns. */
1495 (void)umount2("./proc", MNT_DETACH
);
1497 /* It is weird, but chdir("..") moves us in a new root */
1500 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1504 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1509 /* (The following explanation is copied verbatim from the kernel.)
1511 * pivot_root Semantics:
1512 * Moves the root file system of the current process to the directory put_old,
1513 * makes new_root as the new root file system of the current process, and sets
1514 * root/cwd of all processes which had them on the current root to new_root.
1517 * The new_root and put_old must be directories, and must not be on the
1518 * same file system as the current process root. The put_old must be
1519 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1520 * pointed to by put_old must yield the same directory as new_root. No other
1521 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1523 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1524 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1525 * in this situation.
1528 * - we don't move root/cwd if they are not at the root (reason: if something
1529 * cared enough to change them, it's probably wrong to force them elsewhere)
1530 * - it's okay to pick a root that isn't the root of a file system, e.g.
1531 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1532 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1535 static int lxc_pivot_root(const struct lxc_rootfs
*rootfs
)
1537 __do_close
int fd_oldroot
= -EBADF
;
1540 fd_oldroot
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
1542 return log_error_errno(-1, errno
, "Failed to open old root directory");
1544 /* change into new root fs */
1545 ret
= fchdir(rootfs
->dfd_mnt
);
1547 return log_error_errno(-errno
, errno
, "Failed to change into new root directory \"%s\"", rootfs
->mount
);
1549 /* pivot_root into our new root fs */
1550 ret
= pivot_root(".", ".");
1552 return log_error_errno(-errno
, errno
, "Failed to pivot into new root directory \"%s\"", rootfs
->mount
);
1554 /* At this point the old-root is mounted on top of our new-root. To
1555 * unmounted it we must not be chdir'd into it, so escape back to
1558 ret
= fchdir(fd_oldroot
);
1560 return log_error_errno(-errno
, errno
, "Failed to enter old root directory");
1563 * Make fd_oldroot a depedent mount to make sure our umounts don't
1564 * propagate to the host.
1566 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1568 return log_error_errno(-errno
, errno
, "Failed to recursively turn old root mount tree into dependent mount");
1570 ret
= umount2(".", MNT_DETACH
);
1572 return log_error_errno(-errno
, errno
, "Failed to detach old root directory");
1574 ret
= fchdir(rootfs
->dfd_mnt
);
1576 return log_error_errno(-errno
, errno
, "Failed to re-enter new root directory \"%s\"", rootfs
->mount
);
1578 TRACE("Changed into new rootfs \"%s\"", rootfs
->mount
);
1582 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1585 return log_debug(0, "Container does not have a rootfs");
1587 if (detect_ramfs_rootfs())
1588 return lxc_chroot(rootfs
);
1590 return lxc_pivot_root(rootfs
);
1593 static const struct id_map
*find_mapped_nsid_entry(const struct lxc_conf
*conf
,
1597 struct lxc_list
*it
;
1599 struct id_map
*retmap
= NULL
;
1601 /* Shortcut for container's root mappings. */
1603 if (idtype
== ID_TYPE_UID
)
1604 return conf
->root_nsuid_map
;
1606 if (idtype
== ID_TYPE_GID
)
1607 return conf
->root_nsgid_map
;
1610 lxc_list_for_each(it
, &conf
->id_map
) {
1612 if (map
->idtype
!= idtype
)
1615 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1624 static int lxc_recv_devpts_from_child(struct lxc_handler
*handler
)
1628 if (handler
->conf
->pty_max
<= 0)
1631 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1],
1632 &handler
->conf
->devpts_fd
,
1633 &handler
->conf
->devpts_fd
,
1634 sizeof(handler
->conf
->devpts_fd
));
1636 return log_error_errno(-1, errno
, "Failed to receive devpts fd from child");
1638 TRACE("Received devpts file descriptor %d from child", handler
->conf
->devpts_fd
);
1642 static int lxc_setup_devpts_child(struct lxc_handler
*handler
)
1644 __do_close
int devpts_fd
= -EBADF
, fd_fs
= -EBADF
;
1645 struct lxc_conf
*conf
= handler
->conf
;
1646 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1649 if (conf
->pty_max
<= 0)
1650 return log_debug(0, "No new devpts instance will be mounted since no pts devices are requested");
1652 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
),
1653 "/proc/self/fd/%d/pts", rootfs
->dfd_dev
);
1655 return syserror("Failed to create path");
1657 (void)umount2(rootfs
->buf
, MNT_DETACH
);
1659 /* Create mountpoint for devpts instance. */
1660 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1661 if (ret
< 0 && errno
!= EEXIST
)
1662 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1664 if (can_use_mount_api()) {
1665 fd_fs
= fs_prepare("devpts", -EBADF
, "", 0, 0);
1667 return syserror("Failed to prepare filesystem context for devpts");
1669 ret
= fs_set_property(fd_fs
, "source", "devpts");
1671 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs
);
1673 ret
= fs_set_property(fd_fs
, "gid", "5");
1675 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs
);
1677 ret
= fs_set_flag(fd_fs
, "newinstance");
1679 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs
);
1681 ret
= fs_set_property(fd_fs
, "ptmxmode", "0666");
1683 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs
);
1685 ret
= fs_set_property(fd_fs
, "mode", "0620");
1687 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs
);
1689 ret
= fs_set_property(fd_fs
, "max", fdstr(conf
->pty_max
));
1691 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf
->pty_max
, fd_fs
);
1693 ret
= fsconfig(fd_fs
, FSCONFIG_CMD_CREATE
, NULL
, NULL
, 0);
1695 return syserror("Failed to finalize filesystem context %d", fd_fs
);
1697 devpts_fd
= fsmount(fd_fs
, FSMOUNT_CLOEXEC
, MOUNT_ATTR_NOSUID
| MOUNT_ATTR_NOEXEC
);
1699 return syserror("Failed to create new mount for filesystem context %d", fd_fs
);
1700 TRACE("Created detached devpts mount %d", devpts_fd
);
1702 ret
= move_mount(devpts_fd
, "", rootfs
->dfd_dev
, "pts", MOVE_MOUNT_F_EMPTY_PATH
);
1704 return syserror("Failed to attach devpts mount %d to %d/pts", conf
->devpts_fd
, rootfs
->dfd_dev
);
1706 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd
, rootfs
->dfd_dev
);
1709 char devpts_mntopts
[256];
1710 char *mntopt_sets
[5];
1711 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1714 * Fallback codepath in case the new mount API can't be used to
1715 * create detached mounts.
1718 ret
= strnprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1719 default_devpts_mntopts
, conf
->pty_max
);
1723 /* Create mountpoint for devpts instance. */
1724 ret
= mkdirat(rootfs
->dfd_dev
, "pts", 0755);
1725 if (ret
< 0 && errno
!= EEXIST
)
1726 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1729 mntopt_sets
[0] = devpts_mntopts
;
1731 /* !gid=5 && max= */
1732 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1734 /* gid=5 && !max= */
1735 mntopt_sets
[2] = default_devpts_mntopts
;
1737 /* !gid=5 && !max= */
1738 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1741 mntopt_sets
[4] = NULL
;
1743 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1744 /* mount new devpts instance */
1745 ret
= mount_at(rootfs
->dfd_dev
, "", 0,
1746 rootfs
->dfd_dev
, "pts", PROTECT_LOOKUP_BENEATH
,
1747 "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1752 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1754 devpts_fd
= open_at(rootfs
->dfd_dev
, "pts", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
1755 if (devpts_fd
< 0) {
1757 TRACE("Failed to create detached devpts mount");
1760 DEBUG("Mounted new devpts instance with options \"%s\"", *opts
);
1762 handler
->conf
->devpts_fd
= move_fd(devpts_fd
);
1764 /* Remove any pre-existing /dev/ptmx file. */
1765 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1767 if (errno
!= ENOENT
)
1768 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1770 DEBUG("Removed existing \"/dev/ptmx\" file");
1773 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1774 ret
= mknodat(rootfs
->dfd_dev
, "ptmx", S_IFREG
| 0000, 0);
1775 if (ret
< 0 && errno
!= EEXIST
)
1776 return log_error_errno(-1, errno
, "Failed to create \"/dev/ptmx\" file as bind mount target");
1777 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
1779 /* Main option: use a bind-mount to please AppArmor */
1780 ret
= mount_at(rootfs
->dfd_dev
, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1781 rootfs
->dfd_dev
, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
& ~RESOLVE_NO_XDEV
),
1782 NULL
, MS_BIND
, NULL
);
1784 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1786 /* Fallthrough and try to create a symlink. */
1787 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1789 /* Remove the placeholder /dev/ptmx file we created above. */
1790 ret
= unlinkat(rootfs
->dfd_dev
, "ptmx", 0);
1792 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1794 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1795 ret
= symlinkat("/dev/pts/ptmx", rootfs
->dfd_dev
, "dev/ptmx");
1797 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1799 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1803 static int lxc_send_devpts_to_parent(struct lxc_handler
*handler
)
1807 if (handler
->conf
->pty_max
<= 0)
1808 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1810 ret
= lxc_abstract_unix_send_fds(handler
->data_sock
[0], &handler
->conf
->devpts_fd
, 1, NULL
, 0);
1812 SYSERROR("Failed to send devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1814 TRACE("Sent devpts file descriptor %d to parent", handler
->conf
->devpts_fd
);
1816 close_prot_errno_disarm(handler
->conf
->devpts_fd
);
1821 static int setup_personality(personality_t persona
)
1825 if (persona
== LXC_ARCH_UNCHANGED
)
1826 return log_debug(0, "Retaining original personality");
1828 ret
= lxc_personality(persona
);
1830 return syserror("Failed to set personality to \"0lx%lx\"", persona
);
1832 INFO("Set personality to \"0lx%lx\"", persona
);
1836 static int bind_mount_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1837 struct lxc_terminal
*console
, int fd_to
)
1839 __do_close
int fd_pty
= -EBADF
;
1841 if (is_empty_string(console
->name
))
1842 return ret_errno(EINVAL
);
1845 * When the pty fd stashed in console->pty has been retrieved via the
1846 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1847 * allocating new pty devices we can't reopen it through openat2() or
1848 * created a detached mount through open_tree() from it. This means we
1849 * would need to mount using the path stased in console->name which is
1850 * unsafe. We could be mounting a device that isn't identical to the
1851 * one we've already safely opened and stashed in console->pty.
1852 * So, what we do is we open an O_PATH file descriptor for
1853 * console->name and verify that the opened fd and the fd we stashed in
1854 * console->pty refer to the same device. If they do we can go on and
1855 * created a detached mount based on the newly opened O_PATH file
1856 * descriptor and then safely mount.
1858 fd_pty
= open_at_same(console
->pty
, fd_devpts
, fdstr(console
->pty_nr
),
1859 PROTECT_OPATH_FILE
, PROTECT_LOOKUP_ABSOLUTE_XDEV
, 0);
1861 return syserror("Failed to open \"%s\"", console
->name
);
1864 * Note, there are intentionally no open or lookup restrictions since
1865 * we're operating directly on the fd.
1867 if (can_use_mount_api())
1868 return fd_bind_mount(fd_pty
, "", 0, 0, fd_to
, "", 0, 0, 0, false);
1870 return mount_fd(fd_pty
, fd_to
, "none", MS_BIND
, 0);
1873 static int lxc_setup_dev_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1874 struct lxc_terminal
*console
)
1876 __do_close
int fd_console
= -EBADF
;
1880 * When we are asked to setup a console we remove any previous
1881 * /dev/console bind-mounts.
1883 if (exists_file_at(rootfs
->dfd_dev
, "console")) {
1884 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1886 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
1890 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
1892 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
1894 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
1898 * For unprivileged containers autodev or automounts will already have
1899 * taken care of creating /dev/console.
1901 fd_console
= open_at(rootfs
->dfd_dev
,
1903 PROTECT_OPEN
| O_CREAT
,
1904 PROTECT_LOOKUP_BENEATH
,
1907 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
1909 ret
= fchmod(console
->pty
, 0620);
1911 return syserror("Failed to change console mode");
1913 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_console
);
1915 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1916 console
->pty
, console
->name
, fd_console
);
1918 TRACE("Setup console \"%s\"", console
->name
);
1922 static int lxc_setup_ttydir_console(int fd_devpts
, struct lxc_rootfs
*rootfs
,
1923 struct lxc_terminal
*console
,
1926 __do_close
int fd_ttydir
= -EBADF
, fd_dev_console
= -EBADF
,
1927 fd_reg_console
= -EBADF
, fd_reg_ttydir_console
= -EBADF
;
1930 /* create dev/<ttydir> */
1931 ret
= mkdirat(rootfs
->dfd_dev
, ttydir
, 0755);
1932 if (ret
< 0 && errno
!= EEXIST
)
1933 return syserror("Failed to create \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
1935 fd_ttydir
= open_at(rootfs
->dfd_dev
,
1937 PROTECT_OPATH_DIRECTORY
,
1938 PROTECT_LOOKUP_BENEATH
,
1941 return syserror("Failed to open \"%d/%s\"", rootfs
->dfd_dev
, ttydir
);
1943 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/console", ttydir
);
1947 /* create dev/<ttydir>/console */
1948 fd_reg_ttydir_console
= open_at(fd_ttydir
,
1950 PROTECT_OPEN
| O_CREAT
,
1951 PROTECT_LOOKUP_BENEATH
,
1953 if (fd_reg_ttydir_console
< 0)
1954 return syserror("Failed to create \"%d/console\"", fd_ttydir
);
1956 if (file_exists(rootfs
->buf
)) {
1957 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1959 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/dev/console", rootfs_path
);
1963 ret
= lxc_unstack_mountpoint(rootfs
->buf
, false);
1965 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", rootfs
->buf
);
1967 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, rootfs
->buf
);
1970 /* create dev/console */
1971 fd_reg_console
= open_at(rootfs
->dfd_dev
,
1973 PROTECT_OPEN
| O_CREAT
,
1974 PROTECT_LOOKUP_BENEATH
,
1976 if (fd_reg_console
< 0)
1977 return syserror("Failed to create \"%d/console\"", rootfs
->dfd_dev
);
1979 ret
= fchmod(console
->pty
, 0620);
1981 return syserror("Failed to change console mode");
1983 /* bind mount console to '/dev/<ttydir>/console' */
1984 ret
= bind_mount_console(fd_devpts
, rootfs
, console
, fd_reg_ttydir_console
);
1986 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1987 console
->pty
, console
->name
, fd_reg_ttydir_console
);
1989 fd_dev_console
= open_at_same(console
->pty
,
1993 PROTECT_LOOKUP_BENEATH_XDEV
,
1995 if (fd_dev_console
< 0)
1996 return syserror("Failed to open \"%d/console\"", fd_ttydir
);
1998 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1999 if (can_use_mount_api())
2000 ret
= fd_bind_mount(fd_dev_console
,
2003 PROTECT_LOOKUP_BENEATH_XDEV
,
2007 PROTECT_LOOKUP_BENEATH
,
2011 ret
= mount_fd(fd_dev_console
, fd_reg_console
, "none", MS_BIND
, 0);
2013 return syserror("Failed to mount \"%d\" on \"%d\"",
2014 fd_dev_console
, fd_reg_console
);
2016 TRACE("Setup console \"%s\"", console
->name
);
2020 static int lxc_setup_console(const struct lxc_handler
*handler
,
2021 struct lxc_rootfs
*rootfs
,
2022 struct lxc_terminal
*console
, char *ttydir
)
2024 __do_close
int fd_devpts_host
= -EBADF
;
2025 int fd_devpts
= handler
->conf
->devpts_fd
;
2028 if (!wants_console(console
))
2029 return log_trace(0, "Skipping console setup");
2031 if (console
->pty
< 0) {
2033 * Allocate a console from the container's devpts instance. We
2034 * have checked on the host that we have enough pty devices
2037 ret
= lxc_devpts_terminal(handler
->conf
->devpts_fd
, &console
->ptx
,
2038 &console
->pty
, &console
->pty_nr
, false);
2040 return syserror("Failed to allocate console from container's devpts instance");
2042 ret
= strnprintf(console
->name
, sizeof(console
->name
),
2043 "/dev/pts/%d", console
->pty_nr
);
2045 return syserror("Failed to create console path");
2048 * We're using a console from the host's devpts instance. Open
2049 * it again so we can later verify that the console we're
2050 * supposed to use is still the same as the one we opened on
2053 fd_devpts_host
= open_at(rootfs
->dfd_host
,
2055 PROTECT_OPATH_DIRECTORY
,
2056 PROTECT_LOOKUP_BENEATH_XDEV
,
2058 if (fd_devpts_host
< 0)
2059 return syserror("Failed to open host devpts");
2061 fd_devpts
= fd_devpts_host
;
2065 ret
= lxc_setup_ttydir_console(fd_devpts
, rootfs
, console
, ttydir
);
2067 ret
= lxc_setup_dev_console(fd_devpts
, rootfs
, console
);
2069 return syserror("Failed to setup console");
2072 * Some init's such as busybox will set sane tty settings on stdin,
2073 * stdout, stderr which it thinks is the console. We already set them
2074 * the way we wanted on the real terminal, and we want init to do its
2075 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2076 * make sure that that pty is stdin,stdout,stderr.
2078 if (console
->pty
>= 0) {
2079 if (handler
->daemonize
|| !handler
->conf
->is_execute
)
2080 ret
= set_stdfds(console
->pty
);
2082 ret
= lxc_terminal_set_stdfds(console
->pty
);
2084 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console
->pty
);
2087 * If the console has been allocated from the host's devpts
2088 * we're done and we don't need to send fds to the parent.
2090 if (fd_devpts_host
>= 0)
2091 lxc_terminal_delete(console
);
2097 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
2101 /* If '=' is contained in opt, the option must go into data. */
2102 if (!strchr(opt
, '=')) {
2104 * If opt is found in mount_opt, set or clear flags.
2105 * Otherwise append it to data.
2107 size_t opt_len
= strlen(opt
);
2108 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2109 size_t mo_name_len
= strlen(mo
->name
);
2111 if (opt_len
== mo_name_len
&& strnequal(opt
, mo
->name
, mo_name_len
)) {
2113 *flags
&= ~mo
->legacy_flag
;
2115 *flags
|= mo
->legacy_flag
;
2121 if (strlen(*data
)) {
2122 ret
= strlcat(*data
, ",", size
);
2124 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
2127 ret
= strlcat(*data
, opt
, size
);
2129 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
2134 int parse_mntopts_legacy(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
2136 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2137 char *mntopt_cur
= NULL
;
2140 if (*mntdata
|| *mntflags
)
2141 return ret_errno(EINVAL
);
2146 mntopts_dup
= strdup(mntopts
);
2148 return ret_errno(ENOMEM
);
2150 size
= strlen(mntopts_dup
) + 1;
2151 mntopts_new
= zalloc(size
);
2153 return ret_errno(ENOMEM
);
2155 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
2156 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
2157 return ret_errno(EINVAL
);
2160 *mntdata
= move_ptr(mntopts_new
);
2165 static int parse_vfs_attr(struct lxc_mount_options
*opts
, char *opt
, size_t size
)
2168 * If opt is found in mount_opt, set or clear flags.
2169 * Otherwise append it to data.
2171 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2172 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2175 /* This is a recursive bind-mount. */
2176 if (strequal(mo
->name
, "rbind")) {
2177 opts
->recursive
= 1;
2182 /* This is a bind-mount. */
2183 if (strequal(mo
->name
, "bind")) {
2189 return log_info(0, "Ignoring %s mount option", mo
->name
);
2192 opts
->attr
.attr_clr
|= mo
->flag
;
2193 TRACE("Lowering %s", mo
->name
);
2195 opts
->attr
.attr_set
|= mo
->flag
;
2196 TRACE("Raising %s", mo
->name
);
2202 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
2203 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2206 /* TODO: Handle recursive propagation requests. */
2207 opts
->attr
.propagation
= mo
->flag
;
2214 static int parse_mount_attrs(struct lxc_mount_options
*opts
, const char *mntopts
)
2216 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
2217 char *end
= NULL
, *mntopt_cur
= NULL
;
2222 return ret_errno(EINVAL
);
2227 mntopts_dup
= strdup(mntopts
);
2229 return ret_errno(ENOMEM
);
2231 size
= strlen(mntopts_dup
) + 1;
2232 mntopts_new
= zalloc(size
);
2234 return ret_errno(ENOMEM
);
2236 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",") {
2237 /* This is a filesystem specific option. */
2238 if (strchr(mntopt_cur
, '=')) {
2240 end
= stpcpy(mntopts_new
, mntopt_cur
);
2242 end
= stpcpy(end
, ",");
2243 end
= stpcpy(end
, mntopt_cur
);
2249 /* This is a generic vfs option. */
2250 ret
= parse_vfs_attr(opts
, mntopt_cur
, size
);
2252 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur
);
2256 opts
->data
= move_ptr(mntopts_new
);
2261 static void parse_propagationopt(char *opt
, unsigned long *flags
)
2263 struct mount_opt
*mo
;
2265 /* If opt is found in propagation_opt, set or clear flags. */
2266 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
2267 if (!strnequal(opt
, mo
->name
, strlen(mo
->name
)))
2271 *flags
&= ~mo
->legacy_flag
;
2273 *flags
|= mo
->legacy_flag
;
2279 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
2281 __do_free
char *s
= NULL
;
2287 s
= strdup(mntopts
);
2289 return log_error_errno(-ENOMEM
, errno
, "Failed to allocate memory");
2292 lxc_iterate_parts(p
, s
, ",")
2293 parse_propagationopt(p
, pflags
);
2298 static void null_endofword(char *word
)
2300 while (*word
&& *word
!= ' ' && *word
!= '\t')
2305 /* skip @nfields spaces in @src */
2306 static char *get_field(char *src
, int nfields
)
2311 for (i
= 0; i
< nfields
; i
++) {
2312 while (*p
&& *p
!= ' ' && *p
!= '\t')
2324 static int mount_entry(const char *fsname
, const char *target
,
2325 const char *fstype
, unsigned long mountflags
,
2326 unsigned long pflags
, const char *data
, bool optional
,
2327 bool dev
, bool relative
, const char *rootfs
)
2330 char srcbuf
[PATH_MAX
];
2331 const char *srcpath
= fsname
;
2337 ret
= strnprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2339 return log_error_errno(-1, errno
, "source path is too long");
2343 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2347 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2348 srcpath
? srcpath
: "(null)", target
);
2350 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2351 srcpath
? srcpath
: "(null)", target
);
2354 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2356 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2357 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2360 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2361 unsigned long required_flags
= 0;
2363 if (sb
.f_flag
& MS_NOSUID
)
2364 required_flags
|= MS_NOSUID
;
2366 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2367 required_flags
|= MS_NODEV
;
2369 if (sb
.f_flag
& MS_RDONLY
)
2370 required_flags
|= MS_RDONLY
;
2372 if (sb
.f_flag
& MS_NOEXEC
)
2373 required_flags
|= MS_NOEXEC
;
2375 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2376 srcpath
, sb
.f_flag
, required_flags
);
2378 /* If this was a bind mount request, and required_flags
2379 * does not have any flags which are not already in
2380 * mountflags, then skip the remount.
2382 if (!(mountflags
& MS_REMOUNT
) &&
2383 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
2384 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
2388 mountflags
|= required_flags
;
2392 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2395 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
2396 srcpath
? srcpath
: "(null)",
2399 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
2400 srcpath
? srcpath
: "(null)",
2409 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2412 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2414 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
2416 DEBUG("Changed mount propagation for \"%s\"", target
);
2419 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2420 srcpath
? srcpath
: "(null)", target
, fstype
);
2425 const char *lxc_mount_options_info
[LXC_MOUNT_MAX
] = {
2433 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2434 int parse_lxc_mount_attrs(struct lxc_mount_options
*opts
, char *mnt_opts
)
2436 for (size_t i
= LXC_MOUNT_CREATE_DIR
; i
< LXC_MOUNT_MAX
; i
++) {
2437 __do_close
int fd_userns
= -EBADF
;
2438 const char *opt_name
= lxc_mount_options_info
[i
];
2440 char *idmap_path
, *opt
, *opt_next
;
2442 opt
= strstr(mnt_opts
, opt_name
);
2447 case LXC_MOUNT_CREATE_DIR
:
2448 opts
->create_dir
= 1;
2450 case LXC_MOUNT_CREATE_FILE
:
2451 opts
->create_file
= 1;
2453 case LXC_MOUNT_OPTIONAL
:
2456 case LXC_MOUNT_RELATIVE
:
2459 case LXC_MOUNT_IDMAP
:
2461 opt_next
+= STRLITERALLEN("idmap=");
2462 idmap_path
= strchrnul(opt_next
, ',');
2463 len
= idmap_path
- opt_next
+ 1;
2465 if (len
>= sizeof(opts
->userns_path
))
2466 return syserror_set(-EIO
, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2468 strlcpy(opts
->userns_path
, opt_next
, len
);
2470 if (is_empty_string(opts
->userns_path
))
2471 return syserror_set(-EINVAL
, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2473 if (!strequal(opts
->userns_path
, "container")) {
2474 fd_userns
= open(opts
->userns_path
, O_RDONLY
| O_NOCTTY
| O_CLOEXEC
);
2476 return syserror("Failed to open user namespace %s", opts
->userns_path
);
2479 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns
, opts
->userns_path
);
2482 return syserror_set(-EINVAL
, "Unknown LXC specific mount option");
2485 opt_next
= strchr(opt
, ',');
2487 *opt
= '\0'; /* no more mntopts, so just chop it here */
2489 memmove(opt
, opt_next
+ 1, strlen(opt_next
+ 1) + 1);
2495 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2497 const struct lxc_rootfs
*rootfs
,
2498 const char *lxc_name
, const char *lxc_path
)
2500 __do_free
char *p1
= NULL
;
2504 if (strnequal(mntent
->mnt_type
, "overlay", 7)) {
2505 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2510 if (hasmntopt(mntent
, "create=dir")) {
2511 ret
= mkdir_p(path
, 0755);
2512 if (ret
< 0 && errno
!= EEXIST
)
2513 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2516 if (!hasmntopt(mntent
, "create=file"))
2519 ret
= access(path
, F_OK
);
2529 ret
= mkdir_p(p2
, 0755);
2530 if (ret
< 0 && errno
!= EEXIST
)
2531 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
2533 ret
= mknod(path
, S_IFREG
| 0000, 0);
2534 if (ret
< 0 && errno
!= EEXIST
)
2540 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2541 * without a rootfs. */
2542 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2544 const struct lxc_rootfs
*rootfs
,
2545 const char *lxc_name
,
2546 const char *lxc_path
)
2548 __do_free
char *mntdata
= NULL
;
2549 unsigned long mntflags
= 0, pflags
= 0;
2550 char *rootfs_path
= NULL
;
2552 bool dev
, optional
, relative
;
2553 struct lxc_mount_options opts
= {};
2555 optional
= hasmntopt(mntent
, "optional") != NULL
;
2556 dev
= hasmntopt(mntent
, "dev") != NULL
;
2557 relative
= hasmntopt(mntent
, "relative") != NULL
;
2559 if (rootfs
&& rootfs
->path
)
2560 rootfs_path
= rootfs
->mount
;
2562 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2571 ret
= parse_lxc_mount_attrs(&opts
, mntent
->mnt_opts
);
2576 * Idmapped mount entries will be setup by the parent for us. Note that
2577 * we rely on mount_entry_create_dir_file() above to have already
2578 * created the target path for us. So the parent can just open the
2579 * target and send us the target fd.
2582 if (!is_empty_string(opts
.userns_path
))
2583 return systrace_ret(0, "Skipping idmapped mount entry");
2585 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2589 ret
= parse_mntopts_legacy(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2593 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2594 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2599 static inline int mount_entry_on_systemfs(struct lxc_rootfs
*rootfs
,
2600 struct mntent
*mntent
)
2604 /* For containers created without a rootfs all mounts are treated as
2605 * absolute paths starting at / on the host.
2607 if (mntent
->mnt_dir
[0] != '/')
2608 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/%s", mntent
->mnt_dir
);
2610 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s", mntent
->mnt_dir
);
2614 return mount_entry_on_generic(mntent
, rootfs
->buf
, NULL
, NULL
, NULL
);
2617 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2618 struct lxc_rootfs
*rootfs
,
2619 const char *lxc_name
,
2620 const char *lxc_path
)
2624 const char *lxcpath
;
2627 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2631 /* If rootfs->path is a blockdev path, allow container fstab to use
2632 * <lxcpath>/<name>/rootfs" as the target prefix.
2634 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s/rootfs", lxcpath
, lxc_name
);
2638 aux
= strstr(mntent
->mnt_dir
, rootfs
->buf
);
2640 offset
= strlen(rootfs
->buf
);
2645 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2647 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2648 offset
= strlen(rootfs
->path
);
2651 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, aux
+ offset
);
2655 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2658 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2659 struct lxc_rootfs
*rootfs
,
2660 const char *lxc_name
,
2661 const char *lxc_path
)
2665 /* relative to root mount point */
2666 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2670 return mount_entry_on_generic(mntent
, rootfs
->buf
, rootfs
, lxc_name
, lxc_path
);
2673 static int mount_file_entries(struct lxc_rootfs
*rootfs
, FILE *file
,
2674 const char *lxc_name
, const char *lxc_path
)
2677 struct mntent mntent
;
2679 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2683 ret
= mount_entry_on_systemfs(rootfs
, &mntent
);
2684 else if (mntent
.mnt_dir
[0] != '/')
2685 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2686 lxc_name
, lxc_path
);
2688 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2689 lxc_name
, lxc_path
);
2694 if (!feof(file
) || ferror(file
))
2695 return log_error(-1, "Failed to parse mount entries");
2700 static inline void __auto_endmntent__(FILE **f
)
2706 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2708 static int setup_mount_fstab(struct lxc_rootfs
*rootfs
, const char *fstab
,
2709 const char *lxc_name
, const char *lxc_path
)
2711 __do_endmntent
FILE *f
= NULL
;
2717 f
= setmntent(fstab
, "re");
2719 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2721 ret
= mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2723 ERROR("Failed to set up mount entries");
2729 * In order for nested containers to be able to mount /proc and /sys they need
2730 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2732 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2733 * apparmor rule to deny access to them. This is mostly for convenience: The
2734 * container's root user can mount them anyway and thus has access to the two
2735 * file systems. But a non-root user in the container should not be allowed to
2736 * access them as a side effect without explicitly allowing it.
2738 static const char nesting_helpers
[] =
2739 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2740 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2742 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2743 bool include_nesting_helpers
)
2745 __do_close
int fd
= -EBADF
;
2749 struct lxc_list
*iterator
;
2751 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2753 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2755 if (errno
!= ENOSYS
)
2758 fd
= lxc_make_tmpfile(template, true);
2760 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2762 TRACE("Created temporary mount file");
2765 lxc_list_for_each (iterator
, mount
) {
2768 mount_entry
= iterator
->elem
;
2769 len
= strlen(mount_entry
);
2771 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2775 ret
= lxc_write_nointr(fd
, "\n", 1);
2780 if (include_nesting_helpers
) {
2781 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2782 STRARRAYLEN(nesting_helpers
));
2783 if (ret
!= STRARRAYLEN(nesting_helpers
))
2787 ret
= lseek(fd
, 0, SEEK_SET
);
2791 f
= fdopen(fd
, "re+");
2793 move_fd(fd
); /* Transfer ownership of fd. */
2797 static int setup_mount_entries(const struct lxc_conf
*conf
,
2798 struct lxc_rootfs
*rootfs
, struct lxc_list
*mount
,
2799 const char *lxc_name
, const char *lxc_path
)
2801 __do_fclose
FILE *f
= NULL
;
2803 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2807 return mount_file_entries(rootfs
, f
, lxc_name
, lxc_path
);
2810 static int __lxc_idmapped_mounts_child(struct lxc_handler
*handler
, FILE *f
)
2812 struct lxc_conf
*conf
= handler
->conf
;
2813 struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
2817 struct mntent mntent
;
2819 while (getmntent_r(f
, &mntent
, buf
, sizeof(buf
))) {
2820 __do_close
int fd_from
= -EBADF
, fd_to
= -EBADF
,
2822 __do_free
char *__data
= NULL
;
2823 int cur_mnt_seq
= -1;
2824 struct lxc_mount_options opts
= {};
2826 const char *source_relative
, *target_relative
;
2828 ret
= parse_lxc_mount_attrs(&opts
, mntent
.mnt_opts
);
2830 return syserror("Failed to parse LXC specific mount options");
2833 ret
= parse_mount_attrs(&opts
, mntent
.mnt_opts
);
2835 return syserror("Failed to parse mount options");
2837 /* No idmapped mount entry so skip it. */
2838 if (is_empty_string(opts
.userns_path
))
2841 if (!can_use_bind_mounts())
2842 return syserror_set(-EINVAL
, "Kernel does not support idmapped mounts");
2845 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2847 /* We don't support new filesystem mounts yet. */
2848 if (!is_empty_string(mntent
.mnt_type
) &&
2849 !strequal(mntent
.mnt_type
, "none"))
2850 return syserror_set(-EINVAL
, "Only bind mounts can currently be idmapped");
2852 /* Someone specified additional mount options for a bind-mount. */
2853 if (!is_empty_string(opts
.data
))
2854 return syserror_set(-EINVAL
, "Bind mounts don't support non-generic mount options");
2857 * The source path is supposed to be taken relative to the
2858 * container's rootfs mount or - if the container does not have
2859 * a separate rootfs - to the host's /.
2861 source_relative
= deabs(mntent
.mnt_fsname
);
2862 if (opts
.relative
|| !rootfs
->path
)
2863 dfd_from
= rootfs
->dfd_mnt
;
2865 dfd_from
= rootfs
->dfd_host
;
2866 fd_from
= open_tree(dfd_from
, source_relative
,
2867 OPEN_TREE_CLONE
| OPEN_TREE_CLOEXEC
|
2868 (opts
.recursive
? AT_RECURSIVE
: 0));
2870 return syserror("Failed to create detached %smount of %d/%s",
2871 opts
.recursive
? "recursive " : "",
2872 dfd_from
, source_relative
);
2874 if (strequal(opts
.userns_path
, "container"))
2875 fd_userns
= openat(dfd_from
, "proc/self/ns/user", O_RDONLY
| O_CLOEXEC
);
2877 fd_userns
= open_at(-EBADF
, opts
.userns_path
,
2878 PROTECT_OPEN_WITH_TRAILING_SYMLINKS
, 0, 0);
2879 if (fd_userns
< 0) {
2880 if (opts
.optional
) {
2881 TRACE("Skipping optional idmapped mount");
2885 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
2886 opts
.userns_path
, opts
.recursive
? "recursive " : "",
2887 dfd_from
, source_relative
);
2890 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
2892 &opts
, sizeof(opts
));
2894 if (opts
.optional
) {
2895 TRACE("Skipping optional idmapped mount");
2899 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
2900 fd_from
, opts
.recursive
? "recursive " : "",
2901 dfd_from
, source_relative
, fd_userns
,
2905 ret
= lxc_abstract_unix_rcv_credential(handler
->data_sock
[0],
2907 sizeof(cur_mnt_seq
));
2909 if (opts
.optional
) {
2910 TRACE("Skipping optional idmapped mount");
2914 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2915 opts
.recursive
? "recursive " : "",
2916 dfd_from
, source_relative
, fd_userns
);
2919 if (mnt_seq
!= cur_mnt_seq
)
2920 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
2921 mnt_seq
, cur_mnt_seq
);
2924 /* Set remaining mount options. */
2925 ret
= mount_setattr(fd_from
, "", AT_EMPTY_PATH
|
2926 (opts
.recursive
? AT_RECURSIVE
: 0),
2927 &opts
.attr
, sizeof(opts
.attr
));
2929 if (opts
.optional
) {
2930 TRACE("Skipping optional idmapped mount");
2934 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2935 opts
.recursive
? "recursive " : "",
2936 dfd_from
, source_relative
, fd_userns
);
2940 * In contrast to the legacy mount codepath we will simplify
2941 * our lifes and just always treat the target mountpoint to be
2942 * relative to the container's rootfs mountpoint or - if the
2943 * container does not have a separate rootfs - to the host's /.
2946 target_relative
= deabs(mntent
.mnt_dir
);
2948 dfd_from
= rootfs
->dfd_mnt
;
2950 dfd_from
= rootfs
->dfd_host
;
2951 fd_to
= open_at(dfd_from
, target_relative
, PROTECT_OPATH_FILE
, PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS
, 0);
2953 if (opts
.optional
) {
2954 TRACE("Skipping optional idmapped mount");
2958 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
2959 dfd_from
, target_relative
,
2960 opts
.recursive
? "recursive " : "",
2961 fd_userns
, dfd_from
, source_relative
);
2964 ret
= move_detached_mount(fd_from
, fd_to
, "", 0, 0);
2966 if (opts
.optional
) {
2967 TRACE("Skipping optional idmapped mount");
2971 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
2972 opts
.recursive
? "recursive " : "",
2973 fd_userns
, dfd_from
, source_relative
, dfd_from
, target_relative
);
2976 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
2977 opts
.recursive
? "recursive " : "", fd_userns
, dfd_from
,
2978 source_relative
, dfd_from
, target_relative
);
2981 if (!feof(f
) || ferror(f
))
2982 return syserror_set(-EINVAL
, "Failed to parse mount entries");
2987 static int lxc_idmapped_mounts_child(struct lxc_handler
*handler
)
2989 __do_fclose
FILE *f_entries
= NULL
;
2991 struct lxc_conf
*conf
= handler
->conf
;
2992 const char *fstab
= conf
->fstab
;
2993 struct lxc_list
*mount
= &conf
->mount_list
;
2996 f_entries
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2998 SYSERROR("Failed to create anonymous mount file");
3002 ret
= __lxc_idmapped_mounts_child(handler
, f_entries
);
3004 SYSERROR("Failed to setup idmapped mount entries");
3008 TRACE("Finished setting up idmapped mounts");
3011 __do_endmntent
FILE *f_fstab
= NULL
;
3013 f_fstab
= setmntent(fstab
, "re");
3015 SYSERROR("Failed to open fstab format file \"%s\"", fstab
);
3019 ret
= __lxc_idmapped_mounts_child(handler
, f_fstab
);
3021 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3025 TRACE("Finished setting up idmapped mounts specified in fstab");
3031 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[0], NULL
, 0);
3033 return syserror("Failed to inform parent that we are done setting up mounts");
3038 static int parse_cap(const char *cap
)
3042 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
3045 if (strequal(cap
, "none"))
3048 for (i
= 0; i
< end
; i
++) {
3049 if (!strequal(cap
, caps_opt
[i
].name
))
3052 capid
= caps_opt
[i
].value
;
3057 /* Try to see if it's numeric, so the user may specify
3058 * capabilities that the running kernel knows about but we
3062 capid
= strtol(cap
, &ptr
, 10);
3063 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
3064 /* not a valid number */
3066 else if (capid
> lxc_caps_last_cap())
3067 /* we have a number but it's not a valid
3075 int in_caplist(int cap
, struct lxc_list
*caps
)
3078 struct lxc_list
*iterator
;
3080 lxc_list_for_each (iterator
, caps
) {
3081 capid
= parse_cap(iterator
->elem
);
3089 static int setup_caps(struct lxc_list
*caps
)
3093 struct lxc_list
*iterator
;
3095 lxc_list_for_each (iterator
, caps
) {
3098 drop_entry
= iterator
->elem
;
3100 capid
= parse_cap(drop_entry
);
3102 return log_error(-1, "unknown capability %s", drop_entry
);
3104 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
3105 prctl_arg(0), prctl_arg(0));
3107 return log_error_errno(-1, errno
, "Failed to remove %s capability", drop_entry
);
3108 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
3111 DEBUG("Capabilities have been setup");
3115 static int dropcaps_except(struct lxc_list
*caps
)
3117 __do_free
int *caplist
= NULL
;
3118 int i
, capid
, numcaps
;
3120 struct lxc_list
*iterator
;
3122 numcaps
= lxc_caps_last_cap() + 1;
3123 if (numcaps
<= 0 || numcaps
> 200)
3125 TRACE("Found %d capabilities", numcaps
);
3127 /* caplist[i] is 1 if we keep capability i */
3128 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
3129 memset(caplist
, 0, numcaps
* sizeof(int));
3131 lxc_list_for_each (iterator
, caps
) {
3132 keep_entry
= iterator
->elem
;
3134 capid
= parse_cap(keep_entry
);
3139 return log_error(-1, "Unknown capability %s", keep_entry
);
3141 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
3145 for (i
= 0; i
< numcaps
; i
++) {
3151 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
3152 prctl_arg(0), prctl_arg(0));
3154 return log_error_errno(-1, errno
, "Failed to remove capability %d", i
);
3157 DEBUG("Capabilities have been setup");
3161 static int parse_resource(const char *res
)
3167 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
3168 if (strequal(res
, limit_opt
[i
].name
))
3169 return limit_opt
[i
].value
;
3171 /* Try to see if it's numeric, so the user may specify
3172 * resources that the running kernel knows about but
3175 ret
= lxc_safe_int(res
, &resid
);
3182 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
3185 struct lxc_list
*it
;
3186 struct lxc_limit
*lim
;
3188 lxc_list_for_each (it
, limits
) {
3191 resid
= parse_resource(lim
->resource
);
3193 return log_error(-1, "Unknown resource %s", lim
->resource
);
3195 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
3196 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
3197 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
3199 TRACE("Setup \"%s\" limit", lim
->resource
);
3201 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
3208 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
3210 __do_free
char *tmp
= NULL
;
3211 struct lxc_list
*it
;
3212 struct lxc_sysctl
*elem
;
3214 char filename
[PATH_MAX
] = {0};
3216 lxc_list_for_each (it
, sysctls
) {
3218 tmp
= lxc_string_replace(".", "/", elem
->key
);
3220 return log_error(-1, "Failed to replace key %s", elem
->key
);
3222 ret
= strnprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
3224 return log_error(-1, "Error setting up sysctl parameters path");
3226 ret
= lxc_write_to_file(filename
, elem
->value
,
3227 strlen(elem
->value
), false, 0666);
3229 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
3230 elem
->key
, elem
->value
);
3236 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
3238 __do_free
char *tmp
= NULL
;
3239 struct lxc_list
*it
;
3240 struct lxc_proc
*elem
;
3242 char filename
[PATH_MAX
] = {0};
3244 lxc_list_for_each (it
, procs
) {
3246 tmp
= lxc_string_replace(".", "/", elem
->filename
);
3248 return log_error(-1, "Failed to replace key %s", elem
->filename
);
3250 ret
= strnprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
3252 return log_error(-1, "Error setting up proc filesystem path");
3254 ret
= lxc_write_to_file(filename
, elem
->value
,
3255 strlen(elem
->value
), false, 0666);
3257 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s", elem
->filename
, elem
->value
);
3263 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
3265 struct lxc_conf
*lxc_conf_init(void)
3268 struct lxc_conf
*new;
3270 new = zalloc(sizeof(*new));
3274 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
3275 new->personality
= LXC_ARCH_UNCHANGED
;
3277 new->console
.buffer_size
= 0;
3278 new->console
.log_path
= NULL
;
3279 new->console
.log_fd
= -1;
3280 new->console
.log_size
= 0;
3281 new->console
.path
= NULL
;
3282 new->console
.peer
= -1;
3283 new->console
.proxy
.busy
= -1;
3284 new->console
.proxy
.ptx
= -1;
3285 new->console
.proxy
.pty
= -1;
3286 new->console
.ptx
= -EBADF
;
3287 new->console
.pty
= -EBADF
;
3288 new->console
.pty_nr
= -1;
3289 new->console
.name
[0] = '\0';
3290 new->devpts_fd
= -EBADF
;
3291 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
3292 new->maincmd_fd
= -1;
3293 new->monitor_signal_pdeath
= SIGKILL
;
3295 new->rootfs
.mount
= strdup(default_rootfs_mount
);
3296 if (!new->rootfs
.mount
) {
3300 new->rootfs
.managed
= true;
3301 new->rootfs
.dfd_mnt
= -EBADF
;
3302 new->rootfs
.dfd_dev
= -EBADF
;
3303 new->rootfs
.dfd_host
= -EBADF
;
3304 new->rootfs
.fd_path_pin
= -EBADF
;
3305 new->rootfs
.dfd_idmapped
= -EBADF
;
3307 lxc_list_init(&new->cgroup
);
3308 lxc_list_init(&new->cgroup2
);
3309 /* Block ("allowlist") all devices by default. */
3310 new->bpf_devices
.list_type
= LXC_BPF_DEVICE_CGROUP_ALLOWLIST
;
3311 lxc_list_init(&(new->bpf_devices
).device_item
);
3312 lxc_list_init(&new->network
);
3313 lxc_list_init(&new->mount_list
);
3314 lxc_list_init(&new->caps
);
3315 lxc_list_init(&new->keepcaps
);
3316 lxc_list_init(&new->id_map
);
3317 new->root_nsuid_map
= NULL
;
3318 new->root_nsgid_map
= NULL
;
3319 lxc_list_init(&new->includes
);
3320 lxc_list_init(&new->aliens
);
3321 lxc_list_init(&new->environment
);
3322 lxc_list_init(&new->limits
);
3323 lxc_list_init(&new->sysctls
);
3324 lxc_list_init(&new->procs
);
3325 new->hooks_version
= 0;
3326 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
3327 lxc_list_init(&new->hooks
[i
]);
3328 lxc_list_init(&new->groups
);
3329 lxc_list_init(&new->state_clients
);
3330 new->lsm_aa_profile
= NULL
;
3331 lxc_list_init(&new->lsm_aa_raw
);
3332 new->lsm_se_context
= NULL
;
3333 new->lsm_se_keyring_context
= NULL
;
3334 new->keyring_disable_session
= false;
3335 new->transient_procfs_mnt
= false;
3336 new->shmount
.path_host
= NULL
;
3337 new->shmount
.path_cont
= NULL
;
3339 /* if running in a new user namespace, init and COMMAND
3340 * default to running as UID/GID 0 when using lxc-execute */
3343 memset(&new->init_groups
, 0, sizeof(lxc_groups_t
));
3344 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
3345 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
3346 memset(&new->timens
, 0, sizeof(struct timens_offsets
));
3347 seccomp_conf_init(new);
3352 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
3355 __do_close
int fd
= -EBADF
;
3357 char path
[PATH_MAX
];
3359 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
3360 __do_close
int setgroups_fd
= -EBADF
;
3362 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/setgroups", pid
);
3366 setgroups_fd
= open(path
, O_WRONLY
);
3367 if (setgroups_fd
< 0 && errno
!= ENOENT
)
3368 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3370 if (setgroups_fd
>= 0) {
3371 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
3372 STRLITERALLEN("deny\n"));
3373 if (ret
!= STRLITERALLEN("deny\n"))
3374 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
3375 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
3379 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/%cid_map", pid
,
3380 idtype
== ID_TYPE_UID
? 'u' : 'g');
3384 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
3386 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
3388 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
3389 if (ret
!= buf_size
)
3390 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
3391 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
3396 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3398 * @return 1 if functional binary was found
3399 * @return 0 if binary exists but is lacking privilege
3400 * @return -ENOENT if binary does not exist
3401 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
3403 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
3405 __do_free
char *path
= NULL
;
3409 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
3410 return ret_errno(EINVAL
);
3412 path
= on_path(binary
, NULL
);
3414 return ret_errno(ENOENT
);
3416 ret
= stat(path
, &st
);
3420 /* Check if the binary is setuid. */
3421 if (st
.st_mode
& S_ISUID
)
3422 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
3424 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
3425 /* Check if it has the CAP_SETUID capability. */
3426 if ((cap
& CAP_SETUID
) &&
3427 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
3428 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
3429 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3431 /* Check if it has the CAP_SETGID capability. */
3432 if ((cap
& CAP_SETGID
) &&
3433 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
3434 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
3435 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
3440 * If we cannot check for file capabilities we need to give the benefit
3441 * of the doubt. Otherwise we might fail even though all the necessary
3442 * file capabilities are set.
3444 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3449 static int lxc_map_ids_exec_wrapper(void *args
)
3451 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
3455 static struct id_map
*find_mapped_hostid_entry(const struct lxc_list
*idmap
,
3456 unsigned id
, enum idtype idtype
);
3458 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
3463 char cmd_output
[PATH_MAX
];
3465 struct lxc_list
*iterator
;
3467 int ret
= 0, gidmap
= 0, uidmap
= 0;
3468 char mapbuf
[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3469 INTTYPE_TO_STRLEN(pid_t
) + STRLITERALLEN(" ") +
3470 LXC_IDMAPLEN
] = {0};
3471 bool had_entry
= false, maps_host_root
= false, use_shadow
= false;
3472 int hostuid
, hostgid
;
3474 hostuid
= geteuid();
3475 hostgid
= getegid();
3478 * Check whether caller wants to map host root.
3479 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3480 * host root into the child userns as you would be able to write fscaps
3481 * that would be valid in the ancestor userns. Mapping host root should
3482 * rarely be the case but LXC is being clever in a bunch of cases.
3484 if (find_mapped_hostid_entry(idmap
, 0, ID_TYPE_UID
))
3485 maps_host_root
= true;
3487 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3488 * ranges, then insist that root also reserve ranges in subuid. This
3489 * will protected it by preventing another user from being handed the
3492 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
3493 if (uidmap
== -ENOENT
)
3494 WARN("newuidmap binary is missing");
3496 WARN("newuidmap is lacking necessary privileges");
3498 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
3499 if (gidmap
== -ENOENT
)
3500 WARN("newgidmap binary is missing");
3502 WARN("newgidmap is lacking necessary privileges");
3504 if (maps_host_root
) {
3505 INFO("Caller maps host root. Writing mapping directly");
3506 } else if (uidmap
> 0 && gidmap
> 0) {
3507 DEBUG("Functional newuidmap and newgidmap binary found");
3510 /* In case unprivileged users run application containers via
3511 * execute() or a start*() there are valid cases where they may
3512 * only want to map their own {g,u}id. Let's not block them from
3513 * doing so by requiring geteuid() == 0.
3515 DEBUG("No newuidmap and newgidmap binary found. Trying to "
3516 "write directly with euid %d", hostuid
);
3519 /* Check if we really need to use newuidmap and newgidmap.
3520 * If the user is only remapping their own {g,u}id, we don't need it.
3522 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
3524 lxc_list_for_each(iterator
, idmap
) {
3525 map
= iterator
->elem
;
3526 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3527 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3529 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3530 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3537 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3538 type
++, u_or_g
= 'g') {
3542 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3544 lxc_list_for_each(iterator
, idmap
) {
3545 map
= iterator
->elem
;
3546 if (map
->idtype
!= type
)
3551 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3552 fill
= strnprintf(pos
, left
, "%s%lu %lu %lu%s",
3553 use_shadow
? " " : "", map
->nsid
,
3554 map
->hostid
, map
->range
,
3555 use_shadow
? "" : "\n");
3557 * The kernel only takes <= 4k for writes to
3558 * /proc/<pid>/{g,u}id_map
3561 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
3568 /* Try to catch the output of new{g,u}idmap to make debugging
3572 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3573 lxc_map_ids_exec_wrapper
,
3576 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
3577 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3579 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3581 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
3582 TRACE("Wrote mapping \"%s\"", mapbuf
);
3585 memset(mapbuf
, 0, sizeof(mapbuf
));
3592 * Return the host uid/gid to which the container root is mapped in val.
3593 * Return true if id was found, false otherwise.
3595 static id_t
get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
)
3599 struct lxc_list
*it
;
3601 if (idtype
== ID_TYPE_UID
)
3602 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3604 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3606 lxc_list_for_each (it
, &conf
->id_map
) {
3608 if (map
->idtype
!= idtype
)
3610 if (map
->nsid
!= nsid
)
3615 if (idtype
== ID_TYPE_UID
)
3616 return LXC_INVALID_UID
;
3618 return LXC_INVALID_GID
;
3621 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
3624 struct lxc_list
*it
;
3626 lxc_list_for_each (it
, &conf
->id_map
) {
3628 if (map
->idtype
!= idtype
)
3631 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3632 return (id
- map
->hostid
) + map
->nsid
;
3638 int find_unmapped_nsid(const struct lxc_conf
*conf
, enum idtype idtype
)
3641 struct lxc_list
*it
;
3642 unsigned int freeid
= 0;
3645 lxc_list_for_each (it
, &conf
->id_map
) {
3647 if (map
->idtype
!= idtype
)
3650 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3651 freeid
= map
->nsid
+ map
->range
;
3660 * Mount a proc under @rootfs if proc self points to a pid other than
3661 * my own. This is needed to have a known-good proc mount for setting
3662 * up LSMs both at container startup and attach.
3664 * NOTE: not to be called from inside the container namespace!
3666 static int lxc_transient_proc(struct lxc_rootfs
*rootfs
)
3668 __do_close
int fd_proc
= -EBADF
;
3669 int link_to_pid
, link_len
, pid_self
, ret
;
3670 char link
[INTTYPE_TO_STRLEN(pid_t
) + 1];
3672 link_len
= readlinkat(rootfs
->dfd_mnt
, "proc/self", link
, sizeof(link
));
3674 ret
= mkdirat(rootfs
->dfd_mnt
, "proc", 0000);
3675 if (ret
< 0 && errno
!= EEXIST
)
3676 return log_error_errno(-errno
, errno
, "Failed to create %d(proc)", rootfs
->dfd_mnt
);
3679 } else if (link_len
>= sizeof(link
)) {
3680 return log_error_errno(-EIO
, EIO
, "Truncated link target");
3682 link
[link_len
] = '\0';
3684 pid_self
= lxc_raw_getpid();
3685 INFO("Caller's PID is %d; /proc/self points to %s", pid_self
, link
);
3687 ret
= lxc_safe_int(link
, &link_to_pid
);
3689 return log_error_errno(-ret
, ret
, "Failed to parse %s", link
);
3691 /* Correct procfs is already mounted. */
3692 if (link_to_pid
== pid_self
)
3693 return log_trace(0, "Correct procfs instance mounted");
3695 fd_proc
= open_at(rootfs
->dfd_mnt
, "proc", PROTECT_OPATH_DIRECTORY
,
3696 PROTECT_LOOKUP_BENEATH_XDEV
, 0);
3698 return log_error_errno(-errno
, errno
, "Failed to open transient procfs mountpoint");
3700 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "/proc/self/fd/%d", fd_proc
);
3702 return ret_errno(EIO
);
3704 ret
= umount2(rootfs
->buf
, MNT_DETACH
);
3706 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs
->buf
);
3709 /* rootfs is NULL */
3710 if (!rootfs
->path
) {
3711 ret
= mount("proc", rootfs
->buf
, "proc", 0, NULL
);
3713 ret
= safe_mount_beneath_at(rootfs
->dfd_mnt
, "none", "proc", "proc", 0, NULL
);
3715 ret
= strnprintf(rootfs
->buf
, sizeof(rootfs
->buf
), "%s/proc", rootfs
->path
? rootfs
->mount
: "");
3717 return ret_errno(EIO
);
3719 ret
= safe_mount("proc", rootfs
->buf
, "proc", 0, NULL
, rootfs
->mount
);
3723 return log_error_errno(-1, errno
, "Failed to mount temporary procfs");
3725 INFO("Created transient procfs mount");
3729 /* NOTE: Must not be called from inside the container namespace! */
3730 static int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3734 mounted
= lxc_transient_proc(&conf
->rootfs
);
3735 if (mounted
== -1) {
3736 /* continue only if there is no rootfs */
3737 if (conf
->rootfs
.path
)
3738 return log_error_errno(-EPERM
, EPERM
, "Failed to create transient procfs mount");
3739 } else if (mounted
== 1) {
3740 conf
->transient_procfs_mnt
= true;
3746 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3748 if (lxc_conf
->transient_procfs_mnt
) {
3749 (void)umount2("/proc", MNT_DETACH
);
3750 lxc_conf
->transient_procfs_mnt
= false;
3754 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
3755 static void turn_into_dependent_mounts(const struct lxc_rootfs
*rootfs
)
3757 __do_free
char *line
= NULL
;
3758 __do_fclose
FILE *f
= NULL
;
3759 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3764 mntinfo_fd
= open_at(rootfs
->dfd_host
, "proc/self/mountinfo", PROTECT_OPEN
,
3765 (PROTECT_LOOKUP_BENEATH_XDEV
& ~RESOLVE_NO_SYMLINKS
), 0);
3766 if (mntinfo_fd
< 0) {
3767 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs
->dfd_host
);
3771 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3773 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3775 if (errno
!= ENOSYS
) {
3776 SYSERROR("Failed to create temporary in-memory file");
3780 memfd
= lxc_make_tmpfile(template, true);
3782 WARN("Failed to create temporary file");
3787 copied
= fd_to_fd(mntinfo_fd
, memfd
);
3789 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3793 ret
= lseek(memfd
, 0, SEEK_SET
);
3795 SYSERROR("Failed to reset file descriptor offset");
3799 f
= fdopen(memfd
, "re");
3801 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3806 * After a successful fdopen() memfd will be closed when calling
3807 * fclose(f). Calling close(memfd) afterwards is undefined.
3811 while (getline(&line
, &len
, f
) != -1) {
3812 char *opts
, *target
;
3814 target
= get_field(line
, 4);
3818 opts
= get_field(target
, 2);
3822 null_endofword(opts
);
3823 if (!strstr(opts
, "shared"))
3826 null_endofword(target
);
3827 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3829 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3833 TRACE("Turned all mount table entries into dependent mount");
3836 /* This does the work of remounting / if it is shared, calling the container
3837 * pre-mount hooks, and mounting the rootfs.
3839 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3840 const char *lxcpath
)
3844 conf
->rootfs
.dfd_host
= open_at(-EBADF
, "/", PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_ABSOLUTE
, 0);
3845 if (conf
->rootfs
.dfd_host
< 0)
3846 return log_error_errno(-errno
, errno
, "Failed to open \"/\"");
3848 turn_into_dependent_mounts(&conf
->rootfs
);
3850 if (conf
->rootfs_setup
) {
3851 const char *path
= conf
->rootfs
.mount
;
3854 * The rootfs was set up in another namespace. bind-mount it to
3855 * give us a mount in our own ns so we can pivot_root to it
3857 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3859 return log_error(-1, "Failed to bind mount container / onto itself");
3861 conf
->rootfs
.dfd_mnt
= openat(-EBADF
, path
, O_RDONLY
| O_CLOEXEC
| O_DIRECTORY
| O_PATH
| O_NOCTTY
);
3862 if (conf
->rootfs
.dfd_mnt
< 0)
3863 return log_error_errno(-errno
, errno
, "Failed to open file descriptor for container rootfs");
3865 return log_trace(0, "Bind mounted container / onto itself");
3868 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3870 return log_error(-1, "Failed to run pre-mount hooks");
3872 ret
= lxc_mount_rootfs(&conf
->rootfs
);
3874 return log_error(-1, "Failed to setup rootfs for");
3876 conf
->rootfs_setup
= true;
3880 static bool verify_start_hooks(struct lxc_conf
*conf
)
3882 char path
[PATH_MAX
];
3883 struct lxc_list
*it
;
3885 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3887 char *hookname
= it
->elem
;
3889 ret
= strnprintf(path
, sizeof(path
), "%s%s",
3890 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3895 ret
= access(path
, X_OK
);
3897 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
3905 static int lxc_setup_boot_id(void)
3908 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3909 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
3912 if (access(boot_id_path
, F_OK
))
3915 memset(&n
, 0, sizeof(n
));
3916 if (lxc_id128_randomize(&n
)) {
3917 SYSERROR("Failed to generate random data for uuid");
3921 ret
= lxc_id128_write(mock_boot_id_path
, n
);
3923 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
3927 ret
= chmod(mock_boot_id_path
, 0444);
3929 SYSERROR("Failed to chown %s", mock_boot_id_path
);
3930 (void)unlink(mock_boot_id_path
);
3934 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
3936 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
3938 (void)unlink(mock_boot_id_path
);
3942 ret
= mount(NULL
, boot_id_path
, NULL
,
3943 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
3947 SYSERROR("Failed to remount %s read-only", boot_id_path
);
3948 (void)unlink(mock_boot_id_path
);
3955 static int lxc_setup_keyring(struct lsm_ops
*lsm_ops
, const struct lxc_conf
*conf
)
3957 key_serial_t keyring
;
3960 if (conf
->lsm_se_keyring_context
)
3961 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_keyring_context
);
3962 else if (conf
->lsm_se_context
)
3963 ret
= lsm_ops
->keyring_label_set(lsm_ops
, conf
->lsm_se_context
);
3965 return log_error_errno(-1, errno
, "Failed to set keyring context");
3968 * Try to allocate a new session keyring for the container to prevent
3969 * information leaks.
3971 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
3972 prctl_arg(0), prctl_arg(0), prctl_arg(0));
3976 DEBUG("The keyctl() syscall is not supported or blocked");
3981 DEBUG("Failed to access kernel keyring. Continuing...");
3984 SYSERROR("Failed to create kernel keyring");
3992 static int lxc_rootfs_prepare_child(struct lxc_handler
*handler
)
3994 struct lxc_rootfs
*rootfs
= &handler
->conf
->rootfs
;
3995 int dfd_idmapped
= -EBADF
;
3998 if (lxc_list_empty(&handler
->conf
->id_map
))
4001 if (is_empty_string(rootfs
->mnt_opts
.userns_path
))
4004 if (handler
->conf
->rootfs_setup
)
4007 ret
= lxc_abstract_unix_recv_one_fd(handler
->data_sock
[1], &dfd_idmapped
, NULL
, 0);
4009 return syserror("Failed to receive idmapped mount fd");
4011 rootfs
->dfd_idmapped
= dfd_idmapped
;
4012 TRACE("Received detached idmapped mount %d", rootfs
->dfd_idmapped
);
4016 int lxc_idmapped_mounts_parent(struct lxc_handler
*handler
)
4021 __do_close
int fd_from
= -EBADF
, fd_userns
= -EBADF
;
4022 struct lxc_mount_attr attr
= {};
4023 struct lxc_mount_options opts
= {};
4026 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4027 &fd_from
, &fd_userns
,
4028 &opts
, sizeof(opts
));
4030 return syserror("Failed to receive idmapped mount file descriptors from child");
4032 if (fd_from
< 0 || fd_userns
< 0)
4033 return log_trace(0, "Finished receiving idmapped mount file descriptors from child");
4035 attr
.attr_set
= MOUNT_ATTR_IDMAP
;
4036 attr
.userns_fd
= fd_userns
;
4037 ret
= mount_setattr(fd_from
, "",
4039 (opts
.recursive
? AT_RECURSIVE
: 0),
4040 &attr
, sizeof(attr
));
4042 return syserror("Failed to idmap detached %smount %d to %d",
4043 opts
.recursive
? "recursive " : "",
4044 fd_from
, fd_userns
);
4046 ret
= lxc_abstract_unix_send_credential(handler
->data_sock
[1],
4050 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
4051 opts
.recursive
? "recursive " : "",
4052 fd_from
, fd_userns
);
4054 TRACE("Parent idmapped detached %smount %d to user namespace %d",
4055 opts
.recursive
? "recursive " : "", fd_from
, fd_userns
);
4060 static int lxc_recv_ttys_from_child(struct lxc_handler
*handler
)
4062 call_cleaner(lxc_delete_tty
) struct lxc_tty_info
*info_new
= &(struct lxc_tty_info
){};
4063 int sock
= handler
->data_sock
[1];
4064 struct lxc_conf
*conf
= handler
->conf
;
4065 struct lxc_tty_info
*tty_info
= &conf
->ttys
;
4066 size_t ttys_max
= tty_info
->max
;
4067 struct lxc_terminal_info
*terminal_info
;
4073 info_new
->tty
= malloc(sizeof(*(info_new
->tty
)) * ttys_max
);
4075 return ret_errno(ENOMEM
);
4077 for (int i
= 0; i
< ttys_max
; i
++) {
4078 terminal_info
= &info_new
->tty
[i
];
4079 terminal_info
->busy
= -1;
4080 terminal_info
->ptx
= -EBADF
;
4081 terminal_info
->pty
= -EBADF
;
4084 for (int i
= 0; i
< ttys_max
; i
++) {
4085 int ptx
= -EBADF
, pty
= -EBADF
;
4087 ret
= lxc_abstract_unix_recv_two_fds(sock
, &ptx
, &pty
);
4089 return syserror("Failed to receive %zu ttys from child", ttys_max
);
4091 terminal_info
= &info_new
->tty
[i
];
4092 terminal_info
->ptx
= ptx
;
4093 terminal_info
->pty
= pty
;
4094 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4095 terminal_info
->ptx
, terminal_info
->pty
);
4098 tty_info
->tty
= move_ptr(info_new
->tty
);
4099 TRACE("Received %zu ttys from child", ttys_max
);
4103 static int lxc_send_console_to_parent(struct lxc_handler
*handler
)
4105 struct lxc_terminal
*console
= &handler
->conf
->console
;
4108 if (!wants_console(console
))
4111 /* We've already allocated a console from the host's devpts instance. */
4112 if (console
->pty
< 0)
4115 ret
= __lxc_abstract_unix_send_two_fds(handler
->data_sock
[0],
4116 console
->ptx
, console
->pty
,
4118 sizeof(struct lxc_terminal
));
4120 return syserror("Fail to send console to parent");
4122 TRACE("Sent console to parent");
4126 static int lxc_recv_console_from_child(struct lxc_handler
*handler
)
4128 __do_close
int fd_ptx
= -EBADF
, fd_pty
= -EBADF
;
4129 struct lxc_terminal
*console
= &handler
->conf
->console
;
4132 if (!wants_console(console
))
4135 /* We've already allocated a console from the host's devpts instance. */
4136 if (console
->pty
>= 0)
4139 ret
= __lxc_abstract_unix_recv_two_fds(handler
->data_sock
[1],
4142 sizeof(struct lxc_terminal
));
4144 return syserror("Fail to receive console from child");
4146 console
->ptx
= move_fd(fd_ptx
);
4147 console
->pty
= move_fd(fd_pty
);
4149 TRACE("Received console from child");
4153 int lxc_sync_fds_parent(struct lxc_handler
*handler
)
4157 ret
= lxc_seccomp_recv_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[1]);
4159 return syserror_ret(ret
, "Failed to receive seccomp notify fd from child");
4161 ret
= lxc_recv_devpts_from_child(handler
);
4163 return syserror_ret(ret
, "Failed to receive devpts fd from child");
4165 /* Read tty fds allocated by child. */
4166 ret
= lxc_recv_ttys_from_child(handler
);
4168 return syserror_ret(ret
, "Failed to receive tty info from child process");
4170 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4171 ret
= lxc_network_recv_name_and_ifindex_from_child(handler
);
4173 return syserror_ret(ret
, "Failed to receive names and ifindices for network devices from child");
4176 ret
= lxc_recv_console_from_child(handler
);
4178 return syserror_ret(ret
, "Failed to receive console from child");
4180 TRACE("Finished syncing file descriptors with child");
4184 int lxc_sync_fds_child(struct lxc_handler
*handler
)
4188 ret
= lxc_seccomp_send_notifier_fd(&handler
->conf
->seccomp
, handler
->data_sock
[0]);
4190 return syserror_ret(ret
, "Failed to send seccomp notify fd to parent");
4192 ret
= lxc_send_devpts_to_parent(handler
);
4194 return syserror_ret(ret
, "Failed to send seccomp devpts fd to parent");
4196 ret
= lxc_send_ttys_to_parent(handler
);
4198 return syserror_ret(ret
, "Failed to send tty file descriptors to parent");
4200 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4201 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
4203 return syserror_ret(ret
, "Failed to send network device names and ifindices to parent");
4206 ret
= lxc_send_console_to_parent(handler
);
4208 return syserror_ret(ret
, "Failed to send console to parent");
4210 TRACE("Finished syncing file descriptors with parent");
4214 int lxc_setup(struct lxc_handler
*handler
)
4217 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
4218 struct lxc_conf
*lxc_conf
= handler
->conf
;
4220 ret
= lxc_rootfs_prepare_child(handler
);
4222 return syserror("Failed to prepare rootfs");
4224 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
4226 return log_error(-1, "Failed to setup rootfs");
4228 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
4229 ret
= setup_utsname(lxc_conf
->utsname
);
4231 return log_error(-1, "Failed to setup the utsname %s", name
);
4234 if (!lxc_conf
->keyring_disable_session
) {
4235 ret
= lxc_setup_keyring(handler
->lsm_ops
, lxc_conf
);
4237 return log_error(-1, "Failed to setup container keyring");
4240 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
4241 ret
= lxc_network_recv_from_parent(handler
);
4243 return log_error(-1, "Failed to receive veth names from parent");
4245 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
,
4246 &lxc_conf
->network
);
4248 return log_error(-1, "Failed to setup network");
4251 if (lxc_conf
->autodev
> 0) {
4252 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
4254 return log_error(-1, "Failed to mount \"/dev\"");
4257 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4258 * need to wait until other stuff has finished.
4260 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
);
4262 return log_error(-1, "Failed to setup first automatic mounts");
4264 ret
= setup_mount_fstab(&lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
4266 return log_error(-1, "Failed to setup mounts");
4268 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
4269 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
4270 &lxc_conf
->mount_list
, name
, lxcpath
);
4272 return log_error(-1, "Failed to setup mount entries");
4275 if (!lxc_sync_wake_parent(handler
, START_SYNC_IDMAPPED_MOUNTS
))
4278 ret
= lxc_idmapped_mounts_child(handler
);
4280 return syserror("Failed to attached detached idmapped mounts");
4282 lxc_conf
->rootfs
.dfd_dev
= open_at(lxc_conf
->rootfs
.dfd_mnt
, "dev",
4283 PROTECT_OPATH_DIRECTORY
, PROTECT_LOOKUP_BENEATH_XDEV
, 0);
4284 if (lxc_conf
->rootfs
.dfd_dev
< 0 && errno
!= ENOENT
)
4285 return log_error_errno(-errno
, errno
, "Failed to open \"/dev\"");
4287 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4288 * mounted. It is guaranteed to be mounted now either through
4289 * automatically or via fstab entries.
4291 ret
= lxc_mount_auto_mounts(handler
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
);
4293 return log_error(-1, "Failed to setup remaining automatic mounts");
4295 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
4297 return log_error(-1, "Failed to run mount hooks");
4299 if (lxc_conf
->autodev
> 0) {
4300 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
4302 return log_error(-1, "Failed to run autodev hooks");
4304 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
4306 return log_error(-1, "Failed to populate \"/dev\"");
4309 /* Make sure any start hooks are in the container */
4310 if (!verify_start_hooks(lxc_conf
))
4311 return log_error(-1, "Failed to verify start hooks");
4313 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
4315 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
4317 ret
= lxc_setup_devpts_child(handler
);
4319 return log_error(-1, "Failed to prepare new devpts instance");
4321 ret
= lxc_setup_console(handler
, &lxc_conf
->rootfs
, &lxc_conf
->console
,
4322 lxc_conf
->ttys
.dir
);
4324 return log_error(-1, "Failed to setup console");
4326 ret
= lxc_create_ttys(handler
);
4328 return log_error(-1, "Failed to create ttys");
4330 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
4332 return log_error(-1, "Failed to setup \"/dev\" symlinks");
4334 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
4336 return log_error(-1, "Failed to pivot root into rootfs");
4338 /* Setting the boot-id is best-effort for now. */
4339 if (lxc_conf
->autodev
> 0)
4340 (void)lxc_setup_boot_id();
4342 ret
= setup_personality(lxc_conf
->personality
);
4344 return syserror("Failed to set personality");
4346 /* Set sysctl value to a path under /proc/sys as determined from the
4347 * key. For e.g. net.ipv4.ip_forward translated to
4348 * /proc/sys/net/ipv4/ip_forward.
4350 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
4351 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
4353 return log_error(-1, "Failed to setup sysctl parameters");
4356 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
4357 if (!lxc_list_empty(&lxc_conf
->caps
))
4358 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
4360 if (dropcaps_except(&lxc_conf
->keepcaps
))
4361 return log_error(-1, "Failed to keep capabilities");
4362 } else if (setup_caps(&lxc_conf
->caps
)) {
4363 return log_error(-1, "Failed to drop capabilities");
4366 put_lxc_rootfs(&handler
->conf
->rootfs
, true);
4367 NOTICE("The container \"%s\" is set up", name
);
4372 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
4375 struct lxc_list
*it
;
4378 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
4379 if (strequal(hookname
, lxchook_names
[which
]))
4383 if (which
>= NUM_LXC_HOOKS
)
4386 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
4388 char *hook
= it
->elem
;
4390 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
4399 int lxc_clear_config_caps(struct lxc_conf
*c
)
4401 struct lxc_list
*it
, *next
;
4403 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
4409 lxc_list_init(&c
->caps
);
4413 static int lxc_free_idmap(struct lxc_list
*id_map
)
4415 struct lxc_list
*it
, *next
;
4417 lxc_list_for_each_safe(it
, id_map
, next
) {
4423 lxc_list_init(id_map
);
4427 static int __lxc_free_idmap(struct lxc_list
*id_map
)
4429 lxc_free_idmap(id_map
);
4433 define_cleanup_function(struct lxc_list
*, __lxc_free_idmap
);
4435 int lxc_clear_idmaps(struct lxc_conf
*c
)
4437 return lxc_free_idmap(&c
->id_map
);
4440 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
4442 struct lxc_list
*it
, *next
;
4444 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
4450 lxc_list_init(&c
->keepcaps
);
4454 int lxc_clear_namespace(struct lxc_conf
*c
)
4456 for (int i
= 0; i
< LXC_NS_MAX
; i
++)
4457 free_disarm(c
->ns_share
[i
]);
4462 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
4464 char *global_token
, *namespaced_token
;
4465 size_t namespaced_token_len
;
4466 struct lxc_list
*it
, *next
, *list
;
4467 const char *k
= key
;
4470 if (version
== CGROUP2_SUPER_MAGIC
) {
4471 global_token
= "lxc.cgroup2";
4472 namespaced_token
= "lxc.cgroup2.";
4473 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
4475 } else if (version
== CGROUP_SUPER_MAGIC
) {
4476 global_token
= "lxc.cgroup";
4477 namespaced_token
= "lxc.cgroup.";
4478 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
4481 return ret_errno(EINVAL
);
4484 if (strequal(key
, global_token
))
4486 else if (strnequal(key
, namespaced_token
, namespaced_token_len
))
4487 k
+= namespaced_token_len
;
4489 return ret_errno(EINVAL
);
4491 lxc_list_for_each_safe(it
, list
, next
) {
4492 struct lxc_cgroup
*cg
= it
->elem
;
4494 if (!all
&& !strequal(cg
->subsystem
, k
))
4498 free(cg
->subsystem
);
4505 lxc_list_init(list
);
4510 static inline void lxc_clear_cgroups_devices(struct lxc_conf
*conf
)
4512 lxc_clear_cgroup2_devices(&conf
->bpf_devices
);
4515 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
4517 struct lxc_list
*it
, *next
;
4518 const char *k
= NULL
;
4521 if (strequal(key
, "lxc.limit") || strequal(key
, "lxc.prlimit"))
4523 else if (strnequal(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
4524 k
= key
+ STRLITERALLEN("lxc.limit.");
4525 else if (strnequal(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
4526 k
= key
+ STRLITERALLEN("lxc.prlimit.");
4528 return ret_errno(EINVAL
);
4530 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
4531 struct lxc_limit
*lim
= it
->elem
;
4533 if (!all
&& !strequal(lim
->resource
, k
))
4538 free_disarm(lim
->resource
);
4544 lxc_list_init(&c
->limits
);
4549 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
4551 struct lxc_list
*it
, *next
;
4552 const char *k
= NULL
;
4555 if (strequal(key
, "lxc.sysctl"))
4557 else if (strnequal(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
4558 k
= key
+ STRLITERALLEN("lxc.sysctl.");
4562 lxc_list_for_each_safe(it
, &c
->sysctls
, next
) {
4563 struct lxc_sysctl
*elem
= it
->elem
;
4565 if (!all
&& !strequal(elem
->key
, k
))
4576 lxc_list_init(&c
->sysctls
);
4581 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
4583 struct lxc_list
*it
, *next
;
4584 const char *k
= NULL
;
4587 if (strequal(key
, "lxc.proc"))
4589 else if (strnequal(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
4590 k
= key
+ STRLITERALLEN("lxc.proc.");
4594 lxc_list_for_each_safe(it
, &c
->procs
, next
) {
4595 struct lxc_proc
*proc
= it
->elem
;
4597 if (!all
&& !strequal(proc
->filename
, k
))
4601 free(proc
->filename
);
4608 lxc_list_init(&c
->procs
);
4613 int lxc_clear_groups(struct lxc_conf
*c
)
4615 struct lxc_list
*it
, *next
;
4617 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
4623 lxc_list_init(&c
->groups
);
4627 int lxc_clear_environment(struct lxc_conf
*c
)
4629 struct lxc_list
*it
, *next
;
4631 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
4637 lxc_list_init(&c
->environment
);
4641 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4643 struct lxc_list
*it
, *next
;
4645 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
4651 lxc_list_init(&c
->mount_list
);
4655 int lxc_clear_automounts(struct lxc_conf
*c
)
4661 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4663 struct lxc_list
*it
, *next
;
4664 const char *k
= NULL
;
4665 bool all
= false, done
= false;
4667 if (strequal(key
, "lxc.hook"))
4669 else if (strnequal(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
4670 k
= key
+ STRLITERALLEN("lxc.hook.");
4674 for (int i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4675 if (all
|| strequal(k
, lxchook_names
[i
])) {
4676 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
4681 lxc_list_init(&c
->hooks
[i
]);
4688 return log_error(-1, "Invalid hook key: %s", key
);
4693 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4695 struct lxc_list
*it
, *next
;
4697 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4703 lxc_list_init(&conf
->aliens
);
4706 void lxc_clear_includes(struct lxc_conf
*conf
)
4708 struct lxc_list
*it
, *next
;
4710 lxc_list_for_each_safe(it
, &conf
->includes
, next
) {
4716 lxc_list_init(&conf
->includes
);
4719 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4721 struct lxc_list
*it
, *next
;
4723 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4729 lxc_list_init(&c
->lsm_aa_raw
);
4733 void lxc_conf_free(struct lxc_conf
*conf
)
4738 if (current_config
== conf
)
4739 current_config
= NULL
;
4740 lxc_terminal_conf_free(&conf
->console
);
4741 free(conf
->rootfs
.mount
);
4742 free(conf
->rootfs
.bdev_type
);
4743 free(conf
->rootfs
.options
);
4744 free(conf
->rootfs
.path
);
4745 put_lxc_rootfs(&conf
->rootfs
, true);
4746 free(conf
->logfile
);
4747 if (conf
->logfd
!= -1)
4749 free(conf
->utsname
);
4750 free(conf
->ttys
.dir
);
4751 free(conf
->ttys
.tty_names
);
4754 free(conf
->execute_cmd
);
4755 free(conf
->init_cmd
);
4756 free(conf
->init_groups
.list
);
4757 free(conf
->init_cwd
);
4758 free(conf
->unexpanded_config
);
4760 lxc_free_networks(&conf
->network
);
4761 free(conf
->lsm_aa_profile
);
4762 free(conf
->lsm_aa_profile_computed
);
4763 free(conf
->lsm_se_context
);
4764 free(conf
->lsm_se_keyring_context
);
4765 lxc_seccomp_free(&conf
->seccomp
);
4766 lxc_clear_config_caps(conf
);
4767 lxc_clear_config_keepcaps(conf
);
4768 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4769 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4770 lxc_clear_cgroups_devices(conf
);
4771 lxc_clear_hooks(conf
, "lxc.hook");
4772 lxc_clear_mount_entries(conf
);
4773 lxc_clear_idmaps(conf
);
4774 lxc_clear_groups(conf
);
4775 lxc_clear_includes(conf
);
4776 lxc_clear_aliens(conf
);
4777 lxc_clear_environment(conf
);
4778 lxc_clear_limits(conf
, "lxc.prlimit");
4779 lxc_clear_sysctls(conf
, "lxc.sysctl");
4780 lxc_clear_procs(conf
, "lxc.proc");
4781 lxc_clear_apparmor_raw(conf
);
4782 lxc_clear_namespace(conf
);
4783 free(conf
->cgroup_meta
.dir
);
4784 free(conf
->cgroup_meta
.monitor_dir
);
4785 free(conf
->cgroup_meta
.monitor_pivot_dir
);
4786 free(conf
->cgroup_meta
.container_dir
);
4787 free(conf
->cgroup_meta
.namespace_dir
);
4788 free(conf
->cgroup_meta
.controllers
);
4789 free(conf
->shmount
.path_host
);
4790 free(conf
->shmount
.path_cont
);
4794 struct userns_fn_data
{
4796 const char *fn_name
;
4801 static int run_userns_fn(void *data
)
4803 struct userns_fn_data
*d
= data
;
4807 close_prot_errno_disarm(d
->p
[1]);
4810 * Wait for parent to finish establishing a new mapping in the user
4811 * namespace we are executing in.
4813 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4814 close_prot_errno_disarm(d
->p
[0]);
4819 TRACE("Calling function \"%s\"", d
->fn_name
);
4821 /* Call function to run. */
4822 return d
->fn(d
->arg
);
4825 static struct id_map
*mapped_nsid_add(const struct lxc_conf
*conf
, unsigned id
,
4828 const struct id_map
*map
;
4829 struct id_map
*retmap
;
4831 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4835 retmap
= zalloc(sizeof(*retmap
));
4839 memcpy(retmap
, map
, sizeof(*retmap
));
4843 static struct id_map
*find_mapped_hostid_entry(const struct lxc_list
*idmap
,
4844 unsigned id
, enum idtype idtype
)
4847 struct lxc_list
*it
;
4848 struct id_map
*retmap
= NULL
;
4850 lxc_list_for_each (it
, idmap
) {
4852 if (map
->idtype
!= idtype
)
4855 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4864 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4865 * existing one or establish a new one.
4867 static struct id_map
*mapped_hostid_add(const struct lxc_conf
*conf
, uid_t id
,
4870 __do_free
struct id_map
*entry
= NULL
;
4872 struct id_map
*tmp
= NULL
;
4874 entry
= zalloc(sizeof(*entry
));
4878 /* Reuse existing mapping. */
4879 tmp
= find_mapped_hostid_entry(&conf
->id_map
, id
, type
);
4881 memcpy(entry
, tmp
, sizeof(*entry
));
4883 /* Find new mapping. */
4884 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4885 if (hostid_mapped
< 0)
4886 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
4888 entry
->idtype
= type
;
4889 entry
->nsid
= hostid_mapped
;
4890 entry
->hostid
= (unsigned long)id
;
4894 return move_ptr(entry
);
4897 static struct lxc_list
*get_minimal_idmap(const struct lxc_conf
*conf
,
4898 uid_t
*resuid
, gid_t
*resgid
)
4900 __do_free
struct id_map
*container_root_uid
= NULL
,
4901 *container_root_gid
= NULL
,
4902 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4903 __do_free
struct lxc_list
*idmap
= NULL
;
4905 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4906 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4907 struct lxc_list
*tmplist
= NULL
;
4909 /* Find container root mappings. */
4910 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4911 if (!container_root_uid
)
4912 return log_debug(NULL
, "Failed to find mapping for namespace uid %d", 0);
4914 if (euid
>= container_root_uid
->hostid
&&
4915 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4916 host_uid_map
= move_ptr(container_root_uid
);
4918 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4919 if (!container_root_gid
)
4920 return log_debug(NULL
, "Failed to find mapping for namespace gid %d", 0);
4922 if (egid
>= container_root_gid
->hostid
&&
4923 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4924 host_gid_map
= move_ptr(container_root_gid
);
4926 /* Check whether the {g,u}id of the user has a mapping. */
4928 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4930 return log_debug(NULL
, "Failed to find mapping for uid %d", euid
);
4933 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4935 return log_debug(NULL
, "Failed to find mapping for gid %d", egid
);
4937 /* Allocate new {g,u}id map list. */
4938 idmap
= lxc_list_new();
4942 /* Add container root to the map. */
4943 tmplist
= lxc_list_new();
4946 /* idmap will now keep track of that memory. */
4947 lxc_list_add_elem(tmplist
, move_ptr(host_uid_map
));
4948 lxc_list_add_tail(idmap
, tmplist
);
4950 if (container_root_uid
) {
4951 /* Add container root to the map. */
4952 tmplist
= lxc_list_new();
4955 /* idmap will now keep track of that memory. */
4956 lxc_list_add_elem(tmplist
, move_ptr(container_root_uid
));
4957 lxc_list_add_tail(idmap
, tmplist
);
4960 tmplist
= lxc_list_new();
4963 /* idmap will now keep track of that memory. */
4964 lxc_list_add_elem(tmplist
, move_ptr(host_gid_map
));
4965 lxc_list_add_tail(idmap
, tmplist
);
4967 if (container_root_gid
) {
4968 tmplist
= lxc_list_new();
4971 /* idmap will now keep track of that memory. */
4972 lxc_list_add_elem(tmplist
, move_ptr(container_root_gid
));
4973 lxc_list_add_tail(idmap
, tmplist
);
4976 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid
, nsgid
);
4982 return move_ptr(idmap
);
4986 * Run a function in a new user namespace.
4987 * The caller's euid/egid will be mapped if it is not already.
4988 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4989 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4990 * This means we require only to establish a mapping from:
4991 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4992 * - the container root -> some sub{g,u}id
4993 * The former we add, if the user did not specify a mapping. The latter we
4994 * retrieve from the container's configured {g,u}id mappings as it must have been
4995 * there to start the container in the first place.
4997 int userns_exec_1(const struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4998 const char *fn_name
)
5000 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
5001 int ret
= -1, status
= -1;
5003 struct userns_fn_data d
= {
5014 idmap
= get_minimal_idmap(conf
, NULL
, NULL
);
5016 return ret_errno(ENOENT
);
5018 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
5022 d
.p
[0] = pipe_fds
[0];
5023 d
.p
[1] = pipe_fds
[1];
5025 /* Clone child in new user namespace. */
5026 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5028 ERROR("Failed to clone process in new user namespace");
5032 close_prot_errno_disarm(pipe_fds
[0]);
5034 if (lxc_log_trace()) {
5036 struct lxc_list
*it
;
5038 lxc_list_for_each(it
, idmap
) {
5040 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5041 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5045 /* Set up {g,u}id mapping for user namespace of child process. */
5046 ret
= lxc_map_ids(idmap
, pid
);
5048 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5052 /* Tell child to proceed. */
5053 if (lxc_write_nointr(pipe_fds
[1], &c
, 1) != 1) {
5054 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5059 close_prot_errno_disarm(pipe_fds
[0]);
5060 close_prot_errno_disarm(pipe_fds
[1]);
5062 /* Wait for child to finish. */
5064 status
= wait_for_pid(pid
);
5072 int userns_exec_minimal(const struct lxc_conf
*conf
,
5073 int (*fn_parent
)(void *), void *fn_parent_data
,
5074 int (*fn_child
)(void *), void *fn_child_data
)
5076 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
5077 uid_t resuid
= LXC_INVALID_UID
;
5078 gid_t resgid
= LXC_INVALID_GID
;
5084 if (!conf
|| !fn_child
)
5085 return ret_errno(EINVAL
);
5087 idmap
= get_minimal_idmap(conf
, &resuid
, &resgid
);
5089 return ret_errno(ENOENT
);
5091 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5097 SYSERROR("Failed to create new process");
5102 close_prot_errno_disarm(sock_fds
[1]);
5104 ret
= unshare(CLONE_NEWUSER
);
5106 SYSERROR("Failed to unshare new user namespace");
5107 _exit(EXIT_FAILURE
);
5110 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5112 _exit(EXIT_FAILURE
);
5114 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5116 _exit(EXIT_FAILURE
);
5118 close_prot_errno_disarm(sock_fds
[0]);
5120 if (!lxc_drop_groups() && errno
!= EPERM
)
5121 _exit(EXIT_FAILURE
);
5123 ret
= setresgid(resgid
, resgid
, resgid
);
5125 SYSERROR("Failed to setresgid(%d, %d, %d)",
5126 resgid
, resgid
, resgid
);
5127 _exit(EXIT_FAILURE
);
5130 ret
= setresuid(resuid
, resuid
, resuid
);
5132 SYSERROR("Failed to setresuid(%d, %d, %d)",
5133 resuid
, resuid
, resuid
);
5134 _exit(EXIT_FAILURE
);
5137 ret
= fn_child(fn_child_data
);
5139 SYSERROR("Running function in new user namespace failed");
5140 _exit(EXIT_FAILURE
);
5143 _exit(EXIT_SUCCESS
);
5146 close_prot_errno_disarm(sock_fds
[0]);
5148 if (lxc_log_trace()) {
5150 struct lxc_list
*it
;
5152 lxc_list_for_each(it
, idmap
) {
5154 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5155 (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
)
5202 struct lxc_list
*cur
;
5203 struct userns_fn_data d
;
5206 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
5207 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
5208 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
5213 ret
= pipe2(p
, O_CLOEXEC
);
5215 SYSERROR("opening pipe");
5219 d
.fn_name
= fn_name
;
5224 /* Clone child in new user namespace. */
5225 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
5227 ERROR("Failed to clone process in new user namespace");
5237 /* Allocate new {g,u}id map list. */
5238 idmap
= lxc_list_new();
5242 /* Find container root. */
5243 lxc_list_for_each (cur
, &conf
->id_map
) {
5244 struct id_map
*tmpmap
;
5246 tmplist
= lxc_list_new();
5250 tmpmap
= zalloc(sizeof(*tmpmap
));
5256 memset(tmpmap
, 0, sizeof(*tmpmap
));
5257 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
5258 tmplist
->elem
= tmpmap
;
5260 lxc_list_add_tail(idmap
, tmplist
);
5264 if (map
->idtype
== ID_TYPE_UID
)
5265 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
5268 if (map
->idtype
== ID_TYPE_GID
)
5269 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
5275 if (map
->idtype
== ID_TYPE_UID
)
5276 if (container_root_uid
== NULL
)
5277 container_root_uid
= map
;
5279 if (map
->idtype
== ID_TYPE_GID
)
5280 if (container_root_gid
== NULL
)
5281 container_root_gid
= map
;
5284 if (!container_root_uid
|| !container_root_gid
) {
5285 ERROR("No mapping for container root found");
5289 /* Check whether the {g,u}id of the user has a mapping. */
5291 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
5293 host_uid_map
= container_root_uid
;
5296 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
5298 host_gid_map
= container_root_gid
;
5300 if (!host_uid_map
) {
5301 DEBUG("Failed to find mapping for uid %d", euid
);
5305 if (!host_gid_map
) {
5306 DEBUG("Failed to find mapping for gid %d", egid
);
5310 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
5311 /* Add container root to the map. */
5312 tmplist
= lxc_list_new();
5315 lxc_list_add_elem(tmplist
, host_uid_map
);
5316 lxc_list_add_tail(idmap
, tmplist
);
5318 /* idmap will now keep track of that memory. */
5319 host_uid_map
= NULL
;
5321 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
5322 tmplist
= lxc_list_new();
5325 lxc_list_add_elem(tmplist
, host_gid_map
);
5326 lxc_list_add_tail(idmap
, tmplist
);
5328 /* idmap will now keep track of that memory. */
5329 host_gid_map
= NULL
;
5331 if (lxc_log_trace()) {
5332 lxc_list_for_each (cur
, idmap
) {
5334 TRACE("establishing %cid mapping for \"%d\" in new "
5335 "user namespace: nsuid %lu - hostid %lu - range "
5337 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
5338 map
->nsid
, map
->hostid
, map
->range
);
5342 /* Set up {g,u}id mapping for user namespace of child process. */
5343 ret
= lxc_map_ids(idmap
, pid
);
5345 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
5349 /* Tell child to proceed. */
5350 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
5351 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5360 /* Wait for child to finish. */
5362 ret
= wait_for_pid(pid
);
5365 __lxc_free_idmap(idmap
);
5367 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
5369 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
5375 static int add_idmap_entry(struct lxc_list
*idmap
, enum idtype idtype
,
5376 unsigned long nsid
, unsigned long hostid
,
5377 unsigned long range
)
5379 __do_free
struct id_map
*new_idmap
= NULL
;
5380 __do_free
struct lxc_list
*new_list
= NULL
;
5382 new_idmap
= zalloc(sizeof(*new_idmap
));
5384 return ret_errno(ENOMEM
);
5386 new_idmap
->idtype
= idtype
;
5387 new_idmap
->hostid
= hostid
;
5388 new_idmap
->nsid
= nsid
;
5389 new_idmap
->range
= range
;
5391 new_list
= zalloc(sizeof(*new_list
));
5393 return ret_errno(ENOMEM
);
5395 new_list
->elem
= move_ptr(new_idmap
);
5396 lxc_list_add_tail(idmap
, move_ptr(new_list
));
5398 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5399 idtype
== ID_TYPE_UID
? 'u' : 'g', nsid
, hostid
, range
);
5403 int userns_exec_mapped_root(const char *path
, int path_fd
,
5404 const struct lxc_conf
*conf
)
5406 call_cleaner(__lxc_free_idmap
) struct lxc_list
*idmap
= NULL
;
5407 __do_close
int fd
= -EBADF
;
5408 int target_fd
= -EBADF
;
5413 uid_t container_host_uid
, hostuid
;
5414 gid_t container_host_gid
, hostgid
;
5417 if (!conf
|| (!path
&& path_fd
< 0))
5418 return ret_errno(EINVAL
);
5423 container_host_uid
= get_mapped_rootid(conf
, ID_TYPE_UID
);
5424 if (!uid_valid(container_host_uid
))
5425 return log_error(-1, "No uid mapping for container root");
5427 container_host_gid
= get_mapped_rootid(conf
, ID_TYPE_GID
);
5428 if (!gid_valid(container_host_gid
))
5429 return log_error(-1, "No gid mapping for container root");
5432 fd
= open(path
, O_CLOEXEC
| O_NOCTTY
);
5434 return log_error_errno(-errno
, errno
, "Failed to open \"%s\"", path
);
5437 target_fd
= path_fd
;
5440 hostuid
= geteuid();
5441 /* We are root so chown directly. */
5443 ret
= fchown(target_fd
, container_host_uid
, container_host_gid
);
5445 return log_error_errno(-errno
, errno
,
5446 "Failed to fchown(%d(%s), %d, %d)",
5447 target_fd
, path
, container_host_uid
,
5448 container_host_gid
);
5449 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd
, path
,
5450 container_host_uid
, container_host_gid
);
5453 /* The container's root host id matches */
5454 if (container_host_uid
== hostuid
)
5455 return log_info(0, "Container root id is mapped to our uid");
5457 /* Get the current ids of our target. */
5458 ret
= fstat(target_fd
, &st
);
5460 return log_error_errno(-errno
, errno
, "Failed to stat \"%s\"", path
);
5462 hostgid
= getegid();
5463 if (st
.st_uid
== hostuid
&& mapped_hostid(st
.st_gid
, conf
, ID_TYPE_GID
) < 0) {
5464 ret
= fchown(target_fd
, -1, hostgid
);
5466 return log_error_errno(-errno
, errno
,
5467 "Failed to fchown(%d(%s), -1, %d)",
5468 target_fd
, path
, hostgid
);
5469 TRACE("Chowned %d(%s) to -1:%d", target_fd
, path
, hostgid
);
5472 idmap
= lxc_list_new();
5476 /* "u:0:rootuid:1" */
5477 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, 0, container_host_uid
, 1);
5479 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5481 /* "u:hostuid:hostuid:1" */
5482 ret
= add_idmap_entry(idmap
, ID_TYPE_UID
, hostuid
, hostuid
, 1);
5484 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5486 /* "g:0:rootgid:1" */
5487 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, 0, container_host_gid
, 1);
5489 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5491 /* "g:hostgid:hostgid:1" */
5492 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, hostgid
, hostgid
, 1);
5494 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5496 if (hostgid
!= st
.st_gid
) {
5497 /* "g:pathgid:rootgid+pathgid:1" */
5498 ret
= add_idmap_entry(idmap
, ID_TYPE_GID
, st
.st_gid
,
5499 container_host_gid
+ (gid_t
)st
.st_gid
, 1);
5501 return log_error_errno(ret
, -ret
, "Failed to add idmap entry");
5504 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, sock_fds
);
5510 SYSERROR("Failed to create new process");
5515 close_prot_errno_disarm(sock_fds
[1]);
5517 ret
= unshare(CLONE_NEWUSER
);
5519 SYSERROR("Failed to unshare new user namespace");
5520 _exit(EXIT_FAILURE
);
5523 ret
= lxc_write_nointr(sock_fds
[0], &c
, 1);
5525 _exit(EXIT_FAILURE
);
5527 ret
= lxc_read_nointr(sock_fds
[0], &c
, 1);
5529 _exit(EXIT_FAILURE
);
5531 close_prot_errno_disarm(sock_fds
[0]);
5533 if (!lxc_switch_uid_gid(0, 0))
5534 _exit(EXIT_FAILURE
);
5536 if (!lxc_drop_groups())
5537 _exit(EXIT_FAILURE
);
5539 ret
= fchown(target_fd
, 0, st
.st_gid
);
5541 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5542 _exit(EXIT_FAILURE
);
5545 TRACE("Chowned %d(%s) to 0:%d", target_fd
, path
, st
.st_gid
);
5546 _exit(EXIT_SUCCESS
);
5549 close_prot_errno_disarm(sock_fds
[0]);
5551 if (lxc_log_trace()) {
5553 struct lxc_list
*it
;
5555 lxc_list_for_each(it
, idmap
) {
5557 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5558 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
, map
->nsid
, map
->hostid
, map
->range
);
5562 ret
= lxc_read_nointr(sock_fds
[1], &c
, 1);
5564 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid
);
5568 /* Set up {g,u}id mapping for user namespace of child process. */
5569 ret
= lxc_map_ids(idmap
, pid
);
5571 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
5575 /* Tell child to proceed. */
5576 ret
= lxc_write_nointr(sock_fds
[1], &c
, 1);
5578 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
5583 close_prot_errno_disarm(sock_fds
[0]);
5584 close_prot_errno_disarm(sock_fds
[1]);
5586 /* Wait for child to finish. */
5590 return wait_for_pid(pid
);
5593 /* not thread-safe, do not use from api without first forking */
5594 static char *getuname(void)
5596 __do_free
char *buf
= NULL
;
5597 struct passwd pwent
;
5598 struct passwd
*pwentp
= NULL
;
5602 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
5606 buf
= zalloc(bufsize
);
5610 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
5613 WARN("Could not find matched password record.");
5615 return log_error(NULL
, "Failed to get password record - %u", geteuid());
5618 return strdup(pwent
.pw_name
);
5621 /* not thread-safe, do not use from api without first forking */
5622 static char *getgname(void)
5624 __do_free
char *buf
= NULL
;
5626 struct group
*grentp
= NULL
;
5630 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
5634 buf
= zalloc(bufsize
);
5638 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
5641 WARN("Could not find matched group record");
5643 return log_error(NULL
, "Failed to get group record - %u", getegid());
5646 return strdup(grent
.gr_name
);
5649 /* not thread-safe, do not use from api without first forking */
5650 void suggest_default_idmap(void)
5652 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
5653 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
5654 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
5665 subuid_f
= fopen(subuidfile
, "re");
5667 ERROR("Your system is not configured with subuids");
5671 while (getline(&line
, &len
, subuid_f
) != -1) {
5673 size_t no_newline
= 0;
5675 p
= strchr(line
, ':');
5683 if (!strequal(line
, uname
))
5686 p2
= strchr(p
, ':');
5693 no_newline
= strcspn(p2
, "\n");
5694 p2
[no_newline
] = '\0';
5696 if (lxc_safe_uint(p
, &uid
) < 0)
5697 WARN("Could not parse UID");
5698 if (lxc_safe_uint(p2
, &urange
) < 0)
5699 WARN("Could not parse UID range");
5702 subgid_f
= fopen(subgidfile
, "re");
5704 ERROR("Your system is not configured with subgids");
5708 while (getline(&line
, &len
, subgid_f
) != -1) {
5710 size_t no_newline
= 0;
5712 p
= strchr(line
, ':');
5720 if (!strequal(line
, uname
))
5723 p2
= strchr(p
, ':');
5730 no_newline
= strcspn(p2
, "\n");
5731 p2
[no_newline
] = '\0';
5733 if (lxc_safe_uint(p
, &gid
) < 0)
5734 WARN("Could not parse GID");
5735 if (lxc_safe_uint(p2
, &grange
) < 0)
5736 WARN("Could not parse GID range");
5739 if (!urange
|| !grange
) {
5740 ERROR("You do not have subuids or subgids allocated");
5741 ERROR("Unprivileged containers require subuids and subgids");
5745 ERROR("You must either run as root, or define uid mappings");
5746 ERROR("To pass uid mappings to lxc-create, you could create");
5747 ERROR("~/.config/lxc/default.conf:");
5748 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
5749 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
5750 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
5753 static void free_cgroup_settings(struct lxc_list
*result
)
5755 struct lxc_list
*iterator
, *next
;
5757 lxc_list_for_each_safe (iterator
, result
, next
) {
5758 lxc_list_del(iterator
);
5759 free_disarm(iterator
);
5761 free_disarm(result
);
5764 /* Return the list of cgroup_settings sorted according to the following rules
5765 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
5767 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
5769 struct lxc_list
*result
;
5770 struct lxc_cgroup
*cg
= NULL
;
5771 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
5773 result
= lxc_list_new();
5776 lxc_list_init(result
);
5778 /* Iterate over the cgroup settings and copy them to the output list. */
5779 lxc_list_for_each (it
, cgroup_settings
) {
5780 item
= zalloc(sizeof(*item
));
5782 free_cgroup_settings(result
);
5786 item
->elem
= it
->elem
;
5788 if (strequal(cg
->subsystem
, "memory.memsw.limit_in_bytes")) {
5789 /* Store the memsw_limit location */
5791 } else if (strequal(cg
->subsystem
, "memory.limit_in_bytes") &&
5792 memsw_limit
!= NULL
) {
5793 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
5794 * before lxc.cgroup.memory.limit_in_bytes, swap these
5796 item
->elem
= memsw_limit
->elem
;
5797 memsw_limit
->elem
= it
->elem
;
5799 lxc_list_add_tail(result
, item
);