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