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