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