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