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