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