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