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