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