]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/conf.c
Merge pull request #3235 from xinhua9569/master
[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->tmp_umount_proc = false;
2746 new->tmp_umount_proc = 0;
2747 new->shmount.path_host = NULL;
2748 new->shmount.path_cont = NULL;
2749
2750 /* if running in a new user namespace, init and COMMAND
2751 * default to running as UID/GID 0 when using lxc-execute */
2752 new->init_uid = 0;
2753 new->init_gid = 0;
2754 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
2755 memset(&new->ns_share, 0, sizeof(char *) * LXC_NS_MAX);
2756 seccomp_conf_init(new);
2757
2758 return new;
2759 }
2760
2761 int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
2762 size_t buf_size)
2763 {
2764 __do_close_prot_errno int fd = -EBADF;
2765 int ret;
2766 char path[PATH_MAX];
2767
2768 if (geteuid() != 0 && idtype == ID_TYPE_GID) {
2769 __do_close_prot_errno int setgroups_fd = -EBADF;
2770
2771 ret = snprintf(path, PATH_MAX, "/proc/%d/setgroups", pid);
2772 if (ret < 0 || ret >= PATH_MAX)
2773 return -E2BIG;
2774
2775 setgroups_fd = open(path, O_WRONLY);
2776 if (setgroups_fd < 0 && errno != ENOENT) {
2777 SYSERROR("Failed to open \"%s\"", path);
2778 return -1;
2779 }
2780
2781 if (setgroups_fd >= 0) {
2782 ret = lxc_write_nointr(setgroups_fd, "deny\n",
2783 STRLITERALLEN("deny\n"));
2784 if (ret != STRLITERALLEN("deny\n")) {
2785 SYSERROR("Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
2786 return -1;
2787 }
2788 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid);
2789 }
2790 }
2791
2792 ret = snprintf(path, PATH_MAX, "/proc/%d/%cid_map", pid,
2793 idtype == ID_TYPE_UID ? 'u' : 'g');
2794 if (ret < 0 || ret >= PATH_MAX)
2795 return -E2BIG;
2796
2797 fd = open(path, O_WRONLY);
2798 if (fd < 0) {
2799 SYSERROR("Failed to open \"%s\"", path);
2800 return -1;
2801 }
2802
2803 ret = lxc_write_nointr(fd, buf, buf_size);
2804 if (ret != buf_size) {
2805 SYSERROR("Failed to write %cid mapping to \"%s\"",
2806 idtype == ID_TYPE_UID ? 'u' : 'g', path);
2807 return -1;
2808 }
2809
2810 return 0;
2811 }
2812
2813 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2814 *
2815 * @return 1 if functional binary was found
2816 * @return 0 if binary exists but is lacking privilege
2817 * @return -ENOENT if binary does not exist
2818 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2819 */
2820 static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
2821 {
2822 __do_free char *path = NULL;
2823 int ret;
2824 struct stat st;
2825
2826 errno = EINVAL;
2827 if (cap != CAP_SETUID && cap != CAP_SETGID)
2828 return -1;
2829
2830 errno = ENOENT;
2831 path = on_path(binary, NULL);
2832 if (!path)
2833 return -1;
2834
2835 ret = stat(path, &st);
2836 if (ret < 0)
2837 return -1;
2838
2839 /* Check if the binary is setuid. */
2840 if (st.st_mode & S_ISUID) {
2841 DEBUG("The binary \"%s\" does have the setuid bit set", path);
2842 return 1;
2843 }
2844
2845 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2846 /* Check if it has the CAP_SETUID capability. */
2847 if ((cap & CAP_SETUID) &&
2848 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
2849 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED)) {
2850 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2851 "and CAP_PERMITTED sets", path);
2852 return 1;
2853 }
2854
2855 /* Check if it has the CAP_SETGID capability. */
2856 if ((cap & CAP_SETGID) &&
2857 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
2858 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED)) {
2859 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2860 "and CAP_PERMITTED sets", path);
2861 return 1;
2862 }
2863 #else
2864 /* If we cannot check for file capabilities we need to give the benefit
2865 * of the doubt. Otherwise we might fail even though all the necessary
2866 * file capabilities are set.
2867 */
2868 DEBUG("Cannot check for file capabilities as full capability support is "
2869 "missing. Manual intervention needed");
2870 #endif
2871
2872 return 1;
2873 }
2874
2875 int lxc_map_ids_exec_wrapper(void *args)
2876 {
2877 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
2878 return -1;
2879 }
2880
2881 int lxc_map_ids(struct lxc_list *idmap, pid_t pid)
2882 {
2883 int fill, left;
2884 char u_or_g;
2885 char *pos;
2886 char cmd_output[PATH_MAX];
2887 struct id_map *map;
2888 struct lxc_list *iterator;
2889 enum idtype type;
2890 /* strlen("new@idmap") = 9
2891 * +
2892 * strlen(" ") = 1
2893 * +
2894 * INTTYPE_TO_STRLEN(uint32_t)
2895 * +
2896 * strlen(" ") = 1
2897 *
2898 * We add some additional space to make sure that we really have
2899 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2900 */
2901 int ret = 0, gidmap = 0, uidmap = 0;
2902 char mapbuf[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN] = {0};
2903 bool had_entry = false, use_shadow = false;
2904 int hostuid, hostgid;
2905
2906 hostuid = geteuid();
2907 hostgid = getegid();
2908
2909 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2910 * ranges, then insist that root also reserve ranges in subuid. This
2911 * will protected it by preventing another user from being handed the
2912 * range by shadow.
2913 */
2914 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
2915 if (uidmap == -ENOENT)
2916 WARN("newuidmap binary is missing");
2917 else if (!uidmap)
2918 WARN("newuidmap is lacking necessary privileges");
2919
2920 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
2921 if (gidmap == -ENOENT)
2922 WARN("newgidmap binary is missing");
2923 else if (!gidmap)
2924 WARN("newgidmap is lacking necessary privileges");
2925
2926 if (uidmap > 0 && gidmap > 0) {
2927 DEBUG("Functional newuidmap and newgidmap binary found");
2928 use_shadow = true;
2929 } else {
2930 /* In case unprivileged users run application containers via
2931 * execute() or a start*() there are valid cases where they may
2932 * only want to map their own {g,u}id. Let's not block them from
2933 * doing so by requiring geteuid() == 0.
2934 */
2935 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2936 "write directly with euid %d", hostuid);
2937 }
2938
2939 /* Check if we really need to use newuidmap and newgidmap.
2940 * If the user is only remapping his own {g,u}id, we don't need it.
2941 */
2942 if (use_shadow && lxc_list_len(idmap) == 2) {
2943 use_shadow = false;
2944 lxc_list_for_each(iterator, idmap) {
2945 map = iterator->elem;
2946 if (map->idtype == ID_TYPE_UID && map->range == 1 &&
2947 map->nsid == hostuid && map->hostid == hostuid)
2948 continue;
2949 if (map->idtype == ID_TYPE_GID && map->range == 1 &&
2950 map->nsid == hostgid && map->hostid == hostgid)
2951 continue;
2952 use_shadow = true;
2953 break;
2954 }
2955 }
2956
2957 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
2958 type++, u_or_g = 'g') {
2959 pos = mapbuf;
2960
2961 if (use_shadow)
2962 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
2963
2964 lxc_list_for_each(iterator, idmap) {
2965 map = iterator->elem;
2966 if (map->idtype != type)
2967 continue;
2968
2969 had_entry = true;
2970
2971 left = LXC_IDMAPLEN - (pos - mapbuf);
2972 fill = snprintf(pos, left, "%s%lu %lu %lu%s",
2973 use_shadow ? " " : "", map->nsid,
2974 map->hostid, map->range,
2975 use_shadow ? "" : "\n");
2976 if (fill <= 0 || fill >= left) {
2977 /* The kernel only takes <= 4k for writes to
2978 * /proc/<pid>/{g,u}id_map
2979 */
2980 SYSERROR("Too many %cid mappings defined", u_or_g);
2981 return -1;
2982 }
2983
2984 pos += fill;
2985 }
2986 if (!had_entry)
2987 continue;
2988
2989 /* Try to catch the output of new{g,u}idmap to make debugging
2990 * easier.
2991 */
2992 if (use_shadow) {
2993 ret = run_command(cmd_output, sizeof(cmd_output),
2994 lxc_map_ids_exec_wrapper,
2995 (void *)mapbuf);
2996 if (ret < 0) {
2997 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2998 u_or_g, cmd_output, mapbuf);
2999 return -1;
3000 }
3001 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
3002 } else {
3003 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
3004 if (ret < 0) {
3005 ERROR("Failed to write mapping: %s", mapbuf);
3006 return -1;
3007 }
3008 TRACE("Wrote mapping \"%s\"", mapbuf);
3009 }
3010
3011 memset(mapbuf, 0, sizeof(mapbuf));
3012 }
3013
3014 return 0;
3015 }
3016
3017 /* Return the host uid/gid to which the container root is mapped in val.
3018 * Return true if id was found, false otherwise.
3019 */
3020 bool get_mapped_rootid(struct lxc_conf *conf, enum idtype idtype,
3021 unsigned long *val)
3022 {
3023 unsigned nsid;
3024 struct id_map *map;
3025 struct lxc_list *it;
3026
3027 if (idtype == ID_TYPE_UID)
3028 nsid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
3029 else
3030 nsid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
3031
3032 lxc_list_for_each (it, &conf->id_map) {
3033 map = it->elem;
3034 if (map->idtype != idtype)
3035 continue;
3036 if (map->nsid != nsid)
3037 continue;
3038 *val = map->hostid;
3039 return true;
3040 }
3041
3042 return false;
3043 }
3044
3045 int mapped_hostid(unsigned id, struct lxc_conf *conf, enum idtype idtype)
3046 {
3047 struct id_map *map;
3048 struct lxc_list *it;
3049
3050 lxc_list_for_each (it, &conf->id_map) {
3051 map = it->elem;
3052 if (map->idtype != idtype)
3053 continue;
3054
3055 if (id >= map->hostid && id < map->hostid + map->range)
3056 return (id - map->hostid) + map->nsid;
3057 }
3058
3059 return -1;
3060 }
3061
3062 int find_unmapped_nsid(struct lxc_conf *conf, enum idtype idtype)
3063 {
3064 struct id_map *map;
3065 struct lxc_list *it;
3066 unsigned int freeid = 0;
3067
3068 again:
3069 lxc_list_for_each (it, &conf->id_map) {
3070 map = it->elem;
3071 if (map->idtype != idtype)
3072 continue;
3073
3074 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
3075 freeid = map->nsid + map->range;
3076 goto again;
3077 }
3078 }
3079
3080 return freeid;
3081 }
3082
3083 int chown_mapped_root_exec_wrapper(void *args)
3084 {
3085 execvp("lxc-usernsexec", args);
3086 return -1;
3087 }
3088
3089 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3090 * chown a dir to subuid/subgid Y, he needs to run chown as root
3091 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3092 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3093 * root is privileged with respect to hostuid/hostgid X, allowing
3094 * him to do the chown.
3095 */
3096 int chown_mapped_root(const char *path, struct lxc_conf *conf)
3097 {
3098 uid_t rootuid, rootgid;
3099 unsigned long val;
3100 int hostuid, hostgid, ret;
3101 struct stat sb;
3102 char map1[100], map2[100], map3[100], map4[100], map5[100];
3103 char ugid[100];
3104 const char *args1[] = {"lxc-usernsexec",
3105 "-m", map1,
3106 "-m", map2,
3107 "-m", map3,
3108 "-m", map5,
3109 "--", "chown", ugid, path,
3110 NULL};
3111 const char *args2[] = {"lxc-usernsexec",
3112 "-m", map1,
3113 "-m", map2,
3114 "-m", map3,
3115 "-m", map4,
3116 "-m", map5,
3117 "--", "chown", ugid, path,
3118 NULL};
3119 char cmd_output[PATH_MAX];
3120
3121 hostuid = geteuid();
3122 hostgid = getegid();
3123
3124 if (!get_mapped_rootid(conf, ID_TYPE_UID, &val)) {
3125 ERROR("No uid mapping for container root");
3126 return -1;
3127 }
3128 rootuid = (uid_t)val;
3129
3130 if (!get_mapped_rootid(conf, ID_TYPE_GID, &val)) {
3131 ERROR("No gid mapping for container root");
3132 return -1;
3133 }
3134 rootgid = (gid_t)val;
3135
3136 if (hostuid == 0) {
3137 if (chown(path, rootuid, rootgid) < 0) {
3138 ERROR("Error chowning %s", path);
3139 return -1;
3140 }
3141
3142 return 0;
3143 }
3144
3145 if (rootuid == hostuid) {
3146 /* nothing to do */
3147 INFO("Container root is our uid; no need to chown");
3148 return 0;
3149 }
3150
3151 /* save the current gid of "path" */
3152 if (stat(path, &sb) < 0) {
3153 ERROR("Error stat %s", path);
3154 return -1;
3155 }
3156
3157 /* Update the path argument in case this was overlayfs. */
3158 args1[sizeof(args1) / sizeof(args1[0]) - 2] = path;
3159 args2[sizeof(args2) / sizeof(args2[0]) - 2] = path;
3160
3161 /*
3162 * A file has to be group-owned by a gid mapped into the
3163 * container, or the container won't be privileged over it.
3164 */
3165 DEBUG("trying to chown \"%s\" to %d", path, hostgid);
3166 if (sb.st_uid == hostuid &&
3167 mapped_hostid(sb.st_gid, conf, ID_TYPE_GID) < 0 &&
3168 chown(path, -1, hostgid) < 0) {
3169 ERROR("Failed chgrping %s", path);
3170 return -1;
3171 }
3172
3173 /* "u:0:rootuid:1" */
3174 ret = snprintf(map1, 100, "u:0:%d:1", rootuid);
3175 if (ret < 0 || ret >= 100) {
3176 ERROR("Error uid printing map string");
3177 return -1;
3178 }
3179
3180 /* "u:hostuid:hostuid:1" */
3181 ret = snprintf(map2, 100, "u:%d:%d:1", hostuid, hostuid);
3182 if (ret < 0 || ret >= 100) {
3183 ERROR("Error uid printing map string");
3184 return -1;
3185 }
3186
3187 /* "g:0:rootgid:1" */
3188 ret = snprintf(map3, 100, "g:0:%d:1", rootgid);
3189 if (ret < 0 || ret >= 100) {
3190 ERROR("Error gid printing map string");
3191 return -1;
3192 }
3193
3194 /* "g:pathgid:rootgid+pathgid:1" */
3195 ret = snprintf(map4, 100, "g:%d:%d:1", (gid_t)sb.st_gid,
3196 rootgid + (gid_t)sb.st_gid);
3197 if (ret < 0 || ret >= 100) {
3198 ERROR("Error gid printing map string");
3199 return -1;
3200 }
3201
3202 /* "g:hostgid:hostgid:1" */
3203 ret = snprintf(map5, 100, "g:%d:%d:1", hostgid, hostgid);
3204 if (ret < 0 || ret >= 100) {
3205 ERROR("Error gid printing map string");
3206 return -1;
3207 }
3208
3209 /* "0:pathgid" (chown) */
3210 ret = snprintf(ugid, 100, "0:%d", (gid_t)sb.st_gid);
3211 if (ret < 0 || ret >= 100) {
3212 ERROR("Error owner printing format string for chown");
3213 return -1;
3214 }
3215
3216 if (hostgid == sb.st_gid)
3217 ret = run_command(cmd_output, sizeof(cmd_output),
3218 chown_mapped_root_exec_wrapper,
3219 (void *)args1);
3220 else
3221 ret = run_command(cmd_output, sizeof(cmd_output),
3222 chown_mapped_root_exec_wrapper,
3223 (void *)args2);
3224 if (ret < 0)
3225 ERROR("lxc-usernsexec failed: %s", cmd_output);
3226
3227 return ret;
3228 }
3229
3230 /* NOTE: Must not be called from inside the container namespace! */
3231 int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
3232 {
3233 int mounted;
3234
3235 mounted = lxc_mount_proc_if_needed(conf->rootfs.path ? conf->rootfs.mount : "");
3236 if (mounted == -1) {
3237 SYSERROR("Failed to mount proc in the container");
3238 /* continue only if there is no rootfs */
3239 if (conf->rootfs.path)
3240 return -1;
3241 } else if (mounted == 1) {
3242 conf->tmp_umount_proc = true;
3243 }
3244
3245 return 0;
3246 }
3247
3248 void tmp_proc_unmount(struct lxc_conf *lxc_conf)
3249 {
3250 if (!lxc_conf->tmp_umount_proc)
3251 return;
3252
3253 (void)umount2("/proc", MNT_DETACH);
3254 lxc_conf->tmp_umount_proc = false;
3255 }
3256
3257 /* Walk /proc/mounts and change any shared entries to slave. */
3258 void remount_all_slave(void)
3259 {
3260 __do_free char *line = NULL;
3261 __do_fclose FILE *f = NULL;
3262 __do_close_prot_errno int memfd = -EBADF, mntinfo_fd = -EBADF;
3263 int ret;
3264 ssize_t copied;
3265 size_t len = 0;
3266
3267 mntinfo_fd = open("/proc/self/mountinfo", O_RDONLY | O_CLOEXEC);
3268 if (mntinfo_fd < 0) {
3269 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3270 return;
3271 }
3272
3273 memfd = memfd_create(".lxc_mountinfo", MFD_CLOEXEC);
3274 if (memfd < 0) {
3275 char template[] = P_tmpdir "/.lxc_mountinfo_XXXXXX";
3276
3277 if (errno != ENOSYS) {
3278 SYSERROR("Failed to create temporary in-memory file");
3279 return;
3280 }
3281
3282 memfd = lxc_make_tmpfile(template, true);
3283 if (memfd < 0) {
3284 WARN("Failed to create temporary file");
3285 return;
3286 }
3287 }
3288
3289 again:
3290 copied = lxc_sendfile_nointr(memfd, mntinfo_fd, NULL, LXC_SENDFILE_MAX);
3291 if (copied < 0) {
3292 if (errno == EINTR)
3293 goto again;
3294
3295 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3296 return;
3297 }
3298
3299 ret = lseek(memfd, 0, SEEK_SET);
3300 if (ret < 0) {
3301 SYSERROR("Failed to reset file descriptor offset");
3302 return;
3303 }
3304
3305 f = fdopen(memfd, "r");
3306 if (!f) {
3307 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3308 return;
3309 }
3310
3311 /*
3312 * After a successful fdopen() memfd will be closed when calling
3313 * fclose(f). Calling close(memfd) afterwards is undefined.
3314 */
3315 move_fd(memfd);
3316
3317 while (getline(&line, &len, f) != -1) {
3318 char *opts, *target;
3319
3320 target = get_field(line, 4);
3321 if (!target)
3322 continue;
3323
3324 opts = get_field(target, 2);
3325 if (!opts)
3326 continue;
3327
3328 null_endofword(opts);
3329 if (!strstr(opts, "shared"))
3330 continue;
3331
3332 null_endofword(target);
3333 ret = mount(NULL, target, NULL, MS_SLAVE, NULL);
3334 if (ret < 0) {
3335 SYSERROR("Failed to make \"%s\" MS_SLAVE", target);
3336 ERROR("Continuing...");
3337 continue;
3338 }
3339 TRACE("Remounted \"%s\" as MS_SLAVE", target);
3340 }
3341 TRACE("Remounted all mount table entries as MS_SLAVE");
3342 }
3343
3344 static int lxc_execute_bind_init(struct lxc_handler *handler)
3345 {
3346 int ret;
3347 char *p;
3348 char path[PATH_MAX], destpath[PATH_MAX];
3349 struct lxc_conf *conf = handler->conf;
3350
3351 /* If init exists in the container, don't bind mount a static one */
3352 p = choose_init(conf->rootfs.mount);
3353 if (p) {
3354 __do_free char *old = p;
3355
3356 p = strdup(old + strlen(conf->rootfs.mount));
3357 if (!p)
3358 return -ENOMEM;
3359
3360 INFO("Found existing init at \"%s\"", p);
3361 goto out;
3362 }
3363
3364 ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static");
3365 if (ret < 0 || ret >= PATH_MAX)
3366 return -1;
3367
3368 if (!file_exists(path)) {
3369 ERROR("The file \"%s\" does not exist on host", path);
3370 return -1;
3371 }
3372
3373 ret = snprintf(destpath, PATH_MAX, "%s" P_tmpdir "%s", conf->rootfs.mount, "/.lxc-init");
3374 if (ret < 0 || ret >= PATH_MAX)
3375 return -1;
3376
3377 if (!file_exists(destpath)) {
3378 ret = mknod(destpath, S_IFREG | 0000, 0);
3379 if (ret < 0 && errno != EEXIST) {
3380 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath);
3381 return -1;
3382 }
3383 }
3384
3385 ret = safe_mount(path, destpath, "none", MS_BIND, NULL, conf->rootfs.mount);
3386 if (ret < 0) {
3387 SYSERROR("Failed to bind mount lxc.init.static into container");
3388 return -1;
3389 }
3390
3391 p = strdup(destpath + strlen(conf->rootfs.mount));
3392 if (!p)
3393 return -ENOMEM;
3394
3395 INFO("Bind mounted lxc.init.static into container at \"%s\"", path);
3396 out:
3397 ((struct execute_args *)handler->data)->init_fd = -1;
3398 ((struct execute_args *)handler->data)->init_path = p;
3399 return 0;
3400 }
3401
3402 /* This does the work of remounting / if it is shared, calling the container
3403 * pre-mount hooks, and mounting the rootfs.
3404 */
3405 int lxc_setup_rootfs_prepare_root(struct lxc_conf *conf, const char *name,
3406 const char *lxcpath)
3407 {
3408 int ret;
3409
3410 if (conf->rootfs_setup) {
3411 const char *path = conf->rootfs.mount;
3412
3413 /* The rootfs was set up in another namespace. bind-mount it to
3414 * give us a mount in our own ns so we can pivot_root to it
3415 */
3416 ret = mount(path, path, "rootfs", MS_BIND, NULL);
3417 if (ret < 0) {
3418 ERROR("Failed to bind mount container / onto itself");
3419 return -1;
3420 }
3421
3422 TRACE("Bind mounted container / onto itself");
3423 return 0;
3424 }
3425
3426 remount_all_slave();
3427
3428 ret = run_lxc_hooks(name, "pre-mount", conf, NULL);
3429 if (ret < 0) {
3430 ERROR("Failed to run pre-mount hooks");
3431 return -1;
3432 }
3433
3434 ret = lxc_mount_rootfs(conf);
3435 if (ret < 0) {
3436 ERROR("Failed to setup rootfs for");
3437 return -1;
3438 }
3439
3440 conf->rootfs_setup = true;
3441 return 0;
3442 }
3443
3444 static bool verify_start_hooks(struct lxc_conf *conf)
3445 {
3446 char path[PATH_MAX];
3447 struct lxc_list *it;
3448
3449 lxc_list_for_each (it, &conf->hooks[LXCHOOK_START]) {
3450 int ret;
3451 char *hookname = it->elem;
3452
3453 ret = snprintf(path, PATH_MAX, "%s%s",
3454 conf->rootfs.path ? conf->rootfs.mount : "",
3455 hookname);
3456 if (ret < 0 || ret >= PATH_MAX)
3457 return false;
3458
3459 ret = access(path, X_OK);
3460 if (ret < 0) {
3461 SYSERROR("Start hook \"%s\" not found in container",
3462 hookname);
3463 return false;
3464 }
3465
3466 return true;
3467 }
3468
3469 return true;
3470 }
3471
3472 static bool execveat_supported(void)
3473 {
3474 lxc_raw_execveat(-1, "", NULL, NULL, AT_EMPTY_PATH);
3475 if (errno == ENOSYS)
3476 return false;
3477
3478 return true;
3479 }
3480
3481 static int lxc_setup_boot_id(void)
3482 {
3483 int ret;
3484 const char *boot_id_path = "/proc/sys/kernel/random/boot_id";
3485 const char *mock_boot_id_path = "/dev/.lxc-boot-id";
3486 lxc_id128_t n;
3487
3488 if (access(boot_id_path, F_OK))
3489 return 0;
3490
3491 memset(&n, 0, sizeof(n));
3492 if (lxc_id128_randomize(&n)) {
3493 SYSERROR("Failed to generate random data for uuid");
3494 return -1;
3495 }
3496
3497 ret = lxc_id128_write(mock_boot_id_path, n);
3498 if (ret < 0) {
3499 SYSERROR("Failed to write uuid to %s", mock_boot_id_path);
3500 return -1;
3501 }
3502
3503 ret = chmod(mock_boot_id_path, 0444);
3504 if (ret < 0) {
3505 SYSERROR("Failed to chown %s", mock_boot_id_path);
3506 (void)unlink(mock_boot_id_path);
3507 return -1;
3508 }
3509
3510 ret = mount(mock_boot_id_path, boot_id_path, NULL, MS_BIND, NULL);
3511 if (ret < 0) {
3512 SYSERROR("Failed to mount %s to %s", mock_boot_id_path,
3513 boot_id_path);
3514 (void)unlink(mock_boot_id_path);
3515 return -1;
3516 }
3517
3518 ret = mount(NULL, boot_id_path, NULL,
3519 (MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NOEXEC |
3520 MS_NODEV),
3521 NULL);
3522 if (ret < 0) {
3523 SYSERROR("Failed to remount %s read-only", boot_id_path);
3524 (void)unlink(mock_boot_id_path);
3525 return -1;
3526 }
3527
3528 return 0;
3529 }
3530
3531 int lxc_setup(struct lxc_handler *handler)
3532 {
3533 int ret;
3534 const char *lxcpath = handler->lxcpath, *name = handler->name;
3535 struct lxc_conf *lxc_conf = handler->conf;
3536
3537 ret = lxc_setup_rootfs_prepare_root(lxc_conf, name, lxcpath);
3538 if (ret < 0) {
3539 ERROR("Failed to setup rootfs");
3540 return -1;
3541 }
3542
3543 if (handler->nsfd[LXC_NS_UTS] == -1) {
3544 ret = setup_utsname(lxc_conf->utsname);
3545 if (ret < 0) {
3546 ERROR("Failed to setup the utsname %s", name);
3547 return -1;
3548 }
3549 }
3550
3551 ret = lxc_setup_keyring();
3552 if (ret < 0)
3553 return -1;
3554
3555 if (handler->ns_clone_flags & CLONE_NEWNET) {
3556 ret = lxc_setup_network_in_child_namespaces(lxc_conf,
3557 &lxc_conf->network);
3558 if (ret < 0) {
3559 ERROR("Failed to setup network");
3560 return -1;
3561 }
3562
3563 ret = lxc_network_send_name_and_ifindex_to_parent(handler);
3564 if (ret < 0) {
3565 ERROR("Failed to send network device names and ifindices to parent");
3566 return -1;
3567 }
3568 }
3569
3570 if (lxc_conf->autodev > 0) {
3571 ret = mount_autodev(name, &lxc_conf->rootfs, lxc_conf->autodevtmpfssize, lxcpath);
3572 if (ret < 0) {
3573 ERROR("Failed to mount \"/dev\"");
3574 return -1;
3575 }
3576 }
3577
3578 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3579 * need to wait until other stuff has finished.
3580 */
3581 ret = lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler);
3582 if (ret < 0) {
3583 ERROR("Failed to setup first automatic mounts");
3584 return -1;
3585 }
3586
3587 ret = setup_mount(lxc_conf, &lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath);
3588 if (ret < 0) {
3589 ERROR("Failed to setup mounts");
3590 return -1;
3591 }
3592
3593 if (!lxc_list_empty(&lxc_conf->mount_list)) {
3594 ret = setup_mount_entries(lxc_conf, &lxc_conf->rootfs,
3595 &lxc_conf->mount_list, name, lxcpath);
3596 if (ret < 0) {
3597 ERROR("Failed to setup mount entries");
3598 return -1;
3599 }
3600 }
3601
3602 if (lxc_conf->is_execute) {
3603 if (execveat_supported()) {
3604 int fd;
3605 char path[PATH_MAX];
3606
3607 ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static");
3608 if (ret < 0 || ret >= PATH_MAX) {
3609 ERROR("Path to init.lxc.static too long");
3610 return -1;
3611 }
3612
3613 fd = open(path, O_PATH | O_CLOEXEC);
3614 if (fd < 0) {
3615 SYSERROR("Unable to open lxc.init.static");
3616 return -1;
3617 }
3618
3619 ((struct execute_args *)handler->data)->init_fd = fd;
3620 ((struct execute_args *)handler->data)->init_path = NULL;
3621 } else {
3622 ret = lxc_execute_bind_init(handler);
3623 if (ret < 0) {
3624 ERROR("Failed to bind-mount the lxc init system");
3625 return -1;
3626 }
3627 }
3628 }
3629
3630 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3631 * mounted. It is guaranteed to be mounted now either through
3632 * automatically or via fstab entries.
3633 */
3634 ret = lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler);
3635 if (ret < 0) {
3636 ERROR("Failed to setup remaining automatic mounts");
3637 return -1;
3638 }
3639
3640 ret = run_lxc_hooks(name, "mount", lxc_conf, NULL);
3641 if (ret < 0) {
3642 ERROR("Failed to run mount hooks");
3643 return -1;
3644 }
3645
3646 if (lxc_conf->autodev > 0) {
3647 ret = run_lxc_hooks(name, "autodev", lxc_conf, NULL);
3648 if (ret < 0) {
3649 ERROR("Failed to run autodev hooks");
3650 return -1;
3651 }
3652
3653 ret = lxc_fill_autodev(&lxc_conf->rootfs);
3654 if (ret < 0) {
3655 ERROR("Failed to populate \"/dev\"");
3656 return -1;
3657 }
3658 }
3659
3660 /* Make sure any start hooks are in the container */
3661 if (!verify_start_hooks(lxc_conf)) {
3662 ERROR("Failed to verify start hooks");
3663 return -1;
3664 }
3665
3666 ret = lxc_setup_console(&lxc_conf->rootfs, &lxc_conf->console,
3667 lxc_conf->ttys.dir);
3668 if (ret < 0) {
3669 ERROR("Failed to setup console");
3670 return -1;
3671 }
3672
3673 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
3674 if (ret < 0) {
3675 ERROR("Failed to setup \"/dev\" symlinks");
3676 return -1;
3677 }
3678
3679 ret = lxc_create_tmp_proc_mount(lxc_conf);
3680 if (ret < 0) {
3681 ERROR("Failed to \"/proc\" LSMs");
3682 return -1;
3683 }
3684
3685 ret = lxc_setup_rootfs_switch_root(&lxc_conf->rootfs);
3686 if (ret < 0) {
3687 ERROR("Failed to pivot root into rootfs");
3688 return -1;
3689 }
3690
3691 /* Setting the boot-id is best-effort for now. */
3692 if (lxc_conf->autodev > 0)
3693 (void)lxc_setup_boot_id();
3694
3695 ret = lxc_setup_devpts(lxc_conf);
3696 if (ret < 0) {
3697 ERROR("Failed to setup new devpts instance");
3698 return -1;
3699 }
3700
3701 ret = lxc_create_ttys(handler);
3702 if (ret < 0)
3703 return -1;
3704
3705 ret = setup_personality(lxc_conf->personality);
3706 if (ret < 0) {
3707 ERROR("Failed to set personality");
3708 return -1;
3709 }
3710
3711 /* Set sysctl value to a path under /proc/sys as determined from the
3712 * key. For e.g. net.ipv4.ip_forward translated to
3713 * /proc/sys/net/ipv4/ip_forward.
3714 */
3715 if (!lxc_list_empty(&lxc_conf->sysctls)) {
3716 ret = setup_sysctl_parameters(&lxc_conf->sysctls);
3717 if (ret < 0) {
3718 ERROR("Failed to setup sysctl parameters");
3719 return -1;
3720 }
3721 }
3722
3723 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
3724 if (!lxc_list_empty(&lxc_conf->caps)) {
3725 ERROR("Container requests lxc.cap.drop and "
3726 "lxc.cap.keep: either use lxc.cap.drop or "
3727 "lxc.cap.keep, not both");
3728 return -1;
3729 }
3730
3731 if (dropcaps_except(&lxc_conf->keepcaps)) {
3732 ERROR("Failed to keep capabilities");
3733 return -1;
3734 }
3735 } else if (setup_caps(&lxc_conf->caps)) {
3736 ERROR("Failed to drop capabilities");
3737 return -1;
3738 }
3739
3740 NOTICE("The container \"%s\" is set up", name);
3741
3742 return 0;
3743 }
3744
3745 int run_lxc_hooks(const char *name, char *hookname, struct lxc_conf *conf,
3746 char *argv[])
3747 {
3748 struct lxc_list *it;
3749 int which;
3750
3751 for (which = 0; which < NUM_LXC_HOOKS; which ++) {
3752 if (strcmp(hookname, lxchook_names[which]) == 0)
3753 break;
3754 }
3755
3756 if (which >= NUM_LXC_HOOKS)
3757 return -1;
3758
3759 lxc_list_for_each (it, &conf->hooks[which]) {
3760 int ret;
3761 char *hook = it->elem;
3762
3763 ret = run_script_argv(name, conf->hooks_version, "lxc", hook,
3764 hookname, argv);
3765 if (ret < 0)
3766 return -1;
3767 }
3768
3769 return 0;
3770 }
3771
3772 int lxc_clear_config_caps(struct lxc_conf *c)
3773 {
3774 struct lxc_list *it, *next;
3775
3776 lxc_list_for_each_safe (it, &c->caps, next) {
3777 lxc_list_del(it);
3778 free(it->elem);
3779 free(it);
3780 }
3781
3782 return 0;
3783 }
3784
3785 static int lxc_free_idmap(struct lxc_list *id_map)
3786 {
3787 struct lxc_list *it, *next;
3788
3789 lxc_list_for_each_safe (it, id_map, next) {
3790 lxc_list_del(it);
3791 free(it->elem);
3792 free(it);
3793 }
3794
3795 return 0;
3796 }
3797
3798 int lxc_clear_idmaps(struct lxc_conf *c)
3799 {
3800 return lxc_free_idmap(&c->id_map);
3801 }
3802
3803 int lxc_clear_config_keepcaps(struct lxc_conf *c)
3804 {
3805 struct lxc_list *it, *next;
3806
3807 lxc_list_for_each_safe (it, &c->keepcaps, next) {
3808 lxc_list_del(it);
3809 free(it->elem);
3810 free(it);
3811 }
3812
3813 return 0;
3814 }
3815
3816 int lxc_clear_namespace(struct lxc_conf *c)
3817 {
3818 int i;
3819 for (i = 0; i < LXC_NS_MAX; i++) {
3820 free(c->ns_share[i]);
3821 c->ns_share[i] = NULL;
3822 }
3823 return 0;
3824 }
3825
3826 int lxc_clear_cgroups(struct lxc_conf *c, const char *key, int version)
3827 {
3828 char *global_token, *namespaced_token;
3829 size_t namespaced_token_len;
3830 struct lxc_list *it, *next, *list;
3831 const char *k = key;
3832 bool all = false;
3833
3834 if (version == CGROUP2_SUPER_MAGIC) {
3835 global_token = "lxc.cgroup2";
3836 namespaced_token = "lxc.cgroup2.";
3837 namespaced_token_len = STRLITERALLEN("lxc.cgroup2.");
3838 list = &c->cgroup2;
3839 } else if (version == CGROUP_SUPER_MAGIC) {
3840 global_token = "lxc.cgroup";
3841 namespaced_token = "lxc.cgroup.";
3842 namespaced_token_len = STRLITERALLEN("lxc.cgroup.");
3843 list = &c->cgroup;
3844 } else {
3845 return -EINVAL;
3846 }
3847
3848 if (strcmp(key, global_token) == 0)
3849 all = true;
3850 else if (strncmp(key, namespaced_token, namespaced_token_len) == 0)
3851 k += namespaced_token_len;
3852 else
3853 return -EINVAL;
3854
3855 lxc_list_for_each_safe (it, list, next) {
3856 struct lxc_cgroup *cg = it->elem;
3857
3858 if (!all && strcmp(cg->subsystem, k) != 0)
3859 continue;
3860
3861 lxc_list_del(it);
3862 free(cg->subsystem);
3863 free(cg->value);
3864 free(cg);
3865 free(it);
3866 }
3867
3868 return 0;
3869 }
3870
3871 static void lxc_clear_devices(struct lxc_conf *conf)
3872 {
3873 struct lxc_list *list = &conf->devices;
3874 struct lxc_list *it, *next;
3875
3876 lxc_list_for_each_safe(it, list, next) {
3877 lxc_list_del(it);
3878 free(it);
3879 }
3880 }
3881
3882 int lxc_clear_limits(struct lxc_conf *c, const char *key)
3883 {
3884 struct lxc_list *it, *next;
3885 const char *k = NULL;
3886 bool all = false;
3887
3888 if (strcmp(key, "lxc.limit") == 0 || strcmp(key, "lxc.prlimit") == 0)
3889 all = true;
3890 else if (strncmp(key, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3891 k = key + STRLITERALLEN("lxc.limit.");
3892 else if (strncmp(key, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3893 k = key + STRLITERALLEN("lxc.prlimit.");
3894 else
3895 return -1;
3896
3897 lxc_list_for_each_safe (it, &c->limits, next) {
3898 struct lxc_limit *lim = it->elem;
3899
3900 if (!all && strcmp(lim->resource, k) != 0)
3901 continue;
3902
3903 lxc_list_del(it);
3904 free(lim->resource);
3905 free(lim);
3906 free(it);
3907 }
3908
3909 return 0;
3910 }
3911
3912 int lxc_clear_sysctls(struct lxc_conf *c, const char *key)
3913 {
3914 struct lxc_list *it, *next;
3915 const char *k = NULL;
3916 bool all = false;
3917
3918 if (strcmp(key, "lxc.sysctl") == 0)
3919 all = true;
3920 else if (strncmp(key, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3921 k = key + STRLITERALLEN("lxc.sysctl.");
3922 else
3923 return -1;
3924
3925 lxc_list_for_each_safe (it, &c->sysctls, next) {
3926 struct lxc_sysctl *elem = it->elem;
3927
3928 if (!all && strcmp(elem->key, k) != 0)
3929 continue;
3930
3931 lxc_list_del(it);
3932 free(elem->key);
3933 free(elem->value);
3934 free(elem);
3935 free(it);
3936 }
3937
3938 return 0;
3939 }
3940
3941 int lxc_clear_procs(struct lxc_conf *c, const char *key)
3942 {
3943 struct lxc_list *it, *next;
3944 const char *k = NULL;
3945 bool all = false;
3946
3947 if (strcmp(key, "lxc.proc") == 0)
3948 all = true;
3949 else if (strncmp(key, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3950 k = key + STRLITERALLEN("lxc.proc.");
3951 else
3952 return -1;
3953
3954 lxc_list_for_each_safe (it, &c->procs, next) {
3955 struct lxc_proc *proc = it->elem;
3956
3957 if (!all && strcmp(proc->filename, k) != 0)
3958 continue;
3959
3960 lxc_list_del(it);
3961 free(proc->filename);
3962 free(proc->value);
3963 free(proc);
3964 free(it);
3965 }
3966
3967 return 0;
3968 }
3969
3970 int lxc_clear_groups(struct lxc_conf *c)
3971 {
3972 struct lxc_list *it, *next;
3973
3974 lxc_list_for_each_safe (it, &c->groups, next) {
3975 lxc_list_del(it);
3976 free(it->elem);
3977 free(it);
3978 }
3979
3980 return 0;
3981 }
3982
3983 int lxc_clear_environment(struct lxc_conf *c)
3984 {
3985 struct lxc_list *it, *next;
3986
3987 lxc_list_for_each_safe (it, &c->environment, next) {
3988 lxc_list_del(it);
3989 free(it->elem);
3990 free(it);
3991 }
3992
3993 return 0;
3994 }
3995
3996 int lxc_clear_mount_entries(struct lxc_conf *c)
3997 {
3998 struct lxc_list *it, *next;
3999
4000 lxc_list_for_each_safe (it, &c->mount_list, next) {
4001 lxc_list_del(it);
4002 free(it->elem);
4003 free(it);
4004 }
4005
4006 return 0;
4007 }
4008
4009 int lxc_clear_automounts(struct lxc_conf *c)
4010 {
4011 c->auto_mounts = 0;
4012 return 0;
4013 }
4014
4015 int lxc_clear_hooks(struct lxc_conf *c, const char *key)
4016 {
4017 int i;
4018 struct lxc_list *it, *next;
4019 const char *k = NULL;
4020 bool all = false, done = false;
4021
4022 if (strcmp(key, "lxc.hook") == 0)
4023 all = true;
4024 else if (strncmp(key, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
4025 k = key + STRLITERALLEN("lxc.hook.");
4026 else
4027 return -1;
4028
4029 for (i = 0; i < NUM_LXC_HOOKS; i++) {
4030 if (all || strcmp(k, lxchook_names[i]) == 0) {
4031 lxc_list_for_each_safe (it, &c->hooks[i], next) {
4032 lxc_list_del(it);
4033 free(it->elem);
4034 free(it);
4035 }
4036
4037 done = true;
4038 }
4039 }
4040
4041 if (!done) {
4042 ERROR("Invalid hook key: %s", key);
4043 return -1;
4044 }
4045
4046 return 0;
4047 }
4048
4049 static inline void lxc_clear_aliens(struct lxc_conf *conf)
4050 {
4051 struct lxc_list *it, *next;
4052
4053 lxc_list_for_each_safe (it, &conf->aliens, next) {
4054 lxc_list_del(it);
4055 free(it->elem);
4056 free(it);
4057 }
4058 }
4059
4060 void lxc_clear_includes(struct lxc_conf *conf)
4061 {
4062 struct lxc_list *it, *next;
4063
4064 lxc_list_for_each_safe (it, &conf->includes, next) {
4065 lxc_list_del(it);
4066 free(it->elem);
4067 free(it);
4068 }
4069 }
4070
4071 int lxc_clear_apparmor_raw(struct lxc_conf *c)
4072 {
4073 struct lxc_list *it, *next;
4074
4075 lxc_list_for_each_safe (it, &c->lsm_aa_raw, next) {
4076 lxc_list_del(it);
4077 free(it->elem);
4078 free(it);
4079 }
4080
4081 return 0;
4082 }
4083
4084 void lxc_conf_free(struct lxc_conf *conf)
4085 {
4086 if (!conf)
4087 return;
4088
4089 if (current_config == conf)
4090 current_config = NULL;
4091 lxc_terminal_conf_free(&conf->console);
4092 free(conf->rootfs.mount);
4093 free(conf->rootfs.bdev_type);
4094 free(conf->rootfs.options);
4095 free(conf->rootfs.path);
4096 free(conf->rootfs.data);
4097 free(conf->logfile);
4098 if (conf->logfd != -1)
4099 close(conf->logfd);
4100 free(conf->utsname);
4101 free(conf->ttys.dir);
4102 free(conf->ttys.tty_names);
4103 free(conf->fstab);
4104 free(conf->rcfile);
4105 free(conf->execute_cmd);
4106 free(conf->init_cmd);
4107 free(conf->init_cwd);
4108 free(conf->unexpanded_config);
4109 free(conf->syslog);
4110 lxc_free_networks(&conf->network);
4111 free(conf->lsm_aa_profile);
4112 free(conf->lsm_aa_profile_computed);
4113 free(conf->lsm_se_context);
4114 lxc_seccomp_free(&conf->seccomp);
4115 lxc_clear_config_caps(conf);
4116 lxc_clear_config_keepcaps(conf);
4117 lxc_clear_cgroups(conf, "lxc.cgroup", CGROUP_SUPER_MAGIC);
4118 lxc_clear_cgroups(conf, "lxc.cgroup2", CGROUP2_SUPER_MAGIC);
4119 lxc_clear_devices(conf);
4120 lxc_clear_cgroup2_devices(conf);
4121 lxc_clear_hooks(conf, "lxc.hook");
4122 lxc_clear_mount_entries(conf);
4123 lxc_clear_idmaps(conf);
4124 lxc_clear_groups(conf);
4125 lxc_clear_includes(conf);
4126 lxc_clear_aliens(conf);
4127 lxc_clear_environment(conf);
4128 lxc_clear_limits(conf, "lxc.prlimit");
4129 lxc_clear_sysctls(conf, "lxc.sysctl");
4130 lxc_clear_procs(conf, "lxc.proc");
4131 lxc_clear_apparmor_raw(conf);
4132 lxc_clear_namespace(conf);
4133 free(conf->cgroup_meta.dir);
4134 free(conf->cgroup_meta.controllers);
4135 free(conf->shmount.path_host);
4136 free(conf->shmount.path_cont);
4137 free(conf);
4138 }
4139
4140 struct userns_fn_data {
4141 int (*fn)(void *);
4142 const char *fn_name;
4143 void *arg;
4144 int p[2];
4145 };
4146
4147 static int run_userns_fn(void *data)
4148 {
4149 int ret;
4150 char c;
4151 struct userns_fn_data *d = data;
4152
4153 /* Close write end of the pipe. */
4154 close(d->p[1]);
4155
4156 /* Wait for parent to finish establishing a new mapping in the user
4157 * namespace we are executing in.
4158 */
4159 ret = lxc_read_nointr(d->p[0], &c, 1);
4160 /* Close read end of the pipe. */
4161 close(d->p[0]);
4162 if (ret != 1)
4163 return -1;
4164
4165 if (d->fn_name)
4166 TRACE("Calling function \"%s\"", d->fn_name);
4167
4168 /* Call function to run. */
4169 return d->fn(d->arg);
4170 }
4171
4172 static struct id_map *mapped_nsid_add(struct lxc_conf *conf, unsigned id,
4173 enum idtype idtype)
4174 {
4175 const struct id_map *map;
4176 struct id_map *retmap;
4177
4178 map = find_mapped_nsid_entry(conf, id, idtype);
4179 if (!map)
4180 return NULL;
4181
4182 retmap = malloc(sizeof(*retmap));
4183 if (!retmap)
4184 return NULL;
4185
4186 memcpy(retmap, map, sizeof(*retmap));
4187 return retmap;
4188 }
4189
4190 static struct id_map *find_mapped_hostid_entry(struct lxc_conf *conf,
4191 unsigned id, enum idtype idtype)
4192 {
4193 struct id_map *map;
4194 struct lxc_list *it;
4195 struct id_map *retmap = NULL;
4196
4197 lxc_list_for_each (it, &conf->id_map) {
4198 map = it->elem;
4199 if (map->idtype != idtype)
4200 continue;
4201
4202 if (id >= map->hostid && id < map->hostid + map->range) {
4203 retmap = map;
4204 break;
4205 }
4206 }
4207
4208 return retmap;
4209 }
4210
4211 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4212 * existing one or establish a new one.
4213 */
4214 static struct id_map *mapped_hostid_add(struct lxc_conf *conf, uid_t id,
4215 enum idtype type)
4216 {
4217 int hostid_mapped;
4218 struct id_map *entry = NULL, *tmp = NULL;
4219
4220 entry = malloc(sizeof(*entry));
4221 if (!entry)
4222 return NULL;
4223
4224 /* Reuse existing mapping. */
4225 tmp = find_mapped_hostid_entry(conf, id, type);
4226 if (tmp)
4227 return memcpy(entry, tmp, sizeof(*entry));
4228
4229 /* Find new mapping. */
4230 hostid_mapped = find_unmapped_nsid(conf, type);
4231 if (hostid_mapped < 0) {
4232 DEBUG("Failed to find free mapping for id %d", id);
4233 free(entry);
4234 return NULL;
4235 }
4236
4237 entry->idtype = type;
4238 entry->nsid = hostid_mapped;
4239 entry->hostid = (unsigned long)id;
4240 entry->range = 1;
4241
4242 return entry;
4243 }
4244
4245 struct lxc_list *get_minimal_idmap(struct lxc_conf *conf)
4246 {
4247 __do_free struct id_map *container_root_uid = NULL,
4248 *container_root_gid = NULL,
4249 *host_uid_map = NULL, *host_gid_map = NULL;
4250 __do_free struct lxc_list *idmap = NULL;
4251 uid_t euid, egid;
4252 uid_t nsuid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
4253 gid_t nsgid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
4254 struct lxc_list *tmplist = NULL;
4255
4256 /* Find container root mappings. */
4257 container_root_uid = mapped_nsid_add(conf, nsuid, ID_TYPE_UID);
4258 if (!container_root_uid) {
4259 DEBUG("Failed to find mapping for namespace uid %d", 0);
4260 return NULL;
4261 }
4262 euid = geteuid();
4263 if (euid >= container_root_uid->hostid &&
4264 euid < (container_root_uid->hostid + container_root_uid->range))
4265 host_uid_map = container_root_uid;
4266
4267 container_root_gid = mapped_nsid_add(conf, nsgid, ID_TYPE_GID);
4268 if (!container_root_gid) {
4269 DEBUG("Failed to find mapping for namespace gid %d", 0);
4270 return NULL;
4271 }
4272 egid = getegid();
4273 if (egid >= container_root_gid->hostid &&
4274 egid < (container_root_gid->hostid + container_root_gid->range))
4275 host_gid_map = container_root_gid;
4276
4277 /* Check whether the {g,u}id of the user has a mapping. */
4278 if (!host_uid_map)
4279 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
4280 if (!host_uid_map) {
4281 DEBUG("Failed to find mapping for uid %d", euid);
4282 return NULL;
4283 }
4284
4285 if (!host_gid_map)
4286 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
4287 if (!host_gid_map) {
4288 DEBUG("Failed to find mapping for gid %d", egid);
4289 return NULL;
4290 }
4291
4292 /* Allocate new {g,u}id map list. */
4293 idmap = malloc(sizeof(*idmap));
4294 if (!idmap)
4295 return NULL;
4296 lxc_list_init(idmap);
4297
4298 /* Add container root to the map. */
4299 tmplist = malloc(sizeof(*tmplist));
4300 if (!tmplist)
4301 return NULL;
4302 lxc_list_add_elem(tmplist, container_root_uid);
4303 lxc_list_add_tail(idmap, tmplist);
4304
4305 if (host_uid_map && (host_uid_map != container_root_uid)) {
4306 /* idmap will now keep track of that memory. */
4307 move_ptr(container_root_uid);
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, host_uid_map);
4314 lxc_list_add_tail(idmap, tmplist);
4315 }
4316 /* idmap will now keep track of that memory. */
4317 move_ptr(container_root_uid);
4318 /* idmap will now keep track of that memory. */
4319 move_ptr(host_uid_map);
4320
4321 tmplist = malloc(sizeof(*tmplist));
4322 if (!tmplist)
4323 return NULL;
4324 lxc_list_add_elem(tmplist, container_root_gid);
4325 lxc_list_add_tail(idmap, tmplist);
4326
4327 if (host_gid_map && (host_gid_map != container_root_gid)) {
4328 /* idmap will now keep track of that memory. */
4329 move_ptr(container_root_gid);
4330
4331 tmplist = malloc(sizeof(*tmplist));
4332 if (!tmplist)
4333 return NULL;
4334 lxc_list_add_elem(tmplist, host_gid_map);
4335 lxc_list_add_tail(idmap, tmplist);
4336 }
4337 /* idmap will now keep track of that memory. */
4338 move_ptr(container_root_gid);
4339 /* idmap will now keep track of that memory. */
4340 move_ptr(host_gid_map);
4341
4342 TRACE("Allocated minimal idmapping");
4343 return move_ptr(idmap);
4344 }
4345
4346 /* Run a function in a new user namespace.
4347 * The caller's euid/egid will be mapped if it is not already.
4348 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4349 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4350 * This means we require only to establish a mapping from:
4351 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4352 * - the container root -> some sub{g,u}id
4353 * The former we add, if the user did not specify a mapping. The latter we
4354 * retrieve from the container's configured {g,u}id mappings as it must have been
4355 * there to start the container in the first place.
4356 */
4357 int userns_exec_1(struct lxc_conf *conf, int (*fn)(void *), void *data,
4358 const char *fn_name)
4359 {
4360 pid_t pid;
4361 int p[2];
4362 struct userns_fn_data d;
4363 struct lxc_list *idmap;
4364 int ret = -1, status = -1;
4365 char c = '1';
4366
4367 if (!conf)
4368 return -EINVAL;
4369
4370 idmap = get_minimal_idmap(conf);
4371 if (!idmap)
4372 return -1;
4373
4374 ret = pipe2(p, O_CLOEXEC);
4375 if (ret < 0) {
4376 SYSERROR("Failed to create pipe");
4377 return -1;
4378 }
4379 d.fn = fn;
4380 d.fn_name = fn_name;
4381 d.arg = data;
4382 d.p[0] = p[0];
4383 d.p[1] = p[1];
4384
4385 /* Clone child in new user namespace. */
4386 pid = lxc_raw_clone_cb(run_userns_fn, &d, CLONE_NEWUSER, NULL);
4387 if (pid < 0) {
4388 ERROR("Failed to clone process in new user namespace");
4389 goto on_error;
4390 }
4391
4392 close(p[0]);
4393 p[0] = -1;
4394
4395 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
4396 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
4397 struct id_map *map;
4398 struct lxc_list *it;
4399
4400 lxc_list_for_each (it, idmap) {
4401 map = it->elem;
4402 TRACE("Establishing %cid mapping for \"%d\" in new "
4403 "user namespace: nsuid %lu - hostid %lu - range "
4404 "%lu",
4405 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
4406 map->nsid, map->hostid, map->range);
4407 }
4408 }
4409
4410 /* Set up {g,u}id mapping for user namespace of child process. */
4411 ret = lxc_map_ids(idmap, pid);
4412 if (ret < 0) {
4413 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
4414 goto on_error;
4415 }
4416
4417 /* Tell child to proceed. */
4418 if (lxc_write_nointr(p[1], &c, 1) != 1) {
4419 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
4420 goto on_error;
4421 }
4422
4423 on_error:
4424 if (p[0] != -1)
4425 close(p[0]);
4426 close(p[1]);
4427
4428 /* Wait for child to finish. */
4429 if (pid > 0)
4430 status = wait_for_pid(pid);
4431
4432 if (status < 0)
4433 ret = -1;
4434
4435 return ret;
4436 }
4437
4438 int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
4439 const char *fn_name)
4440 {
4441 pid_t pid;
4442 uid_t euid, egid;
4443 int p[2];
4444 struct id_map *map;
4445 struct lxc_list *cur;
4446 struct userns_fn_data d;
4447 int ret = -1;
4448 char c = '1';
4449 struct lxc_list *idmap = NULL, *tmplist = NULL;
4450 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
4451 *host_uid_map = NULL, *host_gid_map = NULL;
4452
4453 if (!conf)
4454 return -EINVAL;
4455
4456 ret = pipe2(p, O_CLOEXEC);
4457 if (ret < 0) {
4458 SYSERROR("opening pipe");
4459 return -1;
4460 }
4461 d.fn = fn;
4462 d.fn_name = fn_name;
4463 d.arg = data;
4464 d.p[0] = p[0];
4465 d.p[1] = p[1];
4466
4467 /* Clone child in new user namespace. */
4468 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER, NULL);
4469 if (pid < 0) {
4470 ERROR("Failed to clone process in new user namespace");
4471 goto on_error;
4472 }
4473
4474 close(p[0]);
4475 p[0] = -1;
4476
4477 euid = geteuid();
4478 egid = getegid();
4479
4480 /* Allocate new {g,u}id map list. */
4481 idmap = malloc(sizeof(*idmap));
4482 if (!idmap)
4483 goto on_error;
4484 lxc_list_init(idmap);
4485
4486 /* Find container root. */
4487 lxc_list_for_each (cur, &conf->id_map) {
4488 struct id_map *tmpmap;
4489
4490 tmplist = malloc(sizeof(*tmplist));
4491 if (!tmplist)
4492 goto on_error;
4493
4494 tmpmap = malloc(sizeof(*tmpmap));
4495 if (!tmpmap) {
4496 free(tmplist);
4497 goto on_error;
4498 }
4499
4500 memset(tmpmap, 0, sizeof(*tmpmap));
4501 memcpy(tmpmap, cur->elem, sizeof(*tmpmap));
4502 tmplist->elem = tmpmap;
4503
4504 lxc_list_add_tail(idmap, tmplist);
4505
4506 map = cur->elem;
4507
4508 if (map->idtype == ID_TYPE_UID)
4509 if (euid >= map->hostid && euid < map->hostid + map->range)
4510 host_uid_map = map;
4511
4512 if (map->idtype == ID_TYPE_GID)
4513 if (egid >= map->hostid && egid < map->hostid + map->range)
4514 host_gid_map = map;
4515
4516 if (map->nsid != 0)
4517 continue;
4518
4519 if (map->idtype == ID_TYPE_UID)
4520 if (container_root_uid == NULL)
4521 container_root_uid = map;
4522
4523 if (map->idtype == ID_TYPE_GID)
4524 if (container_root_gid == NULL)
4525 container_root_gid = map;
4526 }
4527
4528 if (!container_root_uid || !container_root_gid) {
4529 ERROR("No mapping for container root found");
4530 goto on_error;
4531 }
4532
4533 /* Check whether the {g,u}id of the user has a mapping. */
4534 if (!host_uid_map)
4535 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
4536 else
4537 host_uid_map = container_root_uid;
4538
4539 if (!host_gid_map)
4540 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
4541 else
4542 host_gid_map = container_root_gid;
4543
4544 if (!host_uid_map) {
4545 DEBUG("Failed to find mapping for uid %d", euid);
4546 goto on_error;
4547 }
4548
4549 if (!host_gid_map) {
4550 DEBUG("Failed to find mapping for gid %d", egid);
4551 goto on_error;
4552 }
4553
4554 if (host_uid_map && (host_uid_map != container_root_uid)) {
4555 /* Add container root to the map. */
4556 tmplist = malloc(sizeof(*tmplist));
4557 if (!tmplist)
4558 goto on_error;
4559 lxc_list_add_elem(tmplist, host_uid_map);
4560 lxc_list_add_tail(idmap, tmplist);
4561 }
4562 /* idmap will now keep track of that memory. */
4563 host_uid_map = NULL;
4564
4565 if (host_gid_map && (host_gid_map != container_root_gid)) {
4566 tmplist = malloc(sizeof(*tmplist));
4567 if (!tmplist)
4568 goto on_error;
4569 lxc_list_add_elem(tmplist, host_gid_map);
4570 lxc_list_add_tail(idmap, tmplist);
4571 }
4572 /* idmap will now keep track of that memory. */
4573 host_gid_map = NULL;
4574
4575 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE ||
4576 conf->loglevel == LXC_LOG_LEVEL_TRACE) {
4577 lxc_list_for_each (cur, idmap) {
4578 map = cur->elem;
4579 TRACE("establishing %cid mapping for \"%d\" in new "
4580 "user namespace: nsuid %lu - hostid %lu - range "
4581 "%lu",
4582 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
4583 map->nsid, map->hostid, map->range);
4584 }
4585 }
4586
4587 /* Set up {g,u}id mapping for user namespace of child process. */
4588 ret = lxc_map_ids(idmap, pid);
4589 if (ret < 0) {
4590 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid);
4591 goto on_error;
4592 }
4593
4594 /* Tell child to proceed. */
4595 if (lxc_write_nointr(p[1], &c, 1) != 1) {
4596 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
4597 goto on_error;
4598 }
4599
4600 on_error:
4601 if (p[0] != -1)
4602 close(p[0]);
4603 close(p[1]);
4604
4605 /* Wait for child to finish. */
4606 if (pid > 0)
4607 ret = wait_for_pid(pid);
4608
4609 if (idmap) {
4610 lxc_free_idmap(idmap);
4611 free(idmap);
4612 }
4613
4614 if (host_uid_map && (host_uid_map != container_root_uid))
4615 free(host_uid_map);
4616 if (host_gid_map && (host_gid_map != container_root_gid))
4617 free(host_gid_map);
4618
4619 return ret;
4620 }
4621
4622 /* not thread-safe, do not use from api without first forking */
4623 static char *getuname(void)
4624 {
4625 __do_free char *buf = NULL;
4626 struct passwd pwent;
4627 struct passwd *pwentp = NULL;
4628 size_t bufsize;
4629 int ret;
4630
4631 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
4632 if (bufsize == -1)
4633 bufsize = 1024;
4634
4635 buf = malloc(bufsize);
4636 if (!buf)
4637 return NULL;
4638
4639 ret = getpwuid_r(geteuid(), &pwent, buf, bufsize, &pwentp);
4640 if (!pwentp) {
4641 if (ret == 0)
4642 WARN("Could not find matched password record.");
4643
4644 ERROR("Failed to get password record - %u", geteuid());
4645 return NULL;
4646 }
4647
4648 return strdup(pwent.pw_name);
4649 }
4650
4651 /* not thread-safe, do not use from api without first forking */
4652 static char *getgname(void)
4653 {
4654 __do_free char *buf = NULL;
4655 struct group grent;
4656 struct group *grentp = NULL;
4657 size_t bufsize;
4658 int ret;
4659
4660 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
4661 if (bufsize == -1)
4662 bufsize = 1024;
4663
4664 buf = malloc(bufsize);
4665 if (!buf)
4666 return NULL;
4667
4668 ret = getgrgid_r(getegid(), &grent, buf, bufsize, &grentp);
4669 if (!grentp) {
4670 if (ret == 0)
4671 WARN("Could not find matched group record");
4672
4673 ERROR("Failed to get group record - %u", getegid());
4674 return NULL;
4675 }
4676
4677 return strdup(grent.gr_name);
4678 }
4679
4680 /* not thread-safe, do not use from api without first forking */
4681 void suggest_default_idmap(void)
4682 {
4683 __do_free char *gname = NULL, *line = NULL, *uname = NULL;
4684 __do_fclose FILE *subuid_f = NULL, *subgid_f = NULL;
4685 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
4686 size_t len = 0;
4687
4688 uname = getuname();
4689 if (!uname)
4690 return;
4691
4692 gname = getgname();
4693 if (!gname)
4694 return;
4695
4696 subuid_f = fopen(subuidfile, "r");
4697 if (!subuid_f) {
4698 ERROR("Your system is not configured with subuids");
4699 return;
4700 }
4701
4702 while (getline(&line, &len, subuid_f) != -1) {
4703 char *p, *p2;
4704 size_t no_newline = 0;
4705
4706 p = strchr(line, ':');
4707 if (*line == '#')
4708 continue;
4709 if (!p)
4710 continue;
4711 *p = '\0';
4712 p++;
4713
4714 if (strcmp(line, uname))
4715 continue;
4716
4717 p2 = strchr(p, ':');
4718 if (!p2)
4719 continue;
4720 *p2 = '\0';
4721 p2++;
4722 if (!*p2)
4723 continue;
4724 no_newline = strcspn(p2, "\n");
4725 p2[no_newline] = '\0';
4726
4727 if (lxc_safe_uint(p, &uid) < 0)
4728 WARN("Could not parse UID");
4729 if (lxc_safe_uint(p2, &urange) < 0)
4730 WARN("Could not parse UID range");
4731 }
4732
4733 subgid_f = fopen(subgidfile, "r");
4734 if (!subgid_f) {
4735 ERROR("Your system is not configured with subgids");
4736 return;
4737 }
4738
4739 while (getline(&line, &len, subgid_f) != -1) {
4740 char *p, *p2;
4741 size_t no_newline = 0;
4742
4743 p = strchr(line, ':');
4744 if (*line == '#')
4745 continue;
4746 if (!p)
4747 continue;
4748 *p = '\0';
4749 p++;
4750
4751 if (strcmp(line, uname))
4752 continue;
4753
4754 p2 = strchr(p, ':');
4755 if (!p2)
4756 continue;
4757 *p2 = '\0';
4758 p2++;
4759 if (!*p2)
4760 continue;
4761 no_newline = strcspn(p2, "\n");
4762 p2[no_newline] = '\0';
4763
4764 if (lxc_safe_uint(p, &gid) < 0)
4765 WARN("Could not parse GID");
4766 if (lxc_safe_uint(p2, &grange) < 0)
4767 WARN("Could not parse GID range");
4768 }
4769
4770 if (!urange || !grange) {
4771 ERROR("You do not have subuids or subgids allocated");
4772 ERROR("Unprivileged containers require subuids and subgids");
4773 return;
4774 }
4775
4776 ERROR("You must either run as root, or define uid mappings");
4777 ERROR("To pass uid mappings to lxc-create, you could create");
4778 ERROR("~/.config/lxc/default.conf:");
4779 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
4780 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
4781 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
4782 }
4783
4784 static void free_cgroup_settings(struct lxc_list *result)
4785 {
4786 struct lxc_list *iterator, *next;
4787
4788 lxc_list_for_each_safe (iterator, result, next) {
4789 lxc_list_del(iterator);
4790 free(iterator);
4791 }
4792 free(result);
4793 }
4794
4795 /* Return the list of cgroup_settings sorted according to the following rules
4796 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4797 */
4798 struct lxc_list *sort_cgroup_settings(struct lxc_list *cgroup_settings)
4799 {
4800 struct lxc_list *result;
4801 struct lxc_cgroup *cg = NULL;
4802 struct lxc_list *it = NULL, *item = NULL, *memsw_limit = NULL;
4803
4804 result = malloc(sizeof(*result));
4805 if (!result)
4806 return NULL;
4807 lxc_list_init(result);
4808
4809 /* Iterate over the cgroup settings and copy them to the output list. */
4810 lxc_list_for_each (it, cgroup_settings) {
4811 item = malloc(sizeof(*item));
4812 if (!item) {
4813 free_cgroup_settings(result);
4814 return NULL;
4815 }
4816
4817 item->elem = it->elem;
4818 cg = it->elem;
4819 if (strcmp(cg->subsystem, "memory.memsw.limit_in_bytes") == 0) {
4820 /* Store the memsw_limit location */
4821 memsw_limit = item;
4822 } else if (strcmp(cg->subsystem, "memory.limit_in_bytes") == 0 &&
4823 memsw_limit != NULL) {
4824 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4825 * before lxc.cgroup.memory.limit_in_bytes, swap these
4826 * two items */
4827 item->elem = memsw_limit->elem;
4828 memsw_limit->elem = it->elem;
4829 }
4830 lxc_list_add_tail(result, item);
4831 }
4832
4833 return result;
4834 }