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