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