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