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