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