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