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