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