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