]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/conf.c
Merge pull request #3950 from brauner/2021-08-25.list
[mirror_lxc.git] / src / lxc / conf.c
CommitLineData
cc73685d 1/* SPDX-License-Identifier: LGPL-2.1+ */
1d52bdf7 2
d38dd64a
CB
3#ifndef _GNU_SOURCE
4#define _GNU_SOURCE 1
5#endif
9d257a2a 6#include <arpa/inet.h>
8f3e280e
CB
7#include <dirent.h>
8#include <errno.h>
9#include <fcntl.h>
10#include <grp.h>
11#include <inttypes.h>
12#include <libgen.h>
9d257a2a
CB
13#include <linux/loop.h>
14#include <net/if.h>
15#include <netinet/in.h>
8f3e280e
CB
16#include <pwd.h>
17#include <stdarg.h>
1b82d721 18#include <stdbool.h>
0ad19a3f 19#include <stdio.h>
0ad19a3f 20#include <stdlib.h>
0ad19a3f 21#include <string.h>
8f3e280e
CB
22#include <sys/mman.h>
23#include <sys/mount.h>
24#include <sys/param.h>
25#include <sys/prctl.h>
6a49f05e 26#include <sys/sendfile.h>
8f3e280e 27#include <sys/socket.h>
9d257a2a 28#include <sys/stat.h>
2d76d1d7 29#include <sys/syscall.h>
9d257a2a 30#include <sys/sysmacros.h>
97e9cfa0 31#include <sys/types.h>
8f3e280e
CB
32#include <sys/utsname.h>
33#include <sys/wait.h>
9d257a2a
CB
34#include <time.h>
35#include <unistd.h>
1d52bdf7 36
d38dd64a
CB
37#include "af_unix.h"
38#include "caps.h"
5f126977 39#include "cgroups/cgroup.h"
52ce8504 40#include "compiler.h"
d38dd64a
CB
41#include "conf.h"
42#include "config.h"
43#include "confile.h"
44#include "confile_utils.h"
45#include "error.h"
46#include "log.h"
47#include "lsm/lsm.h"
48#include "lxclock.h"
49#include "lxcseccomp.h"
50#include "macro.h"
2f443e88 51#include "memory_utils.h"
7f88a1a2 52#include "mount_utils.h"
d38dd64a
CB
53#include "namespace.h"
54#include "network.h"
55#include "parse.h"
f40988c7 56#include "process_utils.h"
d38dd64a
CB
57#include "ringbuf.h"
58#include "start.h"
5f126977 59#include "storage/storage.h"
d38dd64a 60#include "storage/overlay.h"
1b82d721 61#include "sync.h"
6b3d24d7 62#include "syscall_wrappers.h"
d38dd64a
CB
63#include "terminal.h"
64#include "utils.h"
20502652 65#include "uuid.h"
d38dd64a 66
af6824fc 67#ifdef MAJOR_IN_MKDEV
9d257a2a 68#include <sys/mkdev.h>
af6824fc 69#endif
af6824fc 70
614305f3 71#ifdef HAVE_STATVFS
2938f7c8 72#include <sys/statvfs.h>
614305f3 73#endif
e827ff7e 74
35eb5cdc 75#if HAVE_OPENPTY
b0a33c1e 76#include <pty.h>
e827ff7e
SG
77#else
78#include <../include/openpty.h>
79#endif
0ad19a3f 80
9d257a2a
CB
81#if HAVE_LIBCAP
82#include <sys/capability.h>
83#endif
84
f1e05b90
DJ
85#ifndef HAVE_STRLCAT
86#include "include/strlcat.h"
87#endif
88
9d257a2a
CB
89#if IS_BIONIC
90#include <../include/lxcmntent.h>
91#else
92#include <mntent.h>
93#endif
94
95#if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
96#include <../include/prlimit.h>
97#endif
98
f6815906
CB
99#ifndef HAVE_STRLCPY
100#include "include/strlcpy.h"
101#endif
102
60933dae
CB
103#ifndef HAVE_STRCHRNUL
104#include "include/strchrnul.h"
105#endif
106
ac2cecc4 107lxc_log_define(conf, lxc);
e5bda9ee 108
52ce8504
CB
109/*
110 * The lxc_conf of the container currently being worked on in an API call.
0fd73091
CB
111 * This is used in the error calls.
112 */
d7f19646 113thread_local struct lxc_conf *current_config;
8912711c 114
0fd73091
CB
115char *lxchook_names[NUM_LXC_HOOKS] = {
116 "pre-start",
117 "pre-mount",
118 "mount",
119 "autodev",
120 "start",
121 "stop",
122 "post-stop",
123 "clone",
124 "destroy",
125 "start-host"
126};
72d0e1cb 127
998ac676
RT
128struct mount_opt {
129 char *name;
130 int clear;
1b82d721
CB
131 bool recursive;
132 __u64 flag;
1e4bce2c 133 int legacy_flag;
998ac676
RT
134};
135
81810dd1
DL
136struct caps_opt {
137 char *name;
138 int value;
139};
140
c6d09e15
WB
141struct limit_opt {
142 char *name;
143 int value;
144};
145
998ac676 146static struct mount_opt mount_opt[] = {
1b82d721
CB
147 { "atime", 1, false, MOUNT_ATTR_NOATIME, MS_NOATIME },
148 { "dev", 1, false, MOUNT_ATTR_NODEV, MS_NODEV },
149 { "diratime", 1, false, MOUNT_ATTR_NODIRATIME, MS_NODIRATIME },
150 { "exec", 1, false, MOUNT_ATTR_NOEXEC, MS_NOEXEC },
151 { "noatime", 0, false, MOUNT_ATTR_NOATIME, MS_NOATIME },
152 { "nodev", 0, false, MOUNT_ATTR_NODEV, MS_NODEV },
153 { "nodiratime", 0, false, MOUNT_ATTR_NODIRATIME, MS_NODIRATIME },
154 { "noexec", 0, false, MOUNT_ATTR_NOEXEC, MS_NOEXEC },
155 { "norelatime", 1, false, MOUNT_ATTR_RELATIME, MS_RELATIME },
156 { "nostrictatime", 1, false, MOUNT_ATTR_STRICTATIME, MS_STRICTATIME },
157 { "nosuid", 0, false, MOUNT_ATTR_NOSUID, MS_NOSUID },
158 { "relatime", 0, false, MOUNT_ATTR_RELATIME, MS_RELATIME },
159 { "ro", 0, false, MOUNT_ATTR_RDONLY, MS_RDONLY },
160 { "rw", 1, false, MOUNT_ATTR_RDONLY, MS_RDONLY },
161 { "strictatime", 0, false, MOUNT_ATTR_STRICTATIME, MS_STRICTATIME },
162 { "suid", 1, false, MOUNT_ATTR_NOSUID, MS_NOSUID },
163
164 { "bind", 0, false, 0, MS_BIND },
165 { "defaults", 0, false, 0, 0 },
166 { "rbind", 0, true, 0, MS_BIND | MS_REC },
167
168 { "sync", 0, false, ~0, MS_SYNCHRONOUS },
169 { "async", 1, false, ~0, MS_SYNCHRONOUS },
170 { "dirsync", 0, false, ~0, MS_DIRSYNC },
171 { "lazytime", 0, false, ~0, MS_LAZYTIME },
172 { "mand", 0, false, ~0, MS_MANDLOCK },
173 { "nomand", 1, false, ~0, MS_MANDLOCK },
174 { "remount", 0, false, ~0, MS_REMOUNT },
175
176 { NULL, 0, false, ~0, ~0 },
998ac676
RT
177};
178
d840039e 179static struct mount_opt propagation_opt[] = {
1b82d721
CB
180 { "private", 0, false, MS_PRIVATE, MS_PRIVATE },
181 { "shared", 0, false, MS_SHARED, MS_SHARED },
182 { "slave", 0, false, MS_SLAVE, MS_SLAVE },
183 { "unbindable", 0, false, MS_UNBINDABLE, MS_UNBINDABLE },
184 { "rprivate", 0, true, MS_PRIVATE, MS_PRIVATE | MS_REC },
185 { "rshared", 0, true, MS_SHARED, MS_SHARED | MS_REC },
186 { "rslave", 0, true, MS_SLAVE, MS_SLAVE | MS_REC },
187 { "runbindable", 0, true, MS_UNBINDABLE, MS_UNBINDABLE | MS_REC },
188 { NULL, 0, 0 },
d840039e
YT
189};
190
81810dd1 191static struct caps_opt caps_opt[] = {
8560cd36 192#if HAVE_LIBCAP
7b4cd468
CB
193 { "chown", CAP_CHOWN },
194 { "dac_override", CAP_DAC_OVERRIDE },
195 { "dac_read_search", CAP_DAC_READ_SEARCH },
196 { "fowner", CAP_FOWNER },
197 { "fsetid", CAP_FSETID },
198 { "kill", CAP_KILL },
199 { "setgid", CAP_SETGID },
200 { "setuid", CAP_SETUID },
201 { "setpcap", CAP_SETPCAP },
202 { "linux_immutable", CAP_LINUX_IMMUTABLE },
203 { "net_bind_service", CAP_NET_BIND_SERVICE },
204 { "net_broadcast", CAP_NET_BROADCAST },
205 { "net_admin", CAP_NET_ADMIN },
206 { "net_raw", CAP_NET_RAW },
207 { "ipc_lock", CAP_IPC_LOCK },
208 { "ipc_owner", CAP_IPC_OWNER },
209 { "sys_module", CAP_SYS_MODULE },
210 { "sys_rawio", CAP_SYS_RAWIO },
211 { "sys_chroot", CAP_SYS_CHROOT },
212 { "sys_ptrace", CAP_SYS_PTRACE },
213 { "sys_pacct", CAP_SYS_PACCT },
214 { "sys_admin", CAP_SYS_ADMIN },
215 { "sys_boot", CAP_SYS_BOOT },
216 { "sys_nice", CAP_SYS_NICE },
217 { "sys_resource", CAP_SYS_RESOURCE },
218 { "sys_time", CAP_SYS_TIME },
219 { "sys_tty_config", CAP_SYS_TTY_CONFIG },
220 { "mknod", CAP_MKNOD },
221 { "lease", CAP_LEASE },
222 { "audit_write", CAP_AUDIT_WRITE },
223 { "audit_control", CAP_AUDIT_CONTROL },
224 { "setfcap", CAP_SETFCAP },
225 { "mac_override", CAP_MAC_OVERRIDE },
226 { "mac_admin", CAP_MAC_ADMIN },
227 { "syslog", CAP_SYSLOG },
228 { "wake_alarm", CAP_WAKE_ALARM },
229 { "block_suspend", CAP_BLOCK_SUSPEND },
230 { "audit_read", CAP_AUDIT_READ },
231 { "perfmon", CAP_PERFMON },
232 { "bpf", CAP_BPF },
233 { "checkpoint_restore", CAP_CHECKPOINT_RESTORE },
2b54359b 234#endif
8560cd36 235};
81810dd1 236
c6d09e15
WB
237static struct limit_opt limit_opt[] = {
238#ifdef RLIMIT_AS
239 { "as", RLIMIT_AS },
240#endif
241#ifdef RLIMIT_CORE
242 { "core", RLIMIT_CORE },
243#endif
244#ifdef RLIMIT_CPU
245 { "cpu", RLIMIT_CPU },
246#endif
247#ifdef RLIMIT_DATA
248 { "data", RLIMIT_DATA },
249#endif
250#ifdef RLIMIT_FSIZE
251 { "fsize", RLIMIT_FSIZE },
252#endif
253#ifdef RLIMIT_LOCKS
254 { "locks", RLIMIT_LOCKS },
255#endif
256#ifdef RLIMIT_MEMLOCK
257 { "memlock", RLIMIT_MEMLOCK },
258#endif
259#ifdef RLIMIT_MSGQUEUE
260 { "msgqueue", RLIMIT_MSGQUEUE },
261#endif
262#ifdef RLIMIT_NICE
263 { "nice", RLIMIT_NICE },
264#endif
265#ifdef RLIMIT_NOFILE
266 { "nofile", RLIMIT_NOFILE },
267#endif
268#ifdef RLIMIT_NPROC
269 { "nproc", RLIMIT_NPROC },
270#endif
271#ifdef RLIMIT_RSS
272 { "rss", RLIMIT_RSS },
273#endif
274#ifdef RLIMIT_RTPRIO
275 { "rtprio", RLIMIT_RTPRIO },
276#endif
277#ifdef RLIMIT_RTTIME
278 { "rttime", RLIMIT_RTTIME },
279#endif
280#ifdef RLIMIT_SIGPENDING
281 { "sigpending", RLIMIT_SIGPENDING },
282#endif
283#ifdef RLIMIT_STACK
284 { "stack", RLIMIT_STACK },
285#endif
286};
287
91c3830e
SH
288static int run_buffer(char *buffer)
289{
cc6a0e78 290 __do_free char *output = NULL;
55022530 291 __do_lxc_pclose struct lxc_popen_FILE *f = NULL;
ebf3a6af 292 int fd, ret;
91c3830e 293
ebec9176 294 f = lxc_popen(buffer);
55022530
CB
295 if (!f)
296 return log_error_errno(-1, errno, "Failed to popen() %s", buffer);
91c3830e 297
b8e43ef0 298 output = zalloc(LXC_LOG_BUFFER_SIZE);
55022530
CB
299 if (!output)
300 return log_error_errno(-1, ENOMEM, "Failed to allocate memory for %s", buffer);
91c3830e 301
ebf3a6af 302 fd = fileno(f->f);
55022530
CB
303 if (fd < 0)
304 return log_error_errno(-1, errno, "Failed to retrieve underlying file descriptor");
ebf3a6af
CB
305
306 for (int i = 0; i < 10; i++) {
307 ssize_t bytes_read;
308
309 bytes_read = lxc_read_nointr(fd, output, LXC_LOG_BUFFER_SIZE - 1);
310 if (bytes_read > 0) {
311 output[bytes_read] = '\0';
312 DEBUG("Script %s produced output: %s", buffer, output);
313 continue;
314 }
315
316 break;
317 }
91c3830e 318
55022530
CB
319 ret = lxc_pclose(move_ptr(f));
320 if (ret == -1)
321 return log_error_errno(-1, errno, "Script exited with error");
322 else if (WIFEXITED(ret) && WEXITSTATUS(ret) != 0)
323 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret));
324 else if (WIFSIGNALED(ret))
325 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret));
91c3830e
SH
326
327 return 0;
328}
329
14a7b0f9
CB
330int run_script_argv(const char *name, unsigned int hook_version,
331 const char *section, const char *script,
586b1ce7 332 const char *hookname, char **argv)
148e91f5 333{
e1a94937 334 __do_free char *buffer = NULL;
3f60c2f7 335 int buf_pos, i, ret;
d08e5708 336 size_t size = 0;
148e91f5 337
3f60c2f7 338 if (hook_version == 0)
55022530
CB
339 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
340 script, name, section);
3f60c2f7
CB
341 else
342 INFO("Executing script \"%s\" for container \"%s\"", script, name);
148e91f5 343
586b1ce7
CB
344 for (i = 0; argv && argv[i]; i++)
345 size += strlen(argv[i]) + 1;
148e91f5 346
6333c915
CB
347 size += STRLITERALLEN("exec");
348 size++;
148e91f5 349 size += strlen(script);
3f60c2f7
CB
350 size++;
351
148e91f5 352 if (size > INT_MAX)
3f60c2f7 353 return -EFBIG;
148e91f5 354
3f60c2f7 355 if (hook_version == 0) {
d08e5708
CB
356 size += strlen(hookname);
357 size++;
358
359 size += strlen(name);
360 size++;
361
362 size += strlen(section);
363 size++;
364
365 if (size > INT_MAX)
366 return -EFBIG;
327cce76 367 }
3f60c2f7 368
b8e43ef0 369 buffer = zalloc(size);
6f8d00d2
CB
370 if (!buffer)
371 return -ENOMEM;
372
327cce76 373 if (hook_version == 0)
9bcde680 374 buf_pos = strnprintf(buffer, size, "exec %s %s %s %s", script, name, section, hookname);
327cce76 375 else
9bcde680
CB
376 buf_pos = strnprintf(buffer, size, "exec %s", script);
377 if (buf_pos < 0)
55022530 378 return log_error_errno(-1, errno, "Failed to create command line for script \"%s\"", script);
3f60c2f7 379
327cce76 380 if (hook_version == 1) {
3f60c2f7
CB
381 ret = setenv("LXC_HOOK_TYPE", hookname, 1);
382 if (ret < 0) {
55022530 383 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname);
3f60c2f7 384 }
90f20466 385 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname);
3f60c2f7
CB
386
387 ret = setenv("LXC_HOOK_SECTION", section, 1);
55022530
CB
388 if (ret < 0)
389 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section);
3f60c2f7 390 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section);
14a7b0f9 391
71528742 392 if (strequal(section, "net")) {
14a7b0f9
CB
393 char *parent;
394
586b1ce7 395 if (!argv || !argv[0])
e1a94937 396 return -1;
14a7b0f9 397
586b1ce7 398 ret = setenv("LXC_NET_TYPE", argv[0], 1);
55022530
CB
399 if (ret < 0)
400 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_TYPE=%s", argv[0]);
586b1ce7 401 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv[0]);
14a7b0f9 402
586b1ce7 403 parent = argv[1] ? argv[1] : "";
14a7b0f9 404
71528742 405 if (strequal(argv[0], "macvlan")) {
14a7b0f9 406 ret = setenv("LXC_NET_PARENT", parent, 1);
55022530
CB
407 if (ret < 0)
408 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PARENT=%s", parent);
14a7b0f9 409 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent);
71528742 410 } else if (strequal(argv[0], "phys")) {
14a7b0f9 411 ret = setenv("LXC_NET_PARENT", parent, 1);
55022530
CB
412 if (ret < 0)
413 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PARENT=%s", parent);
14a7b0f9 414 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent);
71528742 415 } else if (strequal(argv[0], "veth")) {
586b1ce7 416 char *peer = argv[2] ? argv[2] : "";
14a7b0f9
CB
417
418 ret = setenv("LXC_NET_PEER", peer, 1);
55022530
CB
419 if (ret < 0)
420 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PEER=%s", peer);
14a7b0f9
CB
421 TRACE("Set environment variable: LXC_NET_PEER=%s", peer);
422
423 ret = setenv("LXC_NET_PARENT", parent, 1);
55022530
CB
424 if (ret < 0)
425 return log_error_errno(-1, errno, "Failed to set environment variable: LXC_NET_PARENT=%s", parent);
14a7b0f9
CB
426 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent);
427 }
428 }
148e91f5
SH
429 }
430
586b1ce7 431 for (i = 0; argv && argv[i]; i++) {
3f60c2f7
CB
432 size_t len = size - buf_pos;
433
9bcde680
CB
434 ret = strnprintf(buffer + buf_pos, len, " %s", argv[i]);
435 if (ret < 0)
55022530 436 return log_error_errno(-1, errno, "Failed to create command line for script \"%s\"", script);
3f60c2f7 437 buf_pos += ret;
148e91f5
SH
438 }
439
e1a94937 440 return run_buffer(buffer);
148e91f5
SH
441}
442
811ef482 443int run_script(const char *name, const char *section, const char *script, ...)
e3b4c4c4 444{
2f443e88 445 __do_free char *buffer = NULL;
abbfd20b 446 int ret;
2f443e88 447 char *p;
abbfd20b 448 va_list ap;
0fd73091 449 size_t size = 0;
751d9dcd 450
0fd73091 451 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
751d9dcd 452 script, name, section);
e3b4c4c4 453
abbfd20b
DL
454 va_start(ap, script);
455 while ((p = va_arg(ap, char *)))
95642a10 456 size += strlen(p) + 1;
abbfd20b
DL
457 va_end(ap);
458
6333c915 459 size += STRLITERALLEN("exec");
abbfd20b
DL
460 size += strlen(script);
461 size += strlen(name);
462 size += strlen(section);
6d1a5f93 463 size += 4;
abbfd20b 464
95642a10
MS
465 if (size > INT_MAX)
466 return -1;
467
2f443e88 468 buffer = must_realloc(NULL, size);
9bcde680
CB
469 ret = strnprintf(buffer, size, "exec %s %s %s", script, name, section);
470 if (ret < 0)
9ba8130c 471 return -1;
751d9dcd 472
abbfd20b 473 va_start(ap, script);
9ba8130c 474 while ((p = va_arg(ap, char *))) {
062b72c6 475 int len = size - ret;
9ba8130c 476 int rc;
9bcde680
CB
477 rc = strnprintf(buffer + ret, len, " %s", p);
478 if (rc < 0) {
7b5a2435 479 va_end(ap);
9ba8130c 480 return -1;
7b5a2435 481 }
9ba8130c
SH
482 ret += rc;
483 }
abbfd20b 484 va_end(ap);
751d9dcd 485
91c3830e 486 return run_buffer(buffer);
e3b4c4c4
ST
487}
488
4e86cad3
CB
489int lxc_storage_prepare(struct lxc_conf *conf)
490{
491 int ret;
492 struct lxc_rootfs *rootfs = &conf->rootfs;
493
494 if (!rootfs->path) {
495 ret = mount("", "/", NULL, MS_SLAVE | MS_REC, 0);
496 if (ret < 0)
497 return log_error_errno(-1, errno, "Failed to recursively turn root mount tree into dependent mount");
498
499 rootfs->dfd_mnt = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
500 if (rootfs->dfd_mnt < 0)
501 return -errno;
502
503 return 0;
504 }
505
506 ret = access(rootfs->mount, F_OK);
507 if (ret != 0)
508 return log_error_errno(-1, errno, "Failed to access to \"%s\". Check it is present",
509 rootfs->mount);
510
511 rootfs->storage = storage_init(conf);
512 if (!rootfs->storage)
513 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
514 rootfs->path, rootfs->mount,
515 rootfs->options ? rootfs->options : "(null)");
516
517 return 0;
518}
519
520void lxc_storage_put(struct lxc_conf *conf)
521{
522 storage_put(conf->rootfs.storage);
523 conf->rootfs.storage = NULL;
524}
525
79ff643d 526/* lxc_rootfs_prepare
63fc76c3 527 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
b7ed4bf0
CS
528 * the duration of the container run, to prevent the container from marking
529 * the underlying fs readonly on shutdown. unlink the file immediately so
63fc76c3
GJ
530 * no name pollution is happens.
531 * don't unlink on NFS to avoid random named stale handles.
0c547523 532 */
239f29c9 533int lxc_rootfs_init(struct lxc_conf *conf, bool userns)
0c547523 534{
1b82d721 535 __do_close int dfd_path = -EBADF, fd_pin = -EBADF;
79ff643d
CB
536 int ret;
537 struct stat st;
538 struct statfs stfs;
4e86cad3
CB
539 struct lxc_rootfs *rootfs = &conf->rootfs;
540
541 ret = lxc_storage_prepare(conf);
542 if (ret)
543 return syserror_set(-EINVAL, "Failed to prepare rootfs storage");
0c547523 544
e26cf563 545 if (!is_empty_string(rootfs->mnt_opts.userns_path)) {
657ed14a
CB
546 if (!rootfs->path)
547 return syserror_set(-EINVAL, "Idmapped rootfs currently only supported with separate rootfs for container");
548
549 if (rootfs->bdev_type && !strequal(rootfs->bdev_type, "dir"))
550 return syserror_set(-EINVAL, "Idmapped rootfs currently only supports the \"dir\" storage driver");
e26cf563
CB
551 }
552
c119f018
CB
553 if (!rootfs->path)
554 return log_trace(0, "Not pinning because container does not have a rootfs");
e99ee0de 555
c119f018
CB
556 if (userns)
557 return log_trace(0, "Not pinning because container runs in user namespace");
79ff643d 558
c119f018
CB
559 if (rootfs->bdev_type) {
560 if (strequal(rootfs->bdev_type, "overlay") ||
561 strequal(rootfs->bdev_type, "overlayfs"))
562 return log_trace_errno(0, EINVAL, "Not pinning on stacking filesystem");
0c547523 563
c119f018
CB
564 if (strequal(rootfs->bdev_type, "zfs"))
565 return log_trace_errno(0, EINVAL, "Not pinning on ZFS filesystem");
e26cf563 566 }
79ff643d 567
c119f018
CB
568 dfd_path = open_at(-EBADF, rootfs->path, PROTECT_OPATH_FILE, 0, 0);
569 if (dfd_path < 0)
570 return syserror("Failed to open \"%s\"", rootfs->path);
571
79ff643d 572 ret = fstat(dfd_path, &st);
957c4704 573 if (ret < 0)
79ff643d 574 return log_trace_errno(-errno, errno, "Failed to retrieve file status");
0c547523 575
79ff643d
CB
576 if (!S_ISDIR(st.st_mode))
577 return log_trace_errno(0, ENOTDIR, "Not pinning because file descriptor is not a directory");
0c547523 578
79ff643d
CB
579 fd_pin = open_at(dfd_path, ".lxc_keep",
580 PROTECT_OPEN | O_CREAT,
581 PROTECT_LOOKUP_BENEATH,
582 S_IWUSR | S_IRUSR);
e859a5ee
WM
583 if (fd_pin < 0) {
584 if (errno == EROFS) {
585 return log_trace_errno(0, EROFS, "Not pinning on read-only filesystem");
586 }
e26cf563 587 return syserror("Failed to pin rootfs");
e859a5ee 588 }
0c547523 589
79ff643d 590 TRACE("Pinned rootfs %d(.lxc_keep)", fd_pin);
0fd73091 591
79ff643d
CB
592 ret = fstatfs(fd_pin, &stfs);
593 if (ret < 0) {
594 SYSWARN("Failed to retrieve filesystem status");
595 goto out;
596 }
63fc76c3 597
79ff643d
CB
598 if (stfs.f_type == NFS_SUPER_MAGIC) {
599 DEBUG("Not unlinking pinned file on NFS");
600 goto out;
601 }
63fc76c3 602
79ff643d
CB
603 if (unlinkat(dfd_path, ".lxc_keep", 0))
604 SYSTRACE("Failed to unlink rootfs pinning file %d(.lxc_keep)", dfd_path);
605 else
606 TRACE("Unlinked pinned file %d(.lxc_keep)", dfd_path);
0fd73091 607
79ff643d
CB
608out:
609 rootfs->fd_path_pin = move_fd(fd_pin);
610 return 0;
0c547523
SH
611}
612
4b875ef9
CB
613int lxc_rootfs_prepare_parent(struct lxc_handler *handler)
614{
615 __do_close int dfd_idmapped = -EBADF, fd_userns = -EBADF;
616 struct lxc_rootfs *rootfs = &handler->conf->rootfs;
617 struct lxc_storage *storage = rootfs->storage;
704cadd5 618 const struct lxc_mount_options *mnt_opts = &rootfs->mnt_opts;
4b875ef9
CB
619 int ret;
620 const char *path_source;
621
622 if (lxc_list_empty(&handler->conf->id_map))
623 return 0;
624
625 if (is_empty_string(rootfs->mnt_opts.userns_path))
626 return 0;
627
628 if (handler->conf->rootfs_setup)
629 return 0;
630
631 if (rootfs_is_blockdev(handler->conf))
632 return syserror_set(-EOPNOTSUPP, "Idmapped mounts on block-backed storage not yet supported");
633
634 if (!can_use_bind_mounts())
635 return syserror_set(-EOPNOTSUPP, "Kernel does not support the new mount api");
636
1b82d721 637 if (strequal(rootfs->mnt_opts.userns_path, "container"))
4b875ef9
CB
638 fd_userns = dup_cloexec(handler->nsfd[LXC_NS_USER]);
639 else
640 fd_userns = open_at(-EBADF, rootfs->mnt_opts.userns_path,
641 PROTECT_OPEN_WITH_TRAILING_SYMLINKS, 0, 0);
642 if (fd_userns < 0)
643 return syserror("Failed to open user namespace");
644
645 path_source = lxc_storage_get_path(storage->src, storage->type);
646
704cadd5
CB
647 dfd_idmapped = create_detached_idmapped_mount(path_source, fd_userns, true,
648 mnt_opts->attr.attr_set,
649 mnt_opts->attr.attr_clr);
4b875ef9
CB
650 if (dfd_idmapped < 0)
651 return syserror("Failed to create detached idmapped mount");
652
653 ret = lxc_abstract_unix_send_fds(handler->data_sock[0], &dfd_idmapped, 1, NULL, 0);
654 if (ret < 0)
655 return syserror("Failed to send detached idmapped mount fd");
656
657 TRACE("Created detached idmapped mount %d", dfd_idmapped);
658 return 0;
659}
660
6b741397
CB
661static int add_shmount_to_list(struct lxc_conf *conf)
662{
6b5a54cd 663 char new_mount[PATH_MAX];
0d190408 664 /* Offset for the leading '/' since the path_cont
6b741397
CB
665 * is absolute inside the container.
666 */
667 int offset = 1, ret = -1;
0d190408 668
9bcde680 669 ret = strnprintf(new_mount, sizeof(new_mount),
6b741397
CB
670 "%s %s none bind,create=dir 0 0", conf->shmount.path_host,
671 conf->shmount.path_cont + offset);
9bcde680 672 if (ret < 0)
0d190408
LT
673 return -1;
674
6b741397 675 return add_elem_to_mount_list(new_mount, conf);
0d190408
LT
676}
677
6d25a524 678static int lxc_mount_auto_mounts(struct lxc_handler *handler, int flags)
368bbc02 679{
7b371c1e 680 int i, ret;
b06b8511
CS
681 static struct {
682 int match_mask;
683 int match_flag;
684 const char *source;
685 const char *destination;
686 const char *fstype;
687 unsigned long flags;
688 const char *options;
e8b9c9ec 689 bool requires_cap_net_admin;
b06b8511 690 } default_mounts[] = {
0fd73091
CB
691 /* Read-only bind-mounting... In older kernels, doing that
692 * required to do one MS_BIND mount and then
693 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
694 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
695 * onwards. However, this apparently does not work on kernel
696 * 3.8. Unfortunately, on that very same kernel, doing the same
697 * trick as above doesn't seem to work either, there one needs
698 * to ALSO specify MS_BIND for the remount, otherwise the
699 * entire fs is remounted read-only or the mount fails because
700 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
701 * kernels as low as 2.6.32...
368bbc02 702 */
5d1bf4c4 703 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL, false },
592fd47a 704 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
cb4889ab 705 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys/net", "%r/proc/tty", NULL, MS_BIND, NULL, true, },
5d1bf4c4
CB
706 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys", "%r/proc/sys", NULL, MS_BIND, NULL, false },
707 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL, false },
708 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/tty", "%r/proc/sys/net", NULL, MS_MOVE, NULL, true },
709 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL, MS_BIND, NULL, false },
710 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sysrq-trigger", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL, false },
711 { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL, false },
712 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RW, "sysfs", "%r/sys", "sysfs", 0, NULL, false },
713 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RO, "sysfs", "%r/sys", "sysfs", MS_RDONLY, NULL, false },
cb4889ab
CB
714 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys", "sysfs", MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL, false },
715 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys/devices/virtual/net", "%r/sys/devices/virtual/net", NULL, MS_BIND, NULL, false },
716 { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys/devices/virtual/net", NULL, MS_REMOUNT|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL, false },
5d1bf4c4 717 { 0, 0, NULL, NULL, NULL, 0, NULL, false }
b06b8511 718 };
6d25a524 719 struct lxc_conf *conf = handler->conf;
e25af1bc
CB
720 struct lxc_rootfs *rootfs = &conf->rootfs;
721 bool has_cap_net_admin;
368bbc02 722
f4bea7cc 723 if (flags & LXC_AUTO_PROC_MASK) {
f6c5aab0
CB
724 if (rootfs->path) {
725 /*
726 * Only unmount procfs if we have a separate rootfs so
727 * we can still access it in safe_mount() below.
728 */
729 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/proc",
730 rootfs->path ? rootfs->mount : "");
731 if (ret < 0)
732 return ret_errno(EIO);
95258e34 733
f6c5aab0
CB
734 ret = umount2(rootfs->buf, MNT_DETACH);
735 if (ret)
736 SYSDEBUG("Tried to ensure procfs is unmounted");
737 }
95258e34 738
ea57e424 739 ret = mkdirat(rootfs->dfd_mnt, "proc" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
f4bea7cc 740 if (ret < 0 && errno != EEXIST)
0d33a382 741 return syserror("Failed to create procfs mountpoint under %d", rootfs->dfd_mnt);
c119f018
CB
742
743 TRACE("Created procfs mountpoint under %d", rootfs->dfd_mnt);
f4bea7cc
CB
744 }
745
746 if (flags & LXC_AUTO_SYS_MASK) {
f6c5aab0
CB
747 if (rootfs->path) {
748 /*
749 * Only unmount sysfs if we have a separate rootfs so
750 * we can still access it in safe_mount() below.
751 */
752 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/sys",
753 rootfs->path ? rootfs->mount : "");
754 if (ret < 0)
755 return ret_errno(EIO);
95258e34 756
f6c5aab0
CB
757 ret = umount2(rootfs->buf, MNT_DETACH);
758 if (ret)
759 SYSDEBUG("Tried to ensure sysfs is unmounted");
760 }
95258e34 761
ea57e424 762 ret = mkdirat(rootfs->dfd_mnt, "sys" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
f4bea7cc 763 if (ret < 0 && errno != EEXIST)
0d33a382 764 return syserror("Failed to create sysfs mountpoint under %d", rootfs->dfd_mnt);
c119f018
CB
765
766 TRACE("Created sysfs mountpoint under %d", rootfs->dfd_mnt);
f4bea7cc
CB
767 }
768
e25af1bc 769 has_cap_net_admin = lxc_wants_cap(CAP_NET_ADMIN, conf);
d84b26bc 770 for (i = 0; default_mounts[i].match_mask; i++) {
8db92302 771 __do_free char *destination = NULL, *source = NULL;
cb4889ab 772 unsigned long mflags = default_mounts[i].flags;
96f306e6 773
0fd73091
CB
774 if ((flags & default_mounts[i].match_mask) != default_mounts[i].match_flag)
775 continue;
776
777 if (default_mounts[i].source) {
cc4fd506 778 /* will act like strdup if %r is not present */
e25af1bc 779 source = lxc_string_replace("%r", rootfs->path ? rootfs->mount : "", default_mounts[i].source);
0fd73091 780 if (!source)
75fca1ac 781 return syserror_set(-ENOMEM, "Failed to create source path");
0fd73091 782 }
f24a52d5 783
55022530 784 if (!default_mounts[i].destination)
75fca1ac 785 return syserror_set(-EINVAL, "BUG: auto mounts destination %d was NULL", i);
0fd73091 786
e8b9c9ec 787 if (!has_cap_net_admin && default_mounts[i].requires_cap_net_admin) {
788 TRACE("Container does not have CAP_NET_ADMIN. Skipping \"%s\" mount", default_mounts[i].source ?: "(null)");
789 continue;
790 }
791
0fd73091 792 /* will act like strdup if %r is not present */
e25af1bc 793 destination = lxc_string_replace("%r", rootfs->path ? rootfs->mount : "", default_mounts[i].destination);
55022530 794 if (!destination)
75fca1ac 795 return syserror_set(-ENOMEM, "Failed to create target path");
0fd73091 796
cb4889ab
CB
797 ret = safe_mount(source, destination,
798 default_mounts[i].fstype,
799 mflags,
800 default_mounts[i].options,
75fca1ac 801 rootfs->path ? rootfs->mount : NULL);
7b371c1e 802 if (ret < 0) {
75fca1ac
CB
803 if (errno != ENOENT)
804 return syserror("Failed to mount \"%s\" on \"%s\" with flags %lu", source, destination, mflags);
805
806 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source, destination);
807 continue;
368bbc02 808 }
cb4889ab
CB
809
810 if (mflags & MS_REMOUNT)
811 TRACE("Remounted automount \"%s\" on \"%s\" %s with flags %lu", source, destination, (mflags & MS_RDONLY) ? "read-only" : "read-write", mflags);
812 else
813 TRACE("Mounted automount \"%s\" on \"%s\" %s with flags %lu", source, destination, (mflags & MS_RDONLY) ? "read-only" : "read-write", mflags);
368bbc02
CS
814 }
815
b06b8511 816 if (flags & LXC_AUTO_CGROUP_MASK) {
0769b82a
CS
817 int cg_flags;
818
3f69fb12 819 cg_flags = flags & (LXC_AUTO_CGROUP_MASK & ~LXC_AUTO_CGROUP_FORCE);
0fd73091
CB
820 /* If the type of cgroup mount was not specified, it depends on
821 * the container's capabilities as to what makes sense: if we
822 * have CAP_SYS_ADMIN, the read-only part can be remounted
823 * read-write anyway, so we may as well default to read-write;
824 * then the admin will not be given a false sense of security.
825 * (And if they really want mixed r/o r/w, then they can
826 * explicitly specify :mixed.) OTOH, if the container lacks
827 * CAP_SYS_ADMIN, do only default to :mixed, because then the
828 * container can't remount it read-write.
829 */
9394b6dc 830 if ((cg_flags == LXC_AUTO_CGROUP_NOSPEC) || (cg_flags == LXC_AUTO_CGROUP_FULL_NOSPEC)) {
0769b82a 831 int has_sys_admin = 0;
b0ee5983
CB
832
833 if (!lxc_list_empty(&conf->keepcaps))
0769b82a 834 has_sys_admin = in_caplist(CAP_SYS_ADMIN, &conf->keepcaps);
b0ee5983 835 else
0769b82a 836 has_sys_admin = !in_caplist(CAP_SYS_ADMIN, &conf->caps);
b0ee5983
CB
837
838 if (cg_flags == LXC_AUTO_CGROUP_NOSPEC)
0769b82a 839 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_RW : LXC_AUTO_CGROUP_MIXED;
b0ee5983 840 else
0769b82a 841 cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_FULL_RW : LXC_AUTO_CGROUP_FULL_MIXED;
0769b82a 842 }
0fd73091 843
3f69fb12 844 if (flags & LXC_AUTO_CGROUP_FORCE)
0fd73091
CB
845 cg_flags |= LXC_AUTO_CGROUP_FORCE;
846
ab8cd5d9 847 if (!handler->cgroup_ops->mount(handler->cgroup_ops, handler, cg_flags))
55022530 848 return log_error_errno(-1, errno, "Failed to mount \"/sys/fs/cgroup\"");
368bbc02
CS
849 }
850
0d190408 851 if (flags & LXC_AUTO_SHMOUNTS_MASK) {
7b371c1e 852 ret = add_shmount_to_list(conf);
55022530
CB
853 if (ret < 0)
854 return log_error(-1, "Failed to add shmount entry to container config");
0d190408
LT
855 }
856
368bbc02 857 return 0;
368bbc02
CS
858}
859
4e5440c6 860static int setup_utsname(struct utsname *utsname)
0ad19a3f 861{
0fd73091
CB
862 int ret;
863
4e5440c6
DL
864 if (!utsname)
865 return 0;
0ad19a3f 866
0fd73091 867 ret = sethostname(utsname->nodename, strlen(utsname->nodename));
55022530
CB
868 if (ret < 0)
869 return log_error_errno(-1, errno, "Failed to set the hostname to \"%s\"",
870 utsname->nodename);
0ad19a3f 871
0fd73091 872 INFO("Set hostname to \"%s\"", utsname->nodename);
cd54d859 873
0ad19a3f 874 return 0;
875}
876
69aa6655
DE
877struct dev_symlinks {
878 const char *oldpath;
879 const char *name;
880};
881
882static const struct dev_symlinks dev_symlinks[] = {
0fd73091
CB
883 { "/proc/self/fd", "fd" },
884 { "/proc/self/fd/0", "stdin" },
885 { "/proc/self/fd/1", "stdout" },
886 { "/proc/self/fd/2", "stderr" },
69aa6655
DE
887};
888
ed8704d0 889static int lxc_setup_dev_symlinks(const struct lxc_rootfs *rootfs)
69aa6655 890{
79019997
CB
891 for (int i = 0; i < sizeof(dev_symlinks) / sizeof(dev_symlinks[0]); i++) {
892 int ret;
893 struct stat s;
69aa6655 894 const struct dev_symlinks *d = &dev_symlinks[i];
0fd73091 895
79019997
CB
896 /*
897 * Stat the path first. If we don't get an error accept it as
0fd73091 898 * is and don't try to create it
09227be2 899 */
a5a08920 900 ret = fstatat(rootfs->dfd_dev, d->name, &s, 0);
0fd73091 901 if (ret == 0)
09227be2 902 continue;
09227be2 903
a5a08920 904 ret = symlinkat(d->oldpath, rootfs->dfd_dev, d->name);
79019997
CB
905 if (ret) {
906 switch (errno) {
907 case EROFS:
908 WARN("Failed to create \"%s\" on read-only filesystem", d->name);
909 __fallthrough;
910 case EEXIST:
911 break;
912 default:
913 return log_error_errno(-errno, errno, "Failed to create \"%s\"", d->name);
914 }
69aa6655
DE
915 }
916 }
0fd73091 917
69aa6655
DE
918 return 0;
919}
920
2187efd3 921/* Build a space-separate list of ptys to pass to systemd. */
885766f5 922static bool append_ttyname(char **pp, char *name)
b0a33c1e 923{
393903d1 924 char *p;
f1e05b90 925 size_t size;
393903d1
SH
926
927 if (!*pp) {
b8e43ef0 928 *pp = zalloc(strlen(name) + strlen("container_ttys=") + 1);
393903d1
SH
929 if (!*pp)
930 return false;
0fd73091 931
393903d1
SH
932 sprintf(*pp, "container_ttys=%s", name);
933 return true;
934 }
0fd73091 935
f1e05b90
DJ
936 size = strlen(*pp) + strlen(name) + 2;
937 p = realloc(*pp, size);
393903d1
SH
938 if (!p)
939 return false;
0fd73091 940
393903d1 941 *pp = p;
f1e05b90
DJ
942 (void)strlcat(p, " ", size);
943 (void)strlcat(p, name, size);
0fd73091 944
393903d1
SH
945 return true;
946}
947
128655e7
PM
948static int open_ttymnt_at(int dfd, const char *path)
949{
950 int fd;
951
777827cb
CB
952 fd = open_at(dfd, path,
953 PROTECT_OPEN | O_CREAT | O_EXCL,
954 PROTECT_LOOKUP_BENEATH,
955 0);
956 if (fd < 0) {
957 if (!IN_SET(errno, ENXIO, EEXIST))
958 return syserror("Failed to create \"%d/\%s\"", dfd, path);
959
960 SYSINFO("Failed to create \"%d/\%s\"", dfd, path);
961 fd = open_at(dfd, path,
962 PROTECT_OPATH_FILE,
963 PROTECT_LOOKUP_BENEATH,
964 0);
965 }
128655e7
PM
966
967 return fd;
968}
969
2187efd3 970static int lxc_setup_ttys(struct lxc_conf *conf)
393903d1 971{
7369e6bf
CB
972 int ret;
973 struct lxc_rootfs *rootfs = &conf->rootfs;
0e4be3cf 974 const struct lxc_tty_info *ttys = &conf->ttys;
885766f5 975 char *ttydir = ttys->dir;
b0a33c1e 976
e8bd4e43 977 if (!conf->rootfs.path)
bc9bd0e3
DL
978 return 0;
979
7369e6bf
CB
980 for (int i = 0; i < ttys->max; i++) {
981 __do_close int fd_to = -EBADF;
0e4be3cf 982 struct lxc_terminal_info *tty = &ttys->tty[i];
b0a33c1e 983
7c6ef2a2 984 if (ttydir) {
7369e6bf 985 char *tty_name, *tty_path;
9e1045e3 986
9bcde680 987 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
7369e6bf 988 "/dev/%s/tty%d", ttydir, i + 1);
9bcde680 989 if (ret < 0)
7369e6bf
CB
990 return ret_errno(-EIO);
991
992 tty_path = &rootfs->buf[STRLITERALLEN("/dev/")];
993 tty_name = tty_path + strlen(ttydir) + 1;
994
995 /* create bind-mount target */
128655e7 996 fd_to = open_ttymnt_at(rootfs->dfd_dev, tty_path);
7369e6bf
CB
997 if (fd_to < 0)
998 return log_error_errno(-errno, errno,
999 "Failed to create tty mount target %d(%s)",
1000 rootfs->dfd_dev, tty_path);
1001
1002 ret = unlinkat(rootfs->dfd_dev, tty_name, 0);
1003 if (ret < 0 && errno != ENOENT)
1004 return log_error_errno(-errno, errno,
1005 "Failed to unlink %d(%s)",
1006 rootfs->dfd_dev, tty_name);
1007
84f8f9e4 1008 if (can_use_mount_api())
7369e6bf
CB
1009 ret = fd_bind_mount(tty->pty, "",
1010 PROTECT_OPATH_FILE,
1011 PROTECT_LOOKUP_BENEATH_XDEV,
1012 fd_to, "",
1013 PROTECT_OPATH_FILE,
704cadd5
CB
1014 PROTECT_LOOKUP_BENEATH_XDEV,
1015 0,
1016 0,
1017 0,
7369e6bf 1018 false);
84f8f9e4
CB
1019 else
1020 ret = mount_fd(tty->pty, fd_to, "none", MS_BIND, 0);
7369e6bf
CB
1021 if (ret < 0)
1022 return log_error_errno(-errno, errno,
1023 "Failed to bind mount \"%s\" onto \"%s\"",
1024 tty->name, rootfs->buf);
1025 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name, rootfs->buf);
9e1045e3 1026
7369e6bf 1027 ret = symlinkat(tty_path, rootfs->dfd_dev, tty_name);
55022530 1028 if (ret < 0)
7369e6bf
CB
1029 return log_error_errno(-errno, errno,
1030 "Failed to create symlink \"%d(%s)\" -> \"%d(%s)\"",
1031 rootfs->dfd_dev, tty_name,
1032 rootfs->dfd_dev, tty_path);
7c6ef2a2 1033 } else {
9bcde680
CB
1034 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "tty%d", i + 1);
1035 if (ret < 0)
7369e6bf
CB
1036 return ret_errno(-EIO);
1037
1038 /* If we populated /dev, then we need to create /dev/tty<idx>. */
128655e7 1039 fd_to = open_ttymnt_at(rootfs->dfd_dev, rootfs->buf);
7369e6bf
CB
1040 if (fd_to < 0)
1041 return log_error_errno(-errno, errno,
1042 "Failed to create tty mount target %d(%s)",
1043 rootfs->dfd_dev, rootfs->buf);
1044
84f8f9e4 1045 if (can_use_mount_api())
7369e6bf
CB
1046 ret = fd_bind_mount(tty->pty, "",
1047 PROTECT_OPATH_FILE,
1048 PROTECT_LOOKUP_BENEATH_XDEV,
1049 fd_to, "",
1050 PROTECT_OPATH_FILE,
704cadd5
CB
1051 PROTECT_LOOKUP_BENEATH,
1052 0,
1053 0,
1054 0,
7369e6bf 1055 false);
84f8f9e4
CB
1056 else
1057 ret = mount_fd(tty->pty, fd_to, "none", MS_BIND, 0);
7369e6bf
CB
1058 if (ret < 0)
1059 return log_error_errno(-errno, errno,
1060 "Failed to bind mount \"%s\" onto \"%s\"",
1061 tty->name, rootfs->buf);
1062 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty->name, rootfs->buf);
393903d1 1063 }
9e1045e3 1064
55022530
CB
1065 if (!append_ttyname(&conf->ttys.tty_names, tty->name))
1066 return log_error(-1, "Error setting up container_ttys string");
b0a33c1e 1067 }
1068
885766f5 1069 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys->max);
b0a33c1e 1070 return 0;
1071}
1072
9d0e129b
CB
1073define_cleanup_function(struct lxc_tty_info *, lxc_delete_tty);
1074
59eac805 1075static int lxc_allocate_ttys(struct lxc_conf *conf)
2187efd3 1076{
9d0e129b 1077 call_cleaner(lxc_delete_tty) struct lxc_tty_info *ttys = &conf->ttys;
fca23691 1078 int ret;
2187efd3
CB
1079
1080 /* no tty in the configuration */
885766f5 1081 if (ttys->max == 0)
2187efd3
CB
1082 return 0;
1083
9d0e129b
CB
1084 ttys->tty = zalloc(sizeof(struct lxc_terminal_info) * ttys->max);
1085 if (!ttys->tty)
2187efd3 1086 return -ENOMEM;
2187efd3 1087
7369e6bf 1088 for (size_t i = 0; i < conf->ttys.max; i++) {
d926c261 1089 int pty_nr = -1;
9d0e129b 1090 struct lxc_terminal_info *tty = &ttys->tty[i];
2187efd3 1091
4dcf0c43 1092 ret = lxc_devpts_terminal(conf->devpts_fd, &tty->ptx,
18129d94 1093 &tty->pty, &pty_nr, false);
77a39805 1094 if (ret < 0) {
7369e6bf 1095 conf->ttys.max = i;
6a2ca1b4 1096 return syserror_set(-ENOTTY, "Failed to create tty %zu", i);
2187efd3 1097 }
d926c261
CB
1098 DEBUG("Created tty with ptx fd %d and pty fd %d and index %d",
1099 tty->ptx, tty->pty, pty_nr);
7581d645 1100 tty->busy = -1;
2187efd3
CB
1101 }
1102
885766f5 1103 INFO("Finished creating %zu tty devices", ttys->max);
9d0e129b 1104 move_ptr(ttys);
2187efd3
CB
1105 return 0;
1106}
1107
0e4be3cf 1108void lxc_delete_tty(struct lxc_tty_info *ttys)
2187efd3 1109{
b35f8f7e 1110 if (!ttys || !ttys->tty)
386e6768
CB
1111 return;
1112
55022530 1113 for (int i = 0; i < ttys->max; i++) {
0e4be3cf 1114 struct lxc_terminal_info *tty = &ttys->tty[i];
36a94ce8 1115 close_prot_errno_disarm(tty->ptx);
41808e20 1116 close_prot_errno_disarm(tty->pty);
2187efd3
CB
1117 }
1118
55022530 1119 free_disarm(ttys->tty);
2187efd3
CB
1120}
1121
1b82d721 1122static int __lxc_send_ttys_to_parent(struct lxc_handler *handler)
2187efd3
CB
1123{
1124 int i;
0fd73091 1125 int ret = -1;
2187efd3 1126 struct lxc_conf *conf = handler->conf;
0e4be3cf 1127 struct lxc_tty_info *ttys = &conf->ttys;
2187efd3 1128 int sock = handler->data_sock[0];
2187efd3 1129
885766f5 1130 if (ttys->max == 0)
2187efd3
CB
1131 return 0;
1132
885766f5 1133 for (i = 0; i < ttys->max; i++) {
2187efd3 1134 int ttyfds[2];
0e4be3cf 1135 struct lxc_terminal_info *tty = &ttys->tty[i];
2187efd3 1136
36a94ce8 1137 ttyfds[0] = tty->ptx;
41808e20 1138 ttyfds[1] = tty->pty;
2187efd3
CB
1139
1140 ret = lxc_abstract_unix_send_fds(sock, ttyfds, 2, NULL, 0);
1141 if (ret < 0)
1142 break;
1143
41808e20
CB
1144 TRACE("Sent tty \"%s\" with ptx fd %d and pty fd %d to parent",
1145 tty->name, tty->ptx, tty->pty);
2187efd3
CB
1146 }
1147
1148 if (ret < 0)
6d1400b5 1149 SYSERROR("Failed to send %zu ttys to parent", ttys->max);
2187efd3 1150 else
885766f5 1151 TRACE("Sent %zu ttys to parent", ttys->max);
2187efd3
CB
1152
1153 return ret;
1154}
1155
1156static int lxc_create_ttys(struct lxc_handler *handler)
1157{
1158 int ret = -1;
1159 struct lxc_conf *conf = handler->conf;
1160
663014ee 1161 ret = lxc_allocate_ttys(conf);
2187efd3
CB
1162 if (ret < 0) {
1163 ERROR("Failed to allocate ttys");
1164 goto on_error;
1165 }
1166
2187efd3
CB
1167 if (!conf->is_execute) {
1168 ret = lxc_setup_ttys(conf);
1169 if (ret < 0) {
1170 ERROR("Failed to setup ttys");
1171 goto on_error;
1172 }
1173 }
1174
885766f5
CB
1175 if (conf->ttys.tty_names) {
1176 ret = setenv("container_ttys", conf->ttys.tty_names, 1);
1b82d721 1177 if (ret < 0) {
885766f5 1178 SYSERROR("Failed to set \"container_ttys=%s\"", conf->ttys.tty_names);
1b82d721
CB
1179 goto on_error;
1180 }
2187efd3
CB
1181 }
1182
1b82d721 1183 return 0;
2187efd3
CB
1184
1185on_error:
0e4be3cf 1186 lxc_delete_tty(&conf->ttys);
2187efd3 1187
1b82d721
CB
1188 return -1;
1189}
1190
111ed96e 1191static int lxc_send_ttys_to_parent(struct lxc_handler *handler)
1b82d721
CB
1192{
1193 int ret = -1;
1194
1195 ret = __lxc_send_ttys_to_parent(handler);
1196 lxc_delete_tty(&handler->conf->ttys);
2187efd3
CB
1197 return ret;
1198}
1199
7133b912
CB
1200/* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1201 * error, log it but don't fail yet.
91c3830e 1202 */
7133b912 1203static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs,
63012bdd 1204 int autodevtmpfssize, const char *lxcpath)
91c3830e 1205{
bfbfeedf 1206 __do_close int fd_fs = -EBADF;
ee8eeba8 1207 const char *path = rootfs->path ? rootfs->mount : NULL;
bfbfeedf 1208 size_t tmpfs_size = (autodevtmpfssize != 0) ? autodevtmpfssize : 500000;
91c3830e 1209 int ret;
87e0e273 1210 mode_t cur_mask;
63012bdd 1211 char mount_options[128];
91c3830e 1212
7133b912 1213 INFO("Preparing \"/dev\"");
bc6928ff 1214
87e0e273 1215 cur_mask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
ea57e424 1216 ret = mkdirat(rootfs->dfd_mnt, "dev" , S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
87e0e273
CB
1217 if (ret < 0 && errno != EEXIST) {
1218 SYSERROR("Failed to create \"/dev\" directory");
1219 ret = -errno;
1220 goto reset_umask;
bc6928ff 1221 }
87da4ec3 1222
de7f9f33 1223 if (can_use_mount_api()) {
635e7bac
CB
1224 fd_fs = fs_prepare("tmpfs", -EBADF, "", 0, 0);
1225 if (fd_fs < 0)
1226 return log_error_errno(-errno, errno, "Failed to prepare filesystem context for tmpfs");
ee8eeba8 1227
bfbfeedf
CB
1228 sprintf(mount_options, "%zu", tmpfs_size);
1229
1230 ret = fs_set_property(fd_fs, "mode", "0755");
1231 if (ret < 0)
1232 return log_error_errno(-errno, errno, "Failed to mount tmpfs onto %d(dev)", fd_fs);
1233
1234 ret = fs_set_property(fd_fs, "size", mount_options);
1235 if (ret < 0)
1236 return log_error_errno(-errno, errno, "Failed to mount tmpfs onto %d(dev)", fd_fs);
1237
89606dfb
CB
1238 ret = fs_attach(fd_fs, rootfs->dfd_mnt, "dev",
1239 PROTECT_OPATH_DIRECTORY,
1240 PROTECT_LOOKUP_BENEATH_XDEV, 0);
635e7bac
CB
1241 } else {
1242 __do_free char *fallback_path = NULL;
1243
1244 sprintf(mount_options, "size=%zu,mode=755", tmpfs_size);
1245 DEBUG("Using mount options: %s", mount_options);
1246
1247 if (path) {
1248 fallback_path = must_make_path(path, "/dev", NULL);
1249 ret = safe_mount("none", fallback_path, "tmpfs", 0, mount_options, path);
1250 } else {
1251 ret = safe_mount("none", "dev", "tmpfs", 0, mount_options, NULL);
1252 }
87e0e273 1253 }
bfbfeedf
CB
1254 if (ret < 0) {
1255 SYSERROR("Failed to mount tmpfs on \"%s\"", path);
1256 goto reset_umask;
1257 }
1258
7133b912 1259 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
bc6928ff
MW
1260 * If not, then create it and exit if that fails...
1261 */
ea57e424 1262 ret = mkdirat(rootfs->dfd_mnt, "dev/pts", S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
87e0e273 1263 if (ret < 0 && errno != EEXIST) {
bfbfeedf 1264 SYSERROR("Failed to create directory \"dev/pts\"");
87e0e273
CB
1265 ret = -errno;
1266 goto reset_umask;
91c3830e
SH
1267 }
1268
87e0e273
CB
1269 ret = 0;
1270
1271reset_umask:
1272 (void)umask(cur_mask);
1273
7133b912 1274 INFO("Prepared \"/dev\"");
87e0e273 1275 return ret;
91c3830e
SH
1276}
1277
5e73416f 1278struct lxc_device_node {
74a3920a 1279 const char *name;
5e73416f
CB
1280 const mode_t mode;
1281 const int maj;
1282 const int min;
c6883f38
SH
1283};
1284
5e73416f 1285static const struct lxc_device_node lxc_devices[] = {
06749971 1286 { "full", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 7 },
5e73416f 1287 { "null", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 3 },
06749971
CB
1288 { "random", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 8 },
1289 { "tty", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 5, 0 },
5e73416f
CB
1290 { "urandom", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 9 },
1291 { "zero", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 5 },
c6883f38
SH
1292};
1293
5067e4dd
CB
1294
1295enum {
1296 LXC_DEVNODE_BIND,
1297 LXC_DEVNODE_MKNOD,
1298 LXC_DEVNODE_PARTIAL,
1299 LXC_DEVNODE_OPEN,
1300};
1301
887ae844 1302static int lxc_fill_autodev(struct lxc_rootfs *rootfs)
c6883f38 1303{
5e73416f 1304 int i, ret;
3a32201c 1305 mode_t cmask;
5067e4dd 1306 int use_mknod = LXC_DEVNODE_MKNOD;
c6883f38 1307
a5a08920 1308 if (rootfs->dfd_dev < 0)
81498328 1309 return log_info(0, "No /dev directory found, skipping setup");
d43d5191 1310
3999be0a
CB
1311 INFO("Populating \"/dev\"");
1312
3a32201c 1313 cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
5e73416f 1314 for (i = 0; i < sizeof(lxc_devices) / sizeof(lxc_devices[0]); i++) {
5e73416f 1315 const struct lxc_device_node *device = &lxc_devices[i];
0728ebf4 1316
5067e4dd 1317 if (use_mknod >= LXC_DEVNODE_MKNOD) {
a5a08920 1318 ret = mknodat(rootfs->dfd_dev, device->name, device->mode, makedev(device->maj, device->min));
5e73416f 1319 if (ret == 0 || (ret < 0 && errno == EEXIST)) {
d43d5191 1320 DEBUG("Created device node \"%s\"", device->name);
5067e4dd 1321 } else if (ret < 0) {
55022530 1322 if (errno != EPERM)
d43d5191 1323 return log_error_errno(-1, errno, "Failed to create device node \"%s\"", device->name);
0bbf8572 1324
5067e4dd 1325 use_mknod = LXC_DEVNODE_BIND;
9cb4d183 1326 }
3999be0a 1327
5067e4dd
CB
1328 /* Device nodes are fully useable. */
1329 if (use_mknod == LXC_DEVNODE_OPEN)
1330 continue;
1331
1332 if (use_mknod == LXC_DEVNODE_MKNOD) {
d43d5191 1333 __do_close int fd = -EBADF;
5067e4dd
CB
1334 /* See
1335 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1336 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1337 */
a5a08920 1338 fd = open_at(rootfs->dfd_dev, device->name, PROTECT_OPEN, PROTECT_LOOKUP_BENEATH, 0);
d43d5191 1339 if (fd >= 0) {
5067e4dd
CB
1340 /* Device nodes are fully useable. */
1341 use_mknod = LXC_DEVNODE_OPEN;
1342 continue;
1343 }
1344
d43d5191 1345 SYSTRACE("Failed to open \"%s\" device", device->name);
5067e4dd
CB
1346 /* Device nodes are only partially useable. */
1347 use_mknod = LXC_DEVNODE_PARTIAL;
1348 }
5e73416f
CB
1349 }
1350
5067e4dd
CB
1351 if (use_mknod != LXC_DEVNODE_PARTIAL) {
1352 /* If we are dealing with partially functional device
1353 * nodes the prio mknod() call will have created the
1354 * device node so we can use it as a bind-mount target.
1355 */
a5a08920 1356 ret = mknodat(rootfs->dfd_dev, device->name, S_IFREG | 0000, 0);
55022530 1357 if (ret < 0 && errno != EEXIST)
d43d5191 1358 return log_error_errno(-1, errno, "Failed to create file \"%s\"", device->name);
5e73416f
CB
1359 }
1360
1361 /* Fallback to bind-mounting the device from the host. */
9bcde680
CB
1362 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "dev/%s", device->name);
1363 if (ret < 0)
b41ff502 1364 return ret_errno(EIO);
5e73416f 1365
de7f9f33 1366 if (can_use_mount_api()) {
887ae844 1367 ret = fd_bind_mount(rootfs->dfd_host, rootfs->buf,
635e7bac
CB
1368 PROTECT_OPATH_FILE,
1369 PROTECT_LOOKUP_BENEATH_XDEV,
1370 rootfs->dfd_dev, device->name,
1371 PROTECT_OPATH_FILE,
704cadd5
CB
1372 PROTECT_LOOKUP_BENEATH,
1373 0,
1374 0,
1375 0,
1376 false);
635e7bac 1377 } else {
927ea337
CB
1378 char path[PATH_MAX];
1379
9bcde680
CB
1380 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/dev/%s", device->name);
1381 if (ret < 0)
927ea337
CB
1382 return ret_errno(EIO);
1383
9bcde680
CB
1384 ret = strnprintf(path, sizeof(path), "%s/dev/%s", get_rootfs_mnt(rootfs), device->name);
1385 if (ret < 0)
927ea337
CB
1386 return log_error(-1, "Failed to create device path for %s", device->name);
1387
887ae844 1388 ret = safe_mount(rootfs->buf, path, 0, MS_BIND, NULL, get_rootfs_mnt(rootfs));
927ea337 1389 if (ret < 0)
887ae844 1390 return log_error_errno(-1, errno, "Failed to bind mount host device node \"%s\" to \"%s\"", rootfs->buf, path);
927ea337 1391
887ae844 1392 DEBUG("Bind mounted host device node \"%s\" to \"%s\"", rootfs->buf, path);
927ea337 1393 continue;
d43d5191 1394 }
887ae844 1395 DEBUG("Bind mounted host device %d(%s) to %d(%s)", rootfs->dfd_host, rootfs->buf, rootfs->dfd_dev, device->name);
c6883f38 1396 }
5e73416f 1397 (void)umask(cmask);
c6883f38 1398
3999be0a 1399 INFO("Populated \"/dev\"");
c6883f38
SH
1400 return 0;
1401}
1402
4e86cad3 1403static int lxc_mount_rootfs(struct lxc_rootfs *rootfs)
0ad19a3f 1404{
9aa76a17 1405 int ret;
cc28d0b0 1406
a0f379bf 1407 if (!rootfs->path) {
0fd73091 1408 ret = mount("", "/", NULL, MS_SLAVE | MS_REC, 0);
55022530 1409 if (ret < 0)
9e61fb1f 1410 return log_error_errno(-1, errno, "Failed to recursively turn root mount tree into dependent mount");
0fd73091 1411
ea57e424
CB
1412 rootfs->dfd_mnt = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
1413 if (rootfs->dfd_mnt < 0)
31f8b2fd
CB
1414 return -errno;
1415
c119f018 1416 return log_trace(0, "Container doesn't use separate rootfs. Opened host's rootfs");
a0f379bf 1417 }
0ad19a3f 1418
0fd73091 1419 ret = access(rootfs->mount, F_OK);
55022530
CB
1420 if (ret != 0)
1421 return log_error_errno(-1, errno, "Failed to access to \"%s\". Check it is present",
1422 rootfs->mount);
b1789442 1423
4e86cad3 1424 ret = rootfs->storage->ops->mount(rootfs->storage);
55022530
CB
1425 if (ret < 0)
1426 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1427 rootfs->path, rootfs->mount,
1428 rootfs->options ? rootfs->options : "(null)");
0ad19a3f 1429
0fd73091 1430 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
91c3e281
CB
1431 rootfs->path, rootfs->mount,
1432 rootfs->options ? rootfs->options : "(null)");
9aa76a17 1433
ea57e424
CB
1434 rootfs->dfd_mnt = open_at(-EBADF, rootfs->mount, PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
1435 if (rootfs->dfd_mnt < 0)
31f8b2fd
CB
1436 return -errno;
1437
c119f018 1438 return log_trace(0, "Container uses separate rootfs. Opened container's rootfs");
ac778708
DL
1439}
1440
59eac805 1441static int lxc_chroot(const struct lxc_rootfs *rootfs)
91e93c71 1442{
b8d88764 1443 __do_free char *nroot = NULL;
0fd73091 1444 int i, ret;
8ce1abc2 1445 char *root = rootfs->mount;
91e93c71 1446
74e7b662 1447 nroot = realpath(root, NULL);
55022530
CB
1448 if (!nroot)
1449 return log_error_errno(-1, errno, "Failed to resolve \"%s\"", root);
91e93c71 1450
0fd73091 1451 ret = chdir("/");
b8d88764 1452 if (ret < 0)
0fd73091 1453 return -1;
91e93c71 1454
0fd73091
CB
1455 /* We could use here MS_MOVE, but in userns this mount is locked and
1456 * can't be moved.
91e93c71 1457 */
8ce1abc2 1458 ret = mount(nroot, "/", NULL, MS_REC | MS_BIND, NULL);
55022530
CB
1459 if (ret < 0)
1460 return log_error_errno(-1, errno, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot);
91e93c71 1461
0fd73091 1462 ret = mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);
55022530
CB
1463 if (ret < 0)
1464 return log_error_errno(-1, errno, "Failed to remount \"/\"");
91e93c71 1465
aa899945 1466 /* The following code cleans up inherited mounts which are not required
0fd73091 1467 * for CT.
91e93c71
AV
1468 *
1469 * The mountinfo file shows not all mounts, if a few points have been
1470 * unmounted between read operations from the mountinfo. So we need to
1471 * read mountinfo a few times.
1472 *
7ded5fa7 1473 * This loop can be skipped if a container uses userns, because all
91e93c71
AV
1474 * inherited mounts are locked and we should live with all this trash.
1475 */
0fd73091 1476 for (;;) {
4fdd1f72 1477 __do_fclose FILE *f = NULL;
f3d38164
CB
1478 __do_free char *line = NULL;
1479 char *slider1, *slider2;
91e93c71 1480 int progress = 0;
f3d38164 1481 size_t len = 0;
91e93c71 1482
4110345b 1483 f = fopen("./proc/self/mountinfo", "re");
55022530
CB
1484 if (!f)
1485 return log_error_errno(-1, errno, "Failed to open \"/proc/self/mountinfo\"");
0fd73091 1486
f3d38164
CB
1487 while (getline(&line, &len, f) > 0) {
1488 for (slider1 = line, i = 0; slider1 && i < 4; i++)
1489 slider1 = strchr(slider1 + 1, ' ');
0fd73091 1490
f3d38164 1491 if (!slider1)
91e93c71 1492 continue;
0fd73091 1493
f3d38164
CB
1494 slider2 = strchr(slider1 + 1, ' ');
1495 if (!slider2)
91e93c71
AV
1496 continue;
1497
f3d38164
CB
1498 *slider2 = '\0';
1499 *slider1 = '.';
91e93c71 1500
71528742 1501 if (strequal(slider1 + 1, "/"))
91e93c71 1502 continue;
0fd73091 1503
71528742 1504 if (strequal(slider1 + 1, "/proc"))
91e93c71
AV
1505 continue;
1506
f3d38164 1507 ret = umount2(slider1, MNT_DETACH);
0fd73091 1508 if (ret == 0)
91e93c71
AV
1509 progress++;
1510 }
0fd73091 1511
91e93c71
AV
1512 if (!progress)
1513 break;
1514 }
1515
7ded5fa7 1516 /* This also can be skipped if a container uses userns. */
0fd73091 1517 (void)umount2("./proc", MNT_DETACH);
91e93c71
AV
1518
1519 /* It is weird, but chdir("..") moves us in a new root */
0fd73091 1520 ret = chdir("..");
55022530
CB
1521 if (ret < 0)
1522 return log_error_errno(-1, errno, "Failed to chdir(\"..\")");
91e93c71 1523
0fd73091 1524 ret = chroot(".");
55022530
CB
1525 if (ret < 0)
1526 return log_error_errno(-1, errno, "Failed to chroot(\".\")");
91e93c71
AV
1527
1528 return 0;
1529}
1530
8ce1abc2
CB
1531/* (The following explanation is copied verbatim from the kernel.)
1532 *
1533 * pivot_root Semantics:
1534 * Moves the root file system of the current process to the directory put_old,
1535 * makes new_root as the new root file system of the current process, and sets
1536 * root/cwd of all processes which had them on the current root to new_root.
1537 *
1538 * Restrictions:
1539 * The new_root and put_old must be directories, and must not be on the
1540 * same file system as the current process root. The put_old must be
1541 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1542 * pointed to by put_old must yield the same directory as new_root. No other
1543 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1544 *
1545 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1546 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1547 * in this situation.
1548 *
1549 * Notes:
1550 * - we don't move root/cwd if they are not at the root (reason: if something
1551 * cared enough to change them, it's probably wrong to force them elsewhere)
1552 * - it's okay to pick a root that isn't the root of a file system, e.g.
1553 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1554 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1555 * first.
1556 */
7f50ec8b 1557static int lxc_pivot_root(const struct lxc_rootfs *rootfs)
ac778708 1558{
7f50ec8b 1559 __do_close int fd_oldroot = -EBADF;
b0d7aac4 1560 int ret;
0fd73091 1561
7f50ec8b
CB
1562 fd_oldroot = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
1563 if (fd_oldroot < 0)
55022530 1564 return log_error_errno(-1, errno, "Failed to open old root directory");
ac778708 1565
8ce1abc2 1566 /* change into new root fs */
ea57e424 1567 ret = fchdir(rootfs->dfd_mnt);
55022530 1568 if (ret < 0)
7f50ec8b 1569 return log_error_errno(-errno, errno, "Failed to change into new root directory \"%s\"", rootfs->mount);
39c7b795 1570
8ce1abc2
CB
1571 /* pivot_root into our new root fs */
1572 ret = pivot_root(".", ".");
55022530 1573 if (ret < 0)
7f50ec8b 1574 return log_error_errno(-errno, errno, "Failed to pivot into new root directory \"%s\"", rootfs->mount);
39c7b795 1575
8ce1abc2
CB
1576 /* At this point the old-root is mounted on top of our new-root. To
1577 * unmounted it we must not be chdir'd into it, so escape back to
1578 * old-root.
1579 */
7f50ec8b 1580 ret = fchdir(fd_oldroot);
55022530 1581 if (ret < 0)
7f50ec8b 1582 return log_error_errno(-errno, errno, "Failed to enter old root directory");
c69bd12f 1583
7f50ec8b
CB
1584 /*
1585 * Make fd_oldroot a depedent mount to make sure our umounts don't
1586 * propagate to the host.
8ce1abc2
CB
1587 */
1588 ret = mount("", ".", "", MS_SLAVE | MS_REC, NULL);
55022530 1589 if (ret < 0)
7f50ec8b 1590 return log_error_errno(-errno, errno, "Failed to recursively turn old root mount tree into dependent mount");
8ce1abc2
CB
1591
1592 ret = umount2(".", MNT_DETACH);
55022530 1593 if (ret < 0)
7f50ec8b 1594 return log_error_errno(-errno, errno, "Failed to detach old root directory");
8ce1abc2 1595
ea57e424 1596 ret = fchdir(rootfs->dfd_mnt);
55022530 1597 if (ret < 0)
7f50ec8b 1598 return log_error_errno(-errno, errno, "Failed to re-enter new root directory \"%s\"", rootfs->mount);
8ce1abc2 1599
7f50ec8b 1600 TRACE("Changed into new rootfs \"%s\"", rootfs->mount);
b0d7aac4 1601 return 0;
0ad19a3f 1602}
1603
8ce1abc2
CB
1604static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs *rootfs)
1605{
55022530
CB
1606 if (!rootfs->path)
1607 return log_debug(0, "Container does not have a rootfs");
8ce1abc2
CB
1608
1609 if (detect_ramfs_rootfs())
1610 return lxc_chroot(rootfs);
1611
7f50ec8b 1612 return lxc_pivot_root(rootfs);
0ad19a3f 1613}
1614
7581a82f 1615static const struct id_map *find_mapped_nsid_entry(const struct lxc_conf *conf,
8ce1abc2
CB
1616 unsigned id,
1617 enum idtype idtype)
f4900711
CB
1618{
1619 struct lxc_list *it;
1620 struct id_map *map;
1621 struct id_map *retmap = NULL;
1622
dcf0ffdf
CB
1623 /* Shortcut for container's root mappings. */
1624 if (id == 0) {
1625 if (idtype == ID_TYPE_UID)
1626 return conf->root_nsuid_map;
1627
1628 if (idtype == ID_TYPE_GID)
1629 return conf->root_nsgid_map;
1630 }
1631
f4900711
CB
1632 lxc_list_for_each(it, &conf->id_map) {
1633 map = it->elem;
1634 if (map->idtype != idtype)
1635 continue;
1636
1637 if (id >= map->nsid && id < map->nsid + map->range) {
1638 retmap = map;
1639 break;
1640 }
1641 }
1642
1643 return retmap;
1644}
1645
42c0d056 1646static int lxc_recv_devpts_from_child(struct lxc_handler *handler)
68f3899e
CB
1647{
1648 int ret;
1649
1650 if (handler->conf->pty_max <= 0)
1651 return 0;
1652
d17c815d
CB
1653 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1],
1654 &handler->conf->devpts_fd,
1655 &handler->conf->devpts_fd,
1656 sizeof(handler->conf->devpts_fd));
68f3899e
CB
1657 if (ret < 0)
1658 return log_error_errno(-1, errno, "Failed to receive devpts fd from child");
1659
1660 TRACE("Received devpts file descriptor %d from child", handler->conf->devpts_fd);
1661 return 0;
1662}
1663
96a980e1 1664static int lxc_setup_devpts_child(struct lxc_handler *handler)
289b707b 1665{
96a980e1 1666 __do_close int devpts_fd = -EBADF, fd_fs = -EBADF;
289b707b 1667 struct lxc_conf *conf = handler->conf;
f30fc74d 1668 struct lxc_rootfs *rootfs = &conf->rootfs;
03585adc 1669 size_t pty_max = conf->pty_max;
289b707b
CB
1670 int ret;
1671
03585adc
CB
1672 pty_max += conf->ttys.max;
1673 if (pty_max <= 0)
1674 return log_debug(0, "No new devpts instance will be mounted since no pts devices are required");
289b707b 1675
f30fc74d
CB
1676 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
1677 "/proc/self/fd/%d/pts", rootfs->dfd_dev);
1678 if (ret < 0)
1679 return syserror("Failed to create path");
1680
1681 (void)umount2(rootfs->buf, MNT_DETACH);
1682
1683 /* Create mountpoint for devpts instance. */
1684 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1685 if (ret < 0 && errno != EEXIST)
1686 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
1687
96a980e1
CB
1688 if (can_use_mount_api()) {
1689 fd_fs = fs_prepare("devpts", -EBADF, "", 0, 0);
1690 if (fd_fs < 0)
1691 return syserror("Failed to prepare filesystem context for devpts");
289b707b 1692
96a980e1
CB
1693 ret = fs_set_property(fd_fs, "source", "devpts");
1694 if (ret < 0)
1695 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs);
289b707b 1696
96a980e1
CB
1697 ret = fs_set_property(fd_fs, "gid", "5");
1698 if (ret < 0)
1699 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs);
289b707b 1700
96a980e1
CB
1701 ret = fs_set_flag(fd_fs, "newinstance");
1702 if (ret < 0)
1703 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs);
289b707b 1704
96a980e1
CB
1705 ret = fs_set_property(fd_fs, "ptmxmode", "0666");
1706 if (ret < 0)
1707 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs);
289b707b 1708
96a980e1
CB
1709 ret = fs_set_property(fd_fs, "mode", "0620");
1710 if (ret < 0)
1711 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs);
289b707b 1712
03585adc 1713 ret = fs_set_property(fd_fs, "max", fdstr(pty_max));
96a980e1
CB
1714 if (ret < 0)
1715 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf->pty_max, fd_fs);
f30fc74d 1716
96a980e1
CB
1717 ret = fsconfig(fd_fs, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
1718 if (ret < 0)
1719 return syserror("Failed to finalize filesystem context %d", fd_fs);
289b707b 1720
96a980e1
CB
1721 devpts_fd = fsmount(fd_fs, FSMOUNT_CLOEXEC, MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC);
1722 if (devpts_fd < 0)
1723 return syserror("Failed to create new mount for filesystem context %d", fd_fs);
1724 TRACE("Created detached devpts mount %d", devpts_fd);
77890c6d 1725
96a980e1
CB
1726 ret = move_mount(devpts_fd, "", rootfs->dfd_dev, "pts", MOVE_MOUNT_F_EMPTY_PATH);
1727 if (ret)
1728 return syserror("Failed to attach devpts mount %d to %d/pts", conf->devpts_fd, rootfs->dfd_dev);
3c26f34e 1729
96a980e1
CB
1730 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd, rootfs->dfd_dev);
1731 } else {
1732 char **opts;
1733 char devpts_mntopts[256];
1734 char *mntopt_sets[5];
1735 char default_devpts_mntopts[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
7e40254a 1736
f30fc74d
CB
1737 /*
1738 * Fallback codepath in case the new mount API can't be used to
1739 * create detached mounts.
1740 */
1741
289b707b 1742 ret = strnprintf(devpts_mntopts, sizeof(devpts_mntopts), "%s,max=%zu",
03585adc 1743 default_devpts_mntopts, pty_max);
289b707b
CB
1744 if (ret < 0)
1745 return -1;
3c26f34e 1746
289b707b
CB
1747 /* Create mountpoint for devpts instance. */
1748 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1749 if (ret < 0 && errno != EEXIST)
1750 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
ce155c60 1751
289b707b
CB
1752 /* gid=5 && max= */
1753 mntopt_sets[0] = devpts_mntopts;
ce155c60 1754
289b707b
CB
1755 /* !gid=5 && max= */
1756 mntopt_sets[1] = devpts_mntopts + STRLITERALLEN("gid=5") + 1;
ce155c60 1757
289b707b
CB
1758 /* gid=5 && !max= */
1759 mntopt_sets[2] = default_devpts_mntopts;
ce155c60 1760
289b707b
CB
1761 /* !gid=5 && !max= */
1762 mntopt_sets[3] = default_devpts_mntopts + STRLITERALLEN("gid=5") + 1;
ce155c60 1763
289b707b
CB
1764 /* end */
1765 mntopt_sets[4] = NULL;
70761e5e 1766
289b707b
CB
1767 for (ret = -1, opts = mntopt_sets; opts && *opts; opts++) {
1768 /* mount new devpts instance */
8b0ccdaa
CB
1769 ret = mount_at(rootfs->dfd_dev, "", 0,
1770 rootfs->dfd_dev, "pts", PROTECT_LOOKUP_BENEATH,
1771 "devpts", MS_NOSUID | MS_NOEXEC, *opts);
289b707b
CB
1772 if (ret == 0)
1773 break;
1774 }
289b707b
CB
1775 if (ret < 0)
1776 return log_error_errno(-1, errno, "Failed to mount new devpts instance");
1777
1778 devpts_fd = open_at(rootfs->dfd_dev, "pts", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
1779 if (devpts_fd < 0) {
1780 devpts_fd = -EBADF;
1781 TRACE("Failed to create detached devpts mount");
1782 }
1783
289b707b
CB
1784 DEBUG("Mounted new devpts instance with options \"%s\"", *opts);
1785 }
03585adc 1786
96a980e1 1787 handler->conf->devpts_fd = move_fd(devpts_fd);
f797f05e 1788
03585adc
CB
1789 /*
1790 * In order to allocate terminal devices the devpts filesystem will
1791 * have to be attached to the filesystem at least ones in the new mount
1792 * api. The reason is lengthy but the gist is that until the new mount
1793 * has been attached to the filesystem it is a detached mount with an
1794 * anonymous mount mamespace attached to it for which the kernel
1795 * refuses certain operations.
1796 * We end up here if the user has requested to allocate tty devices
1797 * while not requestig pty devices be made available to the container.
1798 * We only need the devpts_fd to allocate tty devices.
1799 */
1800 if (conf->pty_max <= 0)
1801 return 0;
1802
d5cb35d6 1803 /* Remove any pre-existing /dev/ptmx file. */
a5a08920 1804 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
b29e05d6 1805 if (ret < 0) {
55022530
CB
1806 if (errno != ENOENT)
1807 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\" file");
b29e05d6 1808 } else {
0fd73091 1809 DEBUG("Removed existing \"/dev/ptmx\" file");
3c26f34e 1810 }
1811
8de0119d 1812 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
a5a08920 1813 ret = mknodat(rootfs->dfd_dev, "ptmx", S_IFREG | 0000, 0);
55022530 1814 if (ret < 0 && errno != EEXIST)
8de0119d
CB
1815 return log_error_errno(-1, errno, "Failed to create \"/dev/ptmx\" file as bind mount target");
1816 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
77890c6d 1817
d27ae999 1818 /* Main option: use a bind-mount to please AppArmor */
8b0ccdaa
CB
1819 ret = mount_at(rootfs->dfd_dev, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1820 rootfs->dfd_dev, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1821 NULL, MS_BIND, NULL);
55022530
CB
1822 if (!ret)
1823 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1824 else
d5cb35d6 1825 /* Fallthrough and try to create a symlink. */
0fd73091 1826 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
d5cb35d6 1827
8de0119d 1828 /* Remove the placeholder /dev/ptmx file we created above. */
a5a08920 1829 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
55022530
CB
1830 if (ret < 0)
1831 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\"");
d5cb35d6
CB
1832
1833 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
06853427 1834 ret = symlinkat("/dev/pts/ptmx", rootfs->dfd_dev, "dev/ptmx");
55022530
CB
1835 if (ret < 0)
1836 return log_error_errno(-1, errno, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
cd54d859 1837
185b9ee9 1838 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
3c26f34e 1839 return 0;
1840}
1841
03585adc
CB
1842static int lxc_finish_devpts_child(struct lxc_handler *handler)
1843{
1844 struct lxc_conf *conf = handler->conf;
1845 struct lxc_rootfs *rootfs = &conf->rootfs;
1846 int ret;
1847
1848 if (conf->pty_max > 0)
1849 return 0;
1850
1851 /*
1852 * We end up here if the user has requested to allocate tty devices
1853 * while not requestig pty devices be made available to the container.
1854 * This means we can unmount the devpts instance. We only need the
1855 * devpts_fd to allocate tty devices.
1856 */
1857 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
1858 "/proc/self/fd/%d/pts", rootfs->dfd_dev);
1859 if (ret < 0)
1860 return syserror("Failed to create path");
1861
1862 close_prot_errno_disarm(conf->devpts_fd);
1863 return umount2(rootfs->buf, MNT_DETACH);
1864}
1865
111ed96e 1866static int lxc_send_devpts_to_parent(struct lxc_handler *handler)
1b82d721
CB
1867{
1868 int ret;
1869
1870 if (handler->conf->pty_max <= 0)
1871 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1872
1873 ret = lxc_abstract_unix_send_fds(handler->data_sock[0], &handler->conf->devpts_fd, 1, NULL, 0);
1874 if (ret < 0)
1875 SYSERROR("Failed to send devpts file descriptor %d to parent", handler->conf->devpts_fd);
1876 else
1877 TRACE("Sent devpts file descriptor %d to parent", handler->conf->devpts_fd);
1878
1879 close_prot_errno_disarm(handler->conf->devpts_fd);
1880
1881 return 0;
1882}
1883
64a04c84 1884static int setup_personality(personality_t persona)
cccc74b5 1885{
0fd73091
CB
1886 int ret;
1887
9c601e1f
CB
1888 if (persona == LXC_ARCH_UNCHANGED)
1889 return log_debug(0, "Retaining original personality");
cccc74b5 1890
64a04c84 1891 ret = lxc_personality(persona);
55022530 1892 if (ret < 0)
9c601e1f 1893 return syserror("Failed to set personality to \"0lx%lx\"", persona);
cccc74b5 1894
38608992 1895 INFO("Set personality to \"0lx%lx\"", persona);
cccc74b5
DL
1896 return 0;
1897}
1898
9f77617b 1899static int bind_mount_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1900 struct lxc_terminal *console, int fd_to)
37c74fd1
CB
1901{
1902 __do_close int fd_pty = -EBADF;
1903
1904 if (is_empty_string(console->name))
1905 return ret_errno(EINVAL);
1906
1907 /*
1908 * When the pty fd stashed in console->pty has been retrieved via the
1909 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1910 * allocating new pty devices we can't reopen it through openat2() or
1911 * created a detached mount through open_tree() from it. This means we
1912 * would need to mount using the path stased in console->name which is
1913 * unsafe. We could be mounting a device that isn't identical to the
1914 * one we've already safely opened and stashed in console->pty.
1915 * So, what we do is we open an O_PATH file descriptor for
1916 * console->name and verify that the opened fd and the fd we stashed in
1917 * console->pty refer to the same device. If they do we can go on and
1918 * created a detached mount based on the newly opened O_PATH file
1919 * descriptor and then safely mount.
1920 */
9f77617b 1921 fd_pty = open_at_same(console->pty, fd_devpts, fdstr(console->pty_nr),
d94a7f09 1922 PROTECT_OPATH_FILE, PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
37c74fd1 1923 if (fd_pty < 0)
d94a7f09 1924 return syserror("Failed to open \"%s\"", console->name);
37c74fd1
CB
1925
1926 /*
1927 * Note, there are intentionally no open or lookup restrictions since
1928 * we're operating directly on the fd.
1929 */
d94a7f09 1930 if (can_use_mount_api())
704cadd5 1931 return fd_bind_mount(fd_pty, "", 0, 0, fd_to, "", 0, 0, 0, 0, 0, false);
d94a7f09
CB
1932
1933 return mount_fd(fd_pty, fd_to, "none", MS_BIND, 0);
37c74fd1
CB
1934}
1935
9f77617b 1936static int lxc_setup_dev_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1937 struct lxc_terminal *console)
6e590161 1938{
af0cf9b7 1939 __do_close int fd_console = -EBADF;
882671aa 1940 int ret;
52e35957 1941
cf68ffd9
CB
1942 /*
1943 * When we are asked to setup a console we remove any previous
8b1b1210
CB
1944 * /dev/console bind-mounts.
1945 */
a5a08920 1946 if (exists_file_at(rootfs->dfd_dev, "console")) {
af0cf9b7
CB
1947 char *rootfs_path = rootfs->path ? rootfs->mount : "";
1948
9bcde680
CB
1949 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
1950 if (ret < 0)
953db219
CB
1951 return -1;
1952
58b38111 1953 ret = lxc_unstack_mountpoint(rootfs->buf, false);
55022530 1954 if (ret < 0)
58b38111 1955 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
55022530 1956 else
58b38111 1957 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
8b1b1210
CB
1958 }
1959
cf68ffd9
CB
1960 /*
1961 * For unprivileged containers autodev or automounts will already have
8b1b1210
CB
1962 * taken care of creating /dev/console.
1963 */
d94a7f09
CB
1964 fd_console = open_at(rootfs->dfd_dev,
1965 "console",
1966 PROTECT_OPEN | O_CREAT,
1967 PROTECT_LOOKUP_BENEATH,
1968 0000);
af0cf9b7 1969 if (fd_console < 0)
d94a7f09 1970 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
52e35957 1971
1dd71c90 1972 ret = fchmod(console->pty, 0620);
55022530 1973 if (ret < 0)
d94a7f09 1974 return syserror("Failed to change console mode");
13954cce 1975
9f77617b 1976 ret = bind_mount_console(fd_devpts, rootfs, console, fd_console);
37c74fd1 1977 if (ret < 0)
d94a7f09
CB
1978 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1979 console->pty, console->name, fd_console);
6e590161 1980
d94a7f09 1981 TRACE("Setup console \"%s\"", console->name);
7c6ef2a2
SH
1982 return 0;
1983}
1984
9f77617b 1985static int lxc_setup_ttydir_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1986 struct lxc_terminal *console,
37c74fd1 1987 char *ttydir)
7c6ef2a2 1988{
d94a7f09
CB
1989 __do_close int fd_ttydir = -EBADF, fd_dev_console = -EBADF,
1990 fd_reg_console = -EBADF, fd_reg_ttydir_console = -EBADF;
3b7e332f 1991 int ret;
7c6ef2a2 1992
f6370f2a
CB
1993 /* create dev/<ttydir> */
1994 ret = mkdirat(rootfs->dfd_dev, ttydir, 0755);
1995 if (ret < 0 && errno != EEXIST)
1996 return syserror("Failed to create \"%d/%s\"", rootfs->dfd_dev, ttydir);
d94a7f09
CB
1997
1998 fd_ttydir = open_at(rootfs->dfd_dev,
1999 ttydir,
2000 PROTECT_OPATH_DIRECTORY,
2001 PROTECT_LOOKUP_BENEATH,
2002 0);
2003 if (fd_ttydir < 0)
2004 return syserror("Failed to open \"%d/%s\"", rootfs->dfd_dev, ttydir);
7c6ef2a2 2005
f6370f2a 2006 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/console", ttydir);
9bcde680 2007 if (ret < 0)
3d7d929a
CB
2008 return -1;
2009
f6370f2a 2010 /* create dev/<ttydir>/console */
d94a7f09
CB
2011 fd_reg_ttydir_console = open_at(fd_ttydir,
2012 "console",
2013 PROTECT_OPEN | O_CREAT,
2014 PROTECT_LOOKUP_BENEATH,
2015 0000);
2016 if (fd_reg_ttydir_console < 0)
2017 return syserror("Failed to create \"%d/console\"", fd_ttydir);
2a12fefd 2018
f6370f2a 2019 if (file_exists(rootfs->buf)) {
d94a7f09
CB
2020 char *rootfs_path = rootfs->path ? rootfs->mount : "";
2021
2022 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
2023 if (ret < 0)
2024 return -1;
2025
f6370f2a 2026 ret = lxc_unstack_mountpoint(rootfs->buf, false);
55022530 2027 if (ret < 0)
f6370f2a 2028 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
55022530 2029 else
f6370f2a 2030 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
3dc035f1 2031 }
2a12fefd 2032
d94a7f09
CB
2033 /* create dev/console */
2034 fd_reg_console = open_at(rootfs->dfd_dev,
2035 "console",
2036 PROTECT_OPEN | O_CREAT,
2037 PROTECT_LOOKUP_BENEATH,
2038 0000);
2039 if (fd_reg_console < 0)
2040 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
7c6ef2a2 2041
1dd71c90 2042 ret = fchmod(console->pty, 0620);
55022530 2043 if (ret < 0)
d94a7f09 2044 return syserror("Failed to change console mode");
2a12fefd 2045
d94a7f09 2046 /* bind mount console to '/dev/<ttydir>/console' */
9f77617b 2047 ret = bind_mount_console(fd_devpts, rootfs, console, fd_reg_ttydir_console);
55022530 2048 if (ret < 0)
d94a7f09
CB
2049 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2050 console->pty, console->name, fd_reg_ttydir_console);
2051
2052 fd_dev_console = open_at_same(console->pty,
2053 fd_ttydir,
2054 "console",
2055 PROTECT_OPATH_FILE,
2056 PROTECT_LOOKUP_BENEATH_XDEV,
2057 0);
2058 if (fd_dev_console < 0)
2059 return syserror("Failed to open \"%d/console\"", fd_ttydir);
2060
2061 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
2062 if (can_use_mount_api())
2063 ret = fd_bind_mount(fd_dev_console,
2064 "",
2065 PROTECT_OPATH_FILE,
2066 PROTECT_LOOKUP_BENEATH_XDEV,
2067 fd_reg_console,
2068 "",
2069 PROTECT_OPATH_FILE,
2070 PROTECT_LOOKUP_BENEATH,
2071 0,
704cadd5
CB
2072 0,
2073 0,
d94a7f09
CB
2074 false);
2075 else
2076 ret = mount_fd(fd_dev_console, fd_reg_console, "none", MS_BIND, 0);
55022530 2077 if (ret < 0)
d94a7f09
CB
2078 return syserror("Failed to mount \"%d\" on \"%d\"",
2079 fd_dev_console, fd_reg_console);
3dc035f1 2080
d94a7f09 2081 TRACE("Setup console \"%s\"", console->name);
6e590161 2082 return 0;
2083}
2084
f3dff080
CB
2085static int lxc_setup_console(const struct lxc_handler *handler,
2086 struct lxc_rootfs *rootfs,
37c74fd1 2087 struct lxc_terminal *console, char *ttydir)
7c6ef2a2 2088{
9f77617b
CB
2089 __do_close int fd_devpts_host = -EBADF;
2090 int fd_devpts = handler->conf->devpts_fd;
2091 int ret = -1;
3d7d929a 2092
37c74fd1
CB
2093 if (!wants_console(console))
2094 return log_trace(0, "Skipping console setup");
7c6ef2a2 2095
9f77617b
CB
2096 if (console->pty < 0) {
2097 /*
2098 * Allocate a console from the container's devpts instance. We
2099 * have checked on the host that we have enough pty devices
2100 * available.
2101 */
2102 ret = lxc_devpts_terminal(handler->conf->devpts_fd, &console->ptx,
18129d94 2103 &console->pty, &console->pty_nr, false);
9f77617b
CB
2104 if (ret < 0)
2105 return syserror("Failed to allocate console from container's devpts instance");
2106
2107 ret = strnprintf(console->name, sizeof(console->name),
2108 "/dev/pts/%d", console->pty_nr);
2109 if (ret < 0)
2110 return syserror("Failed to create console path");
2111 } else {
2112 /*
2113 * We're using a console from the host's devpts instance. Open
2114 * it again so we can later verify that the console we're
2115 * supposed to use is still the same as the one we opened on
2116 * the host.
2117 */
2118 fd_devpts_host = open_at(rootfs->dfd_host,
2119 "dev/pts",
2120 PROTECT_OPATH_DIRECTORY,
2121 PROTECT_LOOKUP_BENEATH_XDEV,
2122 0);
2123 if (fd_devpts_host < 0)
2124 return syserror("Failed to open host devpts");
2125
2126 fd_devpts = fd_devpts_host;
2127 }
2128
37c74fd1 2129 if (ttydir)
9f77617b 2130 ret = lxc_setup_ttydir_console(fd_devpts, rootfs, console, ttydir);
37c74fd1 2131 else
9f77617b 2132 ret = lxc_setup_dev_console(fd_devpts, rootfs, console);
87dfb724
CB
2133 if (ret < 0)
2134 return syserror("Failed to setup console");
2135
f3dff080
CB
2136 /*
2137 * Some init's such as busybox will set sane tty settings on stdin,
2138 * stdout, stderr which it thinks is the console. We already set them
2139 * the way we wanted on the real terminal, and we want init to do its
2140 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2141 * make sure that that pty is stdin,stdout,stderr.
2142 */
9f77617b 2143 if (console->pty >= 0) {
f3dff080 2144 if (handler->daemonize || !handler->conf->is_execute)
9f77617b 2145 ret = set_stdfds(console->pty);
f3dff080 2146 else
9f77617b 2147 ret = lxc_terminal_set_stdfds(console->pty);
f3dff080 2148 if (ret < 0)
9f77617b
CB
2149 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console->pty);
2150
2151 /*
2152 * If the console has been allocated from the host's devpts
2153 * we're done and we don't need to send fds to the parent.
2154 */
2155 if (fd_devpts_host >= 0)
2156 lxc_terminal_delete(console);
f3dff080
CB
2157 }
2158
37c74fd1 2159 return ret;
7c6ef2a2
SH
2160}
2161
a08bfbe3 2162static int parse_mntopt(char *opt, unsigned long *flags, char **data, size_t size)
998ac676 2163{
a08bfbe3 2164 ssize_t ret;
998ac676 2165
85c2de39
MB
2166 /* If '=' is contained in opt, the option must go into data. */
2167 if (!strchr(opt, '=')) {
a08bfbe3
CB
2168 /*
2169 * If opt is found in mount_opt, set or clear flags.
2170 * Otherwise append it to data.
2171 */
85c2de39 2172 size_t opt_len = strlen(opt);
a08bfbe3 2173 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
85c2de39 2174 size_t mo_name_len = strlen(mo->name);
a08bfbe3 2175
eed95eb0 2176 if (opt_len == mo_name_len && strnequal(opt, mo->name, mo_name_len)) {
85c2de39 2177 if (mo->clear)
1e4bce2c 2178 *flags &= ~mo->legacy_flag;
85c2de39 2179 else
1e4bce2c 2180 *flags |= mo->legacy_flag;
a08bfbe3 2181 return 0;
85c2de39 2182 }
998ac676
RT
2183 }
2184 }
2185
a08bfbe3
CB
2186 if (strlen(*data)) {
2187 ret = strlcat(*data, ",", size);
2188 if (ret < 0)
2189 return log_error_errno(ret, errno, "Failed to append \",\" to %s", *data);
2190 }
2191
2192 ret = strlcat(*data, opt, size);
2193 if (ret < 0)
2194 return log_error_errno(ret, errno, "Failed to append \"%s\" to %s", opt, *data);
efed99a4 2195
a08bfbe3 2196 return 0;
998ac676
RT
2197}
2198
d94eb390 2199int parse_mntopts_legacy(const char *mntopts, unsigned long *mntflags, char **mntdata)
998ac676 2200{
a08bfbe3
CB
2201 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
2202 char *mntopt_cur = NULL;
efed99a4 2203 size_t size;
998ac676 2204
a08bfbe3
CB
2205 if (*mntdata || *mntflags)
2206 return ret_errno(EINVAL);
911324ef
DL
2207
2208 if (!mntopts)
998ac676
RT
2209 return 0;
2210
a08bfbe3
CB
2211 mntopts_dup = strdup(mntopts);
2212 if (!mntopts_dup)
2213 return ret_errno(ENOMEM);
998ac676 2214
a08bfbe3
CB
2215 size = strlen(mntopts_dup) + 1;
2216 mntopts_new = zalloc(size);
2217 if (!mntopts_new)
2218 return ret_errno(ENOMEM);
998ac676 2219
a08bfbe3
CB
2220 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",")
2221 if (parse_mntopt(mntopt_cur, mntflags, &mntopts_new, size) < 0)
2222 return ret_errno(EINVAL);
998ac676 2223
a08bfbe3
CB
2224 if (*mntopts_new)
2225 *mntdata = move_ptr(mntopts_new);
998ac676
RT
2226
2227 return 0;
2228}
2229
1b82d721
CB
2230static int parse_vfs_attr(struct lxc_mount_options *opts, char *opt, size_t size)
2231{
2232 /*
2233 * If opt is found in mount_opt, set or clear flags.
2234 * Otherwise append it to data.
2235 */
2236 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
2237 if (!strnequal(opt, mo->name, strlen(mo->name)))
2238 continue;
2239
2240 /* This is a recursive bind-mount. */
2241 if (strequal(mo->name, "rbind")) {
2242 opts->recursive = 1;
2243 opts->bind = 1;
0f43436c 2244 opts->mnt_flags |= mo->legacy_flag; /* MS_BIND | MS_REC */
1b82d721
CB
2245 return 0;
2246 }
2247
2248 /* This is a bind-mount. */
2249 if (strequal(mo->name, "bind")) {
2250 opts->bind = 1;
0f43436c 2251 opts->mnt_flags |= mo->legacy_flag; /* MS_BIND */
1b82d721
CB
2252 return 0;
2253 }
2254
2255 if (mo->flag == ~0)
2256 return log_info(0, "Ignoring %s mount option", mo->name);
2257
2258 if (mo->clear) {
2259 opts->attr.attr_clr |= mo->flag;
0f43436c 2260 opts->mnt_flags &= ~mo->legacy_flag;
1b82d721
CB
2261 TRACE("Lowering %s", mo->name);
2262 } else {
2263 opts->attr.attr_set |= mo->flag;
0f43436c 2264 opts->mnt_flags |= mo->legacy_flag;
1b82d721
CB
2265 TRACE("Raising %s", mo->name);
2266 }
2267
2268 return 0;
2269 }
2270
0f43436c 2271 for (struct mount_opt *mo = &propagation_opt[0]; mo->name != NULL; mo++) {
1b82d721
CB
2272 if (!strnequal(opt, mo->name, strlen(mo->name)))
2273 continue;
2274
2275 /* TODO: Handle recursive propagation requests. */
2276 opts->attr.propagation = mo->flag;
0f43436c 2277 opts->mnt_flags |= mo->legacy_flag;
1b82d721
CB
2278 return 0;
2279 }
2280
2281 return 0;
2282}
2283
704cadd5 2284int parse_mount_attrs(struct lxc_mount_options *opts, const char *mntopts)
1b82d721
CB
2285{
2286 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
380fcc08 2287 char *end = NULL, *mntopt_cur = NULL;
1b82d721
CB
2288 int ret;
2289 size_t size;
2290
2291 if (!opts)
2292 return ret_errno(EINVAL);
2293
2294 if (!mntopts)
2295 return 0;
2296
2297 mntopts_dup = strdup(mntopts);
2298 if (!mntopts_dup)
2299 return ret_errno(ENOMEM);
2300
2301 size = strlen(mntopts_dup) + 1;
2302 mntopts_new = zalloc(size);
2303 if (!mntopts_new)
2304 return ret_errno(ENOMEM);
2305
2306 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",") {
1b82d721
CB
2307 /* This is a filesystem specific option. */
2308 if (strchr(mntopt_cur, '=')) {
2309 if (!end) {
2310 end = stpcpy(mntopts_new, mntopt_cur);
2311 } else {
2312 end = stpcpy(end, ",");
2313 end = stpcpy(end, mntopt_cur);
2314 }
2315
2316 continue;
2317 }
2318
2319 /* This is a generic vfs option. */
2320 ret = parse_vfs_attr(opts, mntopt_cur, size);
2321 if (ret < 0)
2322 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur);
2323 }
2324
2325 if (*mntopts_new)
2326 opts->data = move_ptr(mntopts_new);
2327
2328 return 0;
2329}
2330
d840039e
YT
2331static void parse_propagationopt(char *opt, unsigned long *flags)
2332{
2333 struct mount_opt *mo;
2334
2335 /* If opt is found in propagation_opt, set or clear flags. */
d840039e 2336 for (mo = &propagation_opt[0]; mo->name != NULL; mo++) {
eed95eb0 2337 if (!strnequal(opt, mo->name, strlen(mo->name)))
0fd73091
CB
2338 continue;
2339
2340 if (mo->clear)
1e4bce2c 2341 *flags &= ~mo->legacy_flag;
0fd73091 2342 else
1e4bce2c 2343 *flags |= mo->legacy_flag;
0fd73091
CB
2344
2345 return;
d840039e
YT
2346 }
2347}
2348
8ce1abc2 2349int parse_propagationopts(const char *mntopts, unsigned long *pflags)
d840039e 2350{
dfd2e059
CB
2351 __do_free char *s = NULL;
2352 char *p;
d840039e
YT
2353
2354 if (!mntopts)
2355 return 0;
2356
2357 s = strdup(mntopts);
55022530
CB
2358 if (!s)
2359 return log_error_errno(-ENOMEM, errno, "Failed to allocate memory");
d840039e 2360
0fd73091 2361 *pflags = 0L;
8db9d26f 2362 lxc_iterate_parts(p, s, ",")
d840039e 2363 parse_propagationopt(p, pflags);
0fd73091 2364
d840039e
YT
2365 return 0;
2366}
2367
6fd5e769
SH
2368static void null_endofword(char *word)
2369{
2370 while (*word && *word != ' ' && *word != '\t')
2371 word++;
2372 *word = '\0';
2373}
2374
0fd73091 2375/* skip @nfields spaces in @src */
6fd5e769
SH
2376static char *get_field(char *src, int nfields)
2377{
6fd5e769 2378 int i;
0fd73091 2379 char *p = src;
6fd5e769
SH
2380
2381 for (i = 0; i < nfields; i++) {
2382 while (*p && *p != ' ' && *p != '\t')
2383 p++;
0fd73091 2384
6fd5e769
SH
2385 if (!*p)
2386 break;
0fd73091 2387
6fd5e769
SH
2388 p++;
2389 }
0fd73091 2390
6fd5e769
SH
2391 return p;
2392}
2393
911324ef
DL
2394static int mount_entry(const char *fsname, const char *target,
2395 const char *fstype, unsigned long mountflags,
d840039e
YT
2396 unsigned long pflags, const char *data, bool optional,
2397 bool dev, bool relative, const char *rootfs)
911324ef 2398{
0ac4b28a 2399 int ret;
6b5a54cd 2400 char srcbuf[PATH_MAX];
181437fd 2401 const char *srcpath = fsname;
614305f3 2402#ifdef HAVE_STATVFS
2938f7c8 2403 struct statvfs sb;
614305f3 2404#endif
2938f7c8 2405
181437fd 2406 if (relative) {
9bcde680
CB
2407 ret = strnprintf(srcbuf, sizeof(srcbuf), "%s/%s", rootfs ? rootfs : "/", fsname ? fsname : "");
2408 if (ret < 0)
55022530 2409 return log_error_errno(-1, errno, "source path is too long");
181437fd
YT
2410 srcpath = srcbuf;
2411 }
2412
2413 ret = safe_mount(srcpath, target, fstype, mountflags & ~MS_REMOUNT, data,
0ac4b28a
CB
2414 rootfs);
2415 if (ret < 0) {
55022530
CB
2416 if (optional)
2417 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2418 srcpath ? srcpath : "(null)", target);
0ac4b28a 2419
55022530
CB
2420 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2421 srcpath ? srcpath : "(null)", target);
911324ef
DL
2422 }
2423
2424 if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
0ac4b28a 2425
55022530
CB
2426 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2427 srcpath ? srcpath : "(none)", target ? target : "(none)");
0ac4b28a 2428
614305f3 2429#ifdef HAVE_STATVFS
181437fd 2430 if (srcpath && statvfs(srcpath, &sb) == 0) {
94bef7e4
TA
2431 unsigned long required_flags = 0;
2432
2938f7c8
SH
2433 if (sb.f_flag & MS_NOSUID)
2434 required_flags |= MS_NOSUID;
0ac4b28a 2435
ae7a770e 2436 if (sb.f_flag & MS_NODEV && !dev)
2938f7c8 2437 required_flags |= MS_NODEV;
0ac4b28a 2438
2938f7c8
SH
2439 if (sb.f_flag & MS_RDONLY)
2440 required_flags |= MS_RDONLY;
0ac4b28a 2441
2938f7c8
SH
2442 if (sb.f_flag & MS_NOEXEC)
2443 required_flags |= MS_NOEXEC;
0ac4b28a 2444
55022530
CB
2445 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2446 srcpath, sb.f_flag, required_flags);
0ac4b28a
CB
2447
2448 /* If this was a bind mount request, and required_flags
2938f7c8 2449 * does not have any flags which are not already in
0ac4b28a 2450 * mountflags, then skip the remount.
2938f7c8 2451 */
94bef7e4
TA
2452 if (!(mountflags & MS_REMOUNT) &&
2453 (!(required_flags & ~mountflags) && !(mountflags & MS_RDONLY))) {
15f3e22b
CB
2454 DEBUG("Mountflags already were %lu, skipping remount", mountflags);
2455 goto skipremount;
2938f7c8 2456 }
0ac4b28a 2457
2938f7c8 2458 mountflags |= required_flags;
6fd5e769 2459 }
614305f3 2460#endif
911324ef 2461
181437fd 2462 ret = mount(srcpath, target, fstype, mountflags | MS_REMOUNT, data);
0ac4b28a 2463 if (ret < 0) {
55022530
CB
2464 if (optional)
2465 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2466 srcpath ? srcpath : "(null)",
2467 target);
2468
2469 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2470 srcpath ? srcpath : "(null)",
2471 target);
911324ef
DL
2472 }
2473 }
2474
a3ed9b81 2475#ifdef HAVE_STATVFS
2476skipremount:
2477#endif
d840039e
YT
2478 if (pflags) {
2479 ret = mount(NULL, target, NULL, pflags, NULL);
2480 if (ret < 0) {
55022530
CB
2481 if (optional)
2482 return log_info_errno(0, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
2483 else
2484 return log_error_errno(-1, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
d840039e
YT
2485 }
2486 DEBUG("Changed mount propagation for \"%s\"", target);
2487 }
2488
0103eb53 2489 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
181437fd 2490 srcpath ? srcpath : "(null)", target, fstype);
911324ef
DL
2491
2492 return 0;
2493}
2494
0b932f9d
CB
2495const char *lxc_mount_options_info[LXC_MOUNT_MAX] = {
2496 "create=dir",
2497 "create=file",
2498 "optional",
2499 "relative",
f6815906 2500 "idmap=",
0b932f9d
CB
2501};
2502
c5e30de4 2503/* Remove "optional", "create=dir", and "create=file" from mntopt */
1b82d721 2504int parse_lxc_mount_attrs(struct lxc_mount_options *opts, char *mnt_opts)
4e4ca161 2505{
0b932f9d 2506 for (size_t i = LXC_MOUNT_CREATE_DIR; i < LXC_MOUNT_MAX; i++) {
8e05f350 2507 __do_close int fd_userns = -EBADF;
0b932f9d 2508 const char *opt_name = lxc_mount_options_info[i];
f6815906 2509 size_t len;
d97d9e9f 2510 char *idmap_path, *opt, *opt_next;
c5e30de4 2511
d97d9e9f
CB
2512 opt = strstr(mnt_opts, opt_name);
2513 if (!opt)
4e4ca161 2514 continue;
c5e30de4 2515
0b932f9d
CB
2516 switch (i) {
2517 case LXC_MOUNT_CREATE_DIR:
2518 opts->create_dir = 1;
2519 break;
2520 case LXC_MOUNT_CREATE_FILE:
2521 opts->create_file = 1;
2522 break;
2523 case LXC_MOUNT_OPTIONAL:
2524 opts->optional = 1;
2525 break;
2526 case LXC_MOUNT_RELATIVE:
2527 opts->relative = 1;
2528 break;
f6815906 2529 case LXC_MOUNT_IDMAP:
d97d9e9f
CB
2530 opt_next = opt;
2531 opt_next += STRLITERALLEN("idmap=");
2532 idmap_path = strchrnul(opt_next, ',');
2e5c468a 2533 len = idmap_path - opt_next + 1;
f6815906 2534
f6815906 2535 if (len >= sizeof(opts->userns_path))
16fcdacc
CB
2536 return syserror_set(-EIO, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2537
1b82d721 2538 strlcpy(opts->userns_path, opt_next, len);
2e5c468a 2539
16fcdacc
CB
2540 if (is_empty_string(opts->userns_path))
2541 return syserror_set(-EINVAL, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2542
1b82d721 2543 if (!strequal(opts->userns_path, "container")) {
4b875ef9
CB
2544 fd_userns = open(opts->userns_path, O_RDONLY | O_NOCTTY | O_CLOEXEC);
2545 if (fd_userns < 0)
1b82d721 2546 return syserror("Failed to open user namespace %s", opts->userns_path);
4b875ef9 2547 }
e26cf563
CB
2548
2549 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns, opts->userns_path);
f6815906 2550 break;
0b932f9d 2551 default:
16fcdacc 2552 return syserror_set(-EINVAL, "Unknown LXC specific mount option");
4e4ca161 2553 }
c5e30de4 2554
d97d9e9f
CB
2555 opt_next = strchr(opt, ',');
2556 if (!opt_next)
2557 *opt = '\0'; /* no more mntopts, so just chop it here */
0b932f9d 2558 else
d97d9e9f 2559 memmove(opt, opt_next + 1, strlen(opt_next + 1) + 1);
4e4ca161 2560 }
16fcdacc
CB
2561
2562 return 0;
4e4ca161
SH
2563}
2564
4d5b72a1 2565static int mount_entry_create_dir_file(const struct mntent *mntent,
749f98d9
CB
2566 const char *path,
2567 const struct lxc_rootfs *rootfs,
0fd73091 2568 const char *lxc_name, const char *lxc_path)
0ad19a3f 2569{
7a76eeaa 2570 __do_free char *p1 = NULL;
3b7e332f 2571 int ret;
7a76eeaa 2572 char *p2;
911324ef 2573
eed95eb0 2574 if (strnequal(mntent->mnt_type, "overlay", 7)) {
749f98d9 2575 ret = ovl_mkdir(mntent, rootfs, lxc_name, lxc_path);
12e6ab5d
CB
2576 if (ret < 0)
2577 return -1;
2578 }
6e46cc0d 2579
34cfffb3 2580 if (hasmntopt(mntent, "create=dir")) {
749f98d9 2581 ret = mkdir_p(path, 0755);
55022530
CB
2582 if (ret < 0 && errno != EEXIST)
2583 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
34cfffb3
SG
2584 }
2585
0fd73091
CB
2586 if (!hasmntopt(mntent, "create=file"))
2587 return 0;
749f98d9 2588
0fd73091
CB
2589 ret = access(path, F_OK);
2590 if (ret == 0)
2591 return 0;
749f98d9 2592
0fd73091
CB
2593 p1 = strdup(path);
2594 if (!p1)
2595 return -1;
749f98d9 2596
0fd73091 2597 p2 = dirname(p1);
749f98d9 2598
0fd73091 2599 ret = mkdir_p(p2, 0755);
55022530
CB
2600 if (ret < 0 && errno != EEXIST)
2601 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
749f98d9 2602
3b7e332f
CB
2603 ret = mknod(path, S_IFREG | 0000, 0);
2604 if (ret < 0 && errno != EEXIST)
2605 return -errno;
0fd73091 2606
749f98d9 2607 return 0;
4d5b72a1
NC
2608}
2609
ec50007f
CB
2610/* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2611 * without a rootfs. */
db4aba38 2612static inline int mount_entry_on_generic(struct mntent *mntent,
d8b712bc
CB
2613 const char *path,
2614 const struct lxc_rootfs *rootfs,
2615 const char *lxc_name,
2616 const char *lxc_path)
4d5b72a1 2617{
fd214f37 2618 __do_free char *mntdata = NULL;
a08bfbe3
CB
2619 unsigned long mntflags = 0, pflags = 0;
2620 char *rootfs_path = NULL;
d8b712bc 2621 int ret;
181437fd 2622 bool dev, optional, relative;
0b932f9d 2623 struct lxc_mount_options opts = {};
d8b712bc
CB
2624
2625 optional = hasmntopt(mntent, "optional") != NULL;
2626 dev = hasmntopt(mntent, "dev") != NULL;
181437fd 2627 relative = hasmntopt(mntent, "relative") != NULL;
d8b712bc 2628
ec50007f
CB
2629 if (rootfs && rootfs->path)
2630 rootfs_path = rootfs->mount;
2631
d8b712bc
CB
2632 ret = mount_entry_create_dir_file(mntent, path, rootfs, lxc_name,
2633 lxc_path);
2634 if (ret < 0) {
2635 if (optional)
2636 return 0;
608e3567 2637
d8b712bc
CB
2638 return -1;
2639 }
16fcdacc 2640
1b82d721 2641 ret = parse_lxc_mount_attrs(&opts, mntent->mnt_opts);
16fcdacc
CB
2642 if (ret < 0)
2643 return ret;
4e4ca161 2644
1b82d721
CB
2645 /*
2646 * Idmapped mount entries will be setup by the parent for us. Note that
2647 * we rely on mount_entry_create_dir_file() above to have already
2648 * created the target path for us. So the parent can just open the
2649 * target and send us the target fd.
2650 */
2651 errno = EOPNOTSUPP;
fa8e75f0 2652 if (!is_empty_string(opts.userns_path))
1b82d721 2653 return systrace_ret(0, "Skipping idmapped mount entry");
fa8e75f0 2654
d840039e
YT
2655 ret = parse_propagationopts(mntent->mnt_opts, &pflags);
2656 if (ret < 0)
2657 return -1;
2658
d94eb390 2659 ret = parse_mntopts_legacy(mntent->mnt_opts, &mntflags, &mntdata);
d8b712bc 2660 if (ret < 0)
a08bfbe3 2661 return ret;
a17b1e65 2662
6e46cc0d 2663 ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags,
d840039e 2664 pflags, mntdata, optional, dev, relative, rootfs_path);
68c152ef 2665
911324ef
DL
2666 return ret;
2667}
2668
8183f09e
CB
2669static inline int mount_entry_on_systemfs(struct lxc_rootfs *rootfs,
2670 struct mntent *mntent)
db4aba38 2671{
1433c9f9
CB
2672 int ret;
2673
2674 /* For containers created without a rootfs all mounts are treated as
07667a6a
CB
2675 * absolute paths starting at / on the host.
2676 */
1433c9f9 2677 if (mntent->mnt_dir[0] != '/')
9bcde680 2678 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/%s", mntent->mnt_dir);
1433c9f9 2679 else
9bcde680
CB
2680 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s", mntent->mnt_dir);
2681 if (ret < 0)
1433c9f9 2682 return -1;
1433c9f9 2683
8183f09e 2684 return mount_entry_on_generic(mntent, rootfs->buf, NULL, NULL, NULL);
db4aba38
NC
2685}
2686
4e4ca161 2687static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
9c0fd29a 2688 struct lxc_rootfs *rootfs,
0a2dddd4
CB
2689 const char *lxc_name,
2690 const char *lxc_path)
911324ef 2691{
bdd2b34c 2692 int offset;
013bd428 2693 char *aux;
67e571de 2694 const char *lxcpath;
bdd2b34c 2695 int ret = 0;
0ad19a3f 2696
593e8478 2697 lxcpath = lxc_global_config_value("lxc.lxcpath");
bdd2b34c 2698 if (!lxcpath)
2a59a681 2699 return -1;
2a59a681 2700
bdd2b34c
CB
2701 /* If rootfs->path is a blockdev path, allow container fstab to use
2702 * <lxcpath>/<name>/rootfs" as the target prefix.
2703 */
9bcde680
CB
2704 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s/rootfs", lxcpath, lxc_name);
2705 if (ret < 0)
80a881b2
SH
2706 goto skipvarlib;
2707
9c0fd29a 2708 aux = strstr(mntent->mnt_dir, rootfs->buf);
80a881b2 2709 if (aux) {
9c0fd29a 2710 offset = strlen(rootfs->buf);
80a881b2
SH
2711 goto skipabs;
2712 }
2713
2714skipvarlib:
013bd428 2715 aux = strstr(mntent->mnt_dir, rootfs->path);
55022530
CB
2716 if (!aux)
2717 return log_warn(ret, "Ignoring mount point \"%s\"", mntent->mnt_dir);
80a881b2
SH
2718 offset = strlen(rootfs->path);
2719
2720skipabs:
9bcde680
CB
2721 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, aux + offset);
2722 if (ret < 0)
a17b1e65 2723 return -1;
a17b1e65 2724
9c0fd29a 2725 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
911324ef 2726}
d330fe7b 2727
4e4ca161 2728static int mount_entry_on_relative_rootfs(struct mntent *mntent,
4806d3b9 2729 struct lxc_rootfs *rootfs,
0a2dddd4
CB
2730 const char *lxc_name,
2731 const char *lxc_path)
911324ef 2732{
911324ef 2733 int ret;
d330fe7b 2734
34cfffb3 2735 /* relative to root mount point */
9bcde680
CB
2736 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, mntent->mnt_dir);
2737 if (ret < 0)
9ba8130c 2738 return -1;
911324ef 2739
4806d3b9 2740 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
911324ef
DL
2741}
2742
8183f09e 2743static int mount_file_entries(struct lxc_rootfs *rootfs, FILE *file,
1ae3c19f 2744 const char *lxc_name, const char *lxc_path)
911324ef 2745{
9d03d857 2746 char buf[PATH_MAX];
0fd73091 2747 struct mntent mntent;
e76b8764 2748
aaf901be 2749 while (getmntent_r(file, &mntent, buf, sizeof(buf))) {
9d03d857
CB
2750 int ret;
2751
1ae3c19f 2752 if (!rootfs->path)
8183f09e 2753 ret = mount_entry_on_systemfs(rootfs, &mntent);
1ae3c19f
CB
2754 else if (mntent.mnt_dir[0] != '/')
2755 ret = mount_entry_on_relative_rootfs(&mntent, rootfs,
2756 lxc_name, lxc_path);
2757 else
2758 ret = mount_entry_on_absolute_rootfs(&mntent, rootfs,
9d03d857 2759 lxc_name, lxc_path);
1ae3c19f
CB
2760 if (ret < 0)
2761 return -1;
0ad19a3f 2762 }
cd54d859 2763
55022530
CB
2764 if (!feof(file) || ferror(file))
2765 return log_error(-1, "Failed to parse mount entries");
9d03d857
CB
2766
2767 return 0;
e7938e9e
MN
2768}
2769
55022530
CB
2770static inline void __auto_endmntent__(FILE **f)
2771{
2772 if (*f)
2773 endmntent(*f);
2774}
2775
2776#define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2777
48e5dcc8 2778static int setup_mount_fstab(struct lxc_rootfs *rootfs, const char *fstab,
8183f09e 2779 const char *lxc_name, const char *lxc_path)
e7938e9e 2780{
55022530 2781 __do_endmntent FILE *f = NULL;
e7938e9e
MN
2782 int ret;
2783
2784 if (!fstab)
2785 return 0;
2786
55022530
CB
2787 f = setmntent(fstab, "re");
2788 if (!f)
2789 return log_error_errno(-1, errno, "Failed to open \"%s\"", fstab);
e7938e9e 2790
a7c6e830 2791 ret = mount_file_entries(rootfs, f, lxc_name, lxc_path);
42dff448
CB
2792 if (ret < 0)
2793 ERROR("Failed to set up mount entries");
e7938e9e 2794
0ad19a3f 2795 return ret;
2796}
2797
1800f924
WB
2798/*
2799 * In order for nested containers to be able to mount /proc and /sys they need
2800 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2801 * (like lxcfs).
2802 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2803 * apparmor rule to deny access to them. This is mostly for convenience: The
2804 * container's root user can mount them anyway and thus has access to the two
2805 * file systems. But a non-root user in the container should not be allowed to
2806 * access them as a side effect without explicitly allowing it.
2807 */
2808static const char nesting_helpers[] =
dc691e34
CB
2809"proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2810"sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
1800f924
WB
2811
2812FILE *make_anonymous_mount_file(struct lxc_list *mount,
2813 bool include_nesting_helpers)
e7938e9e 2814{
f62cf1d4 2815 __do_close int fd = -EBADF;
4110345b 2816 FILE *f;
5ef5c9a3 2817 int ret;
e7938e9e 2818 char *mount_entry;
5ef5c9a3 2819 struct lxc_list *iterator;
5ef5c9a3 2820
0fd73091 2821 fd = memfd_create(".lxc_mount_file", MFD_CLOEXEC);
5ef5c9a3 2822 if (fd < 0) {
a324e7eb
CB
2823 char template[] = P_tmpdir "/.lxc_mount_file_XXXXXX";
2824
5ef5c9a3
CB
2825 if (errno != ENOSYS)
2826 return NULL;
a324e7eb
CB
2827
2828 fd = lxc_make_tmpfile(template, true);
55022530
CB
2829 if (fd < 0)
2830 return log_error_errno(NULL, errno, "Could not create temporary mount file");
0fd73091 2831
6bd04140 2832 TRACE("Created temporary mount file");
5ef5c9a3 2833 }
e7938e9e 2834
0fd73091
CB
2835 lxc_list_for_each (iterator, mount) {
2836 size_t len;
2837
e7938e9e 2838 mount_entry = iterator->elem;
0fd73091 2839 len = strlen(mount_entry);
5ef5c9a3 2840
489f39be 2841 ret = lxc_write_nointr(fd, mount_entry, len);
0fd73091 2842 if (ret != len)
79bcf5ee 2843 return NULL;
0fd73091 2844
489f39be 2845 ret = lxc_write_nointr(fd, "\n", 1);
0fd73091 2846 if (ret != 1)
79bcf5ee 2847 return NULL;
e7938e9e
MN
2848 }
2849
1800f924
WB
2850 if (include_nesting_helpers) {
2851 ret = lxc_write_nointr(fd, nesting_helpers,
6333c915
CB
2852 STRARRAYLEN(nesting_helpers));
2853 if (ret != STRARRAYLEN(nesting_helpers))
79bcf5ee 2854 return NULL;
1800f924
WB
2855 }
2856
0fd73091
CB
2857 ret = lseek(fd, 0, SEEK_SET);
2858 if (ret < 0)
79bcf5ee 2859 return NULL;
0fd73091 2860
4110345b
CB
2861 f = fdopen(fd, "re+");
2862 if (f)
2863 move_fd(fd); /* Transfer ownership of fd. */
2864 return f;
9fc7f8c0
TA
2865}
2866
06749971 2867static int setup_mount_entries(const struct lxc_conf *conf,
48e5dcc8
CB
2868 struct lxc_rootfs *rootfs, struct lxc_list *mount,
2869 const char *lxc_name, const char *lxc_path)
9fc7f8c0 2870{
c85ced65 2871 __do_fclose FILE *f = NULL;
9fc7f8c0 2872
1800f924 2873 f = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
19b5d755 2874 if (!f)
9fc7f8c0 2875 return -1;
e7938e9e 2876
a7c6e830 2877 return mount_file_entries(rootfs, f, lxc_name, lxc_path);
e7938e9e
MN
2878}
2879
1b82d721
CB
2880static int __lxc_idmapped_mounts_child(struct lxc_handler *handler, FILE *f)
2881{
2882 struct lxc_conf *conf = handler->conf;
2883 struct lxc_rootfs *rootfs = &conf->rootfs;
5a782dca 2884 int mnt_seq = 0;
1b82d721
CB
2885 int ret;
2886 char buf[PATH_MAX];
2887 struct mntent mntent;
2888
2889 while (getmntent_r(f, &mntent, buf, sizeof(buf))) {
2890 __do_close int fd_from = -EBADF, fd_to = -EBADF,
2891 fd_userns = -EBADF;
2892 __do_free char *__data = NULL;
5a782dca 2893 int cur_mnt_seq = -1;
1b82d721
CB
2894 struct lxc_mount_options opts = {};
2895 int dfd_from;
2896 const char *source_relative, *target_relative;
2897
2898 ret = parse_lxc_mount_attrs(&opts, mntent.mnt_opts);
2899 if (ret < 0)
2900 return syserror("Failed to parse LXC specific mount options");
2901 __data = opts.data;
2902
2903 ret = parse_mount_attrs(&opts, mntent.mnt_opts);
2904 if (ret < 0)
2905 return syserror("Failed to parse mount options");
2906
2907 /* No idmapped mount entry so skip it. */
2908 if (is_empty_string(opts.userns_path))
2909 continue;
2910
2911 if (!can_use_bind_mounts())
2912 return syserror_set(-EINVAL, "Kernel does not support idmapped mounts");
2913
2914 if (!opts.bind)
2915 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2916
2917 /* We don't support new filesystem mounts yet. */
2918 if (!is_empty_string(mntent.mnt_type) &&
2919 !strequal(mntent.mnt_type, "none"))
2920 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2921
2922 /* Someone specified additional mount options for a bind-mount. */
2923 if (!is_empty_string(opts.data))
2924 return syserror_set(-EINVAL, "Bind mounts don't support non-generic mount options");
2925
2926 /*
2927 * The source path is supposed to be taken relative to the
2928 * container's rootfs mount or - if the container does not have
2929 * a separate rootfs - to the host's /.
2930 */
2931 source_relative = deabs(mntent.mnt_fsname);
2932 if (opts.relative || !rootfs->path)
2933 dfd_from = rootfs->dfd_mnt;
2934 else
2935 dfd_from = rootfs->dfd_host;
2936 fd_from = open_tree(dfd_from, source_relative,
2937 OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC |
2938 (opts.recursive ? AT_RECURSIVE : 0));
2939 if (fd_from < 0)
2940 return syserror("Failed to create detached %smount of %d/%s",
2941 opts.recursive ? "recursive " : "",
2942 dfd_from, source_relative);
2943
2944 if (strequal(opts.userns_path, "container"))
2945 fd_userns = openat(dfd_from, "proc/self/ns/user", O_RDONLY | O_CLOEXEC);
2946 else
2947 fd_userns = open_at(-EBADF, opts.userns_path,
2948 PROTECT_OPEN_WITH_TRAILING_SYMLINKS, 0, 0);
2949 if (fd_userns < 0) {
2950 if (opts.optional) {
2951 TRACE("Skipping optional idmapped mount");
2952 continue;
2953 }
2954
2955 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
2956 opts.userns_path, opts.recursive ? "recursive " : "",
2957 dfd_from, source_relative);
2958 }
2959
2960 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
2961 fd_from, fd_userns,
2962 &opts, sizeof(opts));
2963 if (ret <= 0) {
2964 if (opts.optional) {
2965 TRACE("Skipping optional idmapped mount");
2966 continue;
2967 }
2968
2969 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
2970 fd_from, opts.recursive ? "recursive " : "",
2971 dfd_from, source_relative, fd_userns,
2972 opts.userns_path);
2973 }
2974
5a782dca
CB
2975 ret = lxc_abstract_unix_rcv_credential(handler->data_sock[0],
2976 &cur_mnt_seq,
2977 sizeof(cur_mnt_seq));
1b82d721
CB
2978 if (ret <= 0) {
2979 if (opts.optional) {
2980 TRACE("Skipping optional idmapped mount");
2981 continue;
2982 }
2983
2984 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
2985 opts.recursive ? "recursive " : "",
2986 dfd_from, source_relative, fd_userns);
2987 }
2988
5a782dca
CB
2989 if (mnt_seq != cur_mnt_seq)
2990 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
2991 mnt_seq, cur_mnt_seq);
2992 mnt_seq++;
2993
1b82d721
CB
2994 /* Set remaining mount options. */
2995 ret = mount_setattr(fd_from, "", AT_EMPTY_PATH |
2996 (opts.recursive ? AT_RECURSIVE : 0),
2997 &opts.attr, sizeof(opts.attr));
2998 if (ret < 0) {
2999 if (opts.optional) {
3000 TRACE("Skipping optional idmapped mount");
3001 continue;
3002 }
3003
3004 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
3005 opts.recursive ? "recursive " : "",
3006 dfd_from, source_relative, fd_userns);
3007 }
3008
3009 /*
3010 * In contrast to the legacy mount codepath we will simplify
3011 * our lifes and just always treat the target mountpoint to be
3012 * relative to the container's rootfs mountpoint or - if the
3013 * container does not have a separate rootfs - to the host's /.
3014 */
3015
3016 target_relative = deabs(mntent.mnt_dir);
3017 if (rootfs->path)
3018 dfd_from = rootfs->dfd_mnt;
3019 else
3020 dfd_from = rootfs->dfd_host;
3021 fd_to = open_at(dfd_from, target_relative, PROTECT_OPATH_FILE, PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS, 0);
3022 if (fd_to < 0) {
3023 if (opts.optional) {
3024 TRACE("Skipping optional idmapped mount");
3025 continue;
3026 }
3027
3028 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
3029 dfd_from, target_relative,
3030 opts.recursive ? "recursive " : "",
3031 fd_userns, dfd_from, source_relative);
3032 }
3033
3034 ret = move_detached_mount(fd_from, fd_to, "", 0, 0);
3035 if (ret) {
3036 if (opts.optional) {
3037 TRACE("Skipping optional idmapped mount");
3038 continue;
3039 }
3040
3041 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3042 opts.recursive ? "recursive " : "",
3043 fd_userns, dfd_from, source_relative, dfd_from, target_relative);
3044 }
3045
3046 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3047 opts.recursive ? "recursive " : "", fd_userns, dfd_from,
3048 source_relative, dfd_from, target_relative);
3049 }
3050
3051 if (!feof(f) || ferror(f))
3052 return syserror_set(-EINVAL, "Failed to parse mount entries");
3053
3054 return 0;
3055}
3056
3057static int lxc_idmapped_mounts_child(struct lxc_handler *handler)
3058{
3059 __do_fclose FILE *f_entries = NULL;
3060 int fret = -1;
3061 struct lxc_conf *conf = handler->conf;
3062 const char *fstab = conf->fstab;
3063 struct lxc_list *mount = &conf->mount_list;
3064 int ret;
3065
3066 f_entries = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
3067 if (!f_entries) {
3068 SYSERROR("Failed to create anonymous mount file");
3069 goto out;
3070 }
3071
3072 ret = __lxc_idmapped_mounts_child(handler, f_entries);
3073 if (ret) {
3074 SYSERROR("Failed to setup idmapped mount entries");
3075 goto out;
3076 }
3077
3078 TRACE("Finished setting up idmapped mounts");
3079
3080 if (fstab) {
3081 __do_endmntent FILE *f_fstab = NULL;
3082
3083 f_fstab = setmntent(fstab, "re");
3084 if (!f_fstab) {
3085 SYSERROR("Failed to open fstab format file \"%s\"", fstab);
3086 goto out;
3087 }
3088
3089 ret = __lxc_idmapped_mounts_child(handler, f_fstab);
3090 if (ret) {
3091 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3092 goto out;
3093 }
3094
3095 TRACE("Finished setting up idmapped mounts specified in fstab");
3096 }
3097
3098 fret = 0;
3099
3100out:
3101 ret = lxc_abstract_unix_send_credential(handler->data_sock[0], NULL, 0);
3102 if (ret < 0)
caaa223b 3103 return syserror("Failed to inform parent that we are done setting up mounts");
1b82d721
CB
3104
3105 return fret;
3106}
3107
bab88e68
CS
3108static int parse_cap(const char *cap)
3109{
84760c11 3110 size_t i;
3111 int capid = -1;
0fd73091
CB
3112 size_t end = sizeof(caps_opt) / sizeof(caps_opt[0]);
3113 char *ptr = NULL;
bab88e68 3114
71528742 3115 if (strequal(cap, "none"))
7035407c
DE
3116 return -2;
3117
8560cd36 3118 for (i = 0; i < end; i++) {
71528742 3119 if (!strequal(cap, caps_opt[i].name))
bab88e68
CS
3120 continue;
3121
3122 capid = caps_opt[i].value;
3123 break;
3124 }
3125
3126 if (capid < 0) {
0fd73091
CB
3127 /* Try to see if it's numeric, so the user may specify
3128 * capabilities that the running kernel knows about but we
3129 * don't
3130 */
bab88e68
CS
3131 errno = 0;
3132 capid = strtol(cap, &ptr, 10);
3133 if (!ptr || *ptr != '\0' || errno != 0)
3134 /* not a valid number */
3135 capid = -1;
3136 else if (capid > lxc_caps_last_cap())
3137 /* we have a number but it's not a valid
3138 * capability */
3139 capid = -1;
3140 }
3141
3142 return capid;
3143}
3144
0769b82a
CS
3145int in_caplist(int cap, struct lxc_list *caps)
3146{
0769b82a 3147 int capid;
0fd73091 3148 struct lxc_list *iterator;
0769b82a 3149
0fd73091 3150 lxc_list_for_each (iterator, caps) {
0769b82a
CS
3151 capid = parse_cap(iterator->elem);
3152 if (capid == cap)
3153 return 1;
3154 }
3155
3156 return 0;
3157}
3158
81810dd1
DL
3159static int setup_caps(struct lxc_list *caps)
3160{
bab88e68 3161 int capid;
0fd73091
CB
3162 char *drop_entry;
3163 struct lxc_list *iterator;
81810dd1 3164
0fd73091
CB
3165 lxc_list_for_each (iterator, caps) {
3166 int ret;
81810dd1
DL
3167
3168 drop_entry = iterator->elem;
3169
bab88e68 3170 capid = parse_cap(drop_entry);
55022530
CB
3171 if (capid < 0)
3172 return log_error(-1, "unknown capability %s", drop_entry);
81810dd1 3173
b81689a1
CB
3174 ret = prctl(PR_CAPBSET_DROP, prctl_arg(capid), prctl_arg(0),
3175 prctl_arg(0), prctl_arg(0));
55022530
CB
3176 if (ret < 0)
3177 return log_error_errno(-1, errno, "Failed to remove %s capability", drop_entry);
0fd73091 3178 DEBUG("Dropped %s (%d) capability", drop_entry, capid);
81810dd1
DL
3179 }
3180
0fd73091 3181 DEBUG("Capabilities have been setup");
1fb86a7c
SH
3182 return 0;
3183}
3184
3185static int dropcaps_except(struct lxc_list *caps)
3186{
2f443e88 3187 __do_free int *caplist = NULL;
0fd73091 3188 int i, capid, numcaps;
1fb86a7c 3189 char *keep_entry;
0fd73091 3190 struct lxc_list *iterator;
1fb86a7c 3191
0fd73091 3192 numcaps = lxc_caps_last_cap() + 1;
2caf9a97
SH
3193 if (numcaps <= 0 || numcaps > 200)
3194 return -1;
0fd73091 3195 TRACE("Found %d capabilities", numcaps);
2caf9a97 3196
1a0e70ac 3197 /* caplist[i] is 1 if we keep capability i */
2f443e88 3198 caplist = must_realloc(NULL, numcaps * sizeof(int));
1fb86a7c
SH
3199 memset(caplist, 0, numcaps * sizeof(int));
3200
0fd73091 3201 lxc_list_for_each (iterator, caps) {
1fb86a7c
SH
3202 keep_entry = iterator->elem;
3203
bab88e68 3204 capid = parse_cap(keep_entry);
7035407c
DE
3205 if (capid == -2)
3206 continue;
3207
55022530
CB
3208 if (capid < 0)
3209 return log_error(-1, "Unknown capability %s", keep_entry);
1fb86a7c 3210
0fd73091 3211 DEBUG("Keep capability %s (%d)", keep_entry, capid);
1fb86a7c
SH
3212 caplist[capid] = 1;
3213 }
0fd73091
CB
3214
3215 for (i = 0; i < numcaps; i++) {
3216 int ret;
3217
1fb86a7c
SH
3218 if (caplist[i])
3219 continue;
0fd73091 3220
b81689a1
CB
3221 ret = prctl(PR_CAPBSET_DROP, prctl_arg(i), prctl_arg(0),
3222 prctl_arg(0), prctl_arg(0));
55022530
CB
3223 if (ret < 0)
3224 return log_error_errno(-1, errno, "Failed to remove capability %d", i);
1fb86a7c
SH
3225 }
3226
0fd73091 3227 DEBUG("Capabilities have been setup");
81810dd1
DL
3228 return 0;
3229}
3230
0fd73091
CB
3231static int parse_resource(const char *res)
3232{
3233 int ret;
c6d09e15
WB
3234 size_t i;
3235 int resid = -1;
3236
0fd73091 3237 for (i = 0; i < sizeof(limit_opt) / sizeof(limit_opt[0]); ++i)
71528742 3238 if (strequal(res, limit_opt[i].name))
c6d09e15 3239 return limit_opt[i].value;
c6d09e15 3240
0fd73091 3241 /* Try to see if it's numeric, so the user may specify
c6d09e15 3242 * resources that the running kernel knows about but
0fd73091
CB
3243 * we don't.
3244 */
3245 ret = lxc_safe_int(res, &resid);
3246 if (ret < 0)
3247 return -1;
3248
3249 return resid;
c6d09e15
WB
3250}
3251
0fd73091
CB
3252int setup_resource_limits(struct lxc_list *limits, pid_t pid)
3253{
3254 int resid;
c6d09e15
WB
3255 struct lxc_list *it;
3256 struct lxc_limit *lim;
c6d09e15 3257
0fd73091 3258 lxc_list_for_each (it, limits) {
c6d09e15
WB
3259 lim = it->elem;
3260
3261 resid = parse_resource(lim->resource);
55022530
CB
3262 if (resid < 0)
3263 return log_error(-1, "Unknown resource %s", lim->resource);
c6d09e15 3264
f48b5fd8 3265#if HAVE_PRLIMIT || HAVE_PRLIMIT64
55022530
CB
3266 if (prlimit(pid, resid, &lim->limit, NULL) != 0)
3267 return log_error_errno(-1, errno, "Failed to set limit %s", lim->resource);
2de12765
CB
3268
3269 TRACE("Setup \"%s\" limit", lim->resource);
f48b5fd8 3270#else
55022530 3271 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim->resource);
f48b5fd8 3272#endif
c6d09e15 3273 }
0fd73091 3274
c6d09e15
WB
3275 return 0;
3276}
3277
7edd0540
L
3278int setup_sysctl_parameters(struct lxc_list *sysctls)
3279{
e6f76452 3280 __do_free char *tmp = NULL;
7edd0540
L
3281 struct lxc_list *it;
3282 struct lxc_sysctl *elem;
0fd73091 3283 int ret = 0;
6b5a54cd 3284 char filename[PATH_MAX] = {0};
7edd0540 3285
0fd73091 3286 lxc_list_for_each (it, sysctls) {
7edd0540
L
3287 elem = it->elem;
3288 tmp = lxc_string_replace(".", "/", elem->key);
55022530
CB
3289 if (!tmp)
3290 return log_error(-1, "Failed to replace key %s", elem->key);
7edd0540 3291
9bcde680
CB
3292 ret = strnprintf(filename, sizeof(filename), "/proc/sys/%s", tmp);
3293 if (ret < 0)
55022530 3294 return log_error(-1, "Error setting up sysctl parameters path");
7edd0540 3295
0fd73091 3296 ret = lxc_write_to_file(filename, elem->value,
7cea5905 3297 strlen(elem->value), false, 0666);
55022530
CB
3298 if (ret < 0)
3299 return log_error_errno(-1, errno, "Failed to setup sysctl parameters %s to %s",
3300 elem->key, elem->value);
7edd0540 3301 }
0fd73091 3302
7edd0540
L
3303 return 0;
3304}
3305
61d7a733
YT
3306int setup_proc_filesystem(struct lxc_list *procs, pid_t pid)
3307{
0c669152 3308 __do_free char *tmp = NULL;
61d7a733
YT
3309 struct lxc_list *it;
3310 struct lxc_proc *elem;
0fd73091 3311 int ret = 0;
6b5a54cd 3312 char filename[PATH_MAX] = {0};
61d7a733 3313
0fd73091 3314 lxc_list_for_each (it, procs) {
61d7a733
YT
3315 elem = it->elem;
3316 tmp = lxc_string_replace(".", "/", elem->filename);
55022530
CB
3317 if (!tmp)
3318 return log_error(-1, "Failed to replace key %s", elem->filename);
61d7a733 3319
9bcde680
CB
3320 ret = strnprintf(filename, sizeof(filename), "/proc/%d/%s", pid, tmp);
3321 if (ret < 0)
55022530 3322 return log_error(-1, "Error setting up proc filesystem path");
61d7a733 3323
0fd73091 3324 ret = lxc_write_to_file(filename, elem->value,
7cea5905 3325 strlen(elem->value), false, 0666);
55022530
CB
3326 if (ret < 0)
3327 return log_error_errno(-1, errno, "Failed to setup proc filesystem %s to %s", elem->filename, elem->value);
61d7a733 3328 }
0fd73091 3329
61d7a733
YT
3330 return 0;
3331}
3332
ae9242c8
SH
3333static char *default_rootfs_mount = LXCROOTFSMOUNT;
3334
7b379ab3 3335struct lxc_conf *lxc_conf_init(void)
089cd8b8 3336{
26ddeedd 3337 int i;
0fd73091 3338 struct lxc_conf *new;
7b379ab3 3339
b8e43ef0 3340 new = zalloc(sizeof(*new));
0fd73091 3341 if (!new)
7b379ab3 3342 return NULL;
7b379ab3 3343
4b73005c 3344 new->loglevel = LXC_LOG_LEVEL_NOTSET;
9c601e1f 3345 new->personality = LXC_ARCH_UNCHANGED;
124fa0a8 3346 new->autodev = 1;
3a784510 3347 new->console.buffer_size = 0;
596a818d
DE
3348 new->console.log_path = NULL;
3349 new->console.log_fd = -1;
861813e5 3350 new->console.log_size = 0;
28a4b0e5 3351 new->console.path = NULL;
63376d7d 3352 new->console.peer = -1;
fb87aa6a 3353 new->console.proxy.busy = -1;
36a94ce8 3354 new->console.proxy.ptx = -1;
41808e20 3355 new->console.proxy.pty = -1;
f3dff080
CB
3356 new->console.ptx = -EBADF;
3357 new->console.pty = -EBADF;
d926c261 3358 new->console.pty_nr = -1;
63376d7d 3359 new->console.name[0] = '\0';
7294a26d 3360 new->devpts_fd = -EBADF;
732375f5 3361 memset(&new->console.ringbuf, 0, sizeof(struct lxc_ringbuf));
d2e30e99 3362 new->maincmd_fd = -1;
258f8051 3363 new->monitor_signal_pdeath = SIGKILL;
76a26f55 3364 new->nbd_idx = -1;
54c30e29 3365 new->rootfs.mount = strdup(default_rootfs_mount);
53f3f048 3366 if (!new->rootfs.mount) {
53f3f048
SH
3367 free(new);
3368 return NULL;
3369 }
6e54330c 3370 new->rootfs.managed = true;
ea57e424 3371 new->rootfs.dfd_mnt = -EBADF;
a5a08920 3372 new->rootfs.dfd_dev = -EBADF;
ea11a215 3373 new->rootfs.dfd_host = -EBADF;
79ff643d 3374 new->rootfs.fd_path_pin = -EBADF;
4b875ef9 3375 new->rootfs.dfd_idmapped = -EBADF;
858377e4 3376 new->logfd = -1;
7b379ab3 3377 lxc_list_init(&new->cgroup);
54860ed0 3378 lxc_list_init(&new->cgroup2);
a134099d
CB
3379 /* Block ("allowlist") all devices by default. */
3380 new->bpf_devices.list_type = LXC_BPF_DEVICE_CGROUP_ALLOWLIST;
93de768e 3381 INIT_LIST_HEAD(&(new->bpf_devices).devices);
7b379ab3 3382 lxc_list_init(&new->mount_list);
81810dd1 3383 lxc_list_init(&new->caps);
1fb86a7c 3384 lxc_list_init(&new->keepcaps);
f6d3e3e4 3385 lxc_list_init(&new->id_map);
46ad64ab
CB
3386 new->root_nsuid_map = NULL;
3387 new->root_nsgid_map = NULL;
f979ac15 3388 lxc_list_init(&new->includes);
4184c3e1 3389 lxc_list_init(&new->aliens);
7c661726 3390 lxc_list_init(&new->environment);
c6d09e15 3391 lxc_list_init(&new->limits);
7edd0540 3392 lxc_list_init(&new->sysctls);
61d7a733 3393 lxc_list_init(&new->procs);
44ae0fb6 3394 new->hooks_version = 0;
28d9e29e 3395 for (i = 0; i < NUM_LXC_HOOKS; i++)
26ddeedd 3396 lxc_list_init(&new->hooks[i]);
ee1e7aa0 3397 lxc_list_init(&new->groups);
d2e75eba 3398 INIT_LIST_HEAD(&new->state_clients);
fe4de9a6 3399 new->lsm_aa_profile = NULL;
1800f924 3400 lxc_list_init(&new->lsm_aa_raw);
fe4de9a6 3401 new->lsm_se_context = NULL;
4fef78bc 3402 new->lsm_se_keyring_context = NULL;
8f818a84 3403 new->keyring_disable_session = false;
952b5031 3404 new->transient_procfs_mnt = false;
7a41e857
LT
3405 new->shmount.path_host = NULL;
3406 new->shmount.path_cont = NULL;
7b379ab3 3407
72bb04e4
PT
3408 /* if running in a new user namespace, init and COMMAND
3409 * default to running as UID/GID 0 when using lxc-execute */
3410 new->init_uid = 0;
3411 new->init_gid = 0;
c71f64cb 3412 memset(&new->init_groups, 0, sizeof(lxc_groups_t));
43654d34 3413 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
b074bbf1 3414 memset(&new->ns_share, 0, sizeof(char *) * LXC_NS_MAX);
70fd7fc9 3415 memset(&new->timens, 0, sizeof(struct timens_offsets));
c3e3c21a 3416 seccomp_conf_init(new);
72bb04e4 3417
87d0990c
CB
3418 INIT_LIST_HEAD(&new->netdevs);
3419
7b379ab3 3420 return new;
089cd8b8
DL
3421}
3422
344c9d81 3423int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
a19b974f 3424 size_t buf_size)
f6d3e3e4 3425{
f62cf1d4 3426 __do_close int fd = -EBADF;
76bcd422 3427 int ret;
6b5a54cd 3428 char path[PATH_MAX];
f6d3e3e4 3429
a19b974f 3430 if (geteuid() != 0 && idtype == ID_TYPE_GID) {
f62cf1d4 3431 __do_close int setgroups_fd = -EBADF;
a19b974f 3432
9bcde680
CB
3433 ret = strnprintf(path, sizeof(path), "/proc/%d/setgroups", pid);
3434 if (ret < 0)
a19b974f 3435 return -E2BIG;
a19b974f 3436
76bcd422 3437 setgroups_fd = open(path, O_WRONLY);
55022530
CB
3438 if (setgroups_fd < 0 && errno != ENOENT)
3439 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
a19b974f 3440
76bcd422
CB
3441 if (setgroups_fd >= 0) {
3442 ret = lxc_write_nointr(setgroups_fd, "deny\n",
3443 STRLITERALLEN("deny\n"));
55022530
CB
3444 if (ret != STRLITERALLEN("deny\n"))
3445 return log_error_errno(-1, errno, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
395b1a3e 3446 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid);
a19b974f 3447 }
a19b974f
CB
3448 }
3449
9bcde680 3450 ret = strnprintf(path, sizeof(path), "/proc/%d/%cid_map", pid,
29053180 3451 idtype == ID_TYPE_UID ? 'u' : 'g');
9bcde680 3452 if (ret < 0)
f6d3e3e4 3453 return -E2BIG;
29053180 3454
55022530
CB
3455 fd = open(path, O_WRONLY | O_CLOEXEC);
3456 if (fd < 0)
3457 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
29053180 3458
29053180 3459 ret = lxc_write_nointr(fd, buf, buf_size);
55022530
CB
3460 if (ret != buf_size)
3461 return log_error_errno(-1, errno, "Failed to write %cid mapping to \"%s\"",
3462 idtype == ID_TYPE_UID ? 'u' : 'g', path);
29053180
CB
3463
3464 return 0;
f6d3e3e4
SH
3465}
3466
6e50e704
CB
3467/* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3468 *
3469 * @return 1 if functional binary was found
3470 * @return 0 if binary exists but is lacking privilege
3471 * @return -ENOENT if binary does not exist
3472 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
6e50e704 3473 */
df6a2945
CB
3474static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
3475{
48411df2 3476 __do_free char *path = NULL;
df6a2945
CB
3477 int ret;
3478 struct stat st;
df6a2945 3479
6e50e704 3480 if (cap != CAP_SETUID && cap != CAP_SETGID)
83cb7362 3481 return ret_errno(EINVAL);
6e50e704 3482
df6a2945
CB
3483 path = on_path(binary, NULL);
3484 if (!path)
83cb7362 3485 return ret_errno(ENOENT);
df6a2945
CB
3486
3487 ret = stat(path, &st);
3275932b 3488 if (ret < 0)
83cb7362 3489 return -errno;
df6a2945
CB
3490
3491 /* Check if the binary is setuid. */
55022530
CB
3492 if (st.st_mode & S_ISUID)
3493 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path);
df6a2945 3494
0fd73091 3495#if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
df6a2945
CB
3496 /* Check if it has the CAP_SETUID capability. */
3497 if ((cap & CAP_SETUID) &&
3498 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
55022530
CB
3499 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED))
3500 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
df6a2945
CB
3501
3502 /* Check if it has the CAP_SETGID capability. */
3503 if ((cap & CAP_SETGID) &&
3504 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
55022530
CB
3505 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED))
3506 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
a864a2e1
CB
3507
3508 return 0;
0fd73091 3509#else
83cb7362
CB
3510 /*
3511 * If we cannot check for file capabilities we need to give the benefit
69924fff
CB
3512 * of the doubt. Otherwise we might fail even though all the necessary
3513 * file capabilities are set.
3514 */
55022530 3515 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3275932b 3516 return 1;
a864a2e1 3517#endif
df6a2945
CB
3518}
3519
59eac805 3520static int lxc_map_ids_exec_wrapper(void *args)
986ef930
CB
3521{
3522 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
3523 return -1;
3524}
3525
86c78011
CB
3526static struct id_map *find_mapped_hostid_entry(const struct lxc_list *idmap,
3527 unsigned id, enum idtype idtype);
3528
f6d3e3e4
SH
3529int lxc_map_ids(struct lxc_list *idmap, pid_t pid)
3530{
0fd73091 3531 int fill, left;
986ef930 3532 char u_or_g;
4bc3b759 3533 char *pos;
6b5a54cd 3534 char cmd_output[PATH_MAX];
0fd73091
CB
3535 struct id_map *map;
3536 struct lxc_list *iterator;
3537 enum idtype type;
0fd73091 3538 int ret = 0, gidmap = 0, uidmap = 0;
c6ba8981
CB
3539 char mapbuf[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3540 INTTYPE_TO_STRLEN(pid_t) + STRLITERALLEN(" ") +
3541 LXC_IDMAPLEN] = {0};
86c78011 3542 bool had_entry = false, maps_host_root = false, use_shadow = false;
c724025c
JC
3543 int hostuid, hostgid;
3544
3545 hostuid = geteuid();
3546 hostgid = getegid();
df6a2945 3547
86c78011
CB
3548 /*
3549 * Check whether caller wants to map host root.
3550 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3551 * host root into the child userns as you would be able to write fscaps
3552 * that would be valid in the ancestor userns. Mapping host root should
3553 * rarely be the case but LXC is being clever in a bunch of cases.
3554 */
3555 if (find_mapped_hostid_entry(idmap, 0, ID_TYPE_UID))
3556 maps_host_root = true;
3557
df6a2945
CB
3558 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3559 * ranges, then insist that root also reserve ranges in subuid. This
22038de5
SH
3560 * will protected it by preventing another user from being handed the
3561 * range by shadow.
3562 */
df6a2945 3563 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
6e50e704
CB
3564 if (uidmap == -ENOENT)
3565 WARN("newuidmap binary is missing");
3566 else if (!uidmap)
3567 WARN("newuidmap is lacking necessary privileges");
3568
df6a2945 3569 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
6e50e704
CB
3570 if (gidmap == -ENOENT)
3571 WARN("newgidmap binary is missing");
3572 else if (!gidmap)
3573 WARN("newgidmap is lacking necessary privileges");
3574
86c78011
CB
3575 if (maps_host_root) {
3576 INFO("Caller maps host root. Writing mapping directly");
3577 } else if (uidmap > 0 && gidmap > 0) {
0fd73091 3578 DEBUG("Functional newuidmap and newgidmap binary found");
4bc3b759 3579 use_shadow = true;
df6a2945 3580 } else {
99d43365
CB
3581 /* In case unprivileged users run application containers via
3582 * execute() or a start*() there are valid cases where they may
3583 * only want to map their own {g,u}id. Let's not block them from
3584 * doing so by requiring geteuid() == 0.
3585 */
3586 DEBUG("No newuidmap and newgidmap binary found. Trying to "
c724025c
JC
3587 "write directly with euid %d", hostuid);
3588 }
3589
3590 /* Check if we really need to use newuidmap and newgidmap.
f48e8071 3591 * If the user is only remapping their own {g,u}id, we don't need it.
c724025c
JC
3592 */
3593 if (use_shadow && lxc_list_len(idmap) == 2) {
3594 use_shadow = false;
3595 lxc_list_for_each(iterator, idmap) {
3596 map = iterator->elem;
3597 if (map->idtype == ID_TYPE_UID && map->range == 1 &&
3598 map->nsid == hostuid && map->hostid == hostuid)
3599 continue;
3600 if (map->idtype == ID_TYPE_GID && map->range == 1 &&
3601 map->nsid == hostgid && map->hostid == hostgid)
3602 continue;
3603 use_shadow = true;
3604 break;
3605 }
0e6e3a41 3606 }
251d0d2a 3607
986ef930
CB
3608 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
3609 type++, u_or_g = 'g') {
3610 pos = mapbuf;
3611
0e6e3a41 3612 if (use_shadow)
986ef930 3613 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
4f7521b4 3614
cf3ef16d 3615 lxc_list_for_each(iterator, idmap) {
251d0d2a 3616 map = iterator->elem;
cf3ef16d
SH
3617 if (map->idtype != type)
3618 continue;
3619
4bc3b759
CB
3620 had_entry = true;
3621
986ef930 3622 left = LXC_IDMAPLEN - (pos - mapbuf);
9bcde680 3623 fill = strnprintf(pos, left, "%s%lu %lu %lu%s",
4bc3b759
CB
3624 use_shadow ? " " : "", map->nsid,
3625 map->hostid, map->range,
0e6e3a41 3626 use_shadow ? "" : "\n");
55022530
CB
3627 /*
3628 * The kernel only takes <= 4k for writes to
3629 * /proc/<pid>/{g,u}id_map
3630 */
9bcde680 3631 if (fill <= 0)
55022530 3632 return log_error_errno(-1, errno, "Too many %cid mappings defined", u_or_g);
4bc3b759 3633
cf3ef16d 3634 pos += fill;
251d0d2a 3635 }
cf3ef16d 3636 if (!had_entry)
4f7521b4 3637 continue;
cf3ef16d 3638
d85813cd 3639 /* Try to catch the output of new{g,u}idmap to make debugging
986ef930
CB
3640 * easier.
3641 */
3642 if (use_shadow) {
3643 ret = run_command(cmd_output, sizeof(cmd_output),
3644 lxc_map_ids_exec_wrapper,
3645 (void *)mapbuf);
55022530
CB
3646 if (ret < 0)
3647 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g, cmd_output, mapbuf);
54fbbeb5 3648 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
d1838f34 3649 } else {
986ef930 3650 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
55022530
CB
3651 if (ret < 0)
3652 return log_error(-1, "Failed to write mapping: %s", mapbuf);
54fbbeb5 3653 TRACE("Wrote mapping \"%s\"", mapbuf);
d1838f34 3654 }
986ef930
CB
3655
3656 memset(mapbuf, 0, sizeof(mapbuf));
f6d3e3e4 3657 }
251d0d2a 3658
986ef930 3659 return 0;
f6d3e3e4
SH
3660}
3661
234998b4
CB
3662/*
3663 * Return the host uid/gid to which the container root is mapped in val.
0b3a6504 3664 * Return true if id was found, false otherwise.
cf3ef16d 3665 */
234998b4 3666static id_t get_mapped_rootid(const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3667{
4160c3a0 3668 unsigned nsid;
0fd73091
CB
3669 struct id_map *map;
3670 struct lxc_list *it;
4160c3a0
CB
3671
3672 if (idtype == ID_TYPE_UID)
3673 nsid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
3674 else
3675 nsid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
cf3ef16d 3676
0fd73091 3677 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 3678 map = it->elem;
7b50c609 3679 if (map->idtype != idtype)
cf3ef16d 3680 continue;
4160c3a0 3681 if (map->nsid != nsid)
cf3ef16d 3682 continue;
234998b4 3683 return map->hostid;
cf3ef16d 3684 }
4160c3a0 3685
234998b4
CB
3686 if (idtype == ID_TYPE_UID)
3687 return LXC_INVALID_UID;
3688
3689 return LXC_INVALID_GID;
cf3ef16d
SH
3690}
3691
facdf925 3692int mapped_hostid(unsigned id, const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3693{
cf3ef16d 3694 struct id_map *map;
0fd73091
CB
3695 struct lxc_list *it;
3696
3697 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 3698 map = it->elem;
2133f58c 3699 if (map->idtype != idtype)
cf3ef16d 3700 continue;
0fd73091 3701
cf3ef16d 3702 if (id >= map->hostid && id < map->hostid + map->range)
57d116ab 3703 return (id - map->hostid) + map->nsid;
cf3ef16d 3704 }
0fd73091 3705
57d116ab 3706 return -1;
cf3ef16d
SH
3707}
3708
7581a82f 3709int find_unmapped_nsid(const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3710{
cf3ef16d 3711 struct id_map *map;
0fd73091 3712 struct lxc_list *it;
2133f58c 3713 unsigned int freeid = 0;
0fd73091 3714
cf3ef16d 3715again:
0fd73091 3716 lxc_list_for_each (it, &conf->id_map) {
cf3ef16d 3717 map = it->elem;
2133f58c 3718 if (map->idtype != idtype)
cf3ef16d 3719 continue;
0fd73091 3720
cf3ef16d
SH
3721 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
3722 freeid = map->nsid + map->range;
3723 goto again;
3724 }
3725 }
0fd73091 3726
cf3ef16d
SH
3727 return freeid;
3728}
3729
e1b9d6af
CB
3730/*
3731 * Mount a proc under @rootfs if proc self points to a pid other than
3732 * my own. This is needed to have a known-good proc mount for setting
3733 * up LSMs both at container startup and attach.
3734 *
e1b9d6af
CB
3735 * NOTE: not to be called from inside the container namespace!
3736 */
952b5031 3737static int lxc_transient_proc(struct lxc_rootfs *rootfs)
e1b9d6af 3738{
952b5031
CB
3739 __do_close int fd_proc = -EBADF;
3740 int link_to_pid, link_len, pid_self, ret;
3741 char link[INTTYPE_TO_STRLEN(pid_t) + 1];
e1b9d6af 3742
ea57e424 3743 link_len = readlinkat(rootfs->dfd_mnt, "proc/self", link, sizeof(link));
952b5031 3744 if (link_len < 0) {
ea57e424 3745 ret = mkdirat(rootfs->dfd_mnt, "proc", 0000);
952b5031 3746 if (ret < 0 && errno != EEXIST)
ea57e424 3747 return log_error_errno(-errno, errno, "Failed to create %d(proc)", rootfs->dfd_mnt);
e1b9d6af 3748
952b5031
CB
3749 goto domount;
3750 } else if (link_len >= sizeof(link)) {
3751 return log_error_errno(-EIO, EIO, "Truncated link target");
e1b9d6af 3752 }
952b5031 3753 link[link_len] = '\0';
e1b9d6af 3754
952b5031
CB
3755 pid_self = lxc_raw_getpid();
3756 INFO("Caller's PID is %d; /proc/self points to %s", pid_self, link);
e1b9d6af 3757
952b5031
CB
3758 ret = lxc_safe_int(link, &link_to_pid);
3759 if (ret)
3760 return log_error_errno(-ret, ret, "Failed to parse %s", link);
e1b9d6af 3761
952b5031
CB
3762 /* Correct procfs is already mounted. */
3763 if (link_to_pid == pid_self)
3764 return log_trace(0, "Correct procfs instance mounted");
e1b9d6af 3765
ea57e424 3766 fd_proc = open_at(rootfs->dfd_mnt, "proc", PROTECT_OPATH_DIRECTORY,
952b5031
CB
3767 PROTECT_LOOKUP_BENEATH_XDEV, 0);
3768 if (fd_proc < 0)
3769 return log_error_errno(-errno, errno, "Failed to open transient procfs mountpoint");
e1b9d6af 3770
9bcde680
CB
3771 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/proc/self/fd/%d", fd_proc);
3772 if (ret < 0)
952b5031 3773 return ret_errno(EIO);
e1b9d6af 3774
952b5031 3775 ret = umount2(rootfs->buf, MNT_DETACH);
e1b9d6af 3776 if (ret < 0)
952b5031 3777 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs->buf);
e1b9d6af
CB
3778
3779domount:
3780 /* rootfs is NULL */
952b5031
CB
3781 if (!rootfs->path) {
3782 ret = mount("proc", rootfs->buf, "proc", 0, NULL);
3783 } else {
ea57e424 3784 ret = safe_mount_beneath_at(rootfs->dfd_mnt, "none", "proc", "proc", 0, NULL);
952b5031 3785 if (ret < 0) {
9bcde680
CB
3786 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/proc", rootfs->path ? rootfs->mount : "");
3787 if (ret < 0)
952b5031
CB
3788 return ret_errno(EIO);
3789
3790 ret = safe_mount("proc", rootfs->buf, "proc", 0, NULL, rootfs->mount);
3791 }
3792 }
e1b9d6af 3793 if (ret < 0)
952b5031 3794 return log_error_errno(-1, errno, "Failed to mount temporary procfs");
e1b9d6af 3795
952b5031 3796 INFO("Created transient procfs mount");
e1b9d6af
CB
3797 return 1;
3798}
3799
943144d9 3800/* NOTE: Must not be called from inside the container namespace! */
59eac805 3801static int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
5112cd70
SH
3802{
3803 int mounted;
3804
952b5031 3805 mounted = lxc_transient_proc(&conf->rootfs);
5112cd70 3806 if (mounted == -1) {
01958b1f 3807 /* continue only if there is no rootfs */
943144d9 3808 if (conf->rootfs.path)
952b5031 3809 return log_error_errno(-EPERM, EPERM, "Failed to create transient procfs mount");
5112cd70 3810 } else if (mounted == 1) {
952b5031 3811 conf->transient_procfs_mnt = true;
5112cd70 3812 }
943144d9 3813
5112cd70
SH
3814 return 0;
3815}
3816
3817void tmp_proc_unmount(struct lxc_conf *lxc_conf)
3818{
952b5031
CB
3819 if (lxc_conf->transient_procfs_mnt) {
3820 (void)umount2("/proc", MNT_DETACH);
3821 lxc_conf->transient_procfs_mnt = false;
3822 }
5112cd70
SH
3823}
3824
9e61fb1f 3825/* Walk /proc/mounts and change any shared entries to dependent mounts. */
ed41e764 3826static void turn_into_dependent_mounts(const struct lxc_rootfs *rootfs)
e995d7a2 3827{
7969675f 3828 __do_free char *line = NULL;
003be47b 3829 __do_fclose FILE *f = NULL;
f62cf1d4 3830 __do_close int memfd = -EBADF, mntinfo_fd = -EBADF;
e995d7a2 3831 size_t len = 0;
a39fc34b
CB
3832 ssize_t copied;
3833 int ret;
e995d7a2 3834
ed41e764
CB
3835 mntinfo_fd = open_at(rootfs->dfd_host, "proc/self/mountinfo", PROTECT_OPEN,
3836 (PROTECT_LOOKUP_BENEATH_XDEV & ~RESOLVE_NO_SYMLINKS), 0);
fea3b91d 3837 if (mntinfo_fd < 0) {
ed41e764 3838 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs->dfd_host);
6a49f05e 3839 return;
fea3b91d 3840 }
6a49f05e
CB
3841
3842 memfd = memfd_create(".lxc_mountinfo", MFD_CLOEXEC);
3843 if (memfd < 0) {
3844 char template[] = P_tmpdir "/.lxc_mountinfo_XXXXXX";
3845
3846 if (errno != ENOSYS) {
fea3b91d 3847 SYSERROR("Failed to create temporary in-memory file");
6a49f05e
CB
3848 return;
3849 }
3850
3851 memfd = lxc_make_tmpfile(template, true);
fea3b91d 3852 if (memfd < 0) {
fea3b91d
DJ
3853 WARN("Failed to create temporary file");
3854 return;
3855 }
6a49f05e
CB
3856 }
3857
a39fc34b 3858 copied = fd_to_fd(mntinfo_fd, memfd);
6a49f05e 3859 if (copied < 0) {
fea3b91d 3860 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
6a49f05e
CB
3861 return;
3862 }
6a49f05e 3863
6a49f05e
CB
3864 ret = lseek(memfd, 0, SEEK_SET);
3865 if (ret < 0) {
fea3b91d 3866 SYSERROR("Failed to reset file descriptor offset");
6a49f05e
CB
3867 return;
3868 }
3869
4110345b 3870 f = fdopen(memfd, "re");
e995d7a2 3871 if (!f) {
003be47b 3872 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
e995d7a2
SH
3873 return;
3874 }
3875
003be47b
CB
3876 /*
3877 * After a successful fdopen() memfd will be closed when calling
3878 * fclose(f). Calling close(memfd) afterwards is undefined.
3879 */
3880 move_fd(memfd);
3881
e995d7a2 3882 while (getline(&line, &len, f) != -1) {
0fd73091
CB
3883 char *opts, *target;
3884
e995d7a2
SH
3885 target = get_field(line, 4);
3886 if (!target)
3887 continue;
0fd73091 3888
e995d7a2
SH
3889 opts = get_field(target, 2);
3890 if (!opts)
3891 continue;
0fd73091 3892
e995d7a2
SH
3893 null_endofword(opts);
3894 if (!strstr(opts, "shared"))
3895 continue;
0fd73091 3896
e995d7a2 3897 null_endofword(target);
0fd73091
CB
3898 ret = mount(NULL, target, NULL, MS_SLAVE, NULL);
3899 if (ret < 0) {
9e61fb1f 3900 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
6a49f05e 3901 continue;
e995d7a2
SH
3902 }
3903 }
9e61fb1f 3904 TRACE("Turned all mount table entries into dependent mount");
e995d7a2
SH
3905}
3906
0fd73091
CB
3907/* This does the work of remounting / if it is shared, calling the container
3908 * pre-mount hooks, and mounting the rootfs.
35120d9c 3909 */
8ce1abc2
CB
3910int lxc_setup_rootfs_prepare_root(struct lxc_conf *conf, const char *name,
3911 const char *lxcpath)
0ad19a3f 3912{
0fd73091
CB
3913 int ret;
3914
ea11a215
CB
3915 conf->rootfs.dfd_host = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
3916 if (conf->rootfs.dfd_host < 0)
a370f16b
CB
3917 return log_error_errno(-errno, errno, "Failed to open \"/\"");
3918
ed41e764
CB
3919 turn_into_dependent_mounts(&conf->rootfs);
3920
35120d9c 3921 if (conf->rootfs_setup) {
35120d9c 3922 const char *path = conf->rootfs.mount;
0fd73091 3923
ed41e764
CB
3924 /*
3925 * The rootfs was set up in another namespace. bind-mount it to
0fd73091
CB
3926 * give us a mount in our own ns so we can pivot_root to it
3927 */
3928 ret = mount(path, path, "rootfs", MS_BIND, NULL);
55022530
CB
3929 if (ret < 0)
3930 return log_error(-1, "Failed to bind mount container / onto itself");
0fd73091 3931
ea57e424
CB
3932 conf->rootfs.dfd_mnt = openat(-EBADF, path, O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOCTTY);
3933 if (conf->rootfs.dfd_mnt < 0)
26ea5533
CB
3934 return log_error_errno(-errno, errno, "Failed to open file descriptor for container rootfs");
3935
55022530 3936 return log_trace(0, "Bind mounted container / onto itself");
35120d9c 3937 }
d4ef7c50 3938
0fd73091 3939 ret = run_lxc_hooks(name, "pre-mount", conf, NULL);
55022530
CB
3940 if (ret < 0)
3941 return log_error(-1, "Failed to run pre-mount hooks");
35120d9c 3942
4e86cad3 3943 ret = lxc_mount_rootfs(&conf->rootfs);
55022530
CB
3944 if (ret < 0)
3945 return log_error(-1, "Failed to setup rootfs for");
35120d9c
SH
3946
3947 conf->rootfs_setup = true;
3948 return 0;
3949}
3950
1c1c7051
SH
3951static bool verify_start_hooks(struct lxc_conf *conf)
3952{
6b5a54cd 3953 char path[PATH_MAX];
0fd73091
CB
3954 struct lxc_list *it;
3955
3956 lxc_list_for_each (it, &conf->hooks[LXCHOOK_START]) {
1c1c7051 3957 int ret;
0fd73091 3958 char *hookname = it->elem;
1c1c7051 3959
9bcde680 3960 ret = strnprintf(path, sizeof(path), "%s%s",
0fd73091
CB
3961 conf->rootfs.path ? conf->rootfs.mount : "",
3962 hookname);
9bcde680 3963 if (ret < 0)
1c1c7051 3964 return false;
0fd73091 3965
75193660 3966 ret = access(path, X_OK);
55022530
CB
3967 if (ret < 0)
3968 return log_error_errno(false, errno, "Start hook \"%s\" not found in container", hookname);
0fd73091 3969
6a0c909a 3970 return true;
1c1c7051
SH
3971 }
3972
3973 return true;
3974}
3975
20502652
CB
3976static int lxc_setup_boot_id(void)
3977{
3978 int ret;
3979 const char *boot_id_path = "/proc/sys/kernel/random/boot_id";
3980 const char *mock_boot_id_path = "/dev/.lxc-boot-id";
3981 lxc_id128_t n;
3982
3983 if (access(boot_id_path, F_OK))
3984 return 0;
3985
3986 memset(&n, 0, sizeof(n));
3987 if (lxc_id128_randomize(&n)) {
3988 SYSERROR("Failed to generate random data for uuid");
3989 return -1;
3990 }
3991
3992 ret = lxc_id128_write(mock_boot_id_path, n);
3993 if (ret < 0) {
3994 SYSERROR("Failed to write uuid to %s", mock_boot_id_path);
3995 return -1;
3996 }
3997
3998 ret = chmod(mock_boot_id_path, 0444);
3999 if (ret < 0) {
4000 SYSERROR("Failed to chown %s", mock_boot_id_path);
4001 (void)unlink(mock_boot_id_path);
4002 return -1;
4003 }
4004
4005 ret = mount(mock_boot_id_path, boot_id_path, NULL, MS_BIND, NULL);
4006 if (ret < 0) {
4007 SYSERROR("Failed to mount %s to %s", mock_boot_id_path,
4008 boot_id_path);
4009 (void)unlink(mock_boot_id_path);
4010 return -1;
4011 }
4012
4013 ret = mount(NULL, boot_id_path, NULL,
4014 (MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NOEXEC |
4015 MS_NODEV),
4016 NULL);
4017 if (ret < 0) {
4018 SYSERROR("Failed to remount %s read-only", boot_id_path);
4019 (void)unlink(mock_boot_id_path);
4020 return -1;
4021 }
4022
4023 return 0;
4024}
4025
af04d847 4026static int lxc_setup_keyring(struct lsm_ops *lsm_ops, const struct lxc_conf *conf)
d701d729
CB
4027{
4028 key_serial_t keyring;
4029 int ret = 0;
4030
4031 if (conf->lsm_se_keyring_context)
af04d847 4032 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_keyring_context);
d701d729 4033 else if (conf->lsm_se_context)
af04d847 4034 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_context);
d701d729 4035 if (ret < 0)
d2022f30 4036 return syserror("Failed to set keyring context");
d701d729
CB
4037
4038 /*
4039 * Try to allocate a new session keyring for the container to prevent
4040 * information leaks.
4041 */
4042 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, prctl_arg(0),
4043 prctl_arg(0), prctl_arg(0), prctl_arg(0));
4044 if (keyring < 0) {
4045 switch (errno) {
4046 case ENOSYS:
4047 DEBUG("The keyctl() syscall is not supported or blocked");
4048 break;
4049 case EACCES:
4050 __fallthrough;
4051 case EPERM:
4052 DEBUG("Failed to access kernel keyring. Continuing...");
4053 break;
4054 default:
d2022f30 4055 SYSWARN("Failed to create kernel keyring");
d701d729
CB
4056 break;
4057 }
4058 }
4059
4060 return ret;
4061}
4062
4b875ef9
CB
4063static int lxc_rootfs_prepare_child(struct lxc_handler *handler)
4064{
4065 struct lxc_rootfs *rootfs = &handler->conf->rootfs;
4066 int dfd_idmapped = -EBADF;
4067 int ret;
4068
4069 if (lxc_list_empty(&handler->conf->id_map))
4070 return 0;
4071
4072 if (is_empty_string(rootfs->mnt_opts.userns_path))
4073 return 0;
4074
4075 if (handler->conf->rootfs_setup)
4076 return 0;
4077
4078 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1], &dfd_idmapped, NULL, 0);
4079 if (ret < 0)
4080 return syserror("Failed to receive idmapped mount fd");
4081
4082 rootfs->dfd_idmapped = dfd_idmapped;
4083 TRACE("Received detached idmapped mount %d", rootfs->dfd_idmapped);
4084 return 0;
4085}
4086
1b82d721
CB
4087int lxc_idmapped_mounts_parent(struct lxc_handler *handler)
4088{
5a782dca
CB
4089 int mnt_seq = 0;
4090
1b82d721
CB
4091 for (;;) {
4092 __do_close int fd_from = -EBADF, fd_userns = -EBADF;
4093 struct lxc_mount_attr attr = {};
4094 struct lxc_mount_options opts = {};
4095 ssize_t ret;
4096
4097 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4098 &fd_from, &fd_userns,
4099 &opts, sizeof(opts));
4100 if (ret < 0)
4101 return syserror("Failed to receive idmapped mount file descriptors from child");
4102
4103 if (fd_from < 0 || fd_userns < 0)
4104 return log_trace(0, "Finished receiving idmapped mount file descriptors from child");
4105
4106 attr.attr_set = MOUNT_ATTR_IDMAP;
4107 attr.userns_fd = fd_userns;
4108 ret = mount_setattr(fd_from, "",
4109 AT_EMPTY_PATH |
4110 (opts.recursive ? AT_RECURSIVE : 0),
4111 &attr, sizeof(attr));
4112 if (ret)
4113 return syserror("Failed to idmap detached %smount %d to %d",
4114 opts.recursive ? "recursive " : "",
4115 fd_from, fd_userns);
4116
5a782dca
CB
4117 ret = lxc_abstract_unix_send_credential(handler->data_sock[1],
4118 &mnt_seq,
4119 sizeof(mnt_seq));
1b82d721
CB
4120 if (ret < 0)
4121 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
4122 opts.recursive ? "recursive " : "",
4123 fd_from, fd_userns);
4124
4125 TRACE("Parent idmapped detached %smount %d to user namespace %d",
4126 opts.recursive ? "recursive " : "", fd_from, fd_userns);
5a782dca 4127 mnt_seq++;
1b82d721
CB
4128 }
4129}
4130
493ae3fe
CB
4131static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
4132{
b35f8f7e 4133 call_cleaner(lxc_delete_tty) struct lxc_tty_info *info_new = &(struct lxc_tty_info){};
493ae3fe
CB
4134 int sock = handler->data_sock[1];
4135 struct lxc_conf *conf = handler->conf;
b35f8f7e
CB
4136 struct lxc_tty_info *tty_info = &conf->ttys;
4137 size_t ttys_max = tty_info->max;
4138 struct lxc_terminal_info *terminal_info;
4139 int ret;
493ae3fe 4140
b35f8f7e 4141 if (!ttys_max)
493ae3fe
CB
4142 return 0;
4143
b35f8f7e
CB
4144 info_new->tty = malloc(sizeof(*(info_new->tty)) * ttys_max);
4145 if (!info_new->tty)
4146 return ret_errno(ENOMEM);
493ae3fe 4147
b35f8f7e
CB
4148 for (int i = 0; i < ttys_max; i++) {
4149 terminal_info = &info_new->tty[i];
4150 terminal_info->busy = -1;
4151 terminal_info->ptx = -EBADF;
4152 terminal_info->pty = -EBADF;
4153 }
493ae3fe 4154
b35f8f7e
CB
4155 for (int i = 0; i < ttys_max; i++) {
4156 int ptx = -EBADF, pty = -EBADF;
4157
4158 ret = lxc_abstract_unix_recv_two_fds(sock, &ptx, &pty);
493ae3fe 4159 if (ret < 0)
b35f8f7e 4160 return syserror("Failed to receive %zu ttys from child", ttys_max);
493ae3fe 4161
b35f8f7e
CB
4162 terminal_info = &info_new->tty[i];
4163 terminal_info->ptx = ptx;
4164 terminal_info->pty = pty;
4165 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4166 terminal_info->ptx, terminal_info->pty);
493ae3fe
CB
4167 }
4168
b35f8f7e
CB
4169 tty_info->tty = move_ptr(info_new->tty);
4170 TRACE("Received %zu ttys from child", ttys_max);
4171 return 0;
493ae3fe
CB
4172}
4173
9f77617b
CB
4174static int lxc_send_console_to_parent(struct lxc_handler *handler)
4175{
4176 struct lxc_terminal *console = &handler->conf->console;
4177 int ret;
4178
4179 if (!wants_console(console))
4180 return 0;
4181
4182 /* We've already allocated a console from the host's devpts instance. */
4183 if (console->pty < 0)
4184 return 0;
4185
4186 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
4187 console->ptx, console->pty,
4188 console,
4189 sizeof(struct lxc_terminal));
4190 if (ret < 0)
4191 return syserror("Fail to send console to parent");
4192
4193 TRACE("Sent console to parent");
4194 return 0;
4195}
4196
4197static int lxc_recv_console_from_child(struct lxc_handler *handler)
4198{
4199 __do_close int fd_ptx = -EBADF, fd_pty = -EBADF;
4200 struct lxc_terminal *console = &handler->conf->console;
4201 int ret;
4202
4203 if (!wants_console(console))
4204 return 0;
4205
4206 /* We've already allocated a console from the host's devpts instance. */
4207 if (console->pty >= 0)
4208 return 0;
4209
4210 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4211 &fd_ptx, &fd_pty,
4212 console,
4213 sizeof(struct lxc_terminal));
4214 if (ret < 0)
4215 return syserror("Fail to receive console from child");
4216
4217 console->ptx = move_fd(fd_ptx);
4218 console->pty = move_fd(fd_pty);
4219
4220 TRACE("Received console from child");
4221 return 0;
4222}
4223
493ae3fe
CB
4224int lxc_sync_fds_parent(struct lxc_handler *handler)
4225{
4226 int ret;
4227
4228 ret = lxc_seccomp_recv_notifier_fd(&handler->conf->seccomp, handler->data_sock[1]);
4229 if (ret < 0)
4230 return syserror_ret(ret, "Failed to receive seccomp notify fd from child");
4231
42c0d056 4232 ret = lxc_recv_devpts_from_child(handler);
493ae3fe
CB
4233 if (ret < 0)
4234 return syserror_ret(ret, "Failed to receive devpts fd from child");
4235
4236 /* Read tty fds allocated by child. */
4237 ret = lxc_recv_ttys_from_child(handler);
4238 if (ret < 0)
4239 return syserror_ret(ret, "Failed to receive tty info from child process");
4240
4241 if (handler->ns_clone_flags & CLONE_NEWNET) {
4242 ret = lxc_network_recv_name_and_ifindex_from_child(handler);
4243 if (ret < 0)
4244 return syserror_ret(ret, "Failed to receive names and ifindices for network devices from child");
4245 }
4246
9f77617b
CB
4247 ret = lxc_recv_console_from_child(handler);
4248 if (ret < 0)
4249 return syserror_ret(ret, "Failed to receive console from child");
4250
493ae3fe
CB
4251 TRACE("Finished syncing file descriptors with child");
4252 return 0;
4253}
4254
111ed96e
CB
4255int lxc_sync_fds_child(struct lxc_handler *handler)
4256{
4257 int ret;
4258
4259 ret = lxc_seccomp_send_notifier_fd(&handler->conf->seccomp, handler->data_sock[0]);
4260 if (ret < 0)
4261 return syserror_ret(ret, "Failed to send seccomp notify fd to parent");
4262
4263 ret = lxc_send_devpts_to_parent(handler);
4264 if (ret < 0)
4265 return syserror_ret(ret, "Failed to send seccomp devpts fd to parent");
4266
4267 ret = lxc_send_ttys_to_parent(handler);
4268 if (ret < 0)
4269 return syserror_ret(ret, "Failed to send tty file descriptors to parent");
4270
4271 if (handler->ns_clone_flags & CLONE_NEWNET) {
4272 ret = lxc_network_send_name_and_ifindex_to_parent(handler);
4273 if (ret < 0)
4274 return syserror_ret(ret, "Failed to send network device names and ifindices to parent");
4275 }
4276
9f77617b
CB
4277 ret = lxc_send_console_to_parent(handler);
4278 if (ret < 0)
4279 return syserror_ret(ret, "Failed to send console to parent");
4280
111ed96e
CB
4281 TRACE("Finished syncing file descriptors with parent");
4282 return 0;
4283}
4284
3b988b33 4285int lxc_setup(struct lxc_handler *handler)
35120d9c 4286{
2187efd3 4287 int ret;
0fd73091 4288 const char *lxcpath = handler->lxcpath, *name = handler->name;
35120d9c 4289 struct lxc_conf *lxc_conf = handler->conf;
35120d9c 4290
4b875ef9
CB
4291 ret = lxc_rootfs_prepare_child(handler);
4292 if (ret < 0)
4293 return syserror("Failed to prepare rootfs");
4294
8ce1abc2 4295 ret = lxc_setup_rootfs_prepare_root(lxc_conf, name, lxcpath);
55022530
CB
4296 if (ret < 0)
4297 return log_error(-1, "Failed to setup rootfs");
35120d9c 4298
b87ee312 4299 if (handler->nsfd[LXC_NS_UTS] == -EBADF) {
8353b4c9 4300 ret = setup_utsname(lxc_conf->utsname);
55022530
CB
4301 if (ret < 0)
4302 return log_error(-1, "Failed to setup the utsname %s", name);
0ad19a3f 4303 }
4304
8f818a84 4305 if (!lxc_conf->keyring_disable_session) {
d701d729 4306 ret = lxc_setup_keyring(handler->lsm_ops, lxc_conf);
8f818a84 4307 if (ret < 0)
d701d729 4308 return log_error(-1, "Failed to setup container keyring");
8f818a84 4309 }
b25291da 4310
e389f2af 4311 if (handler->ns_clone_flags & CLONE_NEWNET) {
6bc4165d
CB
4312 ret = lxc_network_recv_from_parent(handler);
4313 if (ret < 0)
4314 return log_error(-1, "Failed to receive veth names from parent");
4315
87d0990c 4316 ret = lxc_setup_network_in_child_namespaces(lxc_conf);
55022530
CB
4317 if (ret < 0)
4318 return log_error(-1, "Failed to setup network");
790255cf
CB
4319 }
4320
bc6928ff 4321 if (lxc_conf->autodev > 0) {
63012bdd 4322 ret = mount_autodev(name, &lxc_conf->rootfs, lxc_conf->autodevtmpfssize, lxcpath);
55022530
CB
4323 if (ret < 0)
4324 return log_error(-1, "Failed to mount \"/dev\"");
c6883f38
SH
4325 }
4326
8353b4c9
CB
4327 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4328 * need to wait until other stuff has finished.
368bbc02 4329 */
6d25a524 4330 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK);
55022530
CB
4331 if (ret < 0)
4332 return log_error(-1, "Failed to setup first automatic mounts");
368bbc02 4333
48e5dcc8 4334 ret = setup_mount_fstab(&lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath);
55022530
CB
4335 if (ret < 0)
4336 return log_error(-1, "Failed to setup mounts");
576f946d 4337
c631115d
FA
4338 if (!lxc_list_empty(&lxc_conf->mount_list)) {
4339 ret = setup_mount_entries(lxc_conf, &lxc_conf->rootfs,
4340 &lxc_conf->mount_list, name, lxcpath);
55022530
CB
4341 if (ret < 0)
4342 return log_error(-1, "Failed to setup mount entries");
c631115d
FA
4343 }
4344
1b82d721
CB
4345 if (!lxc_sync_wake_parent(handler, START_SYNC_IDMAPPED_MOUNTS))
4346 return -1;
4347
4348 ret = lxc_idmapped_mounts_child(handler);
4349 if (ret)
4350 return syserror("Failed to attached detached idmapped mounts");
4351
1f0a3b6e
CB
4352 lxc_conf->rootfs.dfd_dev = open_at(lxc_conf->rootfs.dfd_mnt, "dev",
4353 PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
4354 if (lxc_conf->rootfs.dfd_dev < 0 && errno != ENOENT)
4355 return log_error_errno(-errno, errno, "Failed to open \"/dev\"");
4356
8353b4c9
CB
4357 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4358 * mounted. It is guaranteed to be mounted now either through
4359 * automatically or via fstab entries.
368bbc02 4360 */
6d25a524 4361 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK);
55022530
CB
4362 if (ret < 0)
4363 return log_error(-1, "Failed to setup remaining automatic mounts");
368bbc02 4364
8353b4c9 4365 ret = run_lxc_hooks(name, "mount", lxc_conf, NULL);
55022530
CB
4366 if (ret < 0)
4367 return log_error(-1, "Failed to run mount hooks");
773fb9ca 4368
bc6928ff 4369 if (lxc_conf->autodev > 0) {
8353b4c9 4370 ret = run_lxc_hooks(name, "autodev", lxc_conf, NULL);
55022530
CB
4371 if (ret < 0)
4372 return log_error(-1, "Failed to run autodev hooks");
06749971 4373
8353b4c9 4374 ret = lxc_fill_autodev(&lxc_conf->rootfs);
55022530
CB
4375 if (ret < 0)
4376 return log_error(-1, "Failed to populate \"/dev\"");
91c3830e 4377 }
368bbc02 4378
75193660 4379 /* Make sure any start hooks are in the container */
55022530
CB
4380 if (!verify_start_hooks(lxc_conf))
4381 return log_error(-1, "Failed to verify start hooks");
75193660 4382
cf68ffd9
CB
4383 ret = lxc_create_tmp_proc_mount(lxc_conf);
4384 if (ret < 0)
3dd3fc31 4385 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
cf68ffd9 4386
96a980e1 4387 ret = lxc_setup_devpts_child(handler);
289b707b
CB
4388 if (ret < 0)
4389 return log_error(-1, "Failed to prepare new devpts instance");
4390
03585adc
CB
4391 ret = lxc_finish_devpts_child(handler);
4392 if (ret < 0)
4393 return log_error(-1, "Failed to finish devpts setup");
4394
f3dff080 4395 ret = lxc_setup_console(handler, &lxc_conf->rootfs, &lxc_conf->console,
37c74fd1 4396 lxc_conf->ttys.dir);
55022530
CB
4397 if (ret < 0)
4398 return log_error(-1, "Failed to setup console");
6e590161 4399
6a2ca1b4
CB
4400 ret = lxc_create_ttys(handler);
4401 if (ret < 0)
4402 return log_error(-1, "Failed to create ttys");
4403
ed8704d0 4404 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
55022530
CB
4405 if (ret < 0)
4406 return log_error(-1, "Failed to setup \"/dev\" symlinks");
69aa6655 4407
8ce1abc2 4408 ret = lxc_setup_rootfs_switch_root(&lxc_conf->rootfs);
55022530
CB
4409 if (ret < 0)
4410 return log_error(-1, "Failed to pivot root into rootfs");
ed502555 4411
20502652
CB
4412 /* Setting the boot-id is best-effort for now. */
4413 if (lxc_conf->autodev > 0)
4414 (void)lxc_setup_boot_id();
4415
8353b4c9 4416 ret = setup_personality(lxc_conf->personality);
55022530 4417 if (ret < 0)
9c601e1f 4418 return syserror("Failed to set personality");
cccc74b5 4419
8353b4c9
CB
4420 /* Set sysctl value to a path under /proc/sys as determined from the
4421 * key. For e.g. net.ipv4.ip_forward translated to
4422 * /proc/sys/net/ipv4/ip_forward.
7edd0540
L
4423 */
4424 if (!lxc_list_empty(&lxc_conf->sysctls)) {
4425 ret = setup_sysctl_parameters(&lxc_conf->sysctls);
55022530
CB
4426 if (ret < 0)
4427 return log_error(-1, "Failed to setup sysctl parameters");
7edd0540
L
4428 }
4429
97a8f74f 4430 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
55022530
CB
4431 if (!lxc_list_empty(&lxc_conf->caps))
4432 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
8353b4c9 4433
55022530
CB
4434 if (dropcaps_except(&lxc_conf->keepcaps))
4435 return log_error(-1, "Failed to keep capabilities");
97a8f74f 4436 } else if (setup_caps(&lxc_conf->caps)) {
55022530 4437 return log_error(-1, "Failed to drop capabilities");
81810dd1
DL
4438 }
4439
79ff643d 4440 put_lxc_rootfs(&handler->conf->rootfs, true);
8353b4c9 4441 NOTICE("The container \"%s\" is set up", name);
cd54d859 4442
0ad19a3f 4443 return 0;
4444}
26ddeedd 4445
3f60c2f7 4446int run_lxc_hooks(const char *name, char *hookname, struct lxc_conf *conf,
14a7b0f9 4447 char *argv[])
26ddeedd 4448{
26ddeedd 4449 struct lxc_list *it;
3ea957c6
RK
4450 int which;
4451
4452 for (which = 0; which < NUM_LXC_HOOKS; which ++) {
71528742 4453 if (strequal(hookname, lxchook_names[which]))
3ea957c6
RK
4454 break;
4455 }
4456
4457 if (which >= NUM_LXC_HOOKS)
26ddeedd 4458 return -1;
3f60c2f7 4459
0fd73091 4460 lxc_list_for_each (it, &conf->hooks[which]) {
26ddeedd 4461 int ret;
3f60c2f7
CB
4462 char *hook = it->elem;
4463
4464 ret = run_script_argv(name, conf->hooks_version, "lxc", hook,
14a7b0f9 4465 hookname, argv);
3f60c2f7
CB
4466 if (ret < 0)
4467 return -1;
26ddeedd 4468 }
3f60c2f7 4469
26ddeedd
SH
4470 return 0;
4471}
72d0e1cb 4472
72d0e1cb
SG
4473int lxc_clear_config_caps(struct lxc_conf *c)
4474{
1a0e70ac 4475 struct lxc_list *it, *next;
72d0e1cb 4476
0fd73091 4477 lxc_list_for_each_safe (it, &c->caps, next) {
72d0e1cb
SG
4478 lxc_list_del(it);
4479 free(it->elem);
4480 free(it);
4481 }
0fd73091 4482
cc36133d 4483 lxc_list_init(&c->caps);
72d0e1cb
SG
4484 return 0;
4485}
4486
c7e345ae
CB
4487static int lxc_free_idmap(struct lxc_list *id_map)
4488{
27c27d73
SH
4489 struct lxc_list *it, *next;
4490
46bc6f2a 4491 lxc_list_for_each_safe(it, id_map, next) {
27c27d73
SH
4492 lxc_list_del(it);
4493 free(it->elem);
4494 free(it);
4495 }
c7e345ae 4496
cc36133d 4497 lxc_list_init(id_map);
27c27d73
SH
4498 return 0;
4499}
7e621263
CB
4500
4501static int __lxc_free_idmap(struct lxc_list *id_map)
4502{
4503 lxc_free_idmap(id_map);
4504 free(id_map);
4505 return 0;
4506}
4507define_cleanup_function(struct lxc_list *, __lxc_free_idmap);
27c27d73 4508
4355ab5f
SH
4509int lxc_clear_idmaps(struct lxc_conf *c)
4510{
4511 return lxc_free_idmap(&c->id_map);
4512}
4513
1fb86a7c
SH
4514int lxc_clear_config_keepcaps(struct lxc_conf *c)
4515{
0fd73091 4516 struct lxc_list *it, *next;
1fb86a7c 4517
0fd73091 4518 lxc_list_for_each_safe (it, &c->keepcaps, next) {
1fb86a7c
SH
4519 lxc_list_del(it);
4520 free(it->elem);
4521 free(it);
4522 }
0fd73091 4523
cc36133d 4524 lxc_list_init(&c->keepcaps);
1fb86a7c
SH
4525 return 0;
4526}
4527
a3ed9b81 4528int lxc_clear_namespace(struct lxc_conf *c)
4529{
ced5587c
CB
4530 for (int i = 0; i < LXC_NS_MAX; i++)
4531 free_disarm(c->ns_share[i]);
4532
a3ed9b81 4533 return 0;
4534}
4535
54860ed0 4536int lxc_clear_cgroups(struct lxc_conf *c, const char *key, int version)
72d0e1cb 4537{
54860ed0 4538 char *global_token, *namespaced_token;
ab1a6cac 4539 size_t namespaced_token_len;
54860ed0 4540 struct lxc_list *it, *next, *list;
ab1a6cac 4541 const char *k = key;
54860ed0 4542 bool all = false;
72d0e1cb 4543
54860ed0 4544 if (version == CGROUP2_SUPER_MAGIC) {
d6c06927
CB
4545 global_token = "lxc.cgroup2";
4546 namespaced_token = "lxc.cgroup2.";
4547 namespaced_token_len = STRLITERALLEN("lxc.cgroup2.");
54860ed0
CB
4548 list = &c->cgroup2;
4549 } else if (version == CGROUP_SUPER_MAGIC) {
d6c06927
CB
4550 global_token = "lxc.cgroup";
4551 namespaced_token = "lxc.cgroup.";
4552 namespaced_token_len = STRLITERALLEN("lxc.cgroup.");
54860ed0
CB
4553 list = &c->cgroup;
4554 } else {
d6c06927 4555 return ret_errno(EINVAL);
54860ed0
CB
4556 }
4557
71528742 4558 if (strequal(key, global_token))
72d0e1cb 4559 all = true;
eed95eb0 4560 else if (strnequal(key, namespaced_token, namespaced_token_len))
ab1a6cac 4561 k += namespaced_token_len;
a6390f01 4562 else
d6c06927 4563 return ret_errno(EINVAL);
72d0e1cb 4564
ced5587c 4565 lxc_list_for_each_safe(it, list, next) {
72d0e1cb 4566 struct lxc_cgroup *cg = it->elem;
54860ed0 4567
71528742 4568 if (!all && !strequal(cg->subsystem, k))
72d0e1cb 4569 continue;
54860ed0 4570
72d0e1cb
SG
4571 lxc_list_del(it);
4572 free(cg->subsystem);
4573 free(cg->value);
4574 free(cg);
4575 free(it);
4576 }
e409b214 4577
cc36133d
CB
4578 if (all)
4579 lxc_list_init(list);
4580
72d0e1cb
SG
4581 return 0;
4582}
4583
a7744f12 4584static inline void lxc_clear_cgroups_devices(struct lxc_conf *conf)
4bfb655e 4585{
a7744f12 4586 lxc_clear_cgroup2_devices(&conf->bpf_devices);
4bfb655e
CB
4587}
4588
c6d09e15
WB
4589int lxc_clear_limits(struct lxc_conf *c, const char *key)
4590{
4591 struct lxc_list *it, *next;
c6d09e15 4592 const char *k = NULL;
0fd73091 4593 bool all = false;
c6d09e15 4594
71528742 4595 if (strequal(key, "lxc.limit") || strequal(key, "lxc.prlimit"))
c6d09e15 4596 all = true;
eed95eb0 4597 else if (strnequal(key, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
6333c915 4598 k = key + STRLITERALLEN("lxc.limit.");
eed95eb0 4599 else if (strnequal(key, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
6333c915 4600 k = key + STRLITERALLEN("lxc.prlimit.");
c6d09e15 4601 else
786467cb 4602 return ret_errno(EINVAL);
c6d09e15 4603
0fd73091 4604 lxc_list_for_each_safe (it, &c->limits, next) {
c6d09e15 4605 struct lxc_limit *lim = it->elem;
0fd73091 4606
71528742 4607 if (!all && !strequal(lim->resource, k))
c6d09e15 4608 continue;
0fd73091 4609
c6d09e15 4610 lxc_list_del(it);
786467cb
CB
4611
4612 free_disarm(lim->resource);
c6d09e15 4613 free(lim);
59bc24cd 4614 free(it);
c6d09e15 4615 }
b668653c 4616
786467cb
CB
4617 if (all)
4618 lxc_list_init(&c->limits);
4619
c6d09e15
WB
4620 return 0;
4621}
4622
7edd0540
L
4623int lxc_clear_sysctls(struct lxc_conf *c, const char *key)
4624{
4625 struct lxc_list *it, *next;
7edd0540 4626 const char *k = NULL;
0fd73091 4627 bool all = false;
7edd0540 4628
71528742 4629 if (strequal(key, "lxc.sysctl"))
7edd0540 4630 all = true;
eed95eb0 4631 else if (strnequal(key, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
6333c915 4632 k = key + STRLITERALLEN("lxc.sysctl.");
7edd0540
L
4633 else
4634 return -1;
4635
4a2c9b40 4636 lxc_list_for_each_safe(it, &c->sysctls, next) {
7edd0540 4637 struct lxc_sysctl *elem = it->elem;
0fd73091 4638
71528742 4639 if (!all && !strequal(elem->key, k))
7edd0540 4640 continue;
0fd73091 4641
7edd0540
L
4642 lxc_list_del(it);
4643 free(elem->key);
4644 free(elem->value);
4645 free(elem);
4646 free(it);
4647 }
0fd73091 4648
4a2c9b40
CB
4649 if (all)
4650 lxc_list_init(&c->sysctls);
4651
7edd0540
L
4652 return 0;
4653}
4654
61d7a733
YT
4655int lxc_clear_procs(struct lxc_conf *c, const char *key)
4656{
0fd73091 4657 struct lxc_list *it, *next;
61d7a733 4658 const char *k = NULL;
0fd73091 4659 bool all = false;
61d7a733 4660
71528742 4661 if (strequal(key, "lxc.proc"))
61d7a733 4662 all = true;
eed95eb0 4663 else if (strnequal(key, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
6333c915 4664 k = key + STRLITERALLEN("lxc.proc.");
61d7a733
YT
4665 else
4666 return -1;
4667
ced5587c 4668 lxc_list_for_each_safe(it, &c->procs, next) {
61d7a733 4669 struct lxc_proc *proc = it->elem;
0fd73091 4670
71528742 4671 if (!all && !strequal(proc->filename, k))
61d7a733 4672 continue;
0fd73091 4673
61d7a733
YT
4674 lxc_list_del(it);
4675 free(proc->filename);
4676 free(proc->value);
4677 free(proc);
4678 free(it);
4679 }
4680
cc36133d
CB
4681 if (all)
4682 lxc_list_init(&c->procs);
4683
61d7a733
YT
4684 return 0;
4685}
4686
ee1e7aa0
SG
4687int lxc_clear_groups(struct lxc_conf *c)
4688{
0fd73091 4689 struct lxc_list *it, *next;
ee1e7aa0 4690
0fd73091 4691 lxc_list_for_each_safe (it, &c->groups, next) {
ee1e7aa0
SG
4692 lxc_list_del(it);
4693 free(it->elem);
4694 free(it);
4695 }
0fd73091 4696
cc36133d 4697 lxc_list_init(&c->groups);
ee1e7aa0
SG
4698 return 0;
4699}
4700
ab799c0b
SG
4701int lxc_clear_environment(struct lxc_conf *c)
4702{
0fd73091 4703 struct lxc_list *it, *next;
ab799c0b 4704
0fd73091 4705 lxc_list_for_each_safe (it, &c->environment, next) {
ab799c0b
SG
4706 lxc_list_del(it);
4707 free(it->elem);
4708 free(it);
4709 }
0fd73091 4710
cc36133d 4711 lxc_list_init(&c->environment);
ab799c0b
SG
4712 return 0;
4713}
4714
72d0e1cb
SG
4715int lxc_clear_mount_entries(struct lxc_conf *c)
4716{
0fd73091 4717 struct lxc_list *it, *next;
72d0e1cb 4718
0fd73091 4719 lxc_list_for_each_safe (it, &c->mount_list, next) {
72d0e1cb
SG
4720 lxc_list_del(it);
4721 free(it->elem);
4722 free(it);
4723 }
0fd73091 4724
cc36133d 4725 lxc_list_init(&c->mount_list);
72d0e1cb
SG
4726 return 0;
4727}
4728
b099e9e9
SH
4729int lxc_clear_automounts(struct lxc_conf *c)
4730{
4731 c->auto_mounts = 0;
4732 return 0;
4733}
4734
12a50cc6 4735int lxc_clear_hooks(struct lxc_conf *c, const char *key)
72d0e1cb 4736{
0fd73091
CB
4737 struct lxc_list *it, *next;
4738 const char *k = NULL;
4739 bool all = false, done = false;
72d0e1cb 4740
71528742 4741 if (strequal(key, "lxc.hook"))
17ed13a3 4742 all = true;
eed95eb0 4743 else if (strnequal(key, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
6333c915 4744 k = key + STRLITERALLEN("lxc.hook.");
a6390f01
WB
4745 else
4746 return -1;
17ed13a3 4747
ced5587c 4748 for (int i = 0; i < NUM_LXC_HOOKS; i++) {
71528742 4749 if (all || strequal(k, lxchook_names[i])) {
0fd73091 4750 lxc_list_for_each_safe (it, &c->hooks[i], next) {
17ed13a3
SH
4751 lxc_list_del(it);
4752 free(it->elem);
4753 free(it);
4754 }
cc36133d 4755 lxc_list_init(&c->hooks[i]);
0fd73091 4756
17ed13a3 4757 done = true;
72d0e1cb
SG
4758 }
4759 }
17ed13a3 4760
55022530
CB
4761 if (!done)
4762 return log_error(-1, "Invalid hook key: %s", key);
0fd73091 4763
72d0e1cb
SG
4764 return 0;
4765}
8eb5694b 4766
4184c3e1
SH
4767static inline void lxc_clear_aliens(struct lxc_conf *conf)
4768{
0fd73091 4769 struct lxc_list *it, *next;
4184c3e1 4770
0fd73091 4771 lxc_list_for_each_safe (it, &conf->aliens, next) {
4184c3e1
SH
4772 lxc_list_del(it);
4773 free(it->elem);
4774 free(it);
4775 }
cc36133d
CB
4776
4777 lxc_list_init(&conf->aliens);
4184c3e1
SH
4778}
4779
c7b15d1e 4780void lxc_clear_includes(struct lxc_conf *conf)
f979ac15 4781{
0fd73091 4782 struct lxc_list *it, *next;
f979ac15 4783
ced5587c 4784 lxc_list_for_each_safe(it, &conf->includes, next) {
f979ac15
SH
4785 lxc_list_del(it);
4786 free(it->elem);
4787 free(it);
4788 }
cc36133d
CB
4789
4790 lxc_list_init(&conf->includes);
f979ac15
SH
4791}
4792
1800f924
WB
4793int lxc_clear_apparmor_raw(struct lxc_conf *c)
4794{
4795 struct lxc_list *it, *next;
4796
4797 lxc_list_for_each_safe (it, &c->lsm_aa_raw, next) {
4798 lxc_list_del(it);
4799 free(it->elem);
4800 free(it);
4801 }
4802
cc36133d 4803 lxc_list_init(&c->lsm_aa_raw);
1800f924
WB
4804 return 0;
4805}
4806
8eb5694b
SH
4807void lxc_conf_free(struct lxc_conf *conf)
4808{
4809 if (!conf)
4810 return;
0fd73091 4811
858377e4
SH
4812 if (current_config == conf)
4813 current_config = NULL;
aed105d5 4814 lxc_terminal_conf_free(&conf->console);
f10fad2f 4815 free(conf->rootfs.mount);
b3b8c97f 4816 free(conf->rootfs.bdev_type);
f10fad2f
ME
4817 free(conf->rootfs.options);
4818 free(conf->rootfs.path);
79ff643d 4819 put_lxc_rootfs(&conf->rootfs, true);
f10fad2f 4820 free(conf->logfile);
858377e4
SH
4821 if (conf->logfd != -1)
4822 close(conf->logfd);
f10fad2f 4823 free(conf->utsname);
885766f5
CB
4824 free(conf->ttys.dir);
4825 free(conf->ttys.tty_names);
f10fad2f
ME
4826 free(conf->fstab);
4827 free(conf->rcfile);
5cda27c1 4828 free(conf->execute_cmd);
f10fad2f 4829 free(conf->init_cmd);
bf31b337 4830 free(conf->init_groups.list);
3c491553 4831 free(conf->init_cwd);
6b0d5538 4832 free(conf->unexpanded_config);
76d0127f 4833 free(conf->syslog);
87d0990c 4834 lxc_free_networks(conf);
f10fad2f 4835 free(conf->lsm_aa_profile);
1800f924 4836 free(conf->lsm_aa_profile_computed);
f10fad2f 4837 free(conf->lsm_se_context);
1ed59e6d 4838 free(conf->lsm_se_keyring_context);
c3e3c21a 4839 lxc_seccomp_free(&conf->seccomp);
8eb5694b 4840 lxc_clear_config_caps(conf);
1fb86a7c 4841 lxc_clear_config_keepcaps(conf);
54860ed0
CB
4842 lxc_clear_cgroups(conf, "lxc.cgroup", CGROUP_SUPER_MAGIC);
4843 lxc_clear_cgroups(conf, "lxc.cgroup2", CGROUP2_SUPER_MAGIC);
a7744f12 4844 lxc_clear_cgroups_devices(conf);
17ed13a3 4845 lxc_clear_hooks(conf, "lxc.hook");
8eb5694b 4846 lxc_clear_mount_entries(conf);
27c27d73 4847 lxc_clear_idmaps(conf);
ee1e7aa0 4848 lxc_clear_groups(conf);
f979ac15 4849 lxc_clear_includes(conf);
761d81ca 4850 lxc_clear_aliens(conf);
ab799c0b 4851 lxc_clear_environment(conf);
240d4b74 4852 lxc_clear_limits(conf, "lxc.prlimit");
7edd0540 4853 lxc_clear_sysctls(conf, "lxc.sysctl");
61d7a733 4854 lxc_clear_procs(conf, "lxc.proc");
1800f924 4855 lxc_clear_apparmor_raw(conf);
a3ed9b81 4856 lxc_clear_namespace(conf);
43654d34 4857 free(conf->cgroup_meta.dir);
a900cbaf 4858 free(conf->cgroup_meta.monitor_dir);
eb60b564 4859 free(conf->cgroup_meta.monitor_pivot_dir);
a900cbaf
WB
4860 free(conf->cgroup_meta.container_dir);
4861 free(conf->cgroup_meta.namespace_dir);
43654d34 4862 free(conf->cgroup_meta.controllers);
7a41e857
LT
4863 free(conf->shmount.path_host);
4864 free(conf->shmount.path_cont);
8eb5694b
SH
4865 free(conf);
4866}
4355ab5f
SH
4867
4868struct userns_fn_data {
4869 int (*fn)(void *);
c9b7c33e 4870 const char *fn_name;
4355ab5f
SH
4871 void *arg;
4872 int p[2];
4873};
4874
4875static int run_userns_fn(void *data)
4876{
766c5b6d 4877 struct userns_fn_data *d = data;
adaffdd7 4878 int ret;
4355ab5f 4879 char c;
4355ab5f 4880
766c5b6d 4881 close_prot_errno_disarm(d->p[1]);
f8aa4bf3 4882
766c5b6d
CB
4883 /*
4884 * Wait for parent to finish establishing a new mapping in the user
f8aa4bf3
CB
4885 * namespace we are executing in.
4886 */
adaffdd7 4887 ret = lxc_read_nointr(d->p[0], &c, 1);
766c5b6d 4888 close_prot_errno_disarm(d->p[0]);
adaffdd7
CB
4889 if (ret != 1)
4890 return -1;
f8aa4bf3 4891
c9b7c33e 4892 if (d->fn_name)
adaffdd7 4893 TRACE("Calling function \"%s\"", d->fn_name);
0fd73091 4894
f8aa4bf3 4895 /* Call function to run. */
4355ab5f
SH
4896 return d->fn(d->arg);
4897}
4898
7581a82f 4899static struct id_map *mapped_nsid_add(const struct lxc_conf *conf, unsigned id,
db7cfe23
CB
4900 enum idtype idtype)
4901{
5173b710
CB
4902 const struct id_map *map;
4903 struct id_map *retmap;
db7cfe23
CB
4904
4905 map = find_mapped_nsid_entry(conf, id, idtype);
4906 if (!map)
4907 return NULL;
4908
b8e43ef0 4909 retmap = zalloc(sizeof(*retmap));
db7cfe23
CB
4910 if (!retmap)
4911 return NULL;
4912
4913 memcpy(retmap, map, sizeof(*retmap));
4914 return retmap;
4915}
4916
86c78011 4917static struct id_map *find_mapped_hostid_entry(const struct lxc_list *idmap,
c4333195 4918 unsigned id, enum idtype idtype)
f8aa4bf3 4919{
f8aa4bf3 4920 struct id_map *map;
0fd73091 4921 struct lxc_list *it;
f8aa4bf3
CB
4922 struct id_map *retmap = NULL;
4923
86c78011 4924 lxc_list_for_each (it, idmap) {
f8aa4bf3
CB
4925 map = it->elem;
4926 if (map->idtype != idtype)
4927 continue;
4928
4929 if (id >= map->hostid && id < map->hostid + map->range) {
4930 retmap = map;
4931 break;
4932 }
4933 }
4934
f8aa4bf3
CB
4935 return retmap;
4936}
4937
0fd73091 4938/* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
f8aa4bf3 4939 * existing one or establish a new one.
4355ab5f 4940 */
7581a82f 4941static struct id_map *mapped_hostid_add(const struct lxc_conf *conf, uid_t id,
0fd73091 4942 enum idtype type)
4355ab5f 4943{
55022530 4944 __do_free struct id_map *entry = NULL;
28a2d9e7 4945 int hostid_mapped;
55022530 4946 struct id_map *tmp = NULL;
c4333195 4947
b8e43ef0 4948 entry = zalloc(sizeof(*entry));
c4333195
CB
4949 if (!entry)
4950 return NULL;
f8aa4bf3 4951
28a2d9e7 4952 /* Reuse existing mapping. */
86c78011 4953 tmp = find_mapped_hostid_entry(&conf->id_map, id, type);
1758c195
CB
4954 if (tmp) {
4955 memcpy(entry, tmp, sizeof(*entry));
4956 } else {
4957 /* Find new mapping. */
4958 hostid_mapped = find_unmapped_nsid(conf, type);
4959 if (hostid_mapped < 0)
4960 return log_debug(NULL, "Failed to find free mapping for id %d", id);
4961
4962 entry->idtype = type;
4963 entry->nsid = hostid_mapped;
4964 entry->hostid = (unsigned long)id;
4965 entry->range = 1;
4966 }
4355ab5f 4967
55022530 4968 return move_ptr(entry);
4355ab5f
SH
4969}
4970
dbfcdf86
CB
4971static struct lxc_list *get_minimal_idmap(const struct lxc_conf *conf,
4972 uid_t *resuid, gid_t *resgid)
4355ab5f 4973{
00d6cfe2
CB
4974 __do_free struct id_map *container_root_uid = NULL,
4975 *container_root_gid = NULL,
4976 *host_uid_map = NULL, *host_gid_map = NULL;
4977 __do_free struct lxc_list *idmap = NULL;
f8aa4bf3 4978 uid_t euid, egid;
4160c3a0
CB
4979 uid_t nsuid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
4980 gid_t nsgid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
00d6cfe2 4981 struct lxc_list *tmplist = NULL;
4355ab5f 4982
db7cfe23 4983 /* Find container root mappings. */
4160c3a0 4984 container_root_uid = mapped_nsid_add(conf, nsuid, ID_TYPE_UID);
55022530
CB
4985 if (!container_root_uid)
4986 return log_debug(NULL, "Failed to find mapping for namespace uid %d", 0);
dcf0ffdf
CB
4987 euid = geteuid();
4988 if (euid >= container_root_uid->hostid &&
4989 euid < (container_root_uid->hostid + container_root_uid->range))
2c996219 4990 host_uid_map = move_ptr(container_root_uid);
f8aa4bf3 4991
4160c3a0 4992 container_root_gid = mapped_nsid_add(conf, nsgid, ID_TYPE_GID);
55022530
CB
4993 if (!container_root_gid)
4994 return log_debug(NULL, "Failed to find mapping for namespace gid %d", 0);
dcf0ffdf
CB
4995 egid = getegid();
4996 if (egid >= container_root_gid->hostid &&
4997 egid < (container_root_gid->hostid + container_root_gid->range))
2c996219 4998 host_gid_map = move_ptr(container_root_gid);
f8aa4bf3
CB
4999
5000 /* Check whether the {g,u}id of the user has a mapping. */
954b7d9b 5001 if (!host_uid_map)
c4333195 5002 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
55022530
CB
5003 if (!host_uid_map)
5004 return log_debug(NULL, "Failed to find mapping for uid %d", euid);
f8aa4bf3 5005
dcf0ffdf
CB
5006 if (!host_gid_map)
5007 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
55022530
CB
5008 if (!host_gid_map)
5009 return log_debug(NULL, "Failed to find mapping for gid %d", egid);
28a2d9e7
CB
5010
5011 /* Allocate new {g,u}id map list. */
b8e43ef0 5012 idmap = lxc_list_new();
28a2d9e7 5013 if (!idmap)
00d6cfe2 5014 return NULL;
28a2d9e7 5015
f8aa4bf3 5016 /* Add container root to the map. */
b8e43ef0 5017 tmplist = lxc_list_new();
f8aa4bf3 5018 if (!tmplist)
00d6cfe2 5019 return NULL;
47649d5b
CB
5020 /* idmap will now keep track of that memory. */
5021 lxc_list_add_elem(tmplist, move_ptr(host_uid_map));
f8aa4bf3 5022 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 5023
2c996219 5024 if (container_root_uid) {
28a2d9e7 5025 /* Add container root to the map. */
b8e43ef0 5026 tmplist = lxc_list_new();
28a2d9e7 5027 if (!tmplist)
00d6cfe2 5028 return NULL;
47649d5b
CB
5029 /* idmap will now keep track of that memory. */
5030 lxc_list_add_elem(tmplist, move_ptr(container_root_uid));
28a2d9e7 5031 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 5032 }
f8aa4bf3 5033
b8e43ef0 5034 tmplist = lxc_list_new();
f8aa4bf3 5035 if (!tmplist)
00d6cfe2 5036 return NULL;
47649d5b
CB
5037 /* idmap will now keep track of that memory. */
5038 lxc_list_add_elem(tmplist, move_ptr(host_gid_map));
f8aa4bf3 5039 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 5040
2c996219 5041 if (container_root_gid) {
b8e43ef0 5042 tmplist = lxc_list_new();
28a2d9e7 5043 if (!tmplist)
00d6cfe2 5044 return NULL;
47649d5b
CB
5045 /* idmap will now keep track of that memory. */
5046 lxc_list_add_elem(tmplist, move_ptr(container_root_gid));
28a2d9e7 5047 lxc_list_add_tail(idmap, tmplist);
28a2d9e7 5048 }
f8aa4bf3 5049
dbfcdf86
CB
5050 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid, nsgid);
5051
5052 if (resuid)
5053 *resuid = nsuid;
5054 if (resgid)
5055 *resgid = nsgid;
00d6cfe2 5056 return move_ptr(idmap);
dcf0ffdf
CB
5057}
5058
766c5b6d
CB
5059/*
5060 * Run a function in a new user namespace.
dcf0ffdf
CB
5061 * The caller's euid/egid will be mapped if it is not already.
5062 * Afaict, userns_exec_1() is only used to operate based on privileges for the
5063 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
5064 * This means we require only to establish a mapping from:
5065 * - the container root {g,u}id as seen from the host > user's host {g,u}id
5066 * - the container root -> some sub{g,u}id
915e3dbd 5067 * The former we add, if the user did not specify a mapping. The latter we
6f3fd27f 5068 * retrieve from the container's configured {g,u}id mappings as it must have been
dcf0ffdf
CB
5069 * there to start the container in the first place.
5070 */
7581a82f 5071int userns_exec_1(const struct lxc_conf *conf, int (*fn)(void *), void *data,
dcf0ffdf
CB
5072 const char *fn_name)
5073{
7e621263 5074 call_cleaner(__lxc_free_idmap) struct lxc_list *idmap = NULL;
0fd73091
CB
5075 int ret = -1, status = -1;
5076 char c = '1';
46bc6f2a
CB
5077 struct userns_fn_data d = {
5078 .arg = data,
5079 .fn = fn,
5080 .fn_name = fn_name,
5081 };
766c5b6d
CB
5082 pid_t pid;
5083 int pipe_fds[2];
dcf0ffdf 5084
2b2655a8
CB
5085 if (!conf)
5086 return -EINVAL;
5087
dbfcdf86 5088 idmap = get_minimal_idmap(conf, NULL, NULL);
dcf0ffdf 5089 if (!idmap)
766c5b6d 5090 return ret_errno(ENOENT);
dcf0ffdf 5091
766c5b6d
CB
5092 ret = pipe2(pipe_fds, O_CLOEXEC);
5093 if (ret < 0)
5094 return -errno;
5095
766c5b6d
CB
5096 d.p[0] = pipe_fds[0];
5097 d.p[1] = pipe_fds[1];
dcf0ffdf
CB
5098
5099 /* Clone child in new user namespace. */
a59440be 5100 pid = lxc_raw_clone_cb(run_userns_fn, &d, CLONE_NEWUSER, NULL);
dcf0ffdf 5101 if (pid < 0) {
0fd73091 5102 ERROR("Failed to clone process in new user namespace");
dcf0ffdf
CB
5103 goto on_error;
5104 }
5105
766c5b6d 5106 close_prot_errno_disarm(pipe_fds[0]);
dcf0ffdf 5107
62fef886 5108 if (lxc_log_trace()) {
dcf0ffdf 5109 struct id_map *map;
0fd73091 5110 struct lxc_list *it;
dcf0ffdf 5111
766c5b6d 5112 lxc_list_for_each(it, idmap) {
f8aa4bf3 5113 map = it->elem;
766c5b6d
CB
5114 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5115 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
f8aa4bf3 5116 }
4355ab5f
SH
5117 }
5118
f8aa4bf3 5119 /* Set up {g,u}id mapping for user namespace of child process. */
4355ab5f 5120 ret = lxc_map_ids(idmap, pid);
f8aa4bf3 5121 if (ret < 0) {
0fd73091 5122 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
f8aa4bf3 5123 goto on_error;
4355ab5f
SH
5124 }
5125
f8aa4bf3 5126 /* Tell child to proceed. */
766c5b6d 5127 if (lxc_write_nointr(pipe_fds[1], &c, 1) != 1) {
dcf0ffdf 5128 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
f8aa4bf3 5129 goto on_error;
4355ab5f
SH
5130 }
5131
686dd5d1 5132on_error:
766c5b6d
CB
5133 close_prot_errno_disarm(pipe_fds[0]);
5134 close_prot_errno_disarm(pipe_fds[1]);
f8aa4bf3 5135
ee1b16bc
TA
5136 /* Wait for child to finish. */
5137 if (pid > 0)
5138 status = wait_for_pid(pid);
5139
686dd5d1
CB
5140 if (status < 0)
5141 ret = -1;
5142
f8aa4bf3 5143 return ret;
4355ab5f 5144}
97e9cfa0 5145
d1783ef4
CB
5146int userns_exec_minimal(const struct lxc_conf *conf,
5147 int (*fn_parent)(void *), void *fn_parent_data,
5148 int (*fn_child)(void *), void *fn_child_data)
edf88289 5149{
7e621263 5150 call_cleaner(__lxc_free_idmap) struct lxc_list *idmap = NULL;
dbfcdf86
CB
5151 uid_t resuid = LXC_INVALID_UID;
5152 gid_t resgid = LXC_INVALID_GID;
edf88289 5153 char c = '1';
dbfcdf86 5154 ssize_t ret;
edf88289
CB
5155 pid_t pid;
5156 int sock_fds[2];
5157
d1783ef4 5158 if (!conf || !fn_child)
dbfcdf86 5159 return ret_errno(EINVAL);
edf88289 5160
dbfcdf86 5161 idmap = get_minimal_idmap(conf, &resuid, &resgid);
edf88289
CB
5162 if (!idmap)
5163 return ret_errno(ENOENT);
5164
5165 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5166 if (ret < 0)
5167 return -errno;
5168
5169 pid = fork();
5170 if (pid < 0) {
dbfcdf86 5171 SYSERROR("Failed to create new process");
edf88289
CB
5172 goto on_error;
5173 }
5174
5175 if (pid == 0) {
5176 close_prot_errno_disarm(sock_fds[1]);
5177
5178 ret = unshare(CLONE_NEWUSER);
dbfcdf86
CB
5179 if (ret < 0) {
5180 SYSERROR("Failed to unshare new user namespace");
edf88289 5181 _exit(EXIT_FAILURE);
dbfcdf86 5182 }
edf88289 5183
dbfcdf86
CB
5184 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5185 if (ret != 1)
edf88289
CB
5186 _exit(EXIT_FAILURE);
5187
5188 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5189 if (ret != 1)
5190 _exit(EXIT_FAILURE);
5191
5192 close_prot_errno_disarm(sock_fds[0]);
5193
8917c382 5194 if (!lxc_drop_groups() && errno != EPERM)
edf88289
CB
5195 _exit(EXIT_FAILURE);
5196
dbfcdf86
CB
5197 ret = setresgid(resgid, resgid, resgid);
5198 if (ret < 0) {
5199 SYSERROR("Failed to setresgid(%d, %d, %d)",
5200 resgid, resgid, resgid);
edf88289 5201 _exit(EXIT_FAILURE);
dbfcdf86
CB
5202 }
5203
5204 ret = setresuid(resuid, resuid, resuid);
5205 if (ret < 0) {
5206 SYSERROR("Failed to setresuid(%d, %d, %d)",
5207 resuid, resuid, resuid);
5208 _exit(EXIT_FAILURE);
5209 }
edf88289 5210
d1783ef4 5211 ret = fn_child(fn_child_data);
dbfcdf86
CB
5212 if (ret) {
5213 SYSERROR("Running function in new user namespace failed");
edf88289 5214 _exit(EXIT_FAILURE);
dbfcdf86 5215 }
edf88289
CB
5216
5217 _exit(EXIT_SUCCESS);
5218 }
5219
5220 close_prot_errno_disarm(sock_fds[0]);
5221
62fef886 5222 if (lxc_log_trace()) {
edf88289
CB
5223 struct id_map *map;
5224 struct lxc_list *it;
5225
5226 lxc_list_for_each(it, idmap) {
5227 map = it->elem;
5228 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5229 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
5230 }
5231 }
5232
5233 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5234 if (ret != 1) {
5235 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5236 goto on_error;
5237 }
5238
5239 /* Set up {g,u}id mapping for user namespace of child process. */
5240 ret = lxc_map_ids(idmap, pid);
5241 if (ret < 0) {
5242 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5243 goto on_error;
5244 }
5245
5246 /* Tell child to proceed. */
5247 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5248 if (ret != 1) {
5249 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5250 goto on_error;
5251 }
5252
d1783ef4
CB
5253 if (fn_parent && fn_parent(fn_parent_data)) {
5254 SYSERROR("Running parent function failed");
5255 _exit(EXIT_FAILURE);
5256 }
5257
edf88289
CB
5258on_error:
5259 close_prot_errno_disarm(sock_fds[0]);
5260 close_prot_errno_disarm(sock_fds[1]);
5261
5262 /* Wait for child to finish. */
dbfcdf86
CB
5263 if (pid < 0)
5264 return -1;
edf88289 5265
dbfcdf86 5266 return wait_for_pid(pid);
edf88289
CB
5267}
5268
415a8851
CB
5269int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
5270 const char *fn_name)
5271{
5272 pid_t pid;
5273 uid_t euid, egid;
415a8851
CB
5274 int p[2];
5275 struct id_map *map;
5276 struct lxc_list *cur;
0fd73091 5277 struct userns_fn_data d;
415a8851 5278 int ret = -1;
0fd73091 5279 char c = '1';
415a8851
CB
5280 struct lxc_list *idmap = NULL, *tmplist = NULL;
5281 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
5282 *host_uid_map = NULL, *host_gid_map = NULL;
5283
2b2655a8
CB
5284 if (!conf)
5285 return -EINVAL;
5286
979f9e34 5287 ret = pipe2(p, O_CLOEXEC);
415a8851
CB
5288 if (ret < 0) {
5289 SYSERROR("opening pipe");
5290 return -1;
5291 }
5292 d.fn = fn;
5293 d.fn_name = fn_name;
5294 d.arg = data;
5295 d.p[0] = p[0];
5296 d.p[1] = p[1];
5297
5298 /* Clone child in new user namespace. */
33258b95 5299 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER, NULL);
415a8851 5300 if (pid < 0) {
0fd73091 5301 ERROR("Failed to clone process in new user namespace");
415a8851
CB
5302 goto on_error;
5303 }
5304
5305 close(p[0]);
5306 p[0] = -1;
5307
5308 euid = geteuid();
5309 egid = getegid();
5310
5311 /* Allocate new {g,u}id map list. */
b8e43ef0 5312 idmap = lxc_list_new();
415a8851
CB
5313 if (!idmap)
5314 goto on_error;
415a8851
CB
5315
5316 /* Find container root. */
0fd73091 5317 lxc_list_for_each (cur, &conf->id_map) {
415a8851
CB
5318 struct id_map *tmpmap;
5319
b8e43ef0 5320 tmplist = lxc_list_new();
415a8851
CB
5321 if (!tmplist)
5322 goto on_error;
5323
b8e43ef0 5324 tmpmap = zalloc(sizeof(*tmpmap));
415a8851
CB
5325 if (!tmpmap) {
5326 free(tmplist);
5327 goto on_error;
5328 }
5329
5330 memset(tmpmap, 0, sizeof(*tmpmap));
5331 memcpy(tmpmap, cur->elem, sizeof(*tmpmap));
5332 tmplist->elem = tmpmap;
5333
5334 lxc_list_add_tail(idmap, tmplist);
5335
5336 map = cur->elem;
5337
5338 if (map->idtype == ID_TYPE_UID)
5339 if (euid >= map->hostid && euid < map->hostid + map->range)
5340 host_uid_map = map;
5341
5342 if (map->idtype == ID_TYPE_GID)
5343 if (egid >= map->hostid && egid < map->hostid + map->range)
5344 host_gid_map = map;
5345
5346 if (map->nsid != 0)
5347 continue;
5348
5349 if (map->idtype == ID_TYPE_UID)
5350 if (container_root_uid == NULL)
5351 container_root_uid = map;
5352
5353 if (map->idtype == ID_TYPE_GID)
5354 if (container_root_gid == NULL)
5355 container_root_gid = map;
5356 }
5357
5358 if (!container_root_uid || !container_root_gid) {
5359 ERROR("No mapping for container root found");
5360 goto on_error;
5361 }
5362
5363 /* Check whether the {g,u}id of the user has a mapping. */
5364 if (!host_uid_map)
c4333195 5365 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
415a8851
CB
5366 else
5367 host_uid_map = container_root_uid;
5368
5369 if (!host_gid_map)
c4333195 5370 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
415a8851
CB
5371 else
5372 host_gid_map = container_root_gid;
5373
5374 if (!host_uid_map) {
5375 DEBUG("Failed to find mapping for uid %d", euid);
5376 goto on_error;
5377 }
5378
5379 if (!host_gid_map) {
5380 DEBUG("Failed to find mapping for gid %d", egid);
5381 goto on_error;
5382 }
5383
5384 if (host_uid_map && (host_uid_map != container_root_uid)) {
5385 /* Add container root to the map. */
b8e43ef0 5386 tmplist = lxc_list_new();
415a8851
CB
5387 if (!tmplist)
5388 goto on_error;
5389 lxc_list_add_elem(tmplist, host_uid_map);
5390 lxc_list_add_tail(idmap, tmplist);
5391 }
5392 /* idmap will now keep track of that memory. */
5393 host_uid_map = NULL;
5394
5395 if (host_gid_map && (host_gid_map != container_root_gid)) {
b8e43ef0 5396 tmplist = lxc_list_new();
415a8851
CB
5397 if (!tmplist)
5398 goto on_error;
5399 lxc_list_add_elem(tmplist, host_gid_map);
5400 lxc_list_add_tail(idmap, tmplist);
5401 }
5402 /* idmap will now keep track of that memory. */
5403 host_gid_map = NULL;
5404
62fef886 5405 if (lxc_log_trace()) {
0fd73091 5406 lxc_list_for_each (cur, idmap) {
415a8851
CB
5407 map = cur->elem;
5408 TRACE("establishing %cid mapping for \"%d\" in new "
5409 "user namespace: nsuid %lu - hostid %lu - range "
5410 "%lu",
5411 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
5412 map->nsid, map->hostid, map->range);
5413 }
5414 }
5415
5416 /* Set up {g,u}id mapping for user namespace of child process. */
5417 ret = lxc_map_ids(idmap, pid);
5418 if (ret < 0) {
0fd73091 5419 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid);
415a8851
CB
5420 goto on_error;
5421 }
5422
5423 /* Tell child to proceed. */
489f39be 5424 if (lxc_write_nointr(p[1], &c, 1) != 1) {
0fd73091 5425 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
415a8851
CB
5426 goto on_error;
5427 }
5428
686dd5d1 5429on_error:
ee1b16bc
TA
5430 if (p[0] != -1)
5431 close(p[0]);
5432 close(p[1]);
5433
415a8851 5434 /* Wait for child to finish. */
686dd5d1
CB
5435 if (pid > 0)
5436 ret = wait_for_pid(pid);
415a8851 5437
7e621263
CB
5438 if (idmap)
5439 __lxc_free_idmap(idmap);
80758b4b 5440
415a8851
CB
5441 if (host_uid_map && (host_uid_map != container_root_uid))
5442 free(host_uid_map);
5443 if (host_gid_map && (host_gid_map != container_root_gid))
5444 free(host_gid_map);
5445
415a8851
CB
5446 return ret;
5447}
5448
234998b4
CB
5449static int add_idmap_entry(struct lxc_list *idmap, enum idtype idtype,
5450 unsigned long nsid, unsigned long hostid,
5451 unsigned long range)
5452{
5453 __do_free struct id_map *new_idmap = NULL;
5454 __do_free struct lxc_list *new_list = NULL;
5455
5456 new_idmap = zalloc(sizeof(*new_idmap));
5457 if (!new_idmap)
5458 return ret_errno(ENOMEM);
5459
5460 new_idmap->idtype = idtype;
5461 new_idmap->hostid = hostid;
5462 new_idmap->nsid = nsid;
5463 new_idmap->range = range;
5464
5465 new_list = zalloc(sizeof(*new_list));
5466 if (!new_list)
5467 return ret_errno(ENOMEM);
5468
5469 new_list->elem = move_ptr(new_idmap);
5470 lxc_list_add_tail(idmap, move_ptr(new_list));
5471
5472 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5473 idtype == ID_TYPE_UID ? 'u' : 'g', nsid, hostid, range);
5474 return 0;
5475}
5476
5477int userns_exec_mapped_root(const char *path, int path_fd,
5478 const struct lxc_conf *conf)
5479{
7e621263 5480 call_cleaner(__lxc_free_idmap) struct lxc_list *idmap = NULL;
234998b4
CB
5481 __do_close int fd = -EBADF;
5482 int target_fd = -EBADF;
5483 char c = '1';
5484 ssize_t ret;
5485 pid_t pid;
5486 int sock_fds[2];
5487 uid_t container_host_uid, hostuid;
5488 gid_t container_host_gid, hostgid;
5489 struct stat st;
5490
5491 if (!conf || (!path && path_fd < 0))
5492 return ret_errno(EINVAL);
5493
5494 if (!path)
5495 path = "(null)";
5496
5497 container_host_uid = get_mapped_rootid(conf, ID_TYPE_UID);
5498 if (!uid_valid(container_host_uid))
5499 return log_error(-1, "No uid mapping for container root");
5500
5501 container_host_gid = get_mapped_rootid(conf, ID_TYPE_GID);
5502 if (!gid_valid(container_host_gid))
5503 return log_error(-1, "No gid mapping for container root");
5504
cf68ffd9 5505 if (path_fd < 0) {
a72c68f7 5506 fd = open(path, O_CLOEXEC | O_NOCTTY);
234998b4
CB
5507 if (fd < 0)
5508 return log_error_errno(-errno, errno, "Failed to open \"%s\"", path);
5509 target_fd = fd;
5510 } else {
5511 target_fd = path_fd;
5512 }
5513
5514 hostuid = geteuid();
5515 /* We are root so chown directly. */
5516 if (hostuid == 0) {
5517 ret = fchown(target_fd, container_host_uid, container_host_gid);
5518 if (ret)
5519 return log_error_errno(-errno, errno,
5520 "Failed to fchown(%d(%s), %d, %d)",
5521 target_fd, path, container_host_uid,
5522 container_host_gid);
5523 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd, path,
5524 container_host_uid, container_host_gid);
5525 }
5526
5527 /* The container's root host id matches */
5528 if (container_host_uid == hostuid)
5529 return log_info(0, "Container root id is mapped to our uid");
5530
5531 /* Get the current ids of our target. */
5532 ret = fstat(target_fd, &st);
5533 if (ret)
5534 return log_error_errno(-errno, errno, "Failed to stat \"%s\"", path);
5535
5536 hostgid = getegid();
5537 if (st.st_uid == hostuid && mapped_hostid(st.st_gid, conf, ID_TYPE_GID) < 0) {
5538 ret = fchown(target_fd, -1, hostgid);
5539 if (ret)
5540 return log_error_errno(-errno, errno,
5541 "Failed to fchown(%d(%s), -1, %d)",
5542 target_fd, path, hostgid);
2e8013f9 5543 TRACE("Chowned %d(%s) to -1:%d", target_fd, path, hostgid);
234998b4
CB
5544 }
5545
b8e43ef0 5546 idmap = lxc_list_new();
234998b4
CB
5547 if (!idmap)
5548 return -ENOMEM;
234998b4
CB
5549
5550 /* "u:0:rootuid:1" */
5551 ret = add_idmap_entry(idmap, ID_TYPE_UID, 0, container_host_uid, 1);
5552 if (ret < 0)
5553 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5554
5555 /* "u:hostuid:hostuid:1" */
5556 ret = add_idmap_entry(idmap, ID_TYPE_UID, hostuid, hostuid, 1);
5557 if (ret < 0)
5558 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5559
5560 /* "g:0:rootgid:1" */
5561 ret = add_idmap_entry(idmap, ID_TYPE_GID, 0, container_host_gid, 1);
5562 if (ret < 0)
5563 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5564
5565 /* "g:hostgid:hostgid:1" */
5566 ret = add_idmap_entry(idmap, ID_TYPE_GID, hostgid, hostgid, 1);
5567 if (ret < 0)
5568 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5569
5570 if (hostgid != st.st_gid) {
5571 /* "g:pathgid:rootgid+pathgid:1" */
5572 ret = add_idmap_entry(idmap, ID_TYPE_GID, st.st_gid,
5573 container_host_gid + (gid_t)st.st_gid, 1);
5574 if (ret < 0)
5575 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5576 }
5577
5578 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5579 if (ret < 0)
5580 return -errno;
5581
5582 pid = fork();
5583 if (pid < 0) {
5584 SYSERROR("Failed to create new process");
5585 goto on_error;
5586 }
5587
5588 if (pid == 0) {
5589 close_prot_errno_disarm(sock_fds[1]);
5590
5591 ret = unshare(CLONE_NEWUSER);
5592 if (ret < 0) {
5593 SYSERROR("Failed to unshare new user namespace");
5594 _exit(EXIT_FAILURE);
5595 }
5596
5597 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5598 if (ret != 1)
5599 _exit(EXIT_FAILURE);
5600
5601 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5602 if (ret != 1)
5603 _exit(EXIT_FAILURE);
5604
5605 close_prot_errno_disarm(sock_fds[0]);
5606
5607 if (!lxc_switch_uid_gid(0, 0))
5608 _exit(EXIT_FAILURE);
5609
8917c382 5610 if (!lxc_drop_groups())
234998b4
CB
5611 _exit(EXIT_FAILURE);
5612
8053a085 5613 ret = fchown(target_fd, 0, st.st_gid);
234998b4 5614 if (ret) {
8ea93a0f 5615 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd, path, st.st_gid);
234998b4
CB
5616 _exit(EXIT_FAILURE);
5617 }
5618
2e8013f9 5619 TRACE("Chowned %d(%s) to 0:%d", target_fd, path, st.st_gid);
234998b4
CB
5620 _exit(EXIT_SUCCESS);
5621 }
5622
5623 close_prot_errno_disarm(sock_fds[0]);
5624
62fef886 5625 if (lxc_log_trace()) {
234998b4
CB
5626 struct id_map *map;
5627 struct lxc_list *it;
5628
5629 lxc_list_for_each(it, idmap) {
5630 map = it->elem;
5631 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5632 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
5633 }
5634 }
5635
5636 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5637 if (ret != 1) {
5638 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5639 goto on_error;
5640 }
5641
5642 /* Set up {g,u}id mapping for user namespace of child process. */
5643 ret = lxc_map_ids(idmap, pid);
5644 if (ret < 0) {
5645 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5646 goto on_error;
5647 }
5648
5649 /* Tell child to proceed. */
5650 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5651 if (ret != 1) {
5652 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5653 goto on_error;
5654 }
5655
5656on_error:
5657 close_prot_errno_disarm(sock_fds[0]);
5658 close_prot_errno_disarm(sock_fds[1]);
5659
5660 /* Wait for child to finish. */
5661 if (pid < 0)
5662 return -1;
5663
5664 return wait_for_pid(pid);
5665}
5666
a96a8e8c 5667/* not thread-safe, do not use from api without first forking */
0fd73091 5668static char *getuname(void)
97e9cfa0 5669{
4f410b2a 5670 __do_free char *buf = NULL;
cb7aa5e8
DJ
5671 struct passwd pwent;
5672 struct passwd *pwentp = NULL;
cb7aa5e8
DJ
5673 size_t bufsize;
5674 int ret;
97e9cfa0 5675
cb7aa5e8
DJ
5676 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
5677 if (bufsize == -1)
5678 bufsize = 1024;
5679
b8e43ef0 5680 buf = zalloc(bufsize);
cb7aa5e8 5681 if (!buf)
97e9cfa0
SH
5682 return NULL;
5683
cb7aa5e8
DJ
5684 ret = getpwuid_r(geteuid(), &pwent, buf, bufsize, &pwentp);
5685 if (!pwentp) {
5686 if (ret == 0)
5687 WARN("Could not find matched password record.");
5688
55022530 5689 return log_error(NULL, "Failed to get password record - %u", geteuid());
cb7aa5e8
DJ
5690 }
5691
4f410b2a 5692 return strdup(pwent.pw_name);
97e9cfa0
SH
5693}
5694
a96a8e8c 5695/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
5696static char *getgname(void)
5697{
4f410b2a 5698 __do_free char *buf = NULL;
3de9fb4c
DJ
5699 struct group grent;
5700 struct group *grentp = NULL;
3de9fb4c
DJ
5701 size_t bufsize;
5702 int ret;
5703
5704 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
5705 if (bufsize == -1)
5706 bufsize = 1024;
5707
b8e43ef0 5708 buf = zalloc(bufsize);
3de9fb4c
DJ
5709 if (!buf)
5710 return NULL;
5711
5712 ret = getgrgid_r(getegid(), &grent, buf, bufsize, &grentp);
5713 if (!grentp) {
5714 if (ret == 0)
5715 WARN("Could not find matched group record");
97e9cfa0 5716
55022530 5717 return log_error(NULL, "Failed to get group record - %u", getegid());
3de9fb4c
DJ
5718 }
5719
4f410b2a 5720 return strdup(grent.gr_name);
97e9cfa0
SH
5721}
5722
a96a8e8c 5723/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
5724void suggest_default_idmap(void)
5725{
3a6e3bf5 5726 __do_free char *gname = NULL, *line = NULL, *uname = NULL;
4aae564f 5727 __do_fclose FILE *subuid_f = NULL, *subgid_f = NULL;
97e9cfa0 5728 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
97e9cfa0
SH
5729 size_t len = 0;
5730
0fd73091
CB
5731 uname = getuname();
5732 if (!uname)
97e9cfa0
SH
5733 return;
5734
0fd73091 5735 gname = getgname();
3a6e3bf5 5736 if (!gname)
97e9cfa0 5737 return;
97e9cfa0 5738
4110345b 5739 subuid_f = fopen(subuidfile, "re");
4aae564f 5740 if (!subuid_f) {
97e9cfa0 5741 ERROR("Your system is not configured with subuids");
97e9cfa0
SH
5742 return;
5743 }
0fd73091 5744
4aae564f 5745 while (getline(&line, &len, subuid_f) != -1) {
0fd73091 5746 char *p, *p2;
b7930180 5747 size_t no_newline = 0;
0fd73091
CB
5748
5749 p = strchr(line, ':');
97e9cfa0
SH
5750 if (*line == '#')
5751 continue;
5752 if (!p)
5753 continue;
5754 *p = '\0';
5755 p++;
0fd73091 5756
71528742 5757 if (!strequal(line, uname))
97e9cfa0 5758 continue;
0fd73091 5759
97e9cfa0
SH
5760 p2 = strchr(p, ':');
5761 if (!p2)
5762 continue;
5763 *p2 = '\0';
5764 p2++;
5765 if (!*p2)
5766 continue;
b7930180
CB
5767 no_newline = strcspn(p2, "\n");
5768 p2[no_newline] = '\0';
5769
b7b2fde4 5770 if (lxc_safe_uint(p, &uid) < 0)
0fd73091 5771 WARN("Could not parse UID");
b7b2fde4 5772 if (lxc_safe_uint(p2, &urange) < 0)
0fd73091 5773 WARN("Could not parse UID range");
97e9cfa0 5774 }
97e9cfa0 5775
4110345b 5776 subgid_f = fopen(subgidfile, "re");
4aae564f 5777 if (!subgid_f) {
97e9cfa0 5778 ERROR("Your system is not configured with subgids");
97e9cfa0
SH
5779 return;
5780 }
0fd73091 5781
4aae564f 5782 while (getline(&line, &len, subgid_f) != -1) {
0fd73091 5783 char *p, *p2;
b7930180 5784 size_t no_newline = 0;
0fd73091
CB
5785
5786 p = strchr(line, ':');
97e9cfa0
SH
5787 if (*line == '#')
5788 continue;
5789 if (!p)
5790 continue;
5791 *p = '\0';
5792 p++;
0fd73091 5793
71528742 5794 if (!strequal(line, uname))
97e9cfa0 5795 continue;
0fd73091 5796
97e9cfa0
SH
5797 p2 = strchr(p, ':');
5798 if (!p2)
5799 continue;
5800 *p2 = '\0';
5801 p2++;
5802 if (!*p2)
5803 continue;
b7930180
CB
5804 no_newline = strcspn(p2, "\n");
5805 p2[no_newline] = '\0';
5806
b7b2fde4 5807 if (lxc_safe_uint(p, &gid) < 0)
0fd73091 5808 WARN("Could not parse GID");
b7b2fde4 5809 if (lxc_safe_uint(p2, &grange) < 0)
0fd73091 5810 WARN("Could not parse GID range");
97e9cfa0 5811 }
97e9cfa0 5812
97e9cfa0
SH
5813 if (!urange || !grange) {
5814 ERROR("You do not have subuids or subgids allocated");
5815 ERROR("Unprivileged containers require subuids and subgids");
5816 return;
5817 }
5818
5819 ERROR("You must either run as root, or define uid mappings");
5820 ERROR("To pass uid mappings to lxc-create, you could create");
5821 ERROR("~/.config/lxc/default.conf:");
5822 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
bdcbb6b3
CB
5823 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
5824 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
97e9cfa0 5825}
aaf26830 5826
a7307747
SH
5827static void free_cgroup_settings(struct lxc_list *result)
5828{
5829 struct lxc_list *iterator, *next;
5830
0fd73091 5831 lxc_list_for_each_safe (iterator, result, next) {
a7307747 5832 lxc_list_del(iterator);
55022530 5833 free_disarm(iterator);
a7307747 5834 }
55022530 5835 free_disarm(result);
a7307747
SH
5836}
5837
0fd73091 5838/* Return the list of cgroup_settings sorted according to the following rules
aaf26830
KT
5839 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
5840 */
0fd73091 5841struct lxc_list *sort_cgroup_settings(struct lxc_list *cgroup_settings)
aaf26830
KT
5842{
5843 struct lxc_list *result;
aaf26830 5844 struct lxc_cgroup *cg = NULL;
0fd73091 5845 struct lxc_list *it = NULL, *item = NULL, *memsw_limit = NULL;
aaf26830 5846
b8e43ef0 5847 result = lxc_list_new();
0fd73091 5848 if (!result)
fac7c663 5849 return NULL;
aaf26830
KT
5850 lxc_list_init(result);
5851
0fd73091
CB
5852 /* Iterate over the cgroup settings and copy them to the output list. */
5853 lxc_list_for_each (it, cgroup_settings) {
b8e43ef0 5854 item = zalloc(sizeof(*item));
fac7c663 5855 if (!item) {
a7307747 5856 free_cgroup_settings(result);
fac7c663
KT
5857 return NULL;
5858 }
0fd73091 5859
aaf26830
KT
5860 item->elem = it->elem;
5861 cg = it->elem;
71528742 5862 if (strequal(cg->subsystem, "memory.memsw.limit_in_bytes")) {
aaf26830
KT
5863 /* Store the memsw_limit location */
5864 memsw_limit = item;
71528742 5865 } else if (strequal(cg->subsystem, "memory.limit_in_bytes") &&
0fd73091
CB
5866 memsw_limit != NULL) {
5867 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
5868 * before lxc.cgroup.memory.limit_in_bytes, swap these
5869 * two items */
aaf26830
KT
5870 item->elem = memsw_limit->elem;
5871 memsw_limit->elem = it->elem;
5872 }
5873 lxc_list_add_tail(result, item);
5874 }
5875
5876 return result;
a7307747 5877}