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