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