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