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