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