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