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