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