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