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