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