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