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