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