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