]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/conf.c
conf: port environment to new list type
[mirror_lxc.git] / src / lxc / conf.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #ifndef _GNU_SOURCE
4 #define _GNU_SOURCE 1
5 #endif
6 #include <arpa/inet.h>
7 #include <dirent.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <grp.h>
11 #include <inttypes.h>
12 #include <libgen.h>
13 #include <linux/loop.h>
14 #include <net/if.h>
15 #include <netinet/in.h>
16 #include <pwd.h>
17 #include <stdarg.h>
18 #include <stdbool.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/mman.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>
28 #include <sys/stat.h>
29 #include <sys/syscall.h>
30 #include <sys/sysmacros.h>
31 #include <sys/types.h>
32 #include <sys/utsname.h>
33 #include <sys/wait.h>
34 #include <time.h>
35 #include <unistd.h>
36
37 #include "af_unix.h"
38 #include "caps.h"
39 #include "cgroups/cgroup.h"
40 #include "compiler.h"
41 #include "conf.h"
42 #include "config.h"
43 #include "confile.h"
44 #include "confile_utils.h"
45 #include "error.h"
46 #include "log.h"
47 #include "lsm/lsm.h"
48 #include "lxclock.h"
49 #include "lxcseccomp.h"
50 #include "macro.h"
51 #include "memory_utils.h"
52 #include "mount_utils.h"
53 #include "namespace.h"
54 #include "network.h"
55 #include "parse.h"
56 #include "process_utils.h"
57 #include "ringbuf.h"
58 #include "start.h"
59 #include "storage/storage.h"
60 #include "storage/overlay.h"
61 #include "sync.h"
62 #include "syscall_wrappers.h"
63 #include "terminal.h"
64 #include "utils.h"
65 #include "uuid.h"
66
67 #ifdef MAJOR_IN_MKDEV
68 #include <sys/mkdev.h>
69 #endif
70
71 #ifdef HAVE_STATVFS
72 #include <sys/statvfs.h>
73 #endif
74
75 #if HAVE_OPENPTY
76 #include <pty.h>
77 #else
78 #include <../include/openpty.h>
79 #endif
80
81 #if HAVE_LIBCAP
82 #include <sys/capability.h>
83 #endif
84
85 #ifndef HAVE_STRLCAT
86 #include "include/strlcat.h"
87 #endif
88
89 #if IS_BIONIC
90 #include <../include/lxcmntent.h>
91 #else
92 #include <mntent.h>
93 #endif
94
95 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
96 #include <../include/prlimit.h>
97 #endif
98
99 #ifndef HAVE_STRLCPY
100 #include "include/strlcpy.h"
101 #endif
102
103 #ifndef HAVE_STRCHRNUL
104 #include "include/strchrnul.h"
105 #endif
106
107 lxc_log_define(conf, lxc);
108
109 /*
110 * The lxc_conf of the container currently being worked on in an API call.
111 * This is used in the error calls.
112 */
113 thread_local struct lxc_conf *current_config;
114
115 char *lxchook_names[NUM_LXC_HOOKS] = {
116 "pre-start",
117 "pre-mount",
118 "mount",
119 "autodev",
120 "start",
121 "stop",
122 "post-stop",
123 "clone",
124 "destroy",
125 "start-host"
126 };
127
128 struct mount_opt {
129 char *name;
130 int clear;
131 bool recursive;
132 __u64 flag;
133 int legacy_flag;
134 };
135
136 struct caps_opt {
137 char *name;
138 int value;
139 };
140
141 struct limit_opt {
142 char *name;
143 int value;
144 };
145
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 },
163
164 { "bind", 0, false, 0, MS_BIND },
165 { "defaults", 0, false, 0, 0 },
166 { "rbind", 0, true, 0, MS_BIND | MS_REC },
167
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 },
175
176 { NULL, 0, false, ~0, ~0 },
177 };
178
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 },
188 { NULL, 0, 0 },
189 };
190
191 static struct caps_opt caps_opt[] = {
192 #if HAVE_LIBCAP
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 },
232 { "bpf", CAP_BPF },
233 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE },
234 #endif
235 };
236
237 static struct limit_opt limit_opt[] = {
238 #ifdef RLIMIT_AS
239 { "as", RLIMIT_AS },
240 #endif
241 #ifdef RLIMIT_CORE
242 { "core", RLIMIT_CORE },
243 #endif
244 #ifdef RLIMIT_CPU
245 { "cpu", RLIMIT_CPU },
246 #endif
247 #ifdef RLIMIT_DATA
248 { "data", RLIMIT_DATA },
249 #endif
250 #ifdef RLIMIT_FSIZE
251 { "fsize", RLIMIT_FSIZE },
252 #endif
253 #ifdef RLIMIT_LOCKS
254 { "locks", RLIMIT_LOCKS },
255 #endif
256 #ifdef RLIMIT_MEMLOCK
257 { "memlock", RLIMIT_MEMLOCK },
258 #endif
259 #ifdef RLIMIT_MSGQUEUE
260 { "msgqueue", RLIMIT_MSGQUEUE },
261 #endif
262 #ifdef RLIMIT_NICE
263 { "nice", RLIMIT_NICE },
264 #endif
265 #ifdef RLIMIT_NOFILE
266 { "nofile", RLIMIT_NOFILE },
267 #endif
268 #ifdef RLIMIT_NPROC
269 { "nproc", RLIMIT_NPROC },
270 #endif
271 #ifdef RLIMIT_RSS
272 { "rss", RLIMIT_RSS },
273 #endif
274 #ifdef RLIMIT_RTPRIO
275 { "rtprio", RLIMIT_RTPRIO },
276 #endif
277 #ifdef RLIMIT_RTTIME
278 { "rttime", RLIMIT_RTTIME },
279 #endif
280 #ifdef RLIMIT_SIGPENDING
281 { "sigpending", RLIMIT_SIGPENDING },
282 #endif
283 #ifdef RLIMIT_STACK
284 { "stack", RLIMIT_STACK },
285 #endif
286 };
287
288 static int run_buffer(char *buffer)
289 {
290 __do_free char *output = NULL;
291 __do_lxc_pclose struct lxc_popen_FILE *f = NULL;
292 int fd, ret;
293
294 f = lxc_popen(buffer);
295 if (!f)
296 return log_error_errno(-1, errno, "Failed to popen() %s", buffer);
297
298 output = zalloc(LXC_LOG_BUFFER_SIZE);
299 if (!output)
300 return log_error_errno(-1, ENOMEM, "Failed to allocate memory for %s", buffer);
301
302 fd = fileno(f->f);
303 if (fd < 0)
304 return log_error_errno(-1, errno, "Failed to retrieve underlying file descriptor");
305
306 for (int i = 0; i < 10; i++) {
307 ssize_t bytes_read;
308
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);
313 continue;
314 }
315
316 break;
317 }
318
319 ret = lxc_pclose(move_ptr(f));
320 if (ret == -1)
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));
326
327 return 0;
328 }
329
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)
333 {
334 __do_free char *buffer = NULL;
335 int buf_pos, i, ret;
336 size_t size = 0;
337
338 if (hook_version == 0)
339 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
340 script, name, section);
341 else
342 INFO("Executing script \"%s\" for container \"%s\"", script, name);
343
344 for (i = 0; argv && argv[i]; i++)
345 size += strlen(argv[i]) + 1;
346
347 size += STRLITERALLEN("exec");
348 size++;
349 size += strlen(script);
350 size++;
351
352 if (size > INT_MAX)
353 return -EFBIG;
354
355 if (hook_version == 0) {
356 size += strlen(hookname);
357 size++;
358
359 size += strlen(name);
360 size++;
361
362 size += strlen(section);
363 size++;
364
365 if (size > INT_MAX)
366 return -EFBIG;
367 }
368
369 buffer = zalloc(size);
370 if (!buffer)
371 return -ENOMEM;
372
373 if (hook_version == 0)
374 buf_pos = strnprintf(buffer, size, "exec %s %s %s %s", script, name, section, hookname);
375 else
376 buf_pos = strnprintf(buffer, size, "exec %s", script);
377 if (buf_pos < 0)
378 return log_error_errno(-1, errno, "Failed to create command line for script \"%s\"", script);
379
380 if (hook_version == 1) {
381 ret = setenv("LXC_HOOK_TYPE", hookname, 1);
382 if (ret < 0) {
383 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname);
384 }
385 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname);
386
387 ret = setenv("LXC_HOOK_SECTION", section, 1);
388 if (ret < 0)
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);
391
392 if (strequal(section, "net")) {
393 char *parent;
394
395 if (!argv || !argv[0])
396 return -1;
397
398 ret = setenv("LXC_NET_TYPE", argv[0], 1);
399 if (ret < 0)
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]);
402
403 parent = argv[1] ? argv[1] : "";
404
405 if (strequal(argv[0], "macvlan")) {
406 ret = setenv("LXC_NET_PARENT", parent, 1);
407 if (ret < 0)
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);
412 if (ret < 0)
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] : "";
417
418 ret = setenv("LXC_NET_PEER", peer, 1);
419 if (ret < 0)
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);
422
423 ret = setenv("LXC_NET_PARENT", parent, 1);
424 if (ret < 0)
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);
427 }
428 }
429 }
430
431 for (i = 0; argv && argv[i]; i++) {
432 size_t len = size - buf_pos;
433
434 ret = strnprintf(buffer + buf_pos, len, " %s", argv[i]);
435 if (ret < 0)
436 return log_error_errno(-1, errno, "Failed to create command line for script \"%s\"", script);
437 buf_pos += ret;
438 }
439
440 return run_buffer(buffer);
441 }
442
443 int run_script(const char *name, const char *section, const char *script, ...)
444 {
445 __do_free char *buffer = NULL;
446 int ret;
447 char *p;
448 va_list ap;
449 size_t size = 0;
450
451 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
452 script, name, section);
453
454 va_start(ap, script);
455 while ((p = va_arg(ap, char *)))
456 size += strlen(p) + 1;
457 va_end(ap);
458
459 size += STRLITERALLEN("exec");
460 size += strlen(script);
461 size += strlen(name);
462 size += strlen(section);
463 size += 4;
464
465 if (size > INT_MAX)
466 return -1;
467
468 buffer = must_realloc(NULL, size);
469 ret = strnprintf(buffer, size, "exec %s %s %s", script, name, section);
470 if (ret < 0)
471 return -1;
472
473 va_start(ap, script);
474 while ((p = va_arg(ap, char *))) {
475 int len = size - ret;
476 int rc;
477 rc = strnprintf(buffer + ret, len, " %s", p);
478 if (rc < 0) {
479 va_end(ap);
480 return -1;
481 }
482 ret += rc;
483 }
484 va_end(ap);
485
486 return run_buffer(buffer);
487 }
488
489 int lxc_storage_prepare(struct lxc_conf *conf)
490 {
491 int ret;
492 struct lxc_rootfs *rootfs = &conf->rootfs;
493
494 if (!rootfs->path) {
495 ret = mount("", "/", NULL, MS_SLAVE | MS_REC, 0);
496 if (ret < 0)
497 return log_error_errno(-1, errno, "Failed to recursively turn root mount tree into dependent mount");
498
499 rootfs->dfd_mnt = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
500 if (rootfs->dfd_mnt < 0)
501 return -errno;
502
503 return 0;
504 }
505
506 ret = access(rootfs->mount, F_OK);
507 if (ret != 0)
508 return log_error_errno(-1, errno, "Failed to access to \"%s\". Check it is present",
509 rootfs->mount);
510
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->mnt_opts.raw_options ? rootfs->mnt_opts.raw_options : "(null)");
516
517 return 0;
518 }
519
520 void lxc_storage_put(struct lxc_conf *conf)
521 {
522 storage_put(conf->rootfs.storage);
523 conf->rootfs.storage = NULL;
524 }
525
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.
532 */
533 int lxc_rootfs_init(struct lxc_conf *conf, bool userns)
534 {
535 __do_close int dfd_path = -EBADF, fd_pin = -EBADF;
536 int ret;
537 struct stat st;
538 struct statfs stfs;
539 struct lxc_rootfs *rootfs = &conf->rootfs;
540
541 ret = lxc_storage_prepare(conf);
542 if (ret)
543 return syserror_set(-EINVAL, "Failed to prepare rootfs storage");
544
545 if (!is_empty_string(rootfs->mnt_opts.userns_path)) {
546 if (!rootfs->path)
547 return syserror_set(-EINVAL, "Idmapped rootfs currently only supported with separate rootfs for container");
548
549 if (rootfs->bdev_type && !strequal(rootfs->bdev_type, "dir"))
550 return syserror_set(-EINVAL, "Idmapped rootfs currently only supports the \"dir\" storage driver");
551 }
552
553 if (!rootfs->path)
554 return log_trace(0, "Not pinning because container does not have a rootfs");
555
556 if (userns)
557 return log_trace(0, "Not pinning because container runs in user namespace");
558
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");
563
564 if (strequal(rootfs->bdev_type, "zfs"))
565 return log_trace_errno(0, EINVAL, "Not pinning on ZFS filesystem");
566 }
567
568 dfd_path = open_at(-EBADF, rootfs->path, PROTECT_OPATH_FILE, 0, 0);
569 if (dfd_path < 0)
570 return syserror("Failed to open \"%s\"", rootfs->path);
571
572 ret = fstat(dfd_path, &st);
573 if (ret < 0)
574 return log_trace_errno(-errno, errno, "Failed to retrieve file status");
575
576 if (!S_ISDIR(st.st_mode))
577 return log_trace_errno(0, ENOTDIR, "Not pinning because file descriptor is not a directory");
578
579 fd_pin = open_at(dfd_path, ".lxc_keep",
580 PROTECT_OPEN | O_CREAT,
581 PROTECT_LOOKUP_BENEATH,
582 S_IWUSR | S_IRUSR);
583 if (fd_pin < 0) {
584 if (errno == EROFS) {
585 return log_trace_errno(0, EROFS, "Not pinning on read-only filesystem");
586 }
587 return syserror("Failed to pin rootfs");
588 }
589
590 TRACE("Pinned rootfs %d(.lxc_keep)", fd_pin);
591
592 ret = fstatfs(fd_pin, &stfs);
593 if (ret < 0) {
594 SYSWARN("Failed to retrieve filesystem status");
595 goto out;
596 }
597
598 if (stfs.f_type == NFS_SUPER_MAGIC) {
599 DEBUG("Not unlinking pinned file on NFS");
600 goto out;
601 }
602
603 if (unlinkat(dfd_path, ".lxc_keep", 0))
604 SYSTRACE("Failed to unlink rootfs pinning file %d(.lxc_keep)", dfd_path);
605 else
606 TRACE("Unlinked pinned file %d(.lxc_keep)", dfd_path);
607
608 out:
609 rootfs->fd_path_pin = move_fd(fd_pin);
610 return 0;
611 }
612
613 int lxc_rootfs_prepare_parent(struct lxc_handler *handler)
614 {
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;
618 const struct lxc_mount_options *mnt_opts = &rootfs->mnt_opts;
619 int ret;
620 const char *path_source;
621
622 if (list_empty(&handler->conf->id_map))
623 return 0;
624
625 if (is_empty_string(rootfs->mnt_opts.userns_path))
626 return 0;
627
628 if (handler->conf->rootfs_setup)
629 return 0;
630
631 if (rootfs_is_blockdev(handler->conf))
632 return syserror_set(-EOPNOTSUPP, "Idmapped mounts on block-backed storage not yet supported");
633
634 if (!can_use_bind_mounts())
635 return syserror_set(-EOPNOTSUPP, "Kernel does not support the new mount api");
636
637 if (strequal(rootfs->mnt_opts.userns_path, "container"))
638 fd_userns = dup_cloexec(handler->nsfd[LXC_NS_USER]);
639 else
640 fd_userns = open_at(-EBADF, rootfs->mnt_opts.userns_path,
641 PROTECT_OPEN_WITH_TRAILING_SYMLINKS, 0, 0);
642 if (fd_userns < 0)
643 return syserror("Failed to open user namespace");
644
645 path_source = lxc_storage_get_path(storage->src, storage->type);
646
647 dfd_idmapped = create_detached_idmapped_mount(path_source, fd_userns, true,
648 mnt_opts->attr.attr_set,
649 mnt_opts->attr.attr_clr);
650 if (dfd_idmapped < 0)
651 return syserror("Failed to create detached idmapped mount");
652
653 ret = lxc_abstract_unix_send_fds(handler->data_sock[0], &dfd_idmapped, 1, NULL, 0);
654 if (ret < 0)
655 return syserror("Failed to send detached idmapped mount fd");
656
657 TRACE("Created detached idmapped mount %d", dfd_idmapped);
658 return 0;
659 }
660
661 static int add_shmount_to_list(struct lxc_conf *conf)
662 {
663 char new_mount[PATH_MAX];
664 /* Offset for the leading '/' since the path_cont
665 * is absolute inside the container.
666 */
667 int offset = 1, ret = -1;
668
669 ret = strnprintf(new_mount, sizeof(new_mount),
670 "%s %s none bind,create=dir 0 0", conf->shmount.path_host,
671 conf->shmount.path_cont + offset);
672 if (ret < 0)
673 return -1;
674
675 return add_elem_to_mount_list(new_mount, conf);
676 }
677
678 static int lxc_mount_auto_mounts(struct lxc_handler *handler, int flags)
679 {
680 int i, ret;
681 static struct {
682 int match_mask;
683 int match_flag;
684 const char *source;
685 const char *destination;
686 const char *fstype;
687 unsigned long flags;
688 const char *options;
689 bool requires_cap_net_admin;
690 } default_mounts[] = {
691 /* Read-only bind-mounting... In older kernels, doing that
692 * required to do one MS_BIND mount and then
693 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
694 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
695 * onwards. However, this apparently does not work on kernel
696 * 3.8. Unfortunately, on that very same kernel, doing the same
697 * trick as above doesn't seem to work either, there one needs
698 * to ALSO specify MS_BIND for the remount, otherwise the
699 * entire fs is remounted read-only or the mount fails because
700 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
701 * kernels as low as 2.6.32...
702 */
703 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL, false },
704 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
705 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys/net", "%r/proc/tty", NULL, MS_BIND, NULL, true, },
706 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys", "%r/proc/sys", NULL, MS_BIND, NULL, false },
707 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL, false },
708 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/tty", "%r/proc/sys/net", NULL, MS_MOVE, NULL, true },
709 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL, MS_BIND, NULL, false },
710 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sysrq-trigger", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL, false },
711 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL, false },
712 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RW, "sysfs", "%r/sys", "sysfs", 0, NULL, false },
713 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RO, "sysfs", "%r/sys", "sysfs", MS_RDONLY, NULL, false },
714 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys", "sysfs", MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL, false },
715 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys/devices/virtual/net", "%r/sys/devices/virtual/net", NULL, MS_BIND, NULL, false },
716 { 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 },
717 { 0, 0, NULL, NULL, NULL, 0, NULL, false }
718 };
719 struct lxc_conf *conf = handler->conf;
720 struct lxc_rootfs *rootfs = &conf->rootfs;
721 bool has_cap_net_admin;
722
723 if (flags & LXC_AUTO_PROC_MASK) {
724 if (rootfs->path) {
725 /*
726 * Only unmount procfs if we have a separate rootfs so
727 * we can still access it in safe_mount() below.
728 */
729 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/proc",
730 rootfs->path ? rootfs->mount : "");
731 if (ret < 0)
732 return ret_errno(EIO);
733
734 ret = umount2(rootfs->buf, MNT_DETACH);
735 if (ret)
736 SYSDEBUG("Tried to ensure procfs is unmounted");
737 }
738
739 ret = mkdirat(rootfs->dfd_mnt, "proc" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
740 if (ret < 0 && errno != EEXIST)
741 return syserror("Failed to create procfs mountpoint under %d", rootfs->dfd_mnt);
742
743 TRACE("Created procfs mountpoint under %d", rootfs->dfd_mnt);
744 }
745
746 if (flags & LXC_AUTO_SYS_MASK) {
747 if (rootfs->path) {
748 /*
749 * Only unmount sysfs if we have a separate rootfs so
750 * we can still access it in safe_mount() below.
751 */
752 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/sys",
753 rootfs->path ? rootfs->mount : "");
754 if (ret < 0)
755 return ret_errno(EIO);
756
757 ret = umount2(rootfs->buf, MNT_DETACH);
758 if (ret)
759 SYSDEBUG("Tried to ensure sysfs is unmounted");
760 }
761
762 ret = mkdirat(rootfs->dfd_mnt, "sys" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
763 if (ret < 0 && errno != EEXIST)
764 return syserror("Failed to create sysfs mountpoint under %d", rootfs->dfd_mnt);
765
766 TRACE("Created sysfs mountpoint under %d", rootfs->dfd_mnt);
767 }
768
769 has_cap_net_admin = lxc_wants_cap(CAP_NET_ADMIN, conf);
770 for (i = 0; default_mounts[i].match_mask; i++) {
771 __do_free char *destination = NULL, *source = NULL;
772 unsigned long mflags = default_mounts[i].flags;
773
774 if ((flags & default_mounts[i].match_mask) != default_mounts[i].match_flag)
775 continue;
776
777 if (default_mounts[i].source) {
778 /* will act like strdup if %r is not present */
779 source = lxc_string_replace("%r", rootfs->path ? rootfs->mount : "", default_mounts[i].source);
780 if (!source)
781 return syserror_set(-ENOMEM, "Failed to create source path");
782 }
783
784 if (!default_mounts[i].destination)
785 return syserror_set(-EINVAL, "BUG: auto mounts destination %d was NULL", i);
786
787 if (!has_cap_net_admin && default_mounts[i].requires_cap_net_admin) {
788 TRACE("Container does not have CAP_NET_ADMIN. Skipping \"%s\" mount", default_mounts[i].source ?: "(null)");
789 continue;
790 }
791
792 /* will act like strdup if %r is not present */
793 destination = lxc_string_replace("%r", rootfs->path ? rootfs->mount : "", default_mounts[i].destination);
794 if (!destination)
795 return syserror_set(-ENOMEM, "Failed to create target path");
796
797 ret = safe_mount(source, destination,
798 default_mounts[i].fstype,
799 mflags,
800 default_mounts[i].options,
801 rootfs->path ? rootfs->mount : NULL);
802 if (ret < 0) {
803 if (errno != ENOENT)
804 return syserror("Failed to mount \"%s\" on \"%s\" with flags %lu", source, destination, mflags);
805
806 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source, destination);
807 continue;
808 }
809
810 if (mflags & MS_REMOUNT)
811 TRACE("Remounted automount \"%s\" on \"%s\" %s with flags %lu", source, destination, (mflags & MS_RDONLY) ? "read-only" : "read-write", mflags);
812 else
813 TRACE("Mounted automount \"%s\" on \"%s\" %s with flags %lu", source, destination, (mflags & MS_RDONLY) ? "read-only" : "read-write", mflags);
814 }
815
816 if (flags & LXC_AUTO_CGROUP_MASK) {
817 int cg_flags;
818
819 cg_flags = flags & (LXC_AUTO_CGROUP_MASK & ~LXC_AUTO_CGROUP_FORCE);
820 /* If the type of cgroup mount was not specified, it depends on
821 * the container's capabilities as to what makes sense: if we
822 * have CAP_SYS_ADMIN, the read-only part can be remounted
823 * read-write anyway, so we may as well default to read-write;
824 * then the admin will not be given a false sense of security.
825 * (And if they really want mixed r/o r/w, then they can
826 * explicitly specify :mixed.) OTOH, if the container lacks
827 * CAP_SYS_ADMIN, do only default to :mixed, because then the
828 * container can't remount it read-write.
829 */
830 if ((cg_flags == LXC_AUTO_CGROUP_NOSPEC) || (cg_flags == LXC_AUTO_CGROUP_FULL_NOSPEC)) {
831 int has_sys_admin = 0;
832
833 if (!lxc_list_empty(&conf->keepcaps))
834 has_sys_admin = in_caplist(CAP_SYS_ADMIN, &conf->keepcaps);
835 else
836 has_sys_admin = !in_caplist(CAP_SYS_ADMIN, &conf->caps);
837
838 if (cg_flags == LXC_AUTO_CGROUP_NOSPEC)
839 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_RW : LXC_AUTO_CGROUP_MIXED;
840 else
841 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_FULL_RW : LXC_AUTO_CGROUP_FULL_MIXED;
842 }
843
844 if (flags & LXC_AUTO_CGROUP_FORCE)
845 cg_flags |= LXC_AUTO_CGROUP_FORCE;
846
847 if (!handler->cgroup_ops->mount(handler->cgroup_ops, handler, cg_flags))
848 return log_error_errno(-1, errno, "Failed to mount \"/sys/fs/cgroup\"");
849 }
850
851 if (flags & LXC_AUTO_SHMOUNTS_MASK) {
852 ret = add_shmount_to_list(conf);
853 if (ret < 0)
854 return log_error(-1, "Failed to add shmount entry to container config");
855 }
856
857 return 0;
858 }
859
860 static int setup_utsname(struct utsname *utsname)
861 {
862 int ret;
863
864 if (!utsname)
865 return 0;
866
867 ret = sethostname(utsname->nodename, strlen(utsname->nodename));
868 if (ret < 0)
869 return log_error_errno(-1, errno, "Failed to set the hostname to \"%s\"",
870 utsname->nodename);
871
872 INFO("Set hostname to \"%s\"", utsname->nodename);
873
874 return 0;
875 }
876
877 struct dev_symlinks {
878 const char *oldpath;
879 const char *name;
880 };
881
882 static const struct dev_symlinks dev_symlinks[] = {
883 { "/proc/self/fd", "fd" },
884 { "/proc/self/fd/0", "stdin" },
885 { "/proc/self/fd/1", "stdout" },
886 { "/proc/self/fd/2", "stderr" },
887 };
888
889 static int lxc_setup_dev_symlinks(const struct lxc_rootfs *rootfs)
890 {
891 for (int i = 0; i < sizeof(dev_symlinks) / sizeof(dev_symlinks[0]); i++) {
892 int ret;
893 struct stat s;
894 const struct dev_symlinks *d = &dev_symlinks[i];
895
896 /*
897 * Stat the path first. If we don't get an error accept it as
898 * is and don't try to create it
899 */
900 ret = fstatat(rootfs->dfd_dev, d->name, &s, 0);
901 if (ret == 0)
902 continue;
903
904 ret = symlinkat(d->oldpath, rootfs->dfd_dev, d->name);
905 if (ret) {
906 switch (errno) {
907 case EROFS:
908 WARN("Failed to create \"%s\" on read-only filesystem", d->name);
909 __fallthrough;
910 case EEXIST:
911 break;
912 default:
913 return log_error_errno(-errno, errno, "Failed to create \"%s\"", d->name);
914 }
915 }
916 }
917
918 return 0;
919 }
920
921 /* Build a space-separate list of ptys to pass to systemd. */
922 static bool append_ttyname(char **pp, char *name)
923 {
924 char *p;
925 size_t size;
926
927 if (!*pp) {
928 *pp = zalloc(strlen(name) + strlen("container_ttys=") + 1);
929 if (!*pp)
930 return false;
931
932 sprintf(*pp, "container_ttys=%s", name);
933 return true;
934 }
935
936 size = strlen(*pp) + strlen(name) + 2;
937 p = realloc(*pp, size);
938 if (!p)
939 return false;
940
941 *pp = p;
942 (void)strlcat(p, " ", size);
943 (void)strlcat(p, name, size);
944
945 return true;
946 }
947
948 static int open_ttymnt_at(int dfd, const char *path)
949 {
950 int fd;
951
952 fd = open_at(dfd, path,
953 PROTECT_OPEN | O_CREAT | O_EXCL,
954 PROTECT_LOOKUP_BENEATH,
955 0);
956 if (fd < 0) {
957 if (!IN_SET(errno, ENXIO, EEXIST))
958 return syserror("Failed to create \"%d/\%s\"", dfd, path);
959
960 SYSINFO("Failed to create \"%d/\%s\"", dfd, path);
961 fd = open_at(dfd, path,
962 PROTECT_OPATH_FILE,
963 PROTECT_LOOKUP_BENEATH,
964 0);
965 }
966
967 return fd;
968 }
969
970 static int lxc_setup_ttys(struct lxc_conf *conf)
971 {
972 int ret;
973 struct lxc_rootfs *rootfs = &conf->rootfs;
974 const struct lxc_tty_info *ttys = &conf->ttys;
975 char *ttydir = ttys->dir;
976
977 if (!conf->rootfs.path)
978 return 0;
979
980 for (int i = 0; i < ttys->max; i++) {
981 __do_close int fd_to = -EBADF;
982 struct lxc_terminal_info *tty = &ttys->tty[i];
983
984 if (ttydir) {
985 char *tty_name, *tty_path;
986
987 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
988 "/dev/%s/tty%d", ttydir, i + 1);
989 if (ret < 0)
990 return ret_errno(-EIO);
991
992 tty_path = &rootfs->buf[STRLITERALLEN("/dev/")];
993 tty_name = tty_path + strlen(ttydir) + 1;
994
995 /* create bind-mount target */
996 fd_to = open_ttymnt_at(rootfs->dfd_dev, tty_path);
997 if (fd_to < 0)
998 return log_error_errno(-errno, errno,
999 "Failed to create tty mount target %d(%s)",
1000 rootfs->dfd_dev, tty_path);
1001
1002 ret = unlinkat(rootfs->dfd_dev, tty_name, 0);
1003 if (ret < 0 && errno != ENOENT)
1004 return log_error_errno(-errno, errno,
1005 "Failed to unlink %d(%s)",
1006 rootfs->dfd_dev, tty_name);
1007
1008 if (can_use_mount_api())
1009 ret = fd_bind_mount(tty->pty, "",
1010 PROTECT_OPATH_FILE,
1011 PROTECT_LOOKUP_BENEATH_XDEV,
1012 fd_to, "",
1013 PROTECT_OPATH_FILE,
1014 PROTECT_LOOKUP_BENEATH_XDEV,
1015 0,
1016 0,
1017 0,
1018 false);
1019 else
1020 ret = mount_fd(tty->pty, fd_to, "none", MS_BIND, 0);
1021 if (ret < 0)
1022 return log_error_errno(-errno, errno,
1023 "Failed to bind mount \"%s\" onto \"%s\"",
1024 tty->name, rootfs->buf);
1025 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name, rootfs->buf);
1026
1027 ret = symlinkat(tty_path, rootfs->dfd_dev, tty_name);
1028 if (ret < 0)
1029 return log_error_errno(-errno, errno,
1030 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
1031 rootfs->dfd_dev, tty_name,
1032 rootfs->dfd_dev, tty_path);
1033 } else {
1034 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "tty%d", i + 1);
1035 if (ret < 0)
1036 return ret_errno(-EIO);
1037
1038 /* If we populated /dev, then we need to create /dev/tty<idx>. */
1039 fd_to = open_ttymnt_at(rootfs->dfd_dev, rootfs->buf);
1040 if (fd_to < 0)
1041 return log_error_errno(-errno, errno,
1042 "Failed to create tty mount target %d(%s)",
1043 rootfs->dfd_dev, rootfs->buf);
1044
1045 if (can_use_mount_api())
1046 ret = fd_bind_mount(tty->pty, "",
1047 PROTECT_OPATH_FILE,
1048 PROTECT_LOOKUP_BENEATH_XDEV,
1049 fd_to, "",
1050 PROTECT_OPATH_FILE,
1051 PROTECT_LOOKUP_BENEATH,
1052 0,
1053 0,
1054 0,
1055 false);
1056 else
1057 ret = mount_fd(tty->pty, fd_to, "none", MS_BIND, 0);
1058 if (ret < 0)
1059 return log_error_errno(-errno, errno,
1060 "Failed to bind mount \"%s\" onto \"%s\"",
1061 tty->name, rootfs->buf);
1062 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name, rootfs->buf);
1063 }
1064
1065 if (!append_ttyname(&conf->ttys.tty_names, tty->name))
1066 return log_error(-1, "Error setting up container_ttys string");
1067 }
1068
1069 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys->max);
1070 return 0;
1071 }
1072
1073 define_cleanup_function(struct lxc_tty_info *, lxc_delete_tty);
1074
1075 static int lxc_allocate_ttys(struct lxc_conf *conf)
1076 {
1077 call_cleaner(lxc_delete_tty) struct lxc_tty_info *ttys = &conf->ttys;
1078 int ret;
1079
1080 /* no tty in the configuration */
1081 if (ttys->max == 0)
1082 return 0;
1083
1084 ttys->tty = zalloc(sizeof(struct lxc_terminal_info) * ttys->max);
1085 if (!ttys->tty)
1086 return -ENOMEM;
1087
1088 for (size_t i = 0; i < conf->ttys.max; i++) {
1089 int pty_nr = -1;
1090 struct lxc_terminal_info *tty = &ttys->tty[i];
1091
1092 ret = lxc_devpts_terminal(conf->devpts_fd, &tty->ptx,
1093 &tty->pty, &pty_nr, false);
1094 if (ret < 0) {
1095 conf->ttys.max = i;
1096 return syserror_set(-ENOTTY, "Failed to create tty %zu", i);
1097 }
1098 DEBUG("Created tty with ptx fd %d and pty fd %d and index %d",
1099 tty->ptx, tty->pty, pty_nr);
1100 tty->busy = -1;
1101 }
1102
1103 INFO("Finished creating %zu tty devices", ttys->max);
1104 move_ptr(ttys);
1105 return 0;
1106 }
1107
1108 void lxc_delete_tty(struct lxc_tty_info *ttys)
1109 {
1110 if (!ttys || !ttys->tty)
1111 return;
1112
1113 for (int i = 0; i < ttys->max; i++) {
1114 struct lxc_terminal_info *tty = &ttys->tty[i];
1115 close_prot_errno_disarm(tty->ptx);
1116 close_prot_errno_disarm(tty->pty);
1117 }
1118
1119 free_disarm(ttys->tty);
1120 }
1121
1122 static int __lxc_send_ttys_to_parent(struct lxc_handler *handler)
1123 {
1124 int i;
1125 int ret = -1;
1126 struct lxc_conf *conf = handler->conf;
1127 struct lxc_tty_info *ttys = &conf->ttys;
1128 int sock = handler->data_sock[0];
1129
1130 if (ttys->max == 0)
1131 return 0;
1132
1133 for (i = 0; i < ttys->max; i++) {
1134 int ttyfds[2];
1135 struct lxc_terminal_info *tty = &ttys->tty[i];
1136
1137 ttyfds[0] = tty->ptx;
1138 ttyfds[1] = tty->pty;
1139
1140 ret = lxc_abstract_unix_send_fds(sock, ttyfds, 2, NULL, 0);
1141 if (ret < 0)
1142 break;
1143
1144 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1145 tty->name, tty->ptx, tty->pty);
1146 }
1147
1148 if (ret < 0)
1149 SYSERROR("Failed to send %zu ttys to parent", ttys->max);
1150 else
1151 TRACE("Sent %zu ttys to parent", ttys->max);
1152
1153 return ret;
1154 }
1155
1156 static int lxc_create_ttys(struct lxc_handler *handler)
1157 {
1158 int ret = -1;
1159 struct lxc_conf *conf = handler->conf;
1160
1161 ret = lxc_allocate_ttys(conf);
1162 if (ret < 0) {
1163 ERROR("Failed to allocate ttys");
1164 goto on_error;
1165 }
1166
1167 if (!conf->is_execute) {
1168 ret = lxc_setup_ttys(conf);
1169 if (ret < 0) {
1170 ERROR("Failed to setup ttys");
1171 goto on_error;
1172 }
1173 }
1174
1175 if (conf->ttys.tty_names) {
1176 ret = setenv("container_ttys", conf->ttys.tty_names, 1);
1177 if (ret < 0) {
1178 SYSERROR("Failed to set \"container_ttys=%s\"", conf->ttys.tty_names);
1179 goto on_error;
1180 }
1181 }
1182
1183 return 0;
1184
1185 on_error:
1186 lxc_delete_tty(&conf->ttys);
1187
1188 return -1;
1189 }
1190
1191 static int lxc_send_ttys_to_parent(struct lxc_handler *handler)
1192 {
1193 int ret = -1;
1194
1195 ret = __lxc_send_ttys_to_parent(handler);
1196 lxc_delete_tty(&handler->conf->ttys);
1197 return ret;
1198 }
1199
1200 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1201 * error, log it but don't fail yet.
1202 */
1203 static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs,
1204 int autodevtmpfssize, const char *lxcpath)
1205 {
1206 __do_close int fd_fs = -EBADF;
1207 const char *path = rootfs->path ? rootfs->mount : NULL;
1208 size_t tmpfs_size = (autodevtmpfssize != 0) ? autodevtmpfssize : 500000;
1209 int ret;
1210 mode_t cur_mask;
1211 char mount_options[128];
1212
1213 INFO("Preparing \"/dev\"");
1214
1215 cur_mask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
1216 ret = mkdirat(rootfs->dfd_mnt, "dev" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
1217 if (ret < 0 && errno != EEXIST) {
1218 SYSERROR("Failed to create \"/dev\" directory");
1219 ret = -errno;
1220 goto reset_umask;
1221 }
1222
1223 if (can_use_mount_api()) {
1224 fd_fs = fs_prepare("tmpfs", -EBADF, "", 0, 0);
1225 if (fd_fs < 0)
1226 return log_error_errno(-errno, errno, "Failed to prepare filesystem context for tmpfs");
1227
1228 sprintf(mount_options, "%zu", tmpfs_size);
1229
1230 ret = fs_set_property(fd_fs, "mode", "0755");
1231 if (ret < 0)
1232 return log_error_errno(-errno, errno, "Failed to mount tmpfs onto %d(dev)", fd_fs);
1233
1234 ret = fs_set_property(fd_fs, "size", mount_options);
1235 if (ret < 0)
1236 return log_error_errno(-errno, errno, "Failed to mount tmpfs onto %d(dev)", fd_fs);
1237
1238 ret = fs_attach(fd_fs, rootfs->dfd_mnt, "dev",
1239 PROTECT_OPATH_DIRECTORY,
1240 PROTECT_LOOKUP_BENEATH_XDEV, 0);
1241 } else {
1242 __do_free char *fallback_path = NULL;
1243
1244 sprintf(mount_options, "size=%zu,mode=755", tmpfs_size);
1245 DEBUG("Using mount options: %s", mount_options);
1246
1247 if (path) {
1248 fallback_path = must_make_path(path, "/dev", NULL);
1249 ret = safe_mount("none", fallback_path, "tmpfs", 0, mount_options, path);
1250 } else {
1251 ret = safe_mount("none", "dev", "tmpfs", 0, mount_options, NULL);
1252 }
1253 }
1254 if (ret < 0) {
1255 SYSERROR("Failed to mount tmpfs on \"%s\"", path);
1256 goto reset_umask;
1257 }
1258
1259 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1260 * If not, then create it and exit if that fails...
1261 */
1262 ret = mkdirat(rootfs->dfd_mnt, "dev/pts", S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
1263 if (ret < 0 && errno != EEXIST) {
1264 SYSERROR("Failed to create directory \"dev/pts\"");
1265 ret = -errno;
1266 goto reset_umask;
1267 }
1268
1269 ret = 0;
1270
1271 reset_umask:
1272 (void)umask(cur_mask);
1273
1274 INFO("Prepared \"/dev\"");
1275 return ret;
1276 }
1277
1278 struct lxc_device_node {
1279 const char *name;
1280 const mode_t mode;
1281 const int maj;
1282 const int min;
1283 };
1284
1285 static const struct lxc_device_node lxc_devices[] = {
1286 { "full", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 7 },
1287 { "null", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 3 },
1288 { "random", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 8 },
1289 { "tty", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 5, 0 },
1290 { "urandom", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 9 },
1291 { "zero", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 5 },
1292 };
1293
1294
1295 enum {
1296 LXC_DEVNODE_BIND,
1297 LXC_DEVNODE_MKNOD,
1298 LXC_DEVNODE_PARTIAL,
1299 LXC_DEVNODE_OPEN,
1300 };
1301
1302 static int lxc_fill_autodev(struct lxc_rootfs *rootfs)
1303 {
1304 int i, ret;
1305 mode_t cmask;
1306 int use_mknod = LXC_DEVNODE_MKNOD;
1307
1308 if (rootfs->dfd_dev < 0)
1309 return log_info(0, "No /dev directory found, skipping setup");
1310
1311 INFO("Populating \"/dev\"");
1312
1313 cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
1314 for (i = 0; i < sizeof(lxc_devices) / sizeof(lxc_devices[0]); i++) {
1315 const struct lxc_device_node *device = &lxc_devices[i];
1316
1317 if (use_mknod >= LXC_DEVNODE_MKNOD) {
1318 ret = mknodat(rootfs->dfd_dev, device->name, device->mode, makedev(device->maj, device->min));
1319 if (ret == 0 || (ret < 0 && errno == EEXIST)) {
1320 DEBUG("Created device node \"%s\"", device->name);
1321 } else if (ret < 0) {
1322 if (errno != EPERM)
1323 return log_error_errno(-1, errno, "Failed to create device node \"%s\"", device->name);
1324
1325 use_mknod = LXC_DEVNODE_BIND;
1326 }
1327
1328 /* Device nodes are fully useable. */
1329 if (use_mknod == LXC_DEVNODE_OPEN)
1330 continue;
1331
1332 if (use_mknod == LXC_DEVNODE_MKNOD) {
1333 __do_close int fd = -EBADF;
1334 /* See
1335 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1336 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1337 */
1338 fd = open_at(rootfs->dfd_dev, device->name, PROTECT_OPEN, PROTECT_LOOKUP_BENEATH, 0);
1339 if (fd >= 0) {
1340 /* Device nodes are fully useable. */
1341 use_mknod = LXC_DEVNODE_OPEN;
1342 continue;
1343 }
1344
1345 SYSTRACE("Failed to open \"%s\" device", device->name);
1346 /* Device nodes are only partially useable. */
1347 use_mknod = LXC_DEVNODE_PARTIAL;
1348 }
1349 }
1350
1351 if (use_mknod != LXC_DEVNODE_PARTIAL) {
1352 /* If we are dealing with partially functional device
1353 * nodes the prio mknod() call will have created the
1354 * device node so we can use it as a bind-mount target.
1355 */
1356 ret = mknodat(rootfs->dfd_dev, device->name, S_IFREG | 0000, 0);
1357 if (ret < 0 && errno != EEXIST)
1358 return log_error_errno(-1, errno, "Failed to create file \"%s\"", device->name);
1359 }
1360
1361 /* Fallback to bind-mounting the device from the host. */
1362 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "dev/%s", device->name);
1363 if (ret < 0)
1364 return ret_errno(EIO);
1365
1366 if (can_use_mount_api()) {
1367 ret = fd_bind_mount(rootfs->dfd_host, rootfs->buf,
1368 PROTECT_OPATH_FILE,
1369 PROTECT_LOOKUP_BENEATH_XDEV,
1370 rootfs->dfd_dev, device->name,
1371 PROTECT_OPATH_FILE,
1372 PROTECT_LOOKUP_BENEATH,
1373 0,
1374 0,
1375 0,
1376 false);
1377 } else {
1378 char path[PATH_MAX];
1379
1380 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/dev/%s", device->name);
1381 if (ret < 0)
1382 return ret_errno(EIO);
1383
1384 ret = strnprintf(path, sizeof(path), "%s/dev/%s", get_rootfs_mnt(rootfs), device->name);
1385 if (ret < 0)
1386 return log_error(-1, "Failed to create device path for %s", device->name);
1387
1388 ret = safe_mount(rootfs->buf, path, 0, MS_BIND, NULL, get_rootfs_mnt(rootfs));
1389 if (ret < 0)
1390 return log_error_errno(-1, errno, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs->buf, path);
1391
1392 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs->buf, path);
1393 continue;
1394 }
1395 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs->dfd_host, rootfs->buf, rootfs->dfd_dev, device->name);
1396 }
1397 (void)umask(cmask);
1398
1399 INFO("Populated \"/dev\"");
1400 return 0;
1401 }
1402
1403 static int lxc_mount_rootfs(struct lxc_rootfs *rootfs)
1404 {
1405 int ret;
1406
1407 if (!rootfs->path) {
1408 ret = mount("", "/", NULL, MS_SLAVE | MS_REC, 0);
1409 if (ret < 0)
1410 return log_error_errno(-1, errno, "Failed to recursively turn root mount tree into dependent mount");
1411
1412 rootfs->dfd_mnt = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
1413 if (rootfs->dfd_mnt < 0)
1414 return -errno;
1415
1416 return log_trace(0, "Container doesn't use separate rootfs. Opened host's rootfs");
1417 }
1418
1419 ret = access(rootfs->mount, F_OK);
1420 if (ret != 0)
1421 return log_error_errno(-1, errno, "Failed to access to \"%s\". Check it is present",
1422 rootfs->mount);
1423
1424 ret = rootfs->storage->ops->mount(rootfs->storage);
1425 if (ret < 0)
1426 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1427 rootfs->path, rootfs->mount,
1428 rootfs->mnt_opts.raw_options ? rootfs->mnt_opts.raw_options : "(null)");
1429
1430 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1431 rootfs->path, rootfs->mount,
1432 rootfs->mnt_opts.raw_options ? rootfs->mnt_opts.raw_options : "(null)");
1433
1434 rootfs->dfd_mnt = open_at(-EBADF, rootfs->mount, PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
1435 if (rootfs->dfd_mnt < 0)
1436 return -errno;
1437
1438 return log_trace(0, "Container uses separate rootfs. Opened container's rootfs");
1439 }
1440
1441 static int lxc_chroot(const struct lxc_rootfs *rootfs)
1442 {
1443 __do_free char *nroot = NULL;
1444 int i, ret;
1445 char *root = rootfs->mount;
1446
1447 nroot = realpath(root, NULL);
1448 if (!nroot)
1449 return log_error_errno(-1, errno, "Failed to resolve \"%s\"", root);
1450
1451 ret = chdir("/");
1452 if (ret < 0)
1453 return -1;
1454
1455 /* We could use here MS_MOVE, but in userns this mount is locked and
1456 * can't be moved.
1457 */
1458 ret = mount(nroot, "/", NULL, MS_REC | MS_BIND, NULL);
1459 if (ret < 0)
1460 return log_error_errno(-1, errno, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot);
1461
1462 ret = mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);
1463 if (ret < 0)
1464 return log_error_errno(-1, errno, "Failed to remount \"/\"");
1465
1466 /* The following code cleans up inherited mounts which are not required
1467 * for CT.
1468 *
1469 * The mountinfo file shows not all mounts, if a few points have been
1470 * unmounted between read operations from the mountinfo. So we need to
1471 * read mountinfo a few times.
1472 *
1473 * This loop can be skipped if a container uses userns, because all
1474 * inherited mounts are locked and we should live with all this trash.
1475 */
1476 for (;;) {
1477 __do_fclose FILE *f = NULL;
1478 __do_free char *line = NULL;
1479 char *slider1, *slider2;
1480 int progress = 0;
1481 size_t len = 0;
1482
1483 f = fopen("./proc/self/mountinfo", "re");
1484 if (!f)
1485 return log_error_errno(-1, errno, "Failed to open \"/proc/self/mountinfo\"");
1486
1487 while (getline(&line, &len, f) > 0) {
1488 for (slider1 = line, i = 0; slider1 && i < 4; i++)
1489 slider1 = strchr(slider1 + 1, ' ');
1490
1491 if (!slider1)
1492 continue;
1493
1494 slider2 = strchr(slider1 + 1, ' ');
1495 if (!slider2)
1496 continue;
1497
1498 *slider2 = '\0';
1499 *slider1 = '.';
1500
1501 if (strequal(slider1 + 1, "/"))
1502 continue;
1503
1504 if (strequal(slider1 + 1, "/proc"))
1505 continue;
1506
1507 ret = umount2(slider1, MNT_DETACH);
1508 if (ret == 0)
1509 progress++;
1510 }
1511
1512 if (!progress)
1513 break;
1514 }
1515
1516 /* This also can be skipped if a container uses userns. */
1517 (void)umount2("./proc", MNT_DETACH);
1518
1519 /* It is weird, but chdir("..") moves us in a new root */
1520 ret = chdir("..");
1521 if (ret < 0)
1522 return log_error_errno(-1, errno, "Failed to chdir(\"..\")");
1523
1524 ret = chroot(".");
1525 if (ret < 0)
1526 return log_error_errno(-1, errno, "Failed to chroot(\".\")");
1527
1528 return 0;
1529 }
1530
1531 /* (The following explanation is copied verbatim from the kernel.)
1532 *
1533 * pivot_root Semantics:
1534 * Moves the root file system of the current process to the directory put_old,
1535 * makes new_root as the new root file system of the current process, and sets
1536 * root/cwd of all processes which had them on the current root to new_root.
1537 *
1538 * Restrictions:
1539 * The new_root and put_old must be directories, and must not be on the
1540 * same file system as the current process root. The put_old must be
1541 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1542 * pointed to by put_old must yield the same directory as new_root. No other
1543 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1544 *
1545 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1546 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1547 * in this situation.
1548 *
1549 * Notes:
1550 * - we don't move root/cwd if they are not at the root (reason: if something
1551 * cared enough to change them, it's probably wrong to force them elsewhere)
1552 * - it's okay to pick a root that isn't the root of a file system, e.g.
1553 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1554 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1555 * first.
1556 */
1557 static int lxc_pivot_root(const struct lxc_rootfs *rootfs)
1558 {
1559 __do_close int fd_oldroot = -EBADF;
1560 int ret;
1561
1562 fd_oldroot = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
1563 if (fd_oldroot < 0)
1564 return log_error_errno(-1, errno, "Failed to open old root directory");
1565
1566 /* change into new root fs */
1567 ret = fchdir(rootfs->dfd_mnt);
1568 if (ret < 0)
1569 return log_error_errno(-errno, errno, "Failed to change into new root directory \"%s\"", rootfs->mount);
1570
1571 /* pivot_root into our new root fs */
1572 ret = pivot_root(".", ".");
1573 if (ret < 0)
1574 return log_error_errno(-errno, errno, "Failed to pivot into new root directory \"%s\"", rootfs->mount);
1575
1576 /* At this point the old-root is mounted on top of our new-root. To
1577 * unmounted it we must not be chdir'd into it, so escape back to
1578 * old-root.
1579 */
1580 ret = fchdir(fd_oldroot);
1581 if (ret < 0)
1582 return log_error_errno(-errno, errno, "Failed to enter old root directory");
1583
1584 /*
1585 * Make fd_oldroot a depedent mount to make sure our umounts don't
1586 * propagate to the host.
1587 */
1588 ret = mount("", ".", "", MS_SLAVE | MS_REC, NULL);
1589 if (ret < 0)
1590 return log_error_errno(-errno, errno, "Failed to recursively turn old root mount tree into dependent mount");
1591
1592 ret = umount2(".", MNT_DETACH);
1593 if (ret < 0)
1594 return log_error_errno(-errno, errno, "Failed to detach old root directory");
1595
1596 ret = fchdir(rootfs->dfd_mnt);
1597 if (ret < 0)
1598 return log_error_errno(-errno, errno, "Failed to re-enter new root directory \"%s\"", rootfs->mount);
1599
1600 TRACE("Changed into new rootfs \"%s\"", rootfs->mount);
1601 return 0;
1602 }
1603
1604 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs *rootfs)
1605 {
1606 if (!rootfs->path)
1607 return log_debug(0, "Container does not have a rootfs");
1608
1609 if (detect_ramfs_rootfs())
1610 return lxc_chroot(rootfs);
1611
1612 return lxc_pivot_root(rootfs);
1613 }
1614
1615 static const struct id_map *find_mapped_nsid_entry(const struct lxc_conf *conf,
1616 unsigned id,
1617 enum idtype idtype)
1618 {
1619 struct id_map *map;
1620 struct id_map *retmap = NULL;
1621
1622 /* Shortcut for container's root mappings. */
1623 if (id == 0) {
1624 if (idtype == ID_TYPE_UID)
1625 return conf->root_nsuid_map;
1626
1627 if (idtype == ID_TYPE_GID)
1628 return conf->root_nsgid_map;
1629 }
1630
1631 list_for_each_entry(map, &conf->id_map, head) {
1632 if (map->idtype != idtype)
1633 continue;
1634
1635 if (id >= map->nsid && id < map->nsid + map->range) {
1636 retmap = map;
1637 break;
1638 }
1639 }
1640
1641 return retmap;
1642 }
1643
1644 static int lxc_recv_devpts_from_child(struct lxc_handler *handler)
1645 {
1646 int ret;
1647
1648 if (handler->conf->pty_max <= 0)
1649 return 0;
1650
1651 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1],
1652 &handler->conf->devpts_fd,
1653 &handler->conf->devpts_fd,
1654 sizeof(handler->conf->devpts_fd));
1655 if (ret < 0)
1656 return log_error_errno(-1, errno, "Failed to receive devpts fd from child");
1657
1658 TRACE("Received devpts file descriptor %d from child", handler->conf->devpts_fd);
1659 return 0;
1660 }
1661
1662 static int lxc_setup_devpts_child(struct lxc_handler *handler)
1663 {
1664 __do_close int devpts_fd = -EBADF, fd_fs = -EBADF;
1665 struct lxc_conf *conf = handler->conf;
1666 struct lxc_rootfs *rootfs = &conf->rootfs;
1667 size_t pty_max = conf->pty_max;
1668 int ret;
1669
1670 pty_max += conf->ttys.max;
1671 if (pty_max <= 0)
1672 return log_debug(0, "No new devpts instance will be mounted since no pts devices are required");
1673
1674 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
1675 "/proc/self/fd/%d/pts", rootfs->dfd_dev);
1676 if (ret < 0)
1677 return syserror("Failed to create path");
1678
1679 (void)umount2(rootfs->buf, MNT_DETACH);
1680
1681 /* Create mountpoint for devpts instance. */
1682 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1683 if (ret < 0 && errno != EEXIST)
1684 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
1685
1686 if (can_use_mount_api()) {
1687 fd_fs = fs_prepare("devpts", -EBADF, "", 0, 0);
1688 if (fd_fs < 0)
1689 return syserror("Failed to prepare filesystem context for devpts");
1690
1691 ret = fs_set_property(fd_fs, "source", "devpts");
1692 if (ret < 0)
1693 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs);
1694
1695 ret = fs_set_property(fd_fs, "gid", "5");
1696 if (ret < 0)
1697 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs);
1698
1699 ret = fs_set_flag(fd_fs, "newinstance");
1700 if (ret < 0)
1701 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs);
1702
1703 ret = fs_set_property(fd_fs, "ptmxmode", "0666");
1704 if (ret < 0)
1705 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs);
1706
1707 ret = fs_set_property(fd_fs, "mode", "0620");
1708 if (ret < 0)
1709 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs);
1710
1711 ret = fs_set_property(fd_fs, "max", fdstr(pty_max));
1712 if (ret < 0)
1713 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf->pty_max, fd_fs);
1714
1715 ret = fsconfig(fd_fs, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
1716 if (ret < 0)
1717 return syserror("Failed to finalize filesystem context %d", fd_fs);
1718
1719 devpts_fd = fsmount(fd_fs, FSMOUNT_CLOEXEC, MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC);
1720 if (devpts_fd < 0)
1721 return syserror("Failed to create new mount for filesystem context %d", fd_fs);
1722 TRACE("Created detached devpts mount %d", devpts_fd);
1723
1724 ret = move_mount(devpts_fd, "", rootfs->dfd_dev, "pts", MOVE_MOUNT_F_EMPTY_PATH);
1725 if (ret)
1726 return syserror("Failed to attach devpts mount %d to %d/pts", conf->devpts_fd, rootfs->dfd_dev);
1727
1728 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd, rootfs->dfd_dev);
1729 } else {
1730 char **opts;
1731 char devpts_mntopts[256];
1732 char *mntopt_sets[5];
1733 char default_devpts_mntopts[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1734
1735 /*
1736 * Fallback codepath in case the new mount API can't be used to
1737 * create detached mounts.
1738 */
1739
1740 ret = strnprintf(devpts_mntopts, sizeof(devpts_mntopts), "%s,max=%zu",
1741 default_devpts_mntopts, pty_max);
1742 if (ret < 0)
1743 return -1;
1744
1745 /* Create mountpoint for devpts instance. */
1746 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1747 if (ret < 0 && errno != EEXIST)
1748 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
1749
1750 /* gid=5 && max= */
1751 mntopt_sets[0] = devpts_mntopts;
1752
1753 /* !gid=5 && max= */
1754 mntopt_sets[1] = devpts_mntopts + STRLITERALLEN("gid=5") + 1;
1755
1756 /* gid=5 && !max= */
1757 mntopt_sets[2] = default_devpts_mntopts;
1758
1759 /* !gid=5 && !max= */
1760 mntopt_sets[3] = default_devpts_mntopts + STRLITERALLEN("gid=5") + 1;
1761
1762 /* end */
1763 mntopt_sets[4] = NULL;
1764
1765 for (ret = -1, opts = mntopt_sets; opts && *opts; opts++) {
1766 /* mount new devpts instance */
1767 ret = mount_at(rootfs->dfd_dev, "", 0,
1768 rootfs->dfd_dev, "pts", PROTECT_LOOKUP_BENEATH,
1769 "devpts", MS_NOSUID | MS_NOEXEC, *opts);
1770 if (ret == 0)
1771 break;
1772 }
1773 if (ret < 0)
1774 return log_error_errno(-1, errno, "Failed to mount new devpts instance");
1775
1776 devpts_fd = open_at(rootfs->dfd_dev, "pts", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
1777 if (devpts_fd < 0) {
1778 devpts_fd = -EBADF;
1779 TRACE("Failed to create detached devpts mount");
1780 }
1781
1782 DEBUG("Mounted new devpts instance with options \"%s\"", *opts);
1783 }
1784
1785 handler->conf->devpts_fd = move_fd(devpts_fd);
1786
1787 /*
1788 * In order to allocate terminal devices the devpts filesystem will
1789 * have to be attached to the filesystem at least ones in the new mount
1790 * api. The reason is lengthy but the gist is that until the new mount
1791 * has been attached to the filesystem it is a detached mount with an
1792 * anonymous mount mamespace attached to it for which the kernel
1793 * refuses certain operations.
1794 * We end up here if the user has requested to allocate tty devices
1795 * while not requestig pty devices be made available to the container.
1796 * We only need the devpts_fd to allocate tty devices.
1797 */
1798 if (conf->pty_max <= 0)
1799 return 0;
1800
1801 /* Remove any pre-existing /dev/ptmx file. */
1802 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
1803 if (ret < 0) {
1804 if (errno != ENOENT)
1805 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\" file");
1806 } else {
1807 DEBUG("Removed existing \"/dev/ptmx\" file");
1808 }
1809
1810 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1811 ret = mknodat(rootfs->dfd_dev, "ptmx", S_IFREG | 0000, 0);
1812 if (ret < 0 && errno != EEXIST)
1813 return log_error_errno(-1, errno, "Failed to create \"/dev/ptmx\" file as bind mount target");
1814 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
1815
1816 /* Main option: use a bind-mount to please AppArmor */
1817 ret = mount_at(rootfs->dfd_dev, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1818 rootfs->dfd_dev, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1819 NULL, MS_BIND, NULL);
1820 if (!ret)
1821 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1822 else
1823 /* Fallthrough and try to create a symlink. */
1824 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1825
1826 /* Remove the placeholder /dev/ptmx file we created above. */
1827 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
1828 if (ret < 0)
1829 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\"");
1830
1831 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1832 ret = symlinkat("/dev/pts/ptmx", rootfs->dfd_dev, "dev/ptmx");
1833 if (ret < 0)
1834 return log_error_errno(-1, errno, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1835
1836 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1837 return 0;
1838 }
1839
1840 static int lxc_finish_devpts_child(struct lxc_handler *handler)
1841 {
1842 struct lxc_conf *conf = handler->conf;
1843 struct lxc_rootfs *rootfs = &conf->rootfs;
1844 int ret;
1845
1846 if (conf->pty_max > 0)
1847 return 0;
1848
1849 /*
1850 * We end up here if the user has requested to allocate tty devices
1851 * while not requestig pty devices be made available to the container.
1852 * This means we can unmount the devpts instance. We only need the
1853 * devpts_fd to allocate tty devices.
1854 */
1855 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
1856 "/proc/self/fd/%d/pts", rootfs->dfd_dev);
1857 if (ret < 0)
1858 return syserror("Failed to create path");
1859
1860 close_prot_errno_disarm(conf->devpts_fd);
1861 return umount2(rootfs->buf, MNT_DETACH);
1862 }
1863
1864 static int lxc_send_devpts_to_parent(struct lxc_handler *handler)
1865 {
1866 int ret;
1867
1868 if (handler->conf->pty_max <= 0)
1869 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1870
1871 ret = lxc_abstract_unix_send_fds(handler->data_sock[0], &handler->conf->devpts_fd, 1, NULL, 0);
1872 if (ret < 0)
1873 SYSERROR("Failed to send devpts file descriptor %d to parent", handler->conf->devpts_fd);
1874 else
1875 TRACE("Sent devpts file descriptor %d to parent", handler->conf->devpts_fd);
1876
1877 close_prot_errno_disarm(handler->conf->devpts_fd);
1878
1879 return 0;
1880 }
1881
1882 static int setup_personality(personality_t persona)
1883 {
1884 int ret;
1885
1886 if (persona == LXC_ARCH_UNCHANGED)
1887 return log_debug(0, "Retaining original personality");
1888
1889 ret = lxc_personality(persona);
1890 if (ret < 0)
1891 return syserror("Failed to set personality to \"0lx%lx\"", persona);
1892
1893 INFO("Set personality to \"0lx%lx\"", persona);
1894 return 0;
1895 }
1896
1897 static int bind_mount_console(int fd_devpts, struct lxc_rootfs *rootfs,
1898 struct lxc_terminal *console, int fd_to)
1899 {
1900 __do_close int fd_pty = -EBADF;
1901
1902 if (is_empty_string(console->name))
1903 return ret_errno(EINVAL);
1904
1905 /*
1906 * When the pty fd stashed in console->pty has been retrieved via the
1907 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1908 * allocating new pty devices we can't reopen it through openat2() or
1909 * created a detached mount through open_tree() from it. This means we
1910 * would need to mount using the path stased in console->name which is
1911 * unsafe. We could be mounting a device that isn't identical to the
1912 * one we've already safely opened and stashed in console->pty.
1913 * So, what we do is we open an O_PATH file descriptor for
1914 * console->name and verify that the opened fd and the fd we stashed in
1915 * console->pty refer to the same device. If they do we can go on and
1916 * created a detached mount based on the newly opened O_PATH file
1917 * descriptor and then safely mount.
1918 */
1919 fd_pty = open_at_same(console->pty, fd_devpts, fdstr(console->pty_nr),
1920 PROTECT_OPATH_FILE, PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
1921 if (fd_pty < 0)
1922 return syserror("Failed to open \"%s\"", console->name);
1923
1924 /*
1925 * Note, there are intentionally no open or lookup restrictions since
1926 * we're operating directly on the fd.
1927 */
1928 if (can_use_mount_api())
1929 return fd_bind_mount(fd_pty, "", 0, 0, fd_to, "", 0, 0, 0, 0, 0, false);
1930
1931 return mount_fd(fd_pty, fd_to, "none", MS_BIND, 0);
1932 }
1933
1934 static int lxc_setup_dev_console(int fd_devpts, struct lxc_rootfs *rootfs,
1935 struct lxc_terminal *console)
1936 {
1937 __do_close int fd_console = -EBADF;
1938 int ret;
1939
1940 /*
1941 * When we are asked to setup a console we remove any previous
1942 * /dev/console bind-mounts.
1943 */
1944 if (exists_file_at(rootfs->dfd_dev, "console")) {
1945 char *rootfs_path = rootfs->path ? rootfs->mount : "";
1946
1947 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
1948 if (ret < 0)
1949 return -1;
1950
1951 ret = lxc_unstack_mountpoint(rootfs->buf, false);
1952 if (ret < 0)
1953 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
1954 else
1955 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
1956 }
1957
1958 /*
1959 * For unprivileged containers autodev or automounts will already have
1960 * taken care of creating /dev/console.
1961 */
1962 fd_console = open_at(rootfs->dfd_dev,
1963 "console",
1964 PROTECT_OPEN | O_CREAT,
1965 PROTECT_LOOKUP_BENEATH,
1966 0000);
1967 if (fd_console < 0)
1968 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
1969
1970 ret = fchmod(console->pty, 0620);
1971 if (ret < 0)
1972 return syserror("Failed to change console mode");
1973
1974 ret = bind_mount_console(fd_devpts, rootfs, console, fd_console);
1975 if (ret < 0)
1976 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1977 console->pty, console->name, fd_console);
1978
1979 TRACE("Setup console \"%s\"", console->name);
1980 return 0;
1981 }
1982
1983 static int lxc_setup_ttydir_console(int fd_devpts, struct lxc_rootfs *rootfs,
1984 struct lxc_terminal *console,
1985 char *ttydir)
1986 {
1987 __do_close int fd_ttydir = -EBADF, fd_dev_console = -EBADF,
1988 fd_reg_console = -EBADF, fd_reg_ttydir_console = -EBADF;
1989 int ret;
1990
1991 /* create dev/<ttydir> */
1992 ret = mkdirat(rootfs->dfd_dev, ttydir, 0755);
1993 if (ret < 0 && errno != EEXIST)
1994 return syserror("Failed to create \"%d/%s\"", rootfs->dfd_dev, ttydir);
1995
1996 fd_ttydir = open_at(rootfs->dfd_dev,
1997 ttydir,
1998 PROTECT_OPATH_DIRECTORY,
1999 PROTECT_LOOKUP_BENEATH,
2000 0);
2001 if (fd_ttydir < 0)
2002 return syserror("Failed to open \"%d/%s\"", rootfs->dfd_dev, ttydir);
2003
2004 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/console", ttydir);
2005 if (ret < 0)
2006 return -1;
2007
2008 /* create dev/<ttydir>/console */
2009 fd_reg_ttydir_console = open_at(fd_ttydir,
2010 "console",
2011 PROTECT_OPEN | O_CREAT,
2012 PROTECT_LOOKUP_BENEATH,
2013 0000);
2014 if (fd_reg_ttydir_console < 0)
2015 return syserror("Failed to create \"%d/console\"", fd_ttydir);
2016
2017 if (file_exists(rootfs->buf)) {
2018 char *rootfs_path = rootfs->path ? rootfs->mount : "";
2019
2020 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
2021 if (ret < 0)
2022 return -1;
2023
2024 ret = lxc_unstack_mountpoint(rootfs->buf, false);
2025 if (ret < 0)
2026 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
2027 else
2028 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
2029 }
2030
2031 /* create dev/console */
2032 fd_reg_console = open_at(rootfs->dfd_dev,
2033 "console",
2034 PROTECT_OPEN | O_CREAT,
2035 PROTECT_LOOKUP_BENEATH,
2036 0000);
2037 if (fd_reg_console < 0)
2038 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
2039
2040 ret = fchmod(console->pty, 0620);
2041 if (ret < 0)
2042 return syserror("Failed to change console mode");
2043
2044 /* bind mount console to '/dev/<ttydir>/console' */
2045 ret = bind_mount_console(fd_devpts, rootfs, console, fd_reg_ttydir_console);
2046 if (ret < 0)
2047 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2048 console->pty, console->name, fd_reg_ttydir_console);
2049
2050 fd_dev_console = open_at_same(console->pty,
2051 fd_ttydir,
2052 "console",
2053 PROTECT_OPATH_FILE,
2054 PROTECT_LOOKUP_BENEATH_XDEV,
2055 0);
2056 if (fd_dev_console < 0)
2057 return syserror("Failed to open \"%d/console\"", fd_ttydir);
2058
2059 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
2060 if (can_use_mount_api())
2061 ret = fd_bind_mount(fd_dev_console,
2062 "",
2063 PROTECT_OPATH_FILE,
2064 PROTECT_LOOKUP_BENEATH_XDEV,
2065 fd_reg_console,
2066 "",
2067 PROTECT_OPATH_FILE,
2068 PROTECT_LOOKUP_BENEATH,
2069 0,
2070 0,
2071 0,
2072 false);
2073 else
2074 ret = mount_fd(fd_dev_console, fd_reg_console, "none", MS_BIND, 0);
2075 if (ret < 0)
2076 return syserror("Failed to mount \"%d\" on \"%d\"",
2077 fd_dev_console, fd_reg_console);
2078
2079 TRACE("Setup console \"%s\"", console->name);
2080 return 0;
2081 }
2082
2083 static int lxc_setup_console(const struct lxc_handler *handler,
2084 struct lxc_rootfs *rootfs,
2085 struct lxc_terminal *console, char *ttydir)
2086 {
2087 __do_close int fd_devpts_host = -EBADF;
2088 int fd_devpts = handler->conf->devpts_fd;
2089 int ret = -1;
2090
2091 if (!wants_console(console))
2092 return log_trace(0, "Skipping console setup");
2093
2094 if (console->pty < 0) {
2095 /*
2096 * Allocate a console from the container's devpts instance. We
2097 * have checked on the host that we have enough pty devices
2098 * available.
2099 */
2100 ret = lxc_devpts_terminal(handler->conf->devpts_fd, &console->ptx,
2101 &console->pty, &console->pty_nr, false);
2102 if (ret < 0)
2103 return syserror("Failed to allocate console from container's devpts instance");
2104
2105 ret = strnprintf(console->name, sizeof(console->name),
2106 "/dev/pts/%d", console->pty_nr);
2107 if (ret < 0)
2108 return syserror("Failed to create console path");
2109 } else {
2110 /*
2111 * We're using a console from the host's devpts instance. Open
2112 * it again so we can later verify that the console we're
2113 * supposed to use is still the same as the one we opened on
2114 * the host.
2115 */
2116 fd_devpts_host = open_at(rootfs->dfd_host,
2117 "dev/pts",
2118 PROTECT_OPATH_DIRECTORY,
2119 PROTECT_LOOKUP_BENEATH_XDEV,
2120 0);
2121 if (fd_devpts_host < 0)
2122 return syserror("Failed to open host devpts");
2123
2124 fd_devpts = fd_devpts_host;
2125 }
2126
2127 if (ttydir)
2128 ret = lxc_setup_ttydir_console(fd_devpts, rootfs, console, ttydir);
2129 else
2130 ret = lxc_setup_dev_console(fd_devpts, rootfs, console);
2131 if (ret < 0)
2132 return syserror("Failed to setup console");
2133
2134 /*
2135 * Some init's such as busybox will set sane tty settings on stdin,
2136 * stdout, stderr which it thinks is the console. We already set them
2137 * the way we wanted on the real terminal, and we want init to do its
2138 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2139 * make sure that that pty is stdin,stdout,stderr.
2140 */
2141 if (console->pty >= 0) {
2142 if (handler->daemonize || !handler->conf->is_execute)
2143 ret = set_stdfds(console->pty);
2144 else
2145 ret = lxc_terminal_set_stdfds(console->pty);
2146 if (ret < 0)
2147 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console->pty);
2148
2149 /*
2150 * If the console has been allocated from the host's devpts
2151 * we're done and we don't need to send fds to the parent.
2152 */
2153 if (fd_devpts_host >= 0)
2154 lxc_terminal_delete(console);
2155 }
2156
2157 return ret;
2158 }
2159
2160 static int parse_mntopt(char *opt, unsigned long *flags, char **data, size_t size)
2161 {
2162 ssize_t ret;
2163
2164 /* If '=' is contained in opt, the option must go into data. */
2165 if (!strchr(opt, '=')) {
2166 /*
2167 * If opt is found in mount_opt, set or clear flags.
2168 * Otherwise append it to data.
2169 */
2170 size_t opt_len = strlen(opt);
2171 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
2172 size_t mo_name_len = strlen(mo->name);
2173
2174 if (opt_len == mo_name_len && strnequal(opt, mo->name, mo_name_len)) {
2175 if (mo->clear)
2176 *flags &= ~mo->legacy_flag;
2177 else
2178 *flags |= mo->legacy_flag;
2179 return 0;
2180 }
2181 }
2182 }
2183
2184 if (strlen(*data)) {
2185 ret = strlcat(*data, ",", size);
2186 if (ret < 0)
2187 return log_error_errno(ret, errno, "Failed to append \",\" to %s", *data);
2188 }
2189
2190 ret = strlcat(*data, opt, size);
2191 if (ret < 0)
2192 return log_error_errno(ret, errno, "Failed to append \"%s\" to %s", opt, *data);
2193
2194 return 0;
2195 }
2196
2197 int parse_mntopts_legacy(const char *mntopts, unsigned long *mntflags, char **mntdata)
2198 {
2199 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
2200 char *mntopt_cur = NULL;
2201 size_t size;
2202
2203 if (*mntdata || *mntflags)
2204 return ret_errno(EINVAL);
2205
2206 if (!mntopts)
2207 return 0;
2208
2209 mntopts_dup = strdup(mntopts);
2210 if (!mntopts_dup)
2211 return ret_errno(ENOMEM);
2212
2213 size = strlen(mntopts_dup) + 1;
2214 mntopts_new = zalloc(size);
2215 if (!mntopts_new)
2216 return ret_errno(ENOMEM);
2217
2218 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",")
2219 if (parse_mntopt(mntopt_cur, mntflags, &mntopts_new, size) < 0)
2220 return ret_errno(EINVAL);
2221
2222 if (*mntopts_new)
2223 *mntdata = move_ptr(mntopts_new);
2224
2225 return 0;
2226 }
2227
2228 static int parse_vfs_attr(struct lxc_mount_options *opts, char *opt, size_t size)
2229 {
2230 /*
2231 * If opt is found in mount_opt, set or clear flags.
2232 * Otherwise append it to data.
2233 */
2234 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
2235 if (!strnequal(opt, mo->name, strlen(mo->name)))
2236 continue;
2237
2238 /* This is a recursive bind-mount. */
2239 if (strequal(mo->name, "rbind")) {
2240 opts->bind_recursively = 1;
2241 opts->bind = 1;
2242 opts->mnt_flags |= mo->legacy_flag; /* MS_BIND | MS_REC */
2243 return 0;
2244 }
2245
2246 /* This is a bind-mount. */
2247 if (strequal(mo->name, "bind")) {
2248 opts->bind = 1;
2249 opts->mnt_flags |= mo->legacy_flag; /* MS_BIND */
2250 return 0;
2251 }
2252
2253 if (mo->flag == ~0)
2254 return log_info(0, "Ignoring %s mount option", mo->name);
2255
2256 if (mo->clear) {
2257 opts->attr.attr_clr |= mo->flag;
2258 opts->mnt_flags &= ~mo->legacy_flag;
2259 TRACE("Lowering %s", mo->name);
2260 } else {
2261 opts->attr.attr_set |= mo->flag;
2262 opts->mnt_flags |= mo->legacy_flag;
2263 TRACE("Raising %s", mo->name);
2264 }
2265
2266 return 0;
2267 }
2268
2269 for (struct mount_opt *mo = &propagation_opt[0]; mo->name != NULL; mo++) {
2270 if (!strnequal(opt, mo->name, strlen(mo->name)))
2271 continue;
2272
2273 if (strequal(mo->name, "rslave") ||
2274 strequal(mo->name, "rshared") ||
2275 strequal(mo->name, "runbindable") ||
2276 strequal(mo->name, "rprivate"))
2277 opts->propagate_recursively = 1;
2278
2279 opts->attr.propagation = mo->flag;
2280 opts->prop_flags |= mo->legacy_flag;
2281 return 0;
2282 }
2283
2284 return 0;
2285 }
2286
2287 int parse_mount_attrs(struct lxc_mount_options *opts, const char *mntopts)
2288 {
2289 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
2290 char *end = NULL, *mntopt_cur = NULL;
2291 int ret;
2292 size_t size;
2293
2294 if (!opts)
2295 return ret_errno(EINVAL);
2296
2297 if (!mntopts)
2298 return 0;
2299
2300 mntopts_dup = strdup(mntopts);
2301 if (!mntopts_dup)
2302 return ret_errno(ENOMEM);
2303
2304 size = strlen(mntopts_dup) + 1;
2305 mntopts_new = zalloc(size);
2306 if (!mntopts_new)
2307 return ret_errno(ENOMEM);
2308
2309 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",") {
2310 /* This is a filesystem specific option. */
2311 if (strchr(mntopt_cur, '=')) {
2312 if (!end) {
2313 end = stpcpy(mntopts_new, mntopt_cur);
2314 } else {
2315 end = stpcpy(end, ",");
2316 end = stpcpy(end, mntopt_cur);
2317 }
2318
2319 continue;
2320 }
2321
2322 /* This is a generic vfs option. */
2323 ret = parse_vfs_attr(opts, mntopt_cur, size);
2324 if (ret < 0)
2325 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur);
2326 }
2327
2328 if (*mntopts_new)
2329 opts->data = move_ptr(mntopts_new);
2330
2331 return 0;
2332 }
2333
2334 static void null_endofword(char *word)
2335 {
2336 while (*word && *word != ' ' && *word != '\t')
2337 word++;
2338 *word = '\0';
2339 }
2340
2341 /* skip @nfields spaces in @src */
2342 static char *get_field(char *src, int nfields)
2343 {
2344 int i;
2345 char *p = src;
2346
2347 for (i = 0; i < nfields; i++) {
2348 while (*p && *p != ' ' && *p != '\t')
2349 p++;
2350
2351 if (!*p)
2352 break;
2353
2354 p++;
2355 }
2356
2357 return p;
2358 }
2359
2360 static int mount_entry(const char *fsname, const char *target,
2361 const char *fstype, unsigned long mountflags,
2362 unsigned long pflags, const char *data, bool optional,
2363 bool dev, bool relative, const char *rootfs)
2364 {
2365 int ret;
2366 char srcbuf[PATH_MAX];
2367 const char *srcpath = fsname;
2368 #ifdef HAVE_STATVFS
2369 struct statvfs sb;
2370 #endif
2371
2372 if (relative) {
2373 ret = strnprintf(srcbuf, sizeof(srcbuf), "%s/%s", rootfs ? rootfs : "/", fsname ? fsname : "");
2374 if (ret < 0)
2375 return log_error_errno(-1, errno, "source path is too long");
2376 srcpath = srcbuf;
2377 }
2378
2379 ret = safe_mount(srcpath, target, fstype, mountflags & ~MS_REMOUNT, data,
2380 rootfs);
2381 if (ret < 0) {
2382 if (optional)
2383 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2384 srcpath ? srcpath : "(null)", target);
2385
2386 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2387 srcpath ? srcpath : "(null)", target);
2388 }
2389
2390 if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
2391
2392 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2393 srcpath ? srcpath : "(none)", target ? target : "(none)");
2394
2395 #ifdef HAVE_STATVFS
2396 if (srcpath && statvfs(srcpath, &sb) == 0) {
2397 unsigned long required_flags = 0;
2398
2399 if (sb.f_flag & MS_NOSUID)
2400 required_flags |= MS_NOSUID;
2401
2402 if (sb.f_flag & MS_NODEV && !dev)
2403 required_flags |= MS_NODEV;
2404
2405 if (sb.f_flag & MS_RDONLY)
2406 required_flags |= MS_RDONLY;
2407
2408 if (sb.f_flag & MS_NOEXEC)
2409 required_flags |= MS_NOEXEC;
2410
2411 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2412 srcpath, sb.f_flag, required_flags);
2413
2414 /* If this was a bind mount request, and required_flags
2415 * does not have any flags which are not already in
2416 * mountflags, then skip the remount.
2417 */
2418 if (!(mountflags & MS_REMOUNT) &&
2419 (!(required_flags & ~mountflags) && !(mountflags & MS_RDONLY))) {
2420 DEBUG("Mountflags already were %lu, skipping remount", mountflags);
2421 goto skipremount;
2422 }
2423
2424 mountflags |= required_flags;
2425 }
2426 #endif
2427
2428 ret = mount(srcpath, target, fstype, mountflags | MS_REMOUNT, data);
2429 if (ret < 0) {
2430 if (optional)
2431 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2432 srcpath ? srcpath : "(null)",
2433 target);
2434
2435 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2436 srcpath ? srcpath : "(null)",
2437 target);
2438 }
2439 }
2440
2441 #ifdef HAVE_STATVFS
2442 skipremount:
2443 #endif
2444 if (pflags) {
2445 ret = mount(NULL, target, NULL, pflags, NULL);
2446 if (ret < 0) {
2447 if (optional)
2448 return log_info_errno(0, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
2449 else
2450 return log_error_errno(-1, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
2451 }
2452 DEBUG("Changed mount propagation for \"%s\"", target);
2453 }
2454
2455 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2456 srcpath ? srcpath : "(null)", target, fstype);
2457
2458 return 0;
2459 }
2460
2461 const char *lxc_mount_options_info[LXC_MOUNT_MAX] = {
2462 "create=dir",
2463 "create=file",
2464 "optional",
2465 "relative",
2466 "idmap=",
2467 };
2468
2469 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2470 int parse_lxc_mount_attrs(struct lxc_mount_options *opts, char *mnt_opts)
2471 {
2472 for (size_t i = LXC_MOUNT_CREATE_DIR; i < LXC_MOUNT_MAX; i++) {
2473 __do_close int fd_userns = -EBADF;
2474 const char *opt_name = lxc_mount_options_info[i];
2475 size_t len;
2476 char *idmap_path, *opt, *opt_next;
2477
2478 opt = strstr(mnt_opts, opt_name);
2479 if (!opt)
2480 continue;
2481
2482 switch (i) {
2483 case LXC_MOUNT_CREATE_DIR:
2484 opts->create_dir = 1;
2485 break;
2486 case LXC_MOUNT_CREATE_FILE:
2487 opts->create_file = 1;
2488 break;
2489 case LXC_MOUNT_OPTIONAL:
2490 opts->optional = 1;
2491 break;
2492 case LXC_MOUNT_RELATIVE:
2493 opts->relative = 1;
2494 break;
2495 case LXC_MOUNT_IDMAP:
2496 opt_next = opt;
2497 opt_next += STRLITERALLEN("idmap=");
2498 idmap_path = strchrnul(opt_next, ',');
2499 len = idmap_path - opt_next + 1;
2500
2501 if (len >= sizeof(opts->userns_path))
2502 return syserror_set(-EIO, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2503
2504 strlcpy(opts->userns_path, opt_next, len);
2505
2506 if (is_empty_string(opts->userns_path))
2507 return syserror_set(-EINVAL, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2508
2509 if (!strequal(opts->userns_path, "container")) {
2510 fd_userns = open(opts->userns_path, O_RDONLY | O_NOCTTY | O_CLOEXEC);
2511 if (fd_userns < 0)
2512 return syserror("Failed to open user namespace %s", opts->userns_path);
2513 }
2514
2515 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns, opts->userns_path);
2516 break;
2517 default:
2518 return syserror_set(-EINVAL, "Unknown LXC specific mount option");
2519 }
2520
2521 opt_next = strchr(opt, ',');
2522 if (!opt_next)
2523 *opt = '\0'; /* no more mntopts, so just chop it here */
2524 else
2525 memmove(opt, opt_next + 1, strlen(opt_next + 1) + 1);
2526 }
2527
2528 return 0;
2529 }
2530
2531 static int mount_entry_create_dir_file(const struct mntent *mntent,
2532 const char *path,
2533 const struct lxc_rootfs *rootfs,
2534 const char *lxc_name, const char *lxc_path)
2535 {
2536 __do_free char *p1 = NULL;
2537 int ret;
2538 char *p2;
2539
2540 if (strnequal(mntent->mnt_type, "overlay", 7)) {
2541 ret = ovl_mkdir(mntent, rootfs, lxc_name, lxc_path);
2542 if (ret < 0)
2543 return -1;
2544 }
2545
2546 if (hasmntopt(mntent, "create=dir")) {
2547 ret = mkdir_p(path, 0755);
2548 if (ret < 0 && errno != EEXIST)
2549 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
2550 }
2551
2552 if (!hasmntopt(mntent, "create=file"))
2553 return 0;
2554
2555 ret = access(path, F_OK);
2556 if (ret == 0)
2557 return 0;
2558
2559 p1 = strdup(path);
2560 if (!p1)
2561 return -1;
2562
2563 p2 = dirname(p1);
2564
2565 ret = mkdir_p(p2, 0755);
2566 if (ret < 0 && errno != EEXIST)
2567 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
2568
2569 ret = mknod(path, S_IFREG | 0000, 0);
2570 if (ret < 0 && errno != EEXIST)
2571 return -errno;
2572
2573 return 0;
2574 }
2575
2576 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2577 * without a rootfs. */
2578 static inline int mount_entry_on_generic(struct mntent *mntent,
2579 const char *path,
2580 const struct lxc_rootfs *rootfs,
2581 const char *lxc_name,
2582 const char *lxc_path)
2583 {
2584 __do_free char *mntdata = NULL;
2585 char *rootfs_path = NULL;
2586 int ret;
2587 bool dev, optional, relative;
2588 struct lxc_mount_options opts = {};
2589
2590 optional = hasmntopt(mntent, "optional") != NULL;
2591 dev = hasmntopt(mntent, "dev") != NULL;
2592 relative = hasmntopt(mntent, "relative") != NULL;
2593
2594 if (rootfs && rootfs->path)
2595 rootfs_path = rootfs->mount;
2596
2597 ret = mount_entry_create_dir_file(mntent, path, rootfs, lxc_name,
2598 lxc_path);
2599 if (ret < 0) {
2600 if (optional)
2601 return 0;
2602
2603 return -1;
2604 }
2605
2606 ret = parse_lxc_mount_attrs(&opts, mntent->mnt_opts);
2607 if (ret < 0)
2608 return ret;
2609
2610 /*
2611 * Idmapped mount entries will be setup by the parent for us. Note that
2612 * we rely on mount_entry_create_dir_file() above to have already
2613 * created the target path for us. So the parent can just open the
2614 * target and send us the target fd.
2615 */
2616 errno = EOPNOTSUPP;
2617 if (!is_empty_string(opts.userns_path))
2618 return systrace_ret(0, "Skipping idmapped mount entry");
2619
2620 ret = parse_mount_attrs(&opts, mntent->mnt_opts);
2621 if (ret < 0)
2622 return -1;
2623
2624 ret = mount_entry(mntent->mnt_fsname,
2625 path,
2626 mntent->mnt_type,
2627 opts.mnt_flags,
2628 opts.prop_flags,
2629 opts.data,
2630 optional,
2631 dev,
2632 relative,
2633 rootfs_path);
2634
2635 return ret;
2636 }
2637
2638 static inline int mount_entry_on_systemfs(struct lxc_rootfs *rootfs,
2639 struct mntent *mntent)
2640 {
2641 int ret;
2642
2643 /* For containers created without a rootfs all mounts are treated as
2644 * absolute paths starting at / on the host.
2645 */
2646 if (mntent->mnt_dir[0] != '/')
2647 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/%s", mntent->mnt_dir);
2648 else
2649 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s", mntent->mnt_dir);
2650 if (ret < 0)
2651 return -1;
2652
2653 return mount_entry_on_generic(mntent, rootfs->buf, NULL, NULL, NULL);
2654 }
2655
2656 static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
2657 struct lxc_rootfs *rootfs,
2658 const char *lxc_name,
2659 const char *lxc_path)
2660 {
2661 int offset;
2662 char *aux;
2663 const char *lxcpath;
2664 int ret = 0;
2665
2666 lxcpath = lxc_global_config_value("lxc.lxcpath");
2667 if (!lxcpath)
2668 return -1;
2669
2670 /* If rootfs->path is a blockdev path, allow container fstab to use
2671 * <lxcpath>/<name>/rootfs" as the target prefix.
2672 */
2673 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s/rootfs", lxcpath, lxc_name);
2674 if (ret < 0)
2675 goto skipvarlib;
2676
2677 aux = strstr(mntent->mnt_dir, rootfs->buf);
2678 if (aux) {
2679 offset = strlen(rootfs->buf);
2680 goto skipabs;
2681 }
2682
2683 skipvarlib:
2684 aux = strstr(mntent->mnt_dir, rootfs->path);
2685 if (!aux)
2686 return log_warn(ret, "Ignoring mount point \"%s\"", mntent->mnt_dir);
2687 offset = strlen(rootfs->path);
2688
2689 skipabs:
2690 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, aux + offset);
2691 if (ret < 0)
2692 return -1;
2693
2694 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
2695 }
2696
2697 static int mount_entry_on_relative_rootfs(struct mntent *mntent,
2698 struct lxc_rootfs *rootfs,
2699 const char *lxc_name,
2700 const char *lxc_path)
2701 {
2702 int ret;
2703
2704 /* relative to root mount point */
2705 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, mntent->mnt_dir);
2706 if (ret < 0)
2707 return -1;
2708
2709 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
2710 }
2711
2712 static int mount_file_entries(struct lxc_rootfs *rootfs, FILE *file,
2713 const char *lxc_name, const char *lxc_path)
2714 {
2715 char buf[PATH_MAX];
2716 struct mntent mntent;
2717
2718 while (getmntent_r(file, &mntent, buf, sizeof(buf))) {
2719 int ret;
2720
2721 if (!rootfs->path)
2722 ret = mount_entry_on_systemfs(rootfs, &mntent);
2723 else if (mntent.mnt_dir[0] != '/')
2724 ret = mount_entry_on_relative_rootfs(&mntent, rootfs,
2725 lxc_name, lxc_path);
2726 else
2727 ret = mount_entry_on_absolute_rootfs(&mntent, rootfs,
2728 lxc_name, lxc_path);
2729 if (ret < 0)
2730 return -1;
2731 }
2732
2733 if (!feof(file) || ferror(file))
2734 return log_error(-1, "Failed to parse mount entries");
2735
2736 return 0;
2737 }
2738
2739 static inline void __auto_endmntent__(FILE **f)
2740 {
2741 if (*f)
2742 endmntent(*f);
2743 }
2744
2745 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2746
2747 static int setup_mount_fstab(struct lxc_rootfs *rootfs, const char *fstab,
2748 const char *lxc_name, const char *lxc_path)
2749 {
2750 __do_endmntent FILE *f = NULL;
2751 int ret;
2752
2753 if (!fstab)
2754 return 0;
2755
2756 f = setmntent(fstab, "re");
2757 if (!f)
2758 return log_error_errno(-1, errno, "Failed to open \"%s\"", fstab);
2759
2760 ret = mount_file_entries(rootfs, f, lxc_name, lxc_path);
2761 if (ret < 0)
2762 ERROR("Failed to set up mount entries");
2763
2764 return ret;
2765 }
2766
2767 /*
2768 * In order for nested containers to be able to mount /proc and /sys they need
2769 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2770 * (like lxcfs).
2771 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2772 * apparmor rule to deny access to them. This is mostly for convenience: The
2773 * container's root user can mount them anyway and thus has access to the two
2774 * file systems. But a non-root user in the container should not be allowed to
2775 * access them as a side effect without explicitly allowing it.
2776 */
2777 static const char nesting_helpers[] =
2778 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2779 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2780
2781 FILE *make_anonymous_mount_file(struct lxc_list *mount,
2782 bool include_nesting_helpers)
2783 {
2784 __do_close int fd = -EBADF;
2785 FILE *f;
2786 int ret;
2787 char *mount_entry;
2788 struct lxc_list *iterator;
2789
2790 fd = memfd_create(".lxc_mount_file", MFD_CLOEXEC);
2791 if (fd < 0) {
2792 char template[] = P_tmpdir "/.lxc_mount_file_XXXXXX";
2793
2794 if (errno != ENOSYS)
2795 return NULL;
2796
2797 fd = lxc_make_tmpfile(template, true);
2798 if (fd < 0)
2799 return log_error_errno(NULL, errno, "Could not create temporary mount file");
2800
2801 TRACE("Created temporary mount file");
2802 }
2803
2804 lxc_list_for_each (iterator, mount) {
2805 size_t len;
2806
2807 mount_entry = iterator->elem;
2808 len = strlen(mount_entry);
2809
2810 ret = lxc_write_nointr(fd, mount_entry, len);
2811 if (ret != len)
2812 return NULL;
2813
2814 ret = lxc_write_nointr(fd, "\n", 1);
2815 if (ret != 1)
2816 return NULL;
2817 }
2818
2819 if (include_nesting_helpers) {
2820 ret = lxc_write_nointr(fd, nesting_helpers,
2821 STRARRAYLEN(nesting_helpers));
2822 if (ret != STRARRAYLEN(nesting_helpers))
2823 return NULL;
2824 }
2825
2826 ret = lseek(fd, 0, SEEK_SET);
2827 if (ret < 0)
2828 return NULL;
2829
2830 f = fdopen(fd, "re+");
2831 if (f)
2832 move_fd(fd); /* Transfer ownership of fd. */
2833 return f;
2834 }
2835
2836 static int setup_mount_entries(const struct lxc_conf *conf,
2837 struct lxc_rootfs *rootfs, struct lxc_list *mount,
2838 const char *lxc_name, const char *lxc_path)
2839 {
2840 __do_fclose FILE *f = NULL;
2841
2842 f = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
2843 if (!f)
2844 return -1;
2845
2846 return mount_file_entries(rootfs, f, lxc_name, lxc_path);
2847 }
2848
2849 static int __lxc_idmapped_mounts_child(struct lxc_handler *handler, FILE *f)
2850 {
2851 struct lxc_conf *conf = handler->conf;
2852 struct lxc_rootfs *rootfs = &conf->rootfs;
2853 int mnt_seq = 0;
2854 int ret;
2855 char buf[PATH_MAX];
2856 struct mntent mntent;
2857
2858 while (getmntent_r(f, &mntent, buf, sizeof(buf))) {
2859 __do_close int fd_from = -EBADF, fd_to = -EBADF,
2860 fd_userns = -EBADF;
2861 __do_free char *__data = NULL;
2862 int cur_mnt_seq = -1;
2863 struct lxc_mount_options opts = {};
2864 int dfd_from;
2865 const char *source_relative, *target_relative;
2866 struct lxc_mount_attr attr = {};
2867
2868 ret = parse_lxc_mount_attrs(&opts, mntent.mnt_opts);
2869 if (ret < 0)
2870 return syserror("Failed to parse LXC specific mount options");
2871 __data = opts.data;
2872
2873 ret = parse_mount_attrs(&opts, mntent.mnt_opts);
2874 if (ret < 0)
2875 return syserror("Failed to parse mount options");
2876
2877 /* No idmapped mount entry so skip it. */
2878 if (is_empty_string(opts.userns_path))
2879 continue;
2880
2881 if (!can_use_bind_mounts())
2882 return syserror_set(-EINVAL, "Kernel does not support idmapped mounts");
2883
2884 if (!opts.bind)
2885 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2886
2887 /* We don't support new filesystem mounts yet. */
2888 if (!is_empty_string(mntent.mnt_type) &&
2889 !strequal(mntent.mnt_type, "none"))
2890 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2891
2892 /* Someone specified additional mount options for a bind-mount. */
2893 if (!is_empty_string(opts.data))
2894 return syserror_set(-EINVAL, "Bind mounts don't support non-generic mount options");
2895
2896 /*
2897 * The source path is supposed to be taken relative to the
2898 * container's rootfs mount or - if the container does not have
2899 * a separate rootfs - to the host's /.
2900 */
2901 source_relative = deabs(mntent.mnt_fsname);
2902 if (opts.relative || !rootfs->path)
2903 dfd_from = rootfs->dfd_mnt;
2904 else
2905 dfd_from = rootfs->dfd_host;
2906 fd_from = open_tree(dfd_from, source_relative,
2907 OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC |
2908 (opts.bind_recursively ? AT_RECURSIVE : 0));
2909 if (fd_from < 0)
2910 return syserror("Failed to create detached %smount of %d/%s",
2911 opts.bind_recursively ? "recursive " : "",
2912 dfd_from, source_relative);
2913
2914 if (strequal(opts.userns_path, "container"))
2915 fd_userns = openat(dfd_from, "proc/self/ns/user", O_RDONLY | O_CLOEXEC);
2916 else
2917 fd_userns = open_at(-EBADF, opts.userns_path,
2918 PROTECT_OPEN_WITH_TRAILING_SYMLINKS, 0, 0);
2919 if (fd_userns < 0) {
2920 if (opts.optional) {
2921 TRACE("Skipping optional idmapped mount");
2922 continue;
2923 }
2924
2925 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
2926 opts.userns_path, opts.bind_recursively ? "recursive " : "",
2927 dfd_from, source_relative);
2928 }
2929
2930 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
2931 fd_from, fd_userns,
2932 &opts, sizeof(opts));
2933 if (ret <= 0) {
2934 if (opts.optional) {
2935 TRACE("Skipping optional idmapped mount");
2936 continue;
2937 }
2938
2939 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
2940 fd_from, opts.bind_recursively ? "recursive " : "",
2941 dfd_from, source_relative, fd_userns,
2942 opts.userns_path);
2943 }
2944
2945 ret = lxc_abstract_unix_rcv_credential(handler->data_sock[0],
2946 &cur_mnt_seq,
2947 sizeof(cur_mnt_seq));
2948 if (ret <= 0) {
2949 if (opts.optional) {
2950 TRACE("Skipping optional idmapped mount");
2951 continue;
2952 }
2953
2954 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2955 opts.bind_recursively ? "recursive " : "",
2956 dfd_from, source_relative, fd_userns);
2957 }
2958
2959 if (mnt_seq != cur_mnt_seq)
2960 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
2961 mnt_seq, cur_mnt_seq);
2962 mnt_seq++;
2963
2964 /* Set regular mount options. */
2965 attr = opts.attr;
2966 attr.propagation = 0;
2967 ret = mount_setattr(fd_from,
2968 "",
2969 AT_EMPTY_PATH |
2970 (opts.bind_recursively ? AT_RECURSIVE : 0),
2971 &attr,
2972 sizeof(attr));
2973 if (ret < 0) {
2974 if (opts.optional) {
2975 TRACE("Skipping optional idmapped mount");
2976 continue;
2977 }
2978
2979 return syserror("Failed to set %smount options on detached %d/%s",
2980 opts.bind_recursively ? "recursive " : "",
2981 dfd_from, source_relative);
2982 }
2983
2984 /* Set propagation mount options. */
2985 if (opts.attr.propagation) {
2986 attr = (struct lxc_mount_attr) {
2987 attr.propagation = opts.attr.propagation,
2988 };
2989
2990 ret = mount_setattr(fd_from,
2991 "",
2992 AT_EMPTY_PATH |
2993 (opts.propagate_recursively ? AT_RECURSIVE : 0),
2994 &attr,
2995 sizeof(attr));
2996 if (ret < 0) {
2997 if (opts.optional) {
2998 TRACE("Skipping optional idmapped mount");
2999 continue;
3000 }
3001
3002 return syserror("Failed to set %spropagation mount options on detached %d/%s",
3003 opts.bind_recursively ? "recursive " : "",
3004 dfd_from, source_relative);
3005 }
3006 }
3007
3008
3009 /*
3010 * In contrast to the legacy mount codepath we will simplify
3011 * our lifes and just always treat the target mountpoint to be
3012 * relative to the container's rootfs mountpoint or - if the
3013 * container does not have a separate rootfs - to the host's /.
3014 */
3015
3016 target_relative = deabs(mntent.mnt_dir);
3017 if (rootfs->path)
3018 dfd_from = rootfs->dfd_mnt;
3019 else
3020 dfd_from = rootfs->dfd_host;
3021 fd_to = open_at(dfd_from, target_relative, PROTECT_OPATH_FILE, PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS, 0);
3022 if (fd_to < 0) {
3023 if (opts.optional) {
3024 TRACE("Skipping optional idmapped mount");
3025 continue;
3026 }
3027
3028 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
3029 dfd_from, target_relative,
3030 opts.bind_recursively ? "recursive " : "",
3031 fd_userns, dfd_from, source_relative);
3032 }
3033
3034 ret = move_detached_mount(fd_from, fd_to, "", 0, 0);
3035 if (ret) {
3036 if (opts.optional) {
3037 TRACE("Skipping optional idmapped mount");
3038 continue;
3039 }
3040
3041 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3042 opts.bind_recursively ? "recursive " : "",
3043 fd_userns, dfd_from, source_relative, dfd_from, target_relative);
3044 }
3045
3046 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3047 opts.bind_recursively ? "recursive " : "", fd_userns, dfd_from,
3048 source_relative, dfd_from, target_relative);
3049 }
3050
3051 if (!feof(f) || ferror(f))
3052 return syserror_set(-EINVAL, "Failed to parse mount entries");
3053
3054 return 0;
3055 }
3056
3057 static int lxc_idmapped_mounts_child(struct lxc_handler *handler)
3058 {
3059 __do_fclose FILE *f_entries = NULL;
3060 int fret = -1;
3061 struct lxc_conf *conf = handler->conf;
3062 const char *fstab = conf->fstab;
3063 struct lxc_list *mount = &conf->mount_list;
3064 int ret;
3065
3066 f_entries = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
3067 if (!f_entries) {
3068 SYSERROR("Failed to create anonymous mount file");
3069 goto out;
3070 }
3071
3072 ret = __lxc_idmapped_mounts_child(handler, f_entries);
3073 if (ret) {
3074 SYSERROR("Failed to setup idmapped mount entries");
3075 goto out;
3076 }
3077
3078 TRACE("Finished setting up idmapped mounts");
3079
3080 if (fstab) {
3081 __do_endmntent FILE *f_fstab = NULL;
3082
3083 f_fstab = setmntent(fstab, "re");
3084 if (!f_fstab) {
3085 SYSERROR("Failed to open fstab format file \"%s\"", fstab);
3086 goto out;
3087 }
3088
3089 ret = __lxc_idmapped_mounts_child(handler, f_fstab);
3090 if (ret) {
3091 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3092 goto out;
3093 }
3094
3095 TRACE("Finished setting up idmapped mounts specified in fstab");
3096 }
3097
3098 fret = 0;
3099
3100 out:
3101 ret = lxc_abstract_unix_send_credential(handler->data_sock[0], NULL, 0);
3102 if (ret < 0)
3103 return syserror("Failed to inform parent that we are done setting up mounts");
3104
3105 return fret;
3106 }
3107
3108 static int parse_cap(const char *cap)
3109 {
3110 size_t i;
3111 int capid = -1;
3112 size_t end = sizeof(caps_opt) / sizeof(caps_opt[0]);
3113 char *ptr = NULL;
3114
3115 if (strequal(cap, "none"))
3116 return -2;
3117
3118 for (i = 0; i < end; i++) {
3119 if (!strequal(cap, caps_opt[i].name))
3120 continue;
3121
3122 capid = caps_opt[i].value;
3123 break;
3124 }
3125
3126 if (capid < 0) {
3127 /* Try to see if it's numeric, so the user may specify
3128 * capabilities that the running kernel knows about but we
3129 * don't
3130 */
3131 errno = 0;
3132 capid = strtol(cap, &ptr, 10);
3133 if (!ptr || *ptr != '\0' || errno != 0)
3134 /* not a valid number */
3135 capid = -1;
3136 else if (capid > lxc_caps_last_cap())
3137 /* we have a number but it's not a valid
3138 * capability */
3139 capid = -1;
3140 }
3141
3142 return capid;
3143 }
3144
3145 int in_caplist(int cap, struct lxc_list *caps)
3146 {
3147 int capid;
3148 struct lxc_list *iterator;
3149
3150 lxc_list_for_each (iterator, caps) {
3151 capid = parse_cap(iterator->elem);
3152 if (capid == cap)
3153 return 1;
3154 }
3155
3156 return 0;
3157 }
3158
3159 static int setup_caps(struct lxc_list *caps)
3160 {
3161 int capid;
3162 char *drop_entry;
3163 struct lxc_list *iterator;
3164
3165 lxc_list_for_each (iterator, caps) {
3166 int ret;
3167
3168 drop_entry = iterator->elem;
3169
3170 capid = parse_cap(drop_entry);
3171 if (capid < 0)
3172 return log_error(-1, "unknown capability %s", drop_entry);
3173
3174 ret = prctl(PR_CAPBSET_DROP, prctl_arg(capid), prctl_arg(0),
3175 prctl_arg(0), prctl_arg(0));
3176 if (ret < 0)
3177 return log_error_errno(-1, errno, "Failed to remove %s capability", drop_entry);
3178 DEBUG("Dropped %s (%d) capability", drop_entry, capid);
3179 }
3180
3181 DEBUG("Capabilities have been setup");
3182 return 0;
3183 }
3184
3185 static int dropcaps_except(struct lxc_list *caps)
3186 {
3187 __do_free int *caplist = NULL;
3188 int i, capid, numcaps;
3189 char *keep_entry;
3190 struct lxc_list *iterator;
3191
3192 numcaps = lxc_caps_last_cap() + 1;
3193 if (numcaps <= 0 || numcaps > 200)
3194 return -1;
3195 TRACE("Found %d capabilities", numcaps);
3196
3197 /* caplist[i] is 1 if we keep capability i */
3198 caplist = must_realloc(NULL, numcaps * sizeof(int));
3199 memset(caplist, 0, numcaps * sizeof(int));
3200
3201 lxc_list_for_each (iterator, caps) {
3202 keep_entry = iterator->elem;
3203
3204 capid = parse_cap(keep_entry);
3205 if (capid == -2)
3206 continue;
3207
3208 if (capid < 0)
3209 return log_error(-1, "Unknown capability %s", keep_entry);
3210
3211 DEBUG("Keep capability %s (%d)", keep_entry, capid);
3212 caplist[capid] = 1;
3213 }
3214
3215 for (i = 0; i < numcaps; i++) {
3216 int ret;
3217
3218 if (caplist[i])
3219 continue;
3220
3221 ret = prctl(PR_CAPBSET_DROP, prctl_arg(i), prctl_arg(0),
3222 prctl_arg(0), prctl_arg(0));
3223 if (ret < 0)
3224 return log_error_errno(-1, errno, "Failed to remove capability %d", i);
3225 }
3226
3227 DEBUG("Capabilities have been setup");
3228 return 0;
3229 }
3230
3231 static int parse_resource(const char *res)
3232 {
3233 int ret;
3234 size_t i;
3235 int resid = -1;
3236
3237 for (i = 0; i < sizeof(limit_opt) / sizeof(limit_opt[0]); ++i)
3238 if (strequal(res, limit_opt[i].name))
3239 return limit_opt[i].value;
3240
3241 /* Try to see if it's numeric, so the user may specify
3242 * resources that the running kernel knows about but
3243 * we don't.
3244 */
3245 ret = lxc_safe_int(res, &resid);
3246 if (ret < 0)
3247 return -1;
3248
3249 return resid;
3250 }
3251
3252 int setup_resource_limits(struct lxc_conf *conf, pid_t pid)
3253 {
3254 int resid;
3255 struct lxc_limit *lim;
3256
3257 if (list_empty(&conf->limits))
3258 return 0;
3259
3260 list_for_each_entry(lim, &conf->limits, head) {
3261 resid = parse_resource(lim->resource);
3262 if (resid < 0)
3263 return log_error(-1, "Unknown resource %s", lim->resource);
3264
3265 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
3266 if (prlimit(pid, resid, &lim->limit, NULL) != 0)
3267 return log_error_errno(-1, errno, "Failed to set limit %s", lim->resource);
3268
3269 TRACE("Setup \"%s\" limit", lim->resource);
3270 #else
3271 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim->resource);
3272 #endif
3273 }
3274
3275 TRACE("Setup resource limits");
3276 return 0;
3277 }
3278
3279 int setup_sysctl_parameters(struct lxc_conf *conf)
3280 {
3281 __do_free char *tmp = NULL;
3282 int ret = 0;
3283 char filename[PATH_MAX] = {0};
3284 struct lxc_sysctl *sysctl, *nsysctl;
3285
3286 if (!list_empty(&conf->sysctls))
3287 return 0;
3288
3289 list_for_each_entry_safe(sysctl, nsysctl, &conf->sysctls, head) {
3290 tmp = lxc_string_replace(".", "/", sysctl->key);
3291 if (!tmp)
3292 return log_error(-1, "Failed to replace key %s", sysctl->key);
3293
3294 ret = strnprintf(filename, sizeof(filename), "/proc/sys/%s", tmp);
3295 if (ret < 0)
3296 return log_error(-1, "Error setting up sysctl parameters path");
3297
3298 ret = lxc_write_to_file(filename, sysctl->value,
3299 strlen(sysctl->value), false, 0666);
3300 if (ret < 0)
3301 return log_error_errno(-1, errno, "Failed to setup sysctl parameters %s to %s",
3302 sysctl->key, sysctl->value);
3303 }
3304
3305 return 0;
3306 }
3307
3308 int setup_proc_filesystem(struct lxc_conf *conf, pid_t pid)
3309 {
3310 __do_free char *tmp = NULL;
3311 int ret = 0;
3312 char filename[PATH_MAX] = {0};
3313 struct lxc_proc *proc;
3314
3315 if (!list_empty(&conf->procs))
3316 return 0;
3317
3318 list_for_each_entry(proc, &conf->procs, head) {
3319 tmp = lxc_string_replace(".", "/", proc->filename);
3320 if (!tmp)
3321 return log_error(-1, "Failed to replace key %s", proc->filename);
3322
3323 ret = strnprintf(filename, sizeof(filename), "/proc/%d/%s", pid, tmp);
3324 if (ret < 0)
3325 return log_error(-1, "Error setting up proc filesystem path");
3326
3327 ret = lxc_write_to_file(filename, proc->value,
3328 strlen(proc->value), false, 0666);
3329 if (ret < 0)
3330 return log_error_errno(-1, errno, "Failed to setup proc filesystem %s to %s",
3331 proc->filename, proc->value);
3332 }
3333
3334 TRACE("Setup /proc/%d settings", pid);
3335 return 0;
3336 }
3337
3338 static char *default_rootfs_mount = LXCROOTFSMOUNT;
3339
3340 struct lxc_conf *lxc_conf_init(void)
3341 {
3342 int i;
3343 struct lxc_conf *new;
3344
3345 new = zalloc(sizeof(*new));
3346 if (!new)
3347 return NULL;
3348
3349 new->loglevel = LXC_LOG_LEVEL_NOTSET;
3350 new->personality = LXC_ARCH_UNCHANGED;
3351 new->autodev = 1;
3352 new->console.buffer_size = 0;
3353 new->console.log_path = NULL;
3354 new->console.log_fd = -1;
3355 new->console.log_size = 0;
3356 new->console.path = NULL;
3357 new->console.peer = -1;
3358 new->console.proxy.busy = -1;
3359 new->console.proxy.ptx = -1;
3360 new->console.proxy.pty = -1;
3361 new->console.ptx = -EBADF;
3362 new->console.pty = -EBADF;
3363 new->console.pty_nr = -1;
3364 new->console.name[0] = '\0';
3365 new->devpts_fd = -EBADF;
3366 memset(&new->console.ringbuf, 0, sizeof(struct lxc_ringbuf));
3367 new->maincmd_fd = -1;
3368 new->monitor_signal_pdeath = SIGKILL;
3369 new->nbd_idx = -1;
3370 new->rootfs.mount = strdup(default_rootfs_mount);
3371 if (!new->rootfs.mount) {
3372 free(new);
3373 return NULL;
3374 }
3375 new->rootfs.managed = true;
3376 new->rootfs.dfd_mnt = -EBADF;
3377 new->rootfs.dfd_dev = -EBADF;
3378 new->rootfs.dfd_host = -EBADF;
3379 new->rootfs.fd_path_pin = -EBADF;
3380 new->rootfs.dfd_idmapped = -EBADF;
3381 new->logfd = -1;
3382 INIT_LIST_HEAD(&new->cgroup);
3383 INIT_LIST_HEAD(&new->cgroup2);
3384 /* Block ("allowlist") all devices by default. */
3385 new->bpf_devices.list_type = LXC_BPF_DEVICE_CGROUP_ALLOWLIST;
3386 INIT_LIST_HEAD(&(new->bpf_devices).devices);
3387 lxc_list_init(&new->mount_list);
3388 lxc_list_init(&new->caps);
3389 lxc_list_init(&new->keepcaps);
3390 INIT_LIST_HEAD(&new->id_map);
3391 new->root_nsuid_map = NULL;
3392 new->root_nsgid_map = NULL;
3393 INIT_LIST_HEAD(&new->environment);
3394 INIT_LIST_HEAD(&new->limits);
3395 INIT_LIST_HEAD(&new->sysctls);
3396 INIT_LIST_HEAD(&new->procs);
3397 new->hooks_version = 0;
3398 for (i = 0; i < NUM_LXC_HOOKS; i++)
3399 lxc_list_init(&new->hooks[i]);
3400 lxc_list_init(&new->groups);
3401 INIT_LIST_HEAD(&new->state_clients);
3402 new->lsm_aa_profile = NULL;
3403 lxc_list_init(&new->lsm_aa_raw);
3404 new->lsm_se_context = NULL;
3405 new->lsm_se_keyring_context = NULL;
3406 new->keyring_disable_session = false;
3407 new->transient_procfs_mnt = false;
3408 new->shmount.path_host = NULL;
3409 new->shmount.path_cont = NULL;
3410
3411 /* if running in a new user namespace, init and COMMAND
3412 * default to running as UID/GID 0 when using lxc-execute */
3413 new->init_uid = 0;
3414 new->init_gid = 0;
3415 memset(&new->init_groups, 0, sizeof(lxc_groups_t));
3416 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
3417 memset(&new->ns_share, 0, sizeof(char *) * LXC_NS_MAX);
3418 memset(&new->timens, 0, sizeof(struct timens_offsets));
3419 seccomp_conf_init(new);
3420
3421 INIT_LIST_HEAD(&new->netdevs);
3422
3423 return new;
3424 }
3425
3426 int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
3427 size_t buf_size)
3428 {
3429 __do_close int fd = -EBADF;
3430 int ret;
3431 char path[PATH_MAX];
3432
3433 if (geteuid() != 0 && idtype == ID_TYPE_GID) {
3434 __do_close int setgroups_fd = -EBADF;
3435
3436 ret = strnprintf(path, sizeof(path), "/proc/%d/setgroups", pid);
3437 if (ret < 0)
3438 return -E2BIG;
3439
3440 setgroups_fd = open(path, O_WRONLY);
3441 if (setgroups_fd < 0 && errno != ENOENT)
3442 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
3443
3444 if (setgroups_fd >= 0) {
3445 ret = lxc_write_nointr(setgroups_fd, "deny\n",
3446 STRLITERALLEN("deny\n"));
3447 if (ret != STRLITERALLEN("deny\n"))
3448 return log_error_errno(-1, errno, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
3449 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid);
3450 }
3451 }
3452
3453 ret = strnprintf(path, sizeof(path), "/proc/%d/%cid_map", pid,
3454 idtype == ID_TYPE_UID ? 'u' : 'g');
3455 if (ret < 0)
3456 return -E2BIG;
3457
3458 fd = open(path, O_WRONLY | O_CLOEXEC);
3459 if (fd < 0)
3460 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
3461
3462 ret = lxc_write_nointr(fd, buf, buf_size);
3463 if (ret != buf_size)
3464 return log_error_errno(-1, errno, "Failed to write %cid mapping to \"%s\"",
3465 idtype == ID_TYPE_UID ? 'u' : 'g', path);
3466
3467 return 0;
3468 }
3469
3470 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3471 *
3472 * @return 1 if functional binary was found
3473 * @return 0 if binary exists but is lacking privilege
3474 * @return -ENOENT if binary does not exist
3475 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
3476 */
3477 static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
3478 {
3479 __do_free char *path = NULL;
3480 int ret;
3481 struct stat st;
3482
3483 if (cap != CAP_SETUID && cap != CAP_SETGID)
3484 return ret_errno(EINVAL);
3485
3486 path = on_path(binary, NULL);
3487 if (!path)
3488 return ret_errno(ENOENT);
3489
3490 ret = stat(path, &st);
3491 if (ret < 0)
3492 return -errno;
3493
3494 /* Check if the binary is setuid. */
3495 if (st.st_mode & S_ISUID)
3496 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path);
3497
3498 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
3499 /* Check if it has the CAP_SETUID capability. */
3500 if ((cap & CAP_SETUID) &&
3501 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
3502 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED))
3503 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
3504
3505 /* Check if it has the CAP_SETGID capability. */
3506 if ((cap & CAP_SETGID) &&
3507 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
3508 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED))
3509 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
3510
3511 return 0;
3512 #else
3513 /*
3514 * If we cannot check for file capabilities we need to give the benefit
3515 * of the doubt. Otherwise we might fail even though all the necessary
3516 * file capabilities are set.
3517 */
3518 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3519 return 1;
3520 #endif
3521 }
3522
3523 static int lxc_map_ids_exec_wrapper(void *args)
3524 {
3525 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
3526 return -1;
3527 }
3528
3529 static struct id_map *find_mapped_hostid_entry(const struct list_head *idmap,
3530 unsigned id, enum idtype idtype);
3531
3532 int lxc_map_ids(struct list_head *idmap, pid_t pid)
3533 {
3534 int hostuid, hostgid, fill, left;
3535 char u_or_g;
3536 char *pos;
3537 char cmd_output[PATH_MAX];
3538 struct id_map *map;
3539 enum idtype type;
3540 int ret = 0, gidmap = 0, uidmap = 0;
3541 char mapbuf[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3542 INTTYPE_TO_STRLEN(pid_t) + STRLITERALLEN(" ") +
3543 LXC_IDMAPLEN] = {0};
3544 bool had_entry = false, maps_host_root = false, use_shadow = false;
3545
3546 hostuid = geteuid();
3547 hostgid = getegid();
3548
3549 /*
3550 * Check whether caller wants to map host root.
3551 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3552 * host root into the child userns as you would be able to write fscaps
3553 * that would be valid in the ancestor userns. Mapping host root should
3554 * rarely be the case but LXC is being clever in a bunch of cases.
3555 */
3556 if (find_mapped_hostid_entry(idmap, 0, ID_TYPE_UID))
3557 maps_host_root = true;
3558
3559 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3560 * ranges, then insist that root also reserve ranges in subuid. This
3561 * will protected it by preventing another user from being handed the
3562 * range by shadow.
3563 */
3564 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
3565 if (uidmap == -ENOENT)
3566 WARN("newuidmap binary is missing");
3567 else if (!uidmap)
3568 WARN("newuidmap is lacking necessary privileges");
3569
3570 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
3571 if (gidmap == -ENOENT)
3572 WARN("newgidmap binary is missing");
3573 else if (!gidmap)
3574 WARN("newgidmap is lacking necessary privileges");
3575
3576 if (maps_host_root) {
3577 INFO("Caller maps host root. Writing mapping directly");
3578 } else if (uidmap > 0 && gidmap > 0) {
3579 DEBUG("Functional newuidmap and newgidmap binary found");
3580 use_shadow = true;
3581 } else {
3582 /* In case unprivileged users run application containers via
3583 * execute() or a start*() there are valid cases where they may
3584 * only want to map their own {g,u}id. Let's not block them from
3585 * doing so by requiring geteuid() == 0.
3586 */
3587 DEBUG("No newuidmap and newgidmap binary found. Trying to "
3588 "write directly with euid %d", hostuid);
3589 }
3590
3591 /* Check if we really need to use newuidmap and newgidmap.
3592 * If the user is only remapping their own {g,u}id, we don't need it.
3593 */
3594 if (use_shadow && list_len(idmap) == 2) {
3595 use_shadow = false;
3596 list_for_each_entry(map, idmap, head) {
3597 if (map->idtype == ID_TYPE_UID && map->range == 1 &&
3598 map->nsid == hostuid && map->hostid == hostuid)
3599 continue;
3600 if (map->idtype == ID_TYPE_GID && map->range == 1 &&
3601 map->nsid == hostgid && map->hostid == hostgid)
3602 continue;
3603 use_shadow = true;
3604 break;
3605 }
3606 }
3607
3608 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
3609 type++, u_or_g = 'g') {
3610 pos = mapbuf;
3611
3612 if (use_shadow)
3613 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
3614
3615 list_for_each_entry(map, idmap, head) {
3616 if (map->idtype != type)
3617 continue;
3618
3619 had_entry = true;
3620
3621 left = LXC_IDMAPLEN - (pos - mapbuf);
3622 fill = strnprintf(pos, left, "%s%lu %lu %lu%s",
3623 use_shadow ? " " : "", map->nsid,
3624 map->hostid, map->range,
3625 use_shadow ? "" : "\n");
3626 /*
3627 * The kernel only takes <= 4k for writes to
3628 * /proc/<pid>/{g,u}id_map
3629 */
3630 if (fill <= 0)
3631 return log_error_errno(-1, errno, "Too many %cid mappings defined", u_or_g);
3632
3633 pos += fill;
3634 }
3635 if (!had_entry)
3636 continue;
3637
3638 /* Try to catch the output of new{g,u}idmap to make debugging
3639 * easier.
3640 */
3641 if (use_shadow) {
3642 ret = run_command(cmd_output, sizeof(cmd_output),
3643 lxc_map_ids_exec_wrapper,
3644 (void *)mapbuf);
3645 if (ret < 0)
3646 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g, cmd_output, mapbuf);
3647 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
3648 } else {
3649 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
3650 if (ret < 0)
3651 return log_error(-1, "Failed to write mapping: %s", mapbuf);
3652 TRACE("Wrote mapping \"%s\"", mapbuf);
3653 }
3654
3655 memset(mapbuf, 0, sizeof(mapbuf));
3656 }
3657
3658 return 0;
3659 }
3660
3661 /*
3662 * Return the host uid/gid to which the container root is mapped in val.
3663 * Return true if id was found, false otherwise.
3664 */
3665 static id_t get_mapped_rootid(const struct lxc_conf *conf, enum idtype idtype)
3666 {
3667 unsigned nsid;
3668 struct id_map *map;
3669
3670 if (idtype == ID_TYPE_UID)
3671 nsid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
3672 else
3673 nsid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
3674
3675 list_for_each_entry (map, &conf->id_map, head) {
3676 if (map->idtype != idtype)
3677 continue;
3678 if (map->nsid != nsid)
3679 continue;
3680 return map->hostid;
3681 }
3682
3683 if (idtype == ID_TYPE_UID)
3684 return LXC_INVALID_UID;
3685
3686 return LXC_INVALID_GID;
3687 }
3688
3689 int mapped_hostid(unsigned id, const struct lxc_conf *conf, enum idtype idtype)
3690 {
3691 struct id_map *map;
3692
3693 list_for_each_entry(map, &conf->id_map, head) {
3694 if (map->idtype != idtype)
3695 continue;
3696
3697 if (id >= map->hostid && id < map->hostid + map->range)
3698 return (id - map->hostid) + map->nsid;
3699 }
3700
3701 return -1;
3702 }
3703
3704 int find_unmapped_nsid(const struct lxc_conf *conf, enum idtype idtype)
3705 {
3706 struct id_map *map;
3707 unsigned int freeid = 0;
3708
3709 again:
3710 list_for_each_entry(map, &conf->id_map, head) {
3711 if (map->idtype != idtype)
3712 continue;
3713
3714 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
3715 freeid = map->nsid + map->range;
3716 goto again;
3717 }
3718 }
3719
3720 return freeid;
3721 }
3722
3723 /*
3724 * Mount a proc under @rootfs if proc self points to a pid other than
3725 * my own. This is needed to have a known-good proc mount for setting
3726 * up LSMs both at container startup and attach.
3727 *
3728 * NOTE: not to be called from inside the container namespace!
3729 */
3730 static int lxc_transient_proc(struct lxc_rootfs *rootfs)
3731 {
3732 __do_close int fd_proc = -EBADF;
3733 int link_to_pid, link_len, pid_self, ret;
3734 char link[INTTYPE_TO_STRLEN(pid_t) + 1];
3735
3736 link_len = readlinkat(rootfs->dfd_mnt, "proc/self", link, sizeof(link));
3737 if (link_len < 0) {
3738 ret = mkdirat(rootfs->dfd_mnt, "proc", 0000);
3739 if (ret < 0 && errno != EEXIST)
3740 return log_error_errno(-errno, errno, "Failed to create %d(proc)", rootfs->dfd_mnt);
3741
3742 goto domount;
3743 } else if (link_len >= sizeof(link)) {
3744 return log_error_errno(-EIO, EIO, "Truncated link target");
3745 }
3746 link[link_len] = '\0';
3747
3748 pid_self = lxc_raw_getpid();
3749 INFO("Caller's PID is %d; /proc/self points to %s", pid_self, link);
3750
3751 ret = lxc_safe_int(link, &link_to_pid);
3752 if (ret)
3753 return log_error_errno(-ret, ret, "Failed to parse %s", link);
3754
3755 /* Correct procfs is already mounted. */
3756 if (link_to_pid == pid_self)
3757 return log_trace(0, "Correct procfs instance mounted");
3758
3759 fd_proc = open_at(rootfs->dfd_mnt, "proc", PROTECT_OPATH_DIRECTORY,
3760 PROTECT_LOOKUP_BENEATH_XDEV, 0);
3761 if (fd_proc < 0)
3762 return log_error_errno(-errno, errno, "Failed to open transient procfs mountpoint");
3763
3764 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/proc/self/fd/%d", fd_proc);
3765 if (ret < 0)
3766 return ret_errno(EIO);
3767
3768 ret = umount2(rootfs->buf, MNT_DETACH);
3769 if (ret < 0)
3770 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs->buf);
3771
3772 domount:
3773 /* rootfs is NULL */
3774 if (!rootfs->path) {
3775 ret = mount("proc", rootfs->buf, "proc", 0, NULL);
3776 } else {
3777 ret = safe_mount_beneath_at(rootfs->dfd_mnt, "none", "proc", "proc", 0, NULL);
3778 if (ret < 0) {
3779 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/proc", rootfs->path ? rootfs->mount : "");
3780 if (ret < 0)
3781 return ret_errno(EIO);
3782
3783 ret = safe_mount("proc", rootfs->buf, "proc", 0, NULL, rootfs->mount);
3784 }
3785 }
3786 if (ret < 0)
3787 return log_error_errno(-1, errno, "Failed to mount temporary procfs");
3788
3789 INFO("Created transient procfs mount");
3790 return 1;
3791 }
3792
3793 /* NOTE: Must not be called from inside the container namespace! */
3794 static int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
3795 {
3796 int mounted;
3797
3798 mounted = lxc_transient_proc(&conf->rootfs);
3799 if (mounted == -1) {
3800 /* continue only if there is no rootfs */
3801 if (conf->rootfs.path)
3802 return log_error_errno(-EPERM, EPERM, "Failed to create transient procfs mount");
3803 } else if (mounted == 1) {
3804 conf->transient_procfs_mnt = true;
3805 }
3806
3807 return 0;
3808 }
3809
3810 void tmp_proc_unmount(struct lxc_conf *lxc_conf)
3811 {
3812 if (lxc_conf->transient_procfs_mnt) {
3813 (void)umount2("/proc", MNT_DETACH);
3814 lxc_conf->transient_procfs_mnt = false;
3815 }
3816 }
3817
3818 /* Walk /proc/mounts and change any shared entries to dependent mounts. */
3819 static void turn_into_dependent_mounts(const struct lxc_rootfs *rootfs)
3820 {
3821 __do_free char *line = NULL;
3822 __do_fclose FILE *f = NULL;
3823 __do_close int memfd = -EBADF, mntinfo_fd = -EBADF;
3824 size_t len = 0;
3825 ssize_t copied;
3826 int ret;
3827
3828 mntinfo_fd = open_at(rootfs->dfd_host, "proc/self/mountinfo", PROTECT_OPEN,
3829 (PROTECT_LOOKUP_BENEATH_XDEV & ~RESOLVE_NO_SYMLINKS), 0);
3830 if (mntinfo_fd < 0) {
3831 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs->dfd_host);
3832 return;
3833 }
3834
3835 memfd = memfd_create(".lxc_mountinfo", MFD_CLOEXEC);
3836 if (memfd < 0) {
3837 char template[] = P_tmpdir "/.lxc_mountinfo_XXXXXX";
3838
3839 if (errno != ENOSYS) {
3840 SYSERROR("Failed to create temporary in-memory file");
3841 return;
3842 }
3843
3844 memfd = lxc_make_tmpfile(template, true);
3845 if (memfd < 0) {
3846 WARN("Failed to create temporary file");
3847 return;
3848 }
3849 }
3850
3851 copied = fd_to_fd(mntinfo_fd, memfd);
3852 if (copied < 0) {
3853 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3854 return;
3855 }
3856
3857 ret = lseek(memfd, 0, SEEK_SET);
3858 if (ret < 0) {
3859 SYSERROR("Failed to reset file descriptor offset");
3860 return;
3861 }
3862
3863 f = fdopen(memfd, "re");
3864 if (!f) {
3865 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3866 return;
3867 }
3868
3869 /*
3870 * After a successful fdopen() memfd will be closed when calling
3871 * fclose(f). Calling close(memfd) afterwards is undefined.
3872 */
3873 move_fd(memfd);
3874
3875 while (getline(&line, &len, f) != -1) {
3876 char *opts, *target;
3877
3878 target = get_field(line, 4);
3879 if (!target)
3880 continue;
3881
3882 opts = get_field(target, 2);
3883 if (!opts)
3884 continue;
3885
3886 null_endofword(opts);
3887 if (!strstr(opts, "shared"))
3888 continue;
3889
3890 null_endofword(target);
3891 ret = mount(NULL, target, NULL, MS_SLAVE, NULL);
3892 if (ret < 0) {
3893 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
3894 continue;
3895 }
3896 }
3897 TRACE("Turned all mount table entries into dependent mount");
3898 }
3899
3900 /* This does the work of remounting / if it is shared, calling the container
3901 * pre-mount hooks, and mounting the rootfs.
3902 */
3903 int lxc_setup_rootfs_prepare_root(struct lxc_conf *conf, const char *name,
3904 const char *lxcpath)
3905 {
3906 int ret;
3907
3908 conf->rootfs.dfd_host = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
3909 if (conf->rootfs.dfd_host < 0)
3910 return log_error_errno(-errno, errno, "Failed to open \"/\"");
3911
3912 turn_into_dependent_mounts(&conf->rootfs);
3913
3914 if (conf->rootfs_setup) {
3915 const char *path = conf->rootfs.mount;
3916
3917 /*
3918 * The rootfs was set up in another namespace. bind-mount it to
3919 * give us a mount in our own ns so we can pivot_root to it
3920 */
3921 ret = mount(path, path, "rootfs", MS_BIND, NULL);
3922 if (ret < 0)
3923 return log_error(-1, "Failed to bind mount container / onto itself");
3924
3925 conf->rootfs.dfd_mnt = openat(-EBADF, path, O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOCTTY);
3926 if (conf->rootfs.dfd_mnt < 0)
3927 return log_error_errno(-errno, errno, "Failed to open file descriptor for container rootfs");
3928
3929 return log_trace(0, "Bind mounted container / onto itself");
3930 }
3931
3932 ret = run_lxc_hooks(name, "pre-mount", conf, NULL);
3933 if (ret < 0)
3934 return log_error(-1, "Failed to run pre-mount hooks");
3935
3936 ret = lxc_mount_rootfs(&conf->rootfs);
3937 if (ret < 0)
3938 return log_error(-1, "Failed to setup rootfs for");
3939
3940 conf->rootfs_setup = true;
3941 return 0;
3942 }
3943
3944 static bool verify_start_hooks(struct lxc_conf *conf)
3945 {
3946 char path[PATH_MAX];
3947 struct lxc_list *it;
3948
3949 lxc_list_for_each (it, &conf->hooks[LXCHOOK_START]) {
3950 int ret;
3951 char *hookname = it->elem;
3952
3953 ret = strnprintf(path, sizeof(path), "%s%s",
3954 conf->rootfs.path ? conf->rootfs.mount : "",
3955 hookname);
3956 if (ret < 0)
3957 return false;
3958
3959 ret = access(path, X_OK);
3960 if (ret < 0)
3961 return log_error_errno(false, errno, "Start hook \"%s\" not found in container", hookname);
3962
3963 return true;
3964 }
3965
3966 return true;
3967 }
3968
3969 static int lxc_setup_boot_id(void)
3970 {
3971 int ret;
3972 const char *boot_id_path = "/proc/sys/kernel/random/boot_id";
3973 const char *mock_boot_id_path = "/dev/.lxc-boot-id";
3974 lxc_id128_t n;
3975
3976 if (access(boot_id_path, F_OK))
3977 return 0;
3978
3979 memset(&n, 0, sizeof(n));
3980 if (lxc_id128_randomize(&n)) {
3981 SYSERROR("Failed to generate random data for uuid");
3982 return -1;
3983 }
3984
3985 ret = lxc_id128_write(mock_boot_id_path, n);
3986 if (ret < 0) {
3987 SYSERROR("Failed to write uuid to %s", mock_boot_id_path);
3988 return -1;
3989 }
3990
3991 ret = chmod(mock_boot_id_path, 0444);
3992 if (ret < 0) {
3993 SYSERROR("Failed to chown %s", mock_boot_id_path);
3994 (void)unlink(mock_boot_id_path);
3995 return -1;
3996 }
3997
3998 ret = mount(mock_boot_id_path, boot_id_path, NULL, MS_BIND, NULL);
3999 if (ret < 0) {
4000 SYSERROR("Failed to mount %s to %s", mock_boot_id_path,
4001 boot_id_path);
4002 (void)unlink(mock_boot_id_path);
4003 return -1;
4004 }
4005
4006 ret = mount(NULL, boot_id_path, NULL,
4007 (MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NOEXEC |
4008 MS_NODEV),
4009 NULL);
4010 if (ret < 0) {
4011 SYSERROR("Failed to remount %s read-only", boot_id_path);
4012 (void)unlink(mock_boot_id_path);
4013 return -1;
4014 }
4015
4016 return 0;
4017 }
4018
4019 static int lxc_setup_keyring(struct lsm_ops *lsm_ops, const struct lxc_conf *conf)
4020 {
4021 key_serial_t keyring;
4022 int ret = 0;
4023
4024 if (conf->lsm_se_keyring_context)
4025 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_keyring_context);
4026 else if (conf->lsm_se_context)
4027 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_context);
4028 if (ret < 0)
4029 return syserror("Failed to set keyring context");
4030
4031 /*
4032 * Try to allocate a new session keyring for the container to prevent
4033 * information leaks.
4034 */
4035 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, prctl_arg(0),
4036 prctl_arg(0), prctl_arg(0), prctl_arg(0));
4037 if (keyring < 0) {
4038 switch (errno) {
4039 case ENOSYS:
4040 DEBUG("The keyctl() syscall is not supported or blocked");
4041 break;
4042 case EACCES:
4043 __fallthrough;
4044 case EPERM:
4045 DEBUG("Failed to access kernel keyring. Continuing...");
4046 break;
4047 default:
4048 SYSWARN("Failed to create kernel keyring");
4049 break;
4050 }
4051 }
4052
4053 return ret;
4054 }
4055
4056 static int lxc_rootfs_prepare_child(struct lxc_handler *handler)
4057 {
4058 struct lxc_rootfs *rootfs = &handler->conf->rootfs;
4059 int dfd_idmapped = -EBADF;
4060 int ret;
4061
4062 if (list_empty(&handler->conf->id_map))
4063 return 0;
4064
4065 if (is_empty_string(rootfs->mnt_opts.userns_path))
4066 return 0;
4067
4068 if (handler->conf->rootfs_setup)
4069 return 0;
4070
4071 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1], &dfd_idmapped, NULL, 0);
4072 if (ret < 0)
4073 return syserror("Failed to receive idmapped mount fd");
4074
4075 rootfs->dfd_idmapped = dfd_idmapped;
4076 TRACE("Received detached idmapped mount %d", rootfs->dfd_idmapped);
4077 return 0;
4078 }
4079
4080 int lxc_idmapped_mounts_parent(struct lxc_handler *handler)
4081 {
4082 int mnt_seq = 0;
4083
4084 for (;;) {
4085 __do_close int fd_from = -EBADF, fd_userns = -EBADF;
4086 struct lxc_mount_attr attr = {};
4087 struct lxc_mount_options opts = {};
4088 ssize_t ret;
4089
4090 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4091 &fd_from, &fd_userns,
4092 &opts, sizeof(opts));
4093 if (ret < 0)
4094 return syserror("Failed to receive idmapped mount file descriptors from child");
4095
4096 if (fd_from < 0 || fd_userns < 0)
4097 return log_trace(0, "Finished receiving idmapped mount file descriptors from child");
4098
4099 attr.attr_set = MOUNT_ATTR_IDMAP;
4100 attr.userns_fd = fd_userns;
4101 ret = mount_setattr(fd_from, "",
4102 AT_EMPTY_PATH |
4103 (opts.bind_recursively ? AT_RECURSIVE : 0),
4104 &attr, sizeof(attr));
4105 if (ret)
4106 return syserror("Failed to idmap detached %smount %d to %d",
4107 opts.bind_recursively ? "recursive " : "",
4108 fd_from, fd_userns);
4109
4110 ret = lxc_abstract_unix_send_credential(handler->data_sock[1],
4111 &mnt_seq,
4112 sizeof(mnt_seq));
4113 if (ret < 0)
4114 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
4115 opts.bind_recursively ? "recursive " : "",
4116 fd_from, fd_userns);
4117
4118 TRACE("Parent idmapped detached %smount %d to user namespace %d",
4119 opts.bind_recursively ? "recursive " : "", fd_from, fd_userns);
4120 mnt_seq++;
4121 }
4122 }
4123
4124 static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
4125 {
4126 call_cleaner(lxc_delete_tty) struct lxc_tty_info *info_new = &(struct lxc_tty_info){};
4127 int sock = handler->data_sock[1];
4128 struct lxc_conf *conf = handler->conf;
4129 struct lxc_tty_info *tty_info = &conf->ttys;
4130 size_t ttys_max = tty_info->max;
4131 struct lxc_terminal_info *terminal_info;
4132 int ret;
4133
4134 if (!ttys_max)
4135 return 0;
4136
4137 info_new->tty = malloc(sizeof(*(info_new->tty)) * ttys_max);
4138 if (!info_new->tty)
4139 return ret_errno(ENOMEM);
4140
4141 for (int i = 0; i < ttys_max; i++) {
4142 terminal_info = &info_new->tty[i];
4143 terminal_info->busy = -1;
4144 terminal_info->ptx = -EBADF;
4145 terminal_info->pty = -EBADF;
4146 }
4147
4148 for (int i = 0; i < ttys_max; i++) {
4149 int ptx = -EBADF, pty = -EBADF;
4150
4151 ret = lxc_abstract_unix_recv_two_fds(sock, &ptx, &pty);
4152 if (ret < 0)
4153 return syserror("Failed to receive %zu ttys from child", ttys_max);
4154
4155 terminal_info = &info_new->tty[i];
4156 terminal_info->ptx = ptx;
4157 terminal_info->pty = pty;
4158 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4159 terminal_info->ptx, terminal_info->pty);
4160 }
4161
4162 tty_info->tty = move_ptr(info_new->tty);
4163 TRACE("Received %zu ttys from child", ttys_max);
4164 return 0;
4165 }
4166
4167 static int lxc_send_console_to_parent(struct lxc_handler *handler)
4168 {
4169 struct lxc_terminal *console = &handler->conf->console;
4170 int ret;
4171
4172 if (!wants_console(console))
4173 return 0;
4174
4175 /* We've already allocated a console from the host's devpts instance. */
4176 if (console->pty < 0)
4177 return 0;
4178
4179 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
4180 console->ptx, console->pty,
4181 console,
4182 sizeof(struct lxc_terminal));
4183 if (ret < 0)
4184 return syserror("Fail to send console to parent");
4185
4186 TRACE("Sent console to parent");
4187 return 0;
4188 }
4189
4190 static int lxc_recv_console_from_child(struct lxc_handler *handler)
4191 {
4192 __do_close int fd_ptx = -EBADF, fd_pty = -EBADF;
4193 struct lxc_terminal *console = &handler->conf->console;
4194 int ret;
4195
4196 if (!wants_console(console))
4197 return 0;
4198
4199 /* We've already allocated a console from the host's devpts instance. */
4200 if (console->pty >= 0)
4201 return 0;
4202
4203 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4204 &fd_ptx, &fd_pty,
4205 console,
4206 sizeof(struct lxc_terminal));
4207 if (ret < 0)
4208 return syserror("Fail to receive console from child");
4209
4210 console->ptx = move_fd(fd_ptx);
4211 console->pty = move_fd(fd_pty);
4212
4213 TRACE("Received console from child");
4214 return 0;
4215 }
4216
4217 int lxc_sync_fds_parent(struct lxc_handler *handler)
4218 {
4219 int ret;
4220
4221 ret = lxc_seccomp_recv_notifier_fd(&handler->conf->seccomp, handler->data_sock[1]);
4222 if (ret < 0)
4223 return syserror_ret(ret, "Failed to receive seccomp notify fd from child");
4224
4225 ret = lxc_recv_devpts_from_child(handler);
4226 if (ret < 0)
4227 return syserror_ret(ret, "Failed to receive devpts fd from child");
4228
4229 /* Read tty fds allocated by child. */
4230 ret = lxc_recv_ttys_from_child(handler);
4231 if (ret < 0)
4232 return syserror_ret(ret, "Failed to receive tty info from child process");
4233
4234 if (handler->ns_clone_flags & CLONE_NEWNET) {
4235 ret = lxc_network_recv_name_and_ifindex_from_child(handler);
4236 if (ret < 0)
4237 return syserror_ret(ret, "Failed to receive names and ifindices for network devices from child");
4238 }
4239
4240 ret = lxc_recv_console_from_child(handler);
4241 if (ret < 0)
4242 return syserror_ret(ret, "Failed to receive console from child");
4243
4244 TRACE("Finished syncing file descriptors with child");
4245 return 0;
4246 }
4247
4248 int lxc_sync_fds_child(struct lxc_handler *handler)
4249 {
4250 int ret;
4251
4252 ret = lxc_seccomp_send_notifier_fd(&handler->conf->seccomp, handler->data_sock[0]);
4253 if (ret < 0)
4254 return syserror_ret(ret, "Failed to send seccomp notify fd to parent");
4255
4256 ret = lxc_send_devpts_to_parent(handler);
4257 if (ret < 0)
4258 return syserror_ret(ret, "Failed to send seccomp devpts fd to parent");
4259
4260 ret = lxc_send_ttys_to_parent(handler);
4261 if (ret < 0)
4262 return syserror_ret(ret, "Failed to send tty file descriptors to parent");
4263
4264 if (handler->ns_clone_flags & CLONE_NEWNET) {
4265 ret = lxc_network_send_name_and_ifindex_to_parent(handler);
4266 if (ret < 0)
4267 return syserror_ret(ret, "Failed to send network device names and ifindices to parent");
4268 }
4269
4270 ret = lxc_send_console_to_parent(handler);
4271 if (ret < 0)
4272 return syserror_ret(ret, "Failed to send console to parent");
4273
4274 TRACE("Finished syncing file descriptors with parent");
4275 return 0;
4276 }
4277
4278 int lxc_setup(struct lxc_handler *handler)
4279 {
4280 int ret;
4281 const char *lxcpath = handler->lxcpath, *name = handler->name;
4282 struct lxc_conf *lxc_conf = handler->conf;
4283
4284 ret = lxc_rootfs_prepare_child(handler);
4285 if (ret < 0)
4286 return syserror("Failed to prepare rootfs");
4287
4288 ret = lxc_setup_rootfs_prepare_root(lxc_conf, name, lxcpath);
4289 if (ret < 0)
4290 return log_error(-1, "Failed to setup rootfs");
4291
4292 if (handler->nsfd[LXC_NS_UTS] == -EBADF) {
4293 ret = setup_utsname(lxc_conf->utsname);
4294 if (ret < 0)
4295 return log_error(-1, "Failed to setup the utsname %s", name);
4296 }
4297
4298 if (!lxc_conf->keyring_disable_session) {
4299 ret = lxc_setup_keyring(handler->lsm_ops, lxc_conf);
4300 if (ret < 0)
4301 return log_error(-1, "Failed to setup container keyring");
4302 }
4303
4304 if (handler->ns_clone_flags & CLONE_NEWNET) {
4305 ret = lxc_network_recv_from_parent(handler);
4306 if (ret < 0)
4307 return log_error(-1, "Failed to receive veth names from parent");
4308
4309 ret = lxc_setup_network_in_child_namespaces(lxc_conf);
4310 if (ret < 0)
4311 return log_error(-1, "Failed to setup network");
4312 }
4313
4314 if (lxc_conf->autodev > 0) {
4315 ret = mount_autodev(name, &lxc_conf->rootfs, lxc_conf->autodevtmpfssize, lxcpath);
4316 if (ret < 0)
4317 return log_error(-1, "Failed to mount \"/dev\"");
4318 }
4319
4320 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4321 * need to wait until other stuff has finished.
4322 */
4323 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK);
4324 if (ret < 0)
4325 return log_error(-1, "Failed to setup first automatic mounts");
4326
4327 ret = setup_mount_fstab(&lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath);
4328 if (ret < 0)
4329 return log_error(-1, "Failed to setup mounts");
4330
4331 if (!lxc_list_empty(&lxc_conf->mount_list)) {
4332 ret = setup_mount_entries(lxc_conf, &lxc_conf->rootfs,
4333 &lxc_conf->mount_list, name, lxcpath);
4334 if (ret < 0)
4335 return log_error(-1, "Failed to setup mount entries");
4336 }
4337
4338 if (!lxc_sync_wake_parent(handler, START_SYNC_IDMAPPED_MOUNTS))
4339 return -1;
4340
4341 ret = lxc_idmapped_mounts_child(handler);
4342 if (ret)
4343 return syserror("Failed to attached detached idmapped mounts");
4344
4345 lxc_conf->rootfs.dfd_dev = open_at(lxc_conf->rootfs.dfd_mnt, "dev",
4346 PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
4347 if (lxc_conf->rootfs.dfd_dev < 0 && errno != ENOENT)
4348 return log_error_errno(-errno, errno, "Failed to open \"/dev\"");
4349
4350 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4351 * mounted. It is guaranteed to be mounted now either through
4352 * automatically or via fstab entries.
4353 */
4354 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK);
4355 if (ret < 0)
4356 return log_error(-1, "Failed to setup remaining automatic mounts");
4357
4358 ret = run_lxc_hooks(name, "mount", lxc_conf, NULL);
4359 if (ret < 0)
4360 return log_error(-1, "Failed to run mount hooks");
4361
4362 if (lxc_conf->autodev > 0) {
4363 ret = run_lxc_hooks(name, "autodev", lxc_conf, NULL);
4364 if (ret < 0)
4365 return log_error(-1, "Failed to run autodev hooks");
4366
4367 ret = lxc_fill_autodev(&lxc_conf->rootfs);
4368 if (ret < 0)
4369 return log_error(-1, "Failed to populate \"/dev\"");
4370 }
4371
4372 /* Make sure any start hooks are in the container */
4373 if (!verify_start_hooks(lxc_conf))
4374 return log_error(-1, "Failed to verify start hooks");
4375
4376 ret = lxc_create_tmp_proc_mount(lxc_conf);
4377 if (ret < 0)
4378 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
4379
4380 ret = lxc_setup_devpts_child(handler);
4381 if (ret < 0)
4382 return log_error(-1, "Failed to prepare new devpts instance");
4383
4384 ret = lxc_finish_devpts_child(handler);
4385 if (ret < 0)
4386 return log_error(-1, "Failed to finish devpts setup");
4387
4388 ret = lxc_setup_console(handler, &lxc_conf->rootfs, &lxc_conf->console,
4389 lxc_conf->ttys.dir);
4390 if (ret < 0)
4391 return log_error(-1, "Failed to setup console");
4392
4393 ret = lxc_create_ttys(handler);
4394 if (ret < 0)
4395 return log_error(-1, "Failed to create ttys");
4396
4397 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
4398 if (ret < 0)
4399 return log_error(-1, "Failed to setup \"/dev\" symlinks");
4400
4401 ret = lxc_setup_rootfs_switch_root(&lxc_conf->rootfs);
4402 if (ret < 0)
4403 return log_error(-1, "Failed to pivot root into rootfs");
4404
4405 /* Setting the boot-id is best-effort for now. */
4406 if (lxc_conf->autodev > 0)
4407 (void)lxc_setup_boot_id();
4408
4409 ret = setup_personality(lxc_conf->personality);
4410 if (ret < 0)
4411 return syserror("Failed to set personality");
4412
4413 /* Set sysctl value to a path under /proc/sys as determined from the
4414 * key. For e.g. net.ipv4.ip_forward translated to
4415 * /proc/sys/net/ipv4/ip_forward.
4416 */
4417 ret = setup_sysctl_parameters(lxc_conf);
4418 if (ret < 0)
4419 return log_error(-1, "Failed to setup sysctl parameters");
4420
4421 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
4422 if (!lxc_list_empty(&lxc_conf->caps))
4423 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
4424
4425 if (dropcaps_except(&lxc_conf->keepcaps))
4426 return log_error(-1, "Failed to keep capabilities");
4427 } else if (setup_caps(&lxc_conf->caps)) {
4428 return log_error(-1, "Failed to drop capabilities");
4429 }
4430
4431 put_lxc_rootfs(&handler->conf->rootfs, true);
4432 NOTICE("The container \"%s\" is set up", name);
4433
4434 return 0;
4435 }
4436
4437 int run_lxc_hooks(const char *name, char *hookname, struct lxc_conf *conf,
4438 char *argv[])
4439 {
4440 struct lxc_list *it;
4441 int which;
4442
4443 for (which = 0; which < NUM_LXC_HOOKS; which ++) {
4444 if (strequal(hookname, lxchook_names[which]))
4445 break;
4446 }
4447
4448 if (which >= NUM_LXC_HOOKS)
4449 return -1;
4450
4451 lxc_list_for_each (it, &conf->hooks[which]) {
4452 int ret;
4453 char *hook = it->elem;
4454
4455 ret = run_script_argv(name, conf->hooks_version, "lxc", hook,
4456 hookname, argv);
4457 if (ret < 0)
4458 return -1;
4459 }
4460
4461 return 0;
4462 }
4463
4464 int lxc_clear_config_caps(struct lxc_conf *c)
4465 {
4466 struct lxc_list *it, *next;
4467
4468 lxc_list_for_each_safe (it, &c->caps, next) {
4469 lxc_list_del(it);
4470 free(it->elem);
4471 free(it);
4472 }
4473
4474 lxc_list_init(&c->caps);
4475 return 0;
4476 }
4477
4478 static int lxc_free_idmap(struct list_head *id_map)
4479 {
4480 struct id_map *map, *nmap;
4481
4482 list_for_each_entry_safe(map, nmap, id_map, head) {
4483 list_del(&map->head);
4484 free(map);
4485 }
4486
4487 INIT_LIST_HEAD(id_map);
4488 return 0;
4489 }
4490
4491 static int __lxc_free_idmap(struct list_head *id_map)
4492 {
4493 lxc_free_idmap(id_map);
4494 return 0;
4495 }
4496 define_cleanup_function(struct list_head *, __lxc_free_idmap);
4497
4498 int lxc_clear_idmaps(struct lxc_conf *c)
4499 {
4500 return lxc_free_idmap(&c->id_map);
4501 }
4502
4503 int lxc_clear_config_keepcaps(struct lxc_conf *c)
4504 {
4505 struct lxc_list *it, *next;
4506
4507 lxc_list_for_each_safe (it, &c->keepcaps, next) {
4508 lxc_list_del(it);
4509 free(it->elem);
4510 free(it);
4511 }
4512
4513 lxc_list_init(&c->keepcaps);
4514 return 0;
4515 }
4516
4517 int lxc_clear_namespace(struct lxc_conf *c)
4518 {
4519 for (int i = 0; i < LXC_NS_MAX; i++)
4520 free_disarm(c->ns_share[i]);
4521
4522 return 0;
4523 }
4524
4525 int lxc_clear_cgroups(struct lxc_conf *c, const char *key, int version)
4526 {
4527 const char *k = key;
4528 bool all = false;
4529 char *global_token, *namespaced_token;
4530 size_t namespaced_token_len;
4531 struct list_head *list;
4532 struct lxc_cgroup *cgroup, *ncgroup;
4533
4534 if (version == CGROUP2_SUPER_MAGIC) {
4535 global_token = "lxc.cgroup2";
4536 namespaced_token = "lxc.cgroup2.";
4537 namespaced_token_len = STRLITERALLEN("lxc.cgroup2.");
4538 list = &c->cgroup2;
4539 } else if (version == CGROUP_SUPER_MAGIC) {
4540 global_token = "lxc.cgroup";
4541 namespaced_token = "lxc.cgroup.";
4542 namespaced_token_len = STRLITERALLEN("lxc.cgroup.");
4543 list = &c->cgroup;
4544 } else {
4545 return ret_errno(EINVAL);
4546 }
4547
4548 if (strequal(key, global_token))
4549 all = true;
4550 else if (strnequal(key, namespaced_token, namespaced_token_len))
4551 k += namespaced_token_len;
4552 else
4553 return ret_errno(EINVAL);
4554
4555 list_for_each_entry_safe(cgroup, ncgroup, list, head) {
4556 if (!all && !strequal(cgroup->subsystem, k))
4557 continue;
4558
4559 list_del(&cgroup->head);
4560 free(cgroup->subsystem);
4561 free(cgroup->value);
4562 free(cgroup);
4563 }
4564
4565 if (all)
4566 INIT_LIST_HEAD(list);
4567
4568 return 0;
4569 }
4570
4571 static inline void lxc_clear_cgroups_devices(struct lxc_conf *conf)
4572 {
4573 lxc_clear_cgroup2_devices(&conf->bpf_devices);
4574 }
4575
4576 int lxc_clear_limits(struct lxc_conf *c, const char *key)
4577 {
4578 const char *k = NULL;
4579 bool all = false;
4580 struct lxc_limit *lim, *nlim;
4581
4582 if (strequal(key, "lxc.limit") || strequal(key, "lxc.prlimit"))
4583 all = true;
4584 else if (strnequal(key, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
4585 k = key + STRLITERALLEN("lxc.limit.");
4586 else if (strnequal(key, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
4587 k = key + STRLITERALLEN("lxc.prlimit.");
4588 else
4589 return ret_errno(EINVAL);
4590
4591 list_for_each_entry_safe(lim, nlim, &c->limits, head) {
4592 if (!all && !strequal(lim->resource, k))
4593 continue;
4594
4595 list_del(&lim->head);
4596 free_disarm(lim->resource);
4597 free(lim);
4598 }
4599
4600 if (all)
4601 INIT_LIST_HEAD(&c->limits);
4602
4603 return 0;
4604 }
4605
4606 int lxc_clear_sysctls(struct lxc_conf *c, const char *key)
4607 {
4608 const char *k = NULL;
4609 bool all = false;
4610 struct lxc_sysctl *sysctl, *nsysctl;
4611
4612 if (strequal(key, "lxc.sysctl"))
4613 all = true;
4614 else if (strnequal(key, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
4615 k = key + STRLITERALLEN("lxc.sysctl.");
4616 else
4617 return -1;
4618
4619 list_for_each_entry_safe(sysctl, nsysctl, &c->sysctls, head) {
4620 if (!all && !strequal(sysctl->key, k))
4621 continue;
4622
4623 list_del(&sysctl->head);
4624 free(sysctl->key);
4625 free(sysctl->value);
4626 free(sysctl);
4627 }
4628
4629 if (all)
4630 INIT_LIST_HEAD(&c->sysctls);
4631
4632 return 0;
4633 }
4634
4635 int lxc_clear_procs(struct lxc_conf *c, const char *key)
4636 {
4637 const char *k = NULL;
4638 bool all = false;
4639 struct lxc_proc *proc, *nproc;
4640
4641 if (strequal(key, "lxc.proc"))
4642 all = true;
4643 else if (strnequal(key, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
4644 k = key + STRLITERALLEN("lxc.proc.");
4645 else
4646 return -1;
4647
4648 list_for_each_entry_safe(proc, nproc, &c->procs, head) {
4649 if (!all && !strequal(proc->filename, k))
4650 continue;
4651
4652 list_del(&proc->head);
4653 free(proc->filename);
4654 free(proc->value);
4655 free(proc);
4656 }
4657
4658 if (all)
4659 INIT_LIST_HEAD(&c->procs);
4660
4661 return 0;
4662 }
4663
4664 int lxc_clear_groups(struct lxc_conf *c)
4665 {
4666 struct lxc_list *it, *next;
4667
4668 lxc_list_for_each_safe (it, &c->groups, next) {
4669 lxc_list_del(it);
4670 free(it->elem);
4671 free(it);
4672 }
4673
4674 lxc_list_init(&c->groups);
4675 return 0;
4676 }
4677
4678 int lxc_clear_environment(struct lxc_conf *c)
4679 {
4680 struct environment_entry *env, *nenv;
4681
4682 list_for_each_entry_safe(env, nenv, &c->environment, head) {
4683 list_del(&env->head);
4684 free(env->key);
4685 free(env->val);
4686 free(env);
4687 }
4688
4689 INIT_LIST_HEAD(&c->environment);
4690 return 0;
4691 }
4692
4693 int lxc_clear_mount_entries(struct lxc_conf *c)
4694 {
4695 struct lxc_list *it, *next;
4696
4697 lxc_list_for_each_safe (it, &c->mount_list, next) {
4698 lxc_list_del(it);
4699 free(it->elem);
4700 free(it);
4701 }
4702
4703 lxc_list_init(&c->mount_list);
4704 return 0;
4705 }
4706
4707 int lxc_clear_automounts(struct lxc_conf *c)
4708 {
4709 c->auto_mounts = 0;
4710 return 0;
4711 }
4712
4713 int lxc_clear_hooks(struct lxc_conf *c, const char *key)
4714 {
4715 struct lxc_list *it, *next;
4716 const char *k = NULL;
4717 bool all = false, done = false;
4718
4719 if (strequal(key, "lxc.hook"))
4720 all = true;
4721 else if (strnequal(key, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
4722 k = key + STRLITERALLEN("lxc.hook.");
4723 else
4724 return -1;
4725
4726 for (int i = 0; i < NUM_LXC_HOOKS; i++) {
4727 if (all || strequal(k, lxchook_names[i])) {
4728 lxc_list_for_each_safe (it, &c->hooks[i], next) {
4729 lxc_list_del(it);
4730 free(it->elem);
4731 free(it);
4732 }
4733 lxc_list_init(&c->hooks[i]);
4734
4735 done = true;
4736 }
4737 }
4738
4739 if (!done)
4740 return log_error(-1, "Invalid hook key: %s", key);
4741
4742 return 0;
4743 }
4744
4745 int lxc_clear_apparmor_raw(struct lxc_conf *c)
4746 {
4747 struct lxc_list *it, *next;
4748
4749 lxc_list_for_each_safe (it, &c->lsm_aa_raw, next) {
4750 lxc_list_del(it);
4751 free(it->elem);
4752 free(it);
4753 }
4754
4755 lxc_list_init(&c->lsm_aa_raw);
4756 return 0;
4757 }
4758
4759 void lxc_conf_free(struct lxc_conf *conf)
4760 {
4761 if (!conf)
4762 return;
4763
4764 if (current_config == conf)
4765 current_config = NULL;
4766 lxc_terminal_conf_free(&conf->console);
4767 free(conf->rootfs.mount);
4768 free(conf->rootfs.bdev_type);
4769 free(conf->rootfs.path);
4770 put_lxc_rootfs(&conf->rootfs, true);
4771 free(conf->logfile);
4772 if (conf->logfd != -1)
4773 close(conf->logfd);
4774 free(conf->utsname);
4775 free(conf->ttys.dir);
4776 free(conf->ttys.tty_names);
4777 free(conf->fstab);
4778 free(conf->rcfile);
4779 free(conf->execute_cmd);
4780 free(conf->init_cmd);
4781 free(conf->init_groups.list);
4782 free(conf->init_cwd);
4783 free(conf->unexpanded_config);
4784 free(conf->syslog);
4785 lxc_free_networks(conf);
4786 free(conf->lsm_aa_profile);
4787 free(conf->lsm_aa_profile_computed);
4788 free(conf->lsm_se_context);
4789 free(conf->lsm_se_keyring_context);
4790 lxc_seccomp_free(&conf->seccomp);
4791 lxc_clear_config_caps(conf);
4792 lxc_clear_config_keepcaps(conf);
4793 lxc_clear_cgroups(conf, "lxc.cgroup", CGROUP_SUPER_MAGIC);
4794 lxc_clear_cgroups(conf, "lxc.cgroup2", CGROUP2_SUPER_MAGIC);
4795 lxc_clear_cgroups_devices(conf);
4796 lxc_clear_hooks(conf, "lxc.hook");
4797 lxc_clear_mount_entries(conf);
4798 lxc_clear_idmaps(conf);
4799 lxc_clear_groups(conf);
4800 lxc_clear_environment(conf);
4801 lxc_clear_limits(conf, "lxc.prlimit");
4802 lxc_clear_sysctls(conf, "lxc.sysctl");
4803 lxc_clear_procs(conf, "lxc.proc");
4804 lxc_clear_apparmor_raw(conf);
4805 lxc_clear_namespace(conf);
4806 free(conf->cgroup_meta.dir);
4807 free(conf->cgroup_meta.monitor_dir);
4808 free(conf->cgroup_meta.monitor_pivot_dir);
4809 free(conf->cgroup_meta.container_dir);
4810 free(conf->cgroup_meta.namespace_dir);
4811 free(conf->cgroup_meta.controllers);
4812 free(conf->shmount.path_host);
4813 free(conf->shmount.path_cont);
4814 free(conf);
4815 }
4816
4817 struct userns_fn_data {
4818 int (*fn)(void *);
4819 const char *fn_name;
4820 void *arg;
4821 int p[2];
4822 };
4823
4824 static int run_userns_fn(void *data)
4825 {
4826 struct userns_fn_data *d = data;
4827 int ret;
4828 char c;
4829
4830 close_prot_errno_disarm(d->p[1]);
4831
4832 /*
4833 * Wait for parent to finish establishing a new mapping in the user
4834 * namespace we are executing in.
4835 */
4836 ret = lxc_read_nointr(d->p[0], &c, 1);
4837 close_prot_errno_disarm(d->p[0]);
4838 if (ret != 1)
4839 return -1;
4840
4841 if (d->fn_name)
4842 TRACE("Calling function \"%s\"", d->fn_name);
4843
4844 /* Call function to run. */
4845 return d->fn(d->arg);
4846 }
4847
4848 static struct id_map *mapped_nsid_add(const struct lxc_conf *conf, unsigned id,
4849 enum idtype idtype)
4850 {
4851 const struct id_map *map;
4852 struct id_map *retmap;
4853
4854 map = find_mapped_nsid_entry(conf, id, idtype);
4855 if (!map)
4856 return NULL;
4857
4858 retmap = zalloc(sizeof(*retmap));
4859 if (!retmap)
4860 return NULL;
4861
4862 memcpy(retmap, map, sizeof(*retmap));
4863 return retmap;
4864 }
4865
4866 static struct id_map *find_mapped_hostid_entry(const struct list_head *idmap,
4867 unsigned id, enum idtype idtype)
4868 {
4869 struct id_map *retmap = NULL;
4870 struct id_map *map;
4871
4872 list_for_each_entry(map, idmap, head) {
4873 if (map->idtype != idtype)
4874 continue;
4875
4876 if (id >= map->hostid && id < map->hostid + map->range) {
4877 retmap = map;
4878 break;
4879 }
4880 }
4881
4882 return retmap;
4883 }
4884
4885 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4886 * existing one or establish a new one.
4887 */
4888 static struct id_map *mapped_hostid_add(const struct lxc_conf *conf, uid_t id,
4889 enum idtype type)
4890 {
4891 __do_free struct id_map *entry = NULL;
4892 int hostid_mapped;
4893 struct id_map *tmp = NULL;
4894
4895 entry = zalloc(sizeof(*entry));
4896 if (!entry)
4897 return NULL;
4898
4899 /* Reuse existing mapping. */
4900 tmp = find_mapped_hostid_entry(&conf->id_map, id, type);
4901 if (tmp) {
4902 memcpy(entry, tmp, sizeof(*entry));
4903 } else {
4904 /* Find new mapping. */
4905 hostid_mapped = find_unmapped_nsid(conf, type);
4906 if (hostid_mapped < 0)
4907 return log_debug(NULL, "Failed to find free mapping for id %d", id);
4908
4909 entry->idtype = type;
4910 entry->nsid = hostid_mapped;
4911 entry->hostid = (unsigned long)id;
4912 entry->range = 1;
4913 }
4914
4915 return move_ptr(entry);
4916 }
4917
4918 static int get_minimal_idmap(const struct lxc_conf *conf, uid_t *resuid,
4919 gid_t *resgid, struct list_head *head_ret)
4920 {
4921 __do_free struct id_map *container_root_uid = NULL,
4922 *container_root_gid = NULL,
4923 *host_uid_map = NULL, *host_gid_map = NULL;
4924 uid_t euid, egid;
4925 uid_t nsuid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
4926 gid_t nsgid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
4927
4928 /* Find container root mappings. */
4929 container_root_uid = mapped_nsid_add(conf, nsuid, ID_TYPE_UID);
4930 if (!container_root_uid)
4931 return sysdebug("Failed to find mapping for namespace uid %d", 0);
4932 euid = geteuid();
4933 if (euid >= container_root_uid->hostid &&
4934 euid < (container_root_uid->hostid + container_root_uid->range))
4935 host_uid_map = move_ptr(container_root_uid);
4936
4937 container_root_gid = mapped_nsid_add(conf, nsgid, ID_TYPE_GID);
4938 if (!container_root_gid)
4939 return sysdebug("Failed to find mapping for namespace gid %d", 0);
4940 egid = getegid();
4941 if (egid >= container_root_gid->hostid &&
4942 egid < (container_root_gid->hostid + container_root_gid->range))
4943 host_gid_map = move_ptr(container_root_gid);
4944
4945 /* Check whether the {g,u}id of the user has a mapping. */
4946 if (!host_uid_map)
4947 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
4948 if (!host_uid_map)
4949 return sysdebug("Failed to find mapping for uid %d", euid);
4950
4951 if (!host_gid_map)
4952 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
4953 if (!host_gid_map)
4954 return sysdebug("Failed to find mapping for gid %d", egid);
4955
4956 /* idmap will now keep track of that memory. */
4957 list_add_tail(&host_uid_map->head, head_ret);
4958 move_ptr(host_uid_map);
4959
4960 if (container_root_uid) {
4961 /* idmap will now keep track of that memory. */
4962 list_add_tail(&container_root_uid->head, head_ret);
4963 move_ptr(container_root_uid);
4964 }
4965
4966 /* idmap will now keep track of that memory. */
4967 list_add_tail(&host_gid_map->head, head_ret);
4968 move_ptr(host_gid_map);
4969
4970 if (container_root_gid) {
4971 /* idmap will now keep track of that memory. */
4972 list_add_tail(&container_root_gid->head, head_ret);
4973 move_ptr(container_root_gid);
4974 }
4975
4976 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid, nsgid);
4977
4978 if (resuid)
4979 *resuid = nsuid;
4980 if (resgid)
4981 *resgid = nsgid;
4982
4983 return 0;
4984 }
4985
4986 /*
4987 * Run a function in a new user namespace.
4988 * The caller's euid/egid will be mapped if it is not already.
4989 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4990 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4991 * This means we require only to establish a mapping from:
4992 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4993 * - the container root -> some sub{g,u}id
4994 * The former we add, if the user did not specify a mapping. The latter we
4995 * retrieve from the container's configured {g,u}id mappings as it must have been
4996 * there to start the container in the first place.
4997 */
4998 int userns_exec_1(const struct lxc_conf *conf, int (*fn)(void *), void *data,
4999 const char *fn_name)
5000 {
5001 LIST_HEAD(minimal_idmap);
5002 call_cleaner(__lxc_free_idmap) struct list_head *idmap = &minimal_idmap;
5003 int ret = -1, status = -1;
5004 char c = '1';
5005 struct userns_fn_data d = {
5006 .arg = data,
5007 .fn = fn,
5008 .fn_name = fn_name,
5009 };
5010 pid_t pid;
5011 int pipe_fds[2];
5012
5013 if (!conf)
5014 return -EINVAL;
5015
5016 ret = get_minimal_idmap(conf, NULL, NULL, idmap);
5017 if (ret)
5018 return ret_errno(ENOENT);
5019
5020 ret = pipe2(pipe_fds, O_CLOEXEC);
5021 if (ret < 0)
5022 return -errno;
5023
5024 d.p[0] = pipe_fds[0];
5025 d.p[1] = pipe_fds[1];
5026
5027 /* Clone child in new user namespace. */
5028 pid = lxc_raw_clone_cb(run_userns_fn, &d, CLONE_NEWUSER, NULL);
5029 if (pid < 0) {
5030 ERROR("Failed to clone process in new user namespace");
5031 goto on_error;
5032 }
5033
5034 close_prot_errno_disarm(pipe_fds[0]);
5035
5036 if (lxc_log_trace()) {
5037 struct id_map *map;
5038
5039 list_for_each_entry(map, idmap, head)
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);
5042 }
5043
5044 /* Set up {g,u}id mapping for user namespace of child process. */
5045 ret = lxc_map_ids(idmap, pid);
5046 if (ret < 0) {
5047 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5048 goto on_error;
5049 }
5050
5051 /* Tell child to proceed. */
5052 if (lxc_write_nointr(pipe_fds[1], &c, 1) != 1) {
5053 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5054 goto on_error;
5055 }
5056
5057 on_error:
5058 close_prot_errno_disarm(pipe_fds[0]);
5059 close_prot_errno_disarm(pipe_fds[1]);
5060
5061 /* Wait for child to finish. */
5062 if (pid > 0)
5063 status = wait_for_pid(pid);
5064
5065 if (status < 0)
5066 ret = -1;
5067
5068 return ret;
5069 }
5070
5071 int userns_exec_minimal(const struct lxc_conf *conf,
5072 int (*fn_parent)(void *), void *fn_parent_data,
5073 int (*fn_child)(void *), void *fn_child_data)
5074 {
5075 LIST_HEAD(minimal_idmap);
5076 call_cleaner(__lxc_free_idmap) struct list_head *idmap = &minimal_idmap;
5077 uid_t resuid = LXC_INVALID_UID;
5078 gid_t resgid = LXC_INVALID_GID;
5079 char c = '1';
5080 ssize_t ret;
5081 pid_t pid;
5082 int sock_fds[2];
5083
5084 if (!conf || !fn_child)
5085 return ret_errno(EINVAL);
5086
5087 ret = get_minimal_idmap(conf, &resuid, &resgid, idmap);
5088 if (ret)
5089 return ret_errno(ENOENT);
5090
5091 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5092 if (ret < 0)
5093 return -errno;
5094
5095 pid = fork();
5096 if (pid < 0) {
5097 SYSERROR("Failed to create new process");
5098 goto on_error;
5099 }
5100
5101 if (pid == 0) {
5102 close_prot_errno_disarm(sock_fds[1]);
5103
5104 ret = unshare(CLONE_NEWUSER);
5105 if (ret < 0) {
5106 SYSERROR("Failed to unshare new user namespace");
5107 _exit(EXIT_FAILURE);
5108 }
5109
5110 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5111 if (ret != 1)
5112 _exit(EXIT_FAILURE);
5113
5114 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5115 if (ret != 1)
5116 _exit(EXIT_FAILURE);
5117
5118 close_prot_errno_disarm(sock_fds[0]);
5119
5120 if (!lxc_drop_groups() && errno != EPERM)
5121 _exit(EXIT_FAILURE);
5122
5123 ret = setresgid(resgid, resgid, resgid);
5124 if (ret < 0) {
5125 SYSERROR("Failed to setresgid(%d, %d, %d)",
5126 resgid, resgid, resgid);
5127 _exit(EXIT_FAILURE);
5128 }
5129
5130 ret = setresuid(resuid, resuid, resuid);
5131 if (ret < 0) {
5132 SYSERROR("Failed to setresuid(%d, %d, %d)",
5133 resuid, resuid, resuid);
5134 _exit(EXIT_FAILURE);
5135 }
5136
5137 ret = fn_child(fn_child_data);
5138 if (ret) {
5139 SYSERROR("Running function in new user namespace failed");
5140 _exit(EXIT_FAILURE);
5141 }
5142
5143 _exit(EXIT_SUCCESS);
5144 }
5145
5146 close_prot_errno_disarm(sock_fds[0]);
5147
5148 if (lxc_log_trace()) {
5149 struct id_map *map;
5150
5151 list_for_each_entry(map, idmap, head)
5152 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5153 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
5154 }
5155
5156 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5157 if (ret != 1) {
5158 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5159 goto on_error;
5160 }
5161
5162 /* Set up {g,u}id mapping for user namespace of child process. */
5163 ret = lxc_map_ids(idmap, pid);
5164 if (ret < 0) {
5165 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5166 goto on_error;
5167 }
5168
5169 /* Tell child to proceed. */
5170 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5171 if (ret != 1) {
5172 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5173 goto on_error;
5174 }
5175
5176 if (fn_parent && fn_parent(fn_parent_data)) {
5177 SYSERROR("Running parent function failed");
5178 _exit(EXIT_FAILURE);
5179 }
5180
5181 on_error:
5182 close_prot_errno_disarm(sock_fds[0]);
5183 close_prot_errno_disarm(sock_fds[1]);
5184
5185 /* Wait for child to finish. */
5186 if (pid < 0)
5187 return -1;
5188
5189 return wait_for_pid(pid);
5190 }
5191
5192 int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
5193 const char *fn_name)
5194 {
5195 LIST_HEAD(full_idmap);
5196 int ret = -1;
5197 char c = '1';
5198 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
5199 *host_uid_map = NULL, *host_gid_map = NULL;
5200 pid_t pid;
5201 uid_t euid, egid;
5202 int p[2];
5203 struct id_map *map;
5204 struct userns_fn_data d;
5205
5206 if (!conf)
5207 return -EINVAL;
5208
5209 ret = pipe2(p, O_CLOEXEC);
5210 if (ret < 0)
5211 return -errno;
5212
5213 d.fn = fn;
5214 d.fn_name = fn_name;
5215 d.arg = data;
5216 d.p[0] = p[0];
5217 d.p[1] = p[1];
5218
5219 /* Clone child in new user namespace. */
5220 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER, NULL);
5221 if (pid < 0) {
5222 ERROR("Failed to clone process in new user namespace");
5223 goto on_error;
5224 }
5225
5226 close(p[0]);
5227 p[0] = -1;
5228
5229 euid = geteuid();
5230 egid = getegid();
5231
5232 /* Find container root. */
5233 list_for_each_entry(map, &conf->id_map, head) {
5234 __do_free struct id_map *dup_map = NULL;
5235
5236 dup_map = memdup(map, sizeof(struct id_map));
5237 if (!dup_map)
5238 goto on_error;
5239
5240 list_add_tail(&dup_map->head, &full_idmap);
5241 move_ptr(dup_map);
5242
5243 if (map->idtype == ID_TYPE_UID)
5244 if (euid >= map->hostid && euid < map->hostid + map->range)
5245 host_uid_map = map;
5246
5247 if (map->idtype == ID_TYPE_GID)
5248 if (egid >= map->hostid && egid < map->hostid + map->range)
5249 host_gid_map = map;
5250
5251 if (map->nsid != 0)
5252 continue;
5253
5254 if (map->idtype == ID_TYPE_UID)
5255 if (container_root_uid == NULL)
5256 container_root_uid = map;
5257
5258 if (map->idtype == ID_TYPE_GID)
5259 if (container_root_gid == NULL)
5260 container_root_gid = map;
5261 }
5262
5263 if (!container_root_uid || !container_root_gid) {
5264 ERROR("No mapping for container root found");
5265 goto on_error;
5266 }
5267
5268 /* Check whether the {g,u}id of the user has a mapping. */
5269 if (!host_uid_map)
5270 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
5271 else
5272 host_uid_map = container_root_uid;
5273
5274 if (!host_gid_map)
5275 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
5276 else
5277 host_gid_map = container_root_gid;
5278
5279 if (!host_uid_map) {
5280 DEBUG("Failed to find mapping for uid %d", euid);
5281 goto on_error;
5282 }
5283
5284 if (!host_gid_map) {
5285 DEBUG("Failed to find mapping for gid %d", egid);
5286 goto on_error;
5287 }
5288
5289 if (host_uid_map && (host_uid_map != container_root_uid)) {
5290 /* idmap will now keep track of that memory. */
5291 list_add_tail(&host_uid_map->head, &full_idmap);
5292 move_ptr(host_uid_map);
5293 }
5294
5295 if (host_gid_map && (host_gid_map != container_root_gid)) {
5296 /* idmap will now keep track of that memory. */
5297 list_add_tail(&host_gid_map->head, &full_idmap);
5298 move_ptr(host_gid_map);
5299 }
5300
5301 if (lxc_log_trace()) {
5302 list_for_each_entry(map, &full_idmap, head) {
5303 TRACE("establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5304 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
5305 map->nsid, map->hostid, map->range);
5306 }
5307 }
5308
5309 /* Set up {g,u}id mapping for user namespace of child process. */
5310 ret = lxc_map_ids(&full_idmap, pid);
5311 if (ret < 0) {
5312 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid);
5313 goto on_error;
5314 }
5315
5316 /* Tell child to proceed. */
5317 if (lxc_write_nointr(p[1], &c, 1) != 1) {
5318 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5319 goto on_error;
5320 }
5321
5322 on_error:
5323 if (p[0] != -1)
5324 close(p[0]);
5325 close(p[1]);
5326
5327 /* Wait for child to finish. */
5328 if (pid > 0)
5329 ret = wait_for_pid(pid);
5330
5331 __lxc_free_idmap(&full_idmap);
5332
5333 if (host_uid_map && (host_uid_map != container_root_uid))
5334 free(host_uid_map);
5335 if (host_gid_map && (host_gid_map != container_root_gid))
5336 free(host_gid_map);
5337
5338 return ret;
5339 }
5340
5341 static int add_idmap_entry(struct list_head *idmap_list, enum idtype idtype,
5342 unsigned long nsid, unsigned long hostid,
5343 unsigned long range)
5344 {
5345 __do_free struct id_map *new_idmap = NULL;
5346
5347 new_idmap = zalloc(sizeof(*new_idmap));
5348 if (!new_idmap)
5349 return ret_errno(ENOMEM);
5350
5351 new_idmap->idtype = idtype;
5352 new_idmap->hostid = hostid;
5353 new_idmap->nsid = nsid;
5354 new_idmap->range = range;
5355
5356 list_add_tail(&new_idmap->head, idmap_list);
5357 move_ptr(new_idmap);
5358
5359 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5360 idtype == ID_TYPE_UID ? 'u' : 'g', nsid, hostid, range);
5361 return 0;
5362 }
5363
5364 int userns_exec_mapped_root(const char *path, int path_fd,
5365 const struct lxc_conf *conf)
5366 {
5367 LIST_HEAD(idmap_list);
5368 call_cleaner(__lxc_free_idmap) struct list_head *idmap = &idmap_list;
5369 __do_close int fd = -EBADF;
5370 int target_fd = -EBADF;
5371 char c = '1';
5372 ssize_t ret;
5373 pid_t pid;
5374 int sock_fds[2];
5375 uid_t container_host_uid, hostuid;
5376 gid_t container_host_gid, hostgid;
5377 struct stat st;
5378
5379 if (!conf || (!path && path_fd < 0))
5380 return ret_errno(EINVAL);
5381
5382 if (!path)
5383 path = "(null)";
5384
5385 container_host_uid = get_mapped_rootid(conf, ID_TYPE_UID);
5386 if (!uid_valid(container_host_uid))
5387 return log_error(-1, "No uid mapping for container root");
5388
5389 container_host_gid = get_mapped_rootid(conf, ID_TYPE_GID);
5390 if (!gid_valid(container_host_gid))
5391 return log_error(-1, "No gid mapping for container root");
5392
5393 if (path_fd < 0) {
5394 fd = open(path, O_CLOEXEC | O_NOCTTY);
5395 if (fd < 0)
5396 return log_error_errno(-errno, errno, "Failed to open \"%s\"", path);
5397 target_fd = fd;
5398 } else {
5399 target_fd = path_fd;
5400 }
5401
5402 hostuid = geteuid();
5403 /* We are root so chown directly. */
5404 if (hostuid == 0) {
5405 ret = fchown(target_fd, container_host_uid, container_host_gid);
5406 if (ret)
5407 return log_error_errno(-errno, errno,
5408 "Failed to fchown(%d(%s), %d, %d)",
5409 target_fd, path, container_host_uid,
5410 container_host_gid);
5411 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd, path,
5412 container_host_uid, container_host_gid);
5413 }
5414
5415 /* The container's root host id matches */
5416 if (container_host_uid == hostuid)
5417 return log_info(0, "Container root id is mapped to our uid");
5418
5419 /* Get the current ids of our target. */
5420 ret = fstat(target_fd, &st);
5421 if (ret)
5422 return log_error_errno(-errno, errno, "Failed to stat \"%s\"", path);
5423
5424 hostgid = getegid();
5425 if (st.st_uid == hostuid && mapped_hostid(st.st_gid, conf, ID_TYPE_GID) < 0) {
5426 ret = fchown(target_fd, -1, hostgid);
5427 if (ret)
5428 return log_error_errno(-errno, errno,
5429 "Failed to fchown(%d(%s), -1, %d)",
5430 target_fd, path, hostgid);
5431 TRACE("Chowned %d(%s) to -1:%d", target_fd, path, hostgid);
5432 }
5433
5434 /* "u:0:rootuid:1" */
5435 ret = add_idmap_entry(idmap, ID_TYPE_UID, 0, container_host_uid, 1);
5436 if (ret < 0)
5437 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5438
5439 /* "u:hostuid:hostuid:1" */
5440 ret = add_idmap_entry(idmap, ID_TYPE_UID, hostuid, hostuid, 1);
5441 if (ret < 0)
5442 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5443
5444 /* "g:0:rootgid:1" */
5445 ret = add_idmap_entry(idmap, ID_TYPE_GID, 0, container_host_gid, 1);
5446 if (ret < 0)
5447 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5448
5449 /* "g:hostgid:hostgid:1" */
5450 ret = add_idmap_entry(idmap, ID_TYPE_GID, hostgid, hostgid, 1);
5451 if (ret < 0)
5452 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5453
5454 if (hostgid != st.st_gid) {
5455 /* "g:pathgid:rootgid+pathgid:1" */
5456 ret = add_idmap_entry(idmap, ID_TYPE_GID, st.st_gid,
5457 container_host_gid + (gid_t)st.st_gid, 1);
5458 if (ret < 0)
5459 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5460 }
5461
5462 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5463 if (ret < 0)
5464 return -errno;
5465
5466 pid = fork();
5467 if (pid < 0) {
5468 SYSERROR("Failed to create new process");
5469 goto on_error;
5470 }
5471
5472 if (pid == 0) {
5473 close_prot_errno_disarm(sock_fds[1]);
5474
5475 ret = unshare(CLONE_NEWUSER);
5476 if (ret < 0) {
5477 SYSERROR("Failed to unshare new user namespace");
5478 _exit(EXIT_FAILURE);
5479 }
5480
5481 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5482 if (ret != 1)
5483 _exit(EXIT_FAILURE);
5484
5485 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5486 if (ret != 1)
5487 _exit(EXIT_FAILURE);
5488
5489 close_prot_errno_disarm(sock_fds[0]);
5490
5491 if (!lxc_switch_uid_gid(0, 0))
5492 _exit(EXIT_FAILURE);
5493
5494 if (!lxc_drop_groups())
5495 _exit(EXIT_FAILURE);
5496
5497 ret = fchown(target_fd, 0, st.st_gid);
5498 if (ret) {
5499 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd, path, st.st_gid);
5500 _exit(EXIT_FAILURE);
5501 }
5502
5503 TRACE("Chowned %d(%s) to 0:%d", target_fd, path, st.st_gid);
5504 _exit(EXIT_SUCCESS);
5505 }
5506
5507 close_prot_errno_disarm(sock_fds[0]);
5508
5509 if (lxc_log_trace()) {
5510 struct id_map *map;
5511
5512 list_for_each_entry(map, idmap, head)
5513 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5514 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
5515 }
5516
5517 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5518 if (ret != 1) {
5519 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5520 goto on_error;
5521 }
5522
5523 /* Set up {g,u}id mapping for user namespace of child process. */
5524 ret = lxc_map_ids(idmap, pid);
5525 if (ret < 0) {
5526 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5527 goto on_error;
5528 }
5529
5530 /* Tell child to proceed. */
5531 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5532 if (ret != 1) {
5533 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5534 goto on_error;
5535 }
5536
5537 on_error:
5538 close_prot_errno_disarm(sock_fds[0]);
5539 close_prot_errno_disarm(sock_fds[1]);
5540
5541 /* Wait for child to finish. */
5542 if (pid < 0)
5543 return -1;
5544
5545 return wait_for_pid(pid);
5546 }
5547
5548 /* not thread-safe, do not use from api without first forking */
5549 static char *getuname(void)
5550 {
5551 __do_free char *buf = NULL;
5552 struct passwd pwent;
5553 struct passwd *pwentp = NULL;
5554 size_t bufsize;
5555 int ret;
5556
5557 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
5558 if (bufsize == -1)
5559 bufsize = 1024;
5560
5561 buf = zalloc(bufsize);
5562 if (!buf)
5563 return NULL;
5564
5565 ret = getpwuid_r(geteuid(), &pwent, buf, bufsize, &pwentp);
5566 if (!pwentp) {
5567 if (ret == 0)
5568 WARN("Could not find matched password record.");
5569
5570 return log_error(NULL, "Failed to get password record - %u", geteuid());
5571 }
5572
5573 return strdup(pwent.pw_name);
5574 }
5575
5576 /* not thread-safe, do not use from api without first forking */
5577 static char *getgname(void)
5578 {
5579 __do_free char *buf = NULL;
5580 struct group grent;
5581 struct group *grentp = NULL;
5582 size_t bufsize;
5583 int ret;
5584
5585 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
5586 if (bufsize == -1)
5587 bufsize = 1024;
5588
5589 buf = zalloc(bufsize);
5590 if (!buf)
5591 return NULL;
5592
5593 ret = getgrgid_r(getegid(), &grent, buf, bufsize, &grentp);
5594 if (!grentp) {
5595 if (ret == 0)
5596 WARN("Could not find matched group record");
5597
5598 return log_error(NULL, "Failed to get group record - %u", getegid());
5599 }
5600
5601 return strdup(grent.gr_name);
5602 }
5603
5604 /* not thread-safe, do not use from api without first forking */
5605 void suggest_default_idmap(void)
5606 {
5607 __do_free char *gname = NULL, *line = NULL, *uname = NULL;
5608 __do_fclose FILE *subuid_f = NULL, *subgid_f = NULL;
5609 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
5610 size_t len = 0;
5611
5612 uname = getuname();
5613 if (!uname)
5614 return;
5615
5616 gname = getgname();
5617 if (!gname)
5618 return;
5619
5620 subuid_f = fopen(subuidfile, "re");
5621 if (!subuid_f) {
5622 ERROR("Your system is not configured with subuids");
5623 return;
5624 }
5625
5626 while (getline(&line, &len, subuid_f) != -1) {
5627 char *p, *p2;
5628 size_t no_newline = 0;
5629
5630 p = strchr(line, ':');
5631 if (*line == '#')
5632 continue;
5633 if (!p)
5634 continue;
5635 *p = '\0';
5636 p++;
5637
5638 if (!strequal(line, uname))
5639 continue;
5640
5641 p2 = strchr(p, ':');
5642 if (!p2)
5643 continue;
5644 *p2 = '\0';
5645 p2++;
5646 if (!*p2)
5647 continue;
5648 no_newline = strcspn(p2, "\n");
5649 p2[no_newline] = '\0';
5650
5651 if (lxc_safe_uint(p, &uid) < 0)
5652 WARN("Could not parse UID");
5653 if (lxc_safe_uint(p2, &urange) < 0)
5654 WARN("Could not parse UID range");
5655 }
5656
5657 subgid_f = fopen(subgidfile, "re");
5658 if (!subgid_f) {
5659 ERROR("Your system is not configured with subgids");
5660 return;
5661 }
5662
5663 while (getline(&line, &len, subgid_f) != -1) {
5664 char *p, *p2;
5665 size_t no_newline = 0;
5666
5667 p = strchr(line, ':');
5668 if (*line == '#')
5669 continue;
5670 if (!p)
5671 continue;
5672 *p = '\0';
5673 p++;
5674
5675 if (!strequal(line, uname))
5676 continue;
5677
5678 p2 = strchr(p, ':');
5679 if (!p2)
5680 continue;
5681 *p2 = '\0';
5682 p2++;
5683 if (!*p2)
5684 continue;
5685 no_newline = strcspn(p2, "\n");
5686 p2[no_newline] = '\0';
5687
5688 if (lxc_safe_uint(p, &gid) < 0)
5689 WARN("Could not parse GID");
5690 if (lxc_safe_uint(p2, &grange) < 0)
5691 WARN("Could not parse GID range");
5692 }
5693
5694 if (!urange || !grange) {
5695 ERROR("You do not have subuids or subgids allocated");
5696 ERROR("Unprivileged containers require subuids and subgids");
5697 return;
5698 }
5699
5700 ERROR("You must either run as root, or define uid mappings");
5701 ERROR("To pass uid mappings to lxc-create, you could create");
5702 ERROR("~/.config/lxc/default.conf:");
5703 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
5704 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
5705 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
5706 }
5707
5708 /* Return the list of cgroup_settings sorted according to the following rules
5709 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
5710 */
5711 void sort_cgroup_settings(struct lxc_conf *conf)
5712 {
5713 struct lxc_cgroup *cgroup, *memsw_limit, *ncgroup;
5714
5715 /* Iterate over the cgroup settings and copy them to the output list. */
5716 list_for_each_entry_safe(cgroup, ncgroup, &conf->cgroup, head) {
5717 if (strequal(cgroup->subsystem, "memory.memsw.limit_in_bytes")) {
5718 /* Store the memsw_limit location */
5719 memsw_limit = cgroup;
5720 } else if (memsw_limit && strequal(cgroup->subsystem, "memory.limit_in_bytes")) {
5721 /*
5722 * lxc.cgroup.memory.memsw.limit_in_bytes is found
5723 * before lxc.cgroup.memory.limit_in_bytes, swap these
5724 * two items.
5725 */
5726 list_swap(&memsw_limit->head, &cgroup->head);
5727 }
5728 }
5729 }
5730
5731 int lxc_set_environment(const struct lxc_conf *conf)
5732 {
5733 struct environment_entry *env;
5734
5735 list_for_each_entry(env, &conf->environment, head) {
5736 int ret;
5737
5738 ret = setenv(env->key, env->val, 1);
5739 if (ret < 0)
5740 return syserror("Failed to set environment variable: %s=%s",
5741 env->key, env->val);
5742 TRACE("Set environment variable: %s=%s", env->key, env->val);
5743 }
5744
5745 return 0;
5746 }