]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/conf.c
conf: support recursive propagation options properly
[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,
e73af35b 515 rootfs->mnt_opts.raw_options ? rootfs->mnt_opts.raw_options : "(null)");
4e86cad3
CB
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
0589d744 622 if (list_empty(&handler->conf->id_map))
4b875ef9
CB
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,
e73af35b 1428 rootfs->mnt_opts.raw_options ? rootfs->mnt_opts.raw_options : "(null)");
0ad19a3f 1429
0fd73091 1430 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
91c3e281 1431 rootfs->path, rootfs->mount,
e73af35b 1432 rootfs->mnt_opts.raw_options ? rootfs->mnt_opts.raw_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 1618{
f4900711
CB
1619 struct id_map *map;
1620 struct id_map *retmap = NULL;
1621
dcf0ffdf
CB
1622 /* Shortcut for container's root mappings. */
1623 if (id == 0) {
1624 if (idtype == ID_TYPE_UID)
1625 return conf->root_nsuid_map;
1626
1627 if (idtype == ID_TYPE_GID)
1628 return conf->root_nsgid_map;
1629 }
1630
0589d744 1631 list_for_each_entry(map, &conf->id_map, head) {
f4900711
CB
1632 if (map->idtype != idtype)
1633 continue;
1634
1635 if (id >= map->nsid && id < map->nsid + map->range) {
1636 retmap = map;
1637 break;
1638 }
1639 }
1640
1641 return retmap;
1642}
1643
42c0d056 1644static int lxc_recv_devpts_from_child(struct lxc_handler *handler)
68f3899e
CB
1645{
1646 int ret;
1647
1648 if (handler->conf->pty_max <= 0)
1649 return 0;
1650
d17c815d
CB
1651 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1],
1652 &handler->conf->devpts_fd,
1653 &handler->conf->devpts_fd,
1654 sizeof(handler->conf->devpts_fd));
68f3899e
CB
1655 if (ret < 0)
1656 return log_error_errno(-1, errno, "Failed to receive devpts fd from child");
1657
1658 TRACE("Received devpts file descriptor %d from child", handler->conf->devpts_fd);
1659 return 0;
1660}
1661
96a980e1 1662static int lxc_setup_devpts_child(struct lxc_handler *handler)
289b707b 1663{
96a980e1 1664 __do_close int devpts_fd = -EBADF, fd_fs = -EBADF;
289b707b 1665 struct lxc_conf *conf = handler->conf;
f30fc74d 1666 struct lxc_rootfs *rootfs = &conf->rootfs;
03585adc 1667 size_t pty_max = conf->pty_max;
289b707b
CB
1668 int ret;
1669
03585adc
CB
1670 pty_max += conf->ttys.max;
1671 if (pty_max <= 0)
1672 return log_debug(0, "No new devpts instance will be mounted since no pts devices are required");
289b707b 1673
f30fc74d
CB
1674 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
1675 "/proc/self/fd/%d/pts", rootfs->dfd_dev);
1676 if (ret < 0)
1677 return syserror("Failed to create path");
1678
1679 (void)umount2(rootfs->buf, MNT_DETACH);
1680
1681 /* Create mountpoint for devpts instance. */
1682 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1683 if (ret < 0 && errno != EEXIST)
1684 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
1685
96a980e1
CB
1686 if (can_use_mount_api()) {
1687 fd_fs = fs_prepare("devpts", -EBADF, "", 0, 0);
1688 if (fd_fs < 0)
1689 return syserror("Failed to prepare filesystem context for devpts");
289b707b 1690
96a980e1
CB
1691 ret = fs_set_property(fd_fs, "source", "devpts");
1692 if (ret < 0)
1693 SYSTRACE("Failed to set \"source=devpts\" on devpts filesystem context %d", fd_fs);
289b707b 1694
96a980e1
CB
1695 ret = fs_set_property(fd_fs, "gid", "5");
1696 if (ret < 0)
1697 SYSTRACE("Failed to set \"gid=5\" on devpts filesystem context %d", fd_fs);
289b707b 1698
96a980e1
CB
1699 ret = fs_set_flag(fd_fs, "newinstance");
1700 if (ret < 0)
1701 return syserror("Failed to set \"newinstance\" property on devpts filesystem context %d", fd_fs);
289b707b 1702
96a980e1
CB
1703 ret = fs_set_property(fd_fs, "ptmxmode", "0666");
1704 if (ret < 0)
1705 return syserror("Failed to set \"ptmxmode=0666\" property on devpts filesystem context %d", fd_fs);
289b707b 1706
96a980e1
CB
1707 ret = fs_set_property(fd_fs, "mode", "0620");
1708 if (ret < 0)
1709 return syserror("Failed to set \"mode=0620\" property on devpts filesystem context %d", fd_fs);
289b707b 1710
03585adc 1711 ret = fs_set_property(fd_fs, "max", fdstr(pty_max));
96a980e1
CB
1712 if (ret < 0)
1713 return syserror("Failed to set \"max=%zu\" property on devpts filesystem context %d", conf->pty_max, fd_fs);
f30fc74d 1714
96a980e1
CB
1715 ret = fsconfig(fd_fs, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
1716 if (ret < 0)
1717 return syserror("Failed to finalize filesystem context %d", fd_fs);
289b707b 1718
96a980e1
CB
1719 devpts_fd = fsmount(fd_fs, FSMOUNT_CLOEXEC, MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC);
1720 if (devpts_fd < 0)
1721 return syserror("Failed to create new mount for filesystem context %d", fd_fs);
1722 TRACE("Created detached devpts mount %d", devpts_fd);
77890c6d 1723
96a980e1
CB
1724 ret = move_mount(devpts_fd, "", rootfs->dfd_dev, "pts", MOVE_MOUNT_F_EMPTY_PATH);
1725 if (ret)
1726 return syserror("Failed to attach devpts mount %d to %d/pts", conf->devpts_fd, rootfs->dfd_dev);
3c26f34e 1727
96a980e1
CB
1728 DEBUG("Attached detached devpts mount %d to %d/pts", devpts_fd, rootfs->dfd_dev);
1729 } else {
1730 char **opts;
1731 char devpts_mntopts[256];
1732 char *mntopt_sets[5];
1733 char default_devpts_mntopts[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
7e40254a 1734
f30fc74d
CB
1735 /*
1736 * Fallback codepath in case the new mount API can't be used to
1737 * create detached mounts.
1738 */
1739
289b707b 1740 ret = strnprintf(devpts_mntopts, sizeof(devpts_mntopts), "%s,max=%zu",
03585adc 1741 default_devpts_mntopts, pty_max);
289b707b
CB
1742 if (ret < 0)
1743 return -1;
3c26f34e 1744
289b707b
CB
1745 /* Create mountpoint for devpts instance. */
1746 ret = mkdirat(rootfs->dfd_dev, "pts", 0755);
1747 if (ret < 0 && errno != EEXIST)
1748 return log_error_errno(-1, errno, "Failed to create \"/dev/pts\" directory");
ce155c60 1749
289b707b
CB
1750 /* gid=5 && max= */
1751 mntopt_sets[0] = devpts_mntopts;
ce155c60 1752
289b707b
CB
1753 /* !gid=5 && max= */
1754 mntopt_sets[1] = devpts_mntopts + STRLITERALLEN("gid=5") + 1;
ce155c60 1755
289b707b
CB
1756 /* gid=5 && !max= */
1757 mntopt_sets[2] = default_devpts_mntopts;
ce155c60 1758
289b707b
CB
1759 /* !gid=5 && !max= */
1760 mntopt_sets[3] = default_devpts_mntopts + STRLITERALLEN("gid=5") + 1;
ce155c60 1761
289b707b
CB
1762 /* end */
1763 mntopt_sets[4] = NULL;
70761e5e 1764
289b707b
CB
1765 for (ret = -1, opts = mntopt_sets; opts && *opts; opts++) {
1766 /* mount new devpts instance */
8b0ccdaa
CB
1767 ret = mount_at(rootfs->dfd_dev, "", 0,
1768 rootfs->dfd_dev, "pts", PROTECT_LOOKUP_BENEATH,
1769 "devpts", MS_NOSUID | MS_NOEXEC, *opts);
289b707b
CB
1770 if (ret == 0)
1771 break;
1772 }
289b707b
CB
1773 if (ret < 0)
1774 return log_error_errno(-1, errno, "Failed to mount new devpts instance");
1775
1776 devpts_fd = open_at(rootfs->dfd_dev, "pts", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
1777 if (devpts_fd < 0) {
1778 devpts_fd = -EBADF;
1779 TRACE("Failed to create detached devpts mount");
1780 }
1781
289b707b
CB
1782 DEBUG("Mounted new devpts instance with options \"%s\"", *opts);
1783 }
03585adc 1784
96a980e1 1785 handler->conf->devpts_fd = move_fd(devpts_fd);
f797f05e 1786
03585adc
CB
1787 /*
1788 * In order to allocate terminal devices the devpts filesystem will
1789 * have to be attached to the filesystem at least ones in the new mount
1790 * api. The reason is lengthy but the gist is that until the new mount
1791 * has been attached to the filesystem it is a detached mount with an
1792 * anonymous mount mamespace attached to it for which the kernel
1793 * refuses certain operations.
1794 * We end up here if the user has requested to allocate tty devices
1795 * while not requestig pty devices be made available to the container.
1796 * We only need the devpts_fd to allocate tty devices.
1797 */
1798 if (conf->pty_max <= 0)
1799 return 0;
1800
d5cb35d6 1801 /* Remove any pre-existing /dev/ptmx file. */
a5a08920 1802 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
b29e05d6 1803 if (ret < 0) {
55022530
CB
1804 if (errno != ENOENT)
1805 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\" file");
b29e05d6 1806 } else {
0fd73091 1807 DEBUG("Removed existing \"/dev/ptmx\" file");
3c26f34e 1808 }
1809
8de0119d 1810 /* Create placeholder /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
a5a08920 1811 ret = mknodat(rootfs->dfd_dev, "ptmx", S_IFREG | 0000, 0);
55022530 1812 if (ret < 0 && errno != EEXIST)
8de0119d
CB
1813 return log_error_errno(-1, errno, "Failed to create \"/dev/ptmx\" file as bind mount target");
1814 DEBUG("Created \"/dev/ptmx\" file as bind mount target");
77890c6d 1815
d27ae999 1816 /* Main option: use a bind-mount to please AppArmor */
8b0ccdaa
CB
1817 ret = mount_at(rootfs->dfd_dev, "pts/ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1818 rootfs->dfd_dev, "ptmx", (PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS & ~RESOLVE_NO_XDEV),
1819 NULL, MS_BIND, NULL);
55022530
CB
1820 if (!ret)
1821 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1822 else
d5cb35d6 1823 /* Fallthrough and try to create a symlink. */
0fd73091 1824 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
d5cb35d6 1825
8de0119d 1826 /* Remove the placeholder /dev/ptmx file we created above. */
a5a08920 1827 ret = unlinkat(rootfs->dfd_dev, "ptmx", 0);
55022530
CB
1828 if (ret < 0)
1829 return log_error_errno(-1, errno, "Failed to remove existing \"/dev/ptmx\"");
d5cb35d6
CB
1830
1831 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
06853427 1832 ret = symlinkat("/dev/pts/ptmx", rootfs->dfd_dev, "dev/ptmx");
55022530
CB
1833 if (ret < 0)
1834 return log_error_errno(-1, errno, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
cd54d859 1835
185b9ee9 1836 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
3c26f34e 1837 return 0;
1838}
1839
03585adc
CB
1840static int lxc_finish_devpts_child(struct lxc_handler *handler)
1841{
1842 struct lxc_conf *conf = handler->conf;
1843 struct lxc_rootfs *rootfs = &conf->rootfs;
1844 int ret;
1845
1846 if (conf->pty_max > 0)
1847 return 0;
1848
1849 /*
1850 * We end up here if the user has requested to allocate tty devices
1851 * while not requestig pty devices be made available to the container.
1852 * This means we can unmount the devpts instance. We only need the
1853 * devpts_fd to allocate tty devices.
1854 */
1855 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf),
1856 "/proc/self/fd/%d/pts", rootfs->dfd_dev);
1857 if (ret < 0)
1858 return syserror("Failed to create path");
1859
1860 close_prot_errno_disarm(conf->devpts_fd);
1861 return umount2(rootfs->buf, MNT_DETACH);
1862}
1863
111ed96e 1864static int lxc_send_devpts_to_parent(struct lxc_handler *handler)
1b82d721
CB
1865{
1866 int ret;
1867
1868 if (handler->conf->pty_max <= 0)
1869 return log_debug(0, "No devpts file descriptor will be sent since no pts devices are requested");
1870
1871 ret = lxc_abstract_unix_send_fds(handler->data_sock[0], &handler->conf->devpts_fd, 1, NULL, 0);
1872 if (ret < 0)
1873 SYSERROR("Failed to send devpts file descriptor %d to parent", handler->conf->devpts_fd);
1874 else
1875 TRACE("Sent devpts file descriptor %d to parent", handler->conf->devpts_fd);
1876
1877 close_prot_errno_disarm(handler->conf->devpts_fd);
1878
1879 return 0;
1880}
1881
64a04c84 1882static int setup_personality(personality_t persona)
cccc74b5 1883{
0fd73091
CB
1884 int ret;
1885
9c601e1f
CB
1886 if (persona == LXC_ARCH_UNCHANGED)
1887 return log_debug(0, "Retaining original personality");
cccc74b5 1888
64a04c84 1889 ret = lxc_personality(persona);
55022530 1890 if (ret < 0)
9c601e1f 1891 return syserror("Failed to set personality to \"0lx%lx\"", persona);
cccc74b5 1892
38608992 1893 INFO("Set personality to \"0lx%lx\"", persona);
cccc74b5
DL
1894 return 0;
1895}
1896
9f77617b 1897static int bind_mount_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1898 struct lxc_terminal *console, int fd_to)
37c74fd1
CB
1899{
1900 __do_close int fd_pty = -EBADF;
1901
1902 if (is_empty_string(console->name))
1903 return ret_errno(EINVAL);
1904
1905 /*
1906 * When the pty fd stashed in console->pty has been retrieved via the
1907 * TIOCGPTPEER ioctl() to avoid dangerous path-based lookups when
1908 * allocating new pty devices we can't reopen it through openat2() or
1909 * created a detached mount through open_tree() from it. This means we
1910 * would need to mount using the path stased in console->name which is
1911 * unsafe. We could be mounting a device that isn't identical to the
1912 * one we've already safely opened and stashed in console->pty.
1913 * So, what we do is we open an O_PATH file descriptor for
1914 * console->name and verify that the opened fd and the fd we stashed in
1915 * console->pty refer to the same device. If they do we can go on and
1916 * created a detached mount based on the newly opened O_PATH file
1917 * descriptor and then safely mount.
1918 */
9f77617b 1919 fd_pty = open_at_same(console->pty, fd_devpts, fdstr(console->pty_nr),
d94a7f09 1920 PROTECT_OPATH_FILE, PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
37c74fd1 1921 if (fd_pty < 0)
d94a7f09 1922 return syserror("Failed to open \"%s\"", console->name);
37c74fd1
CB
1923
1924 /*
1925 * Note, there are intentionally no open or lookup restrictions since
1926 * we're operating directly on the fd.
1927 */
d94a7f09 1928 if (can_use_mount_api())
704cadd5 1929 return fd_bind_mount(fd_pty, "", 0, 0, fd_to, "", 0, 0, 0, 0, 0, false);
d94a7f09
CB
1930
1931 return mount_fd(fd_pty, fd_to, "none", MS_BIND, 0);
37c74fd1
CB
1932}
1933
9f77617b 1934static int lxc_setup_dev_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1935 struct lxc_terminal *console)
6e590161 1936{
af0cf9b7 1937 __do_close int fd_console = -EBADF;
882671aa 1938 int ret;
52e35957 1939
cf68ffd9
CB
1940 /*
1941 * When we are asked to setup a console we remove any previous
8b1b1210
CB
1942 * /dev/console bind-mounts.
1943 */
a5a08920 1944 if (exists_file_at(rootfs->dfd_dev, "console")) {
af0cf9b7
CB
1945 char *rootfs_path = rootfs->path ? rootfs->mount : "";
1946
9bcde680
CB
1947 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
1948 if (ret < 0)
953db219
CB
1949 return -1;
1950
58b38111 1951 ret = lxc_unstack_mountpoint(rootfs->buf, false);
55022530 1952 if (ret < 0)
58b38111 1953 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
55022530 1954 else
58b38111 1955 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
8b1b1210
CB
1956 }
1957
cf68ffd9
CB
1958 /*
1959 * For unprivileged containers autodev or automounts will already have
8b1b1210
CB
1960 * taken care of creating /dev/console.
1961 */
d94a7f09
CB
1962 fd_console = open_at(rootfs->dfd_dev,
1963 "console",
1964 PROTECT_OPEN | O_CREAT,
1965 PROTECT_LOOKUP_BENEATH,
1966 0000);
af0cf9b7 1967 if (fd_console < 0)
d94a7f09 1968 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
52e35957 1969
1dd71c90 1970 ret = fchmod(console->pty, 0620);
55022530 1971 if (ret < 0)
d94a7f09 1972 return syserror("Failed to change console mode");
13954cce 1973
9f77617b 1974 ret = bind_mount_console(fd_devpts, rootfs, console, fd_console);
37c74fd1 1975 if (ret < 0)
d94a7f09
CB
1976 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
1977 console->pty, console->name, fd_console);
6e590161 1978
d94a7f09 1979 TRACE("Setup console \"%s\"", console->name);
7c6ef2a2
SH
1980 return 0;
1981}
1982
9f77617b 1983static int lxc_setup_ttydir_console(int fd_devpts, struct lxc_rootfs *rootfs,
d94a7f09 1984 struct lxc_terminal *console,
37c74fd1 1985 char *ttydir)
7c6ef2a2 1986{
d94a7f09
CB
1987 __do_close int fd_ttydir = -EBADF, fd_dev_console = -EBADF,
1988 fd_reg_console = -EBADF, fd_reg_ttydir_console = -EBADF;
3b7e332f 1989 int ret;
7c6ef2a2 1990
f6370f2a
CB
1991 /* create dev/<ttydir> */
1992 ret = mkdirat(rootfs->dfd_dev, ttydir, 0755);
1993 if (ret < 0 && errno != EEXIST)
1994 return syserror("Failed to create \"%d/%s\"", rootfs->dfd_dev, ttydir);
d94a7f09
CB
1995
1996 fd_ttydir = open_at(rootfs->dfd_dev,
1997 ttydir,
1998 PROTECT_OPATH_DIRECTORY,
1999 PROTECT_LOOKUP_BENEATH,
2000 0);
2001 if (fd_ttydir < 0)
2002 return syserror("Failed to open \"%d/%s\"", rootfs->dfd_dev, ttydir);
7c6ef2a2 2003
f6370f2a 2004 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/console", ttydir);
9bcde680 2005 if (ret < 0)
3d7d929a
CB
2006 return -1;
2007
f6370f2a 2008 /* create dev/<ttydir>/console */
d94a7f09
CB
2009 fd_reg_ttydir_console = open_at(fd_ttydir,
2010 "console",
2011 PROTECT_OPEN | O_CREAT,
2012 PROTECT_LOOKUP_BENEATH,
2013 0000);
2014 if (fd_reg_ttydir_console < 0)
2015 return syserror("Failed to create \"%d/console\"", fd_ttydir);
2a12fefd 2016
f6370f2a 2017 if (file_exists(rootfs->buf)) {
d94a7f09
CB
2018 char *rootfs_path = rootfs->path ? rootfs->mount : "";
2019
2020 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/dev/console", rootfs_path);
2021 if (ret < 0)
2022 return -1;
2023
f6370f2a 2024 ret = lxc_unstack_mountpoint(rootfs->buf, false);
55022530 2025 if (ret < 0)
f6370f2a 2026 return log_error_errno(-ret, errno, "Failed to unmount \"%s\"", rootfs->buf);
55022530 2027 else
f6370f2a 2028 DEBUG("Cleared all (%d) mounts from \"%s\"", ret, rootfs->buf);
3dc035f1 2029 }
2a12fefd 2030
d94a7f09
CB
2031 /* create dev/console */
2032 fd_reg_console = open_at(rootfs->dfd_dev,
2033 "console",
2034 PROTECT_OPEN | O_CREAT,
2035 PROTECT_LOOKUP_BENEATH,
2036 0000);
2037 if (fd_reg_console < 0)
2038 return syserror("Failed to create \"%d/console\"", rootfs->dfd_dev);
7c6ef2a2 2039
1dd71c90 2040 ret = fchmod(console->pty, 0620);
55022530 2041 if (ret < 0)
d94a7f09 2042 return syserror("Failed to change console mode");
2a12fefd 2043
d94a7f09 2044 /* bind mount console to '/dev/<ttydir>/console' */
9f77617b 2045 ret = bind_mount_console(fd_devpts, rootfs, console, fd_reg_ttydir_console);
55022530 2046 if (ret < 0)
d94a7f09
CB
2047 return syserror("Failed to mount \"%d(%s)\" on \"%d\"",
2048 console->pty, console->name, fd_reg_ttydir_console);
2049
2050 fd_dev_console = open_at_same(console->pty,
2051 fd_ttydir,
2052 "console",
2053 PROTECT_OPATH_FILE,
2054 PROTECT_LOOKUP_BENEATH_XDEV,
2055 0);
2056 if (fd_dev_console < 0)
2057 return syserror("Failed to open \"%d/console\"", fd_ttydir);
2058
2059 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
2060 if (can_use_mount_api())
2061 ret = fd_bind_mount(fd_dev_console,
2062 "",
2063 PROTECT_OPATH_FILE,
2064 PROTECT_LOOKUP_BENEATH_XDEV,
2065 fd_reg_console,
2066 "",
2067 PROTECT_OPATH_FILE,
2068 PROTECT_LOOKUP_BENEATH,
2069 0,
704cadd5
CB
2070 0,
2071 0,
d94a7f09
CB
2072 false);
2073 else
2074 ret = mount_fd(fd_dev_console, fd_reg_console, "none", MS_BIND, 0);
55022530 2075 if (ret < 0)
d94a7f09
CB
2076 return syserror("Failed to mount \"%d\" on \"%d\"",
2077 fd_dev_console, fd_reg_console);
3dc035f1 2078
d94a7f09 2079 TRACE("Setup console \"%s\"", console->name);
6e590161 2080 return 0;
2081}
2082
f3dff080
CB
2083static int lxc_setup_console(const struct lxc_handler *handler,
2084 struct lxc_rootfs *rootfs,
37c74fd1 2085 struct lxc_terminal *console, char *ttydir)
7c6ef2a2 2086{
9f77617b
CB
2087 __do_close int fd_devpts_host = -EBADF;
2088 int fd_devpts = handler->conf->devpts_fd;
2089 int ret = -1;
3d7d929a 2090
37c74fd1
CB
2091 if (!wants_console(console))
2092 return log_trace(0, "Skipping console setup");
7c6ef2a2 2093
9f77617b
CB
2094 if (console->pty < 0) {
2095 /*
2096 * Allocate a console from the container's devpts instance. We
2097 * have checked on the host that we have enough pty devices
2098 * available.
2099 */
2100 ret = lxc_devpts_terminal(handler->conf->devpts_fd, &console->ptx,
18129d94 2101 &console->pty, &console->pty_nr, false);
9f77617b
CB
2102 if (ret < 0)
2103 return syserror("Failed to allocate console from container's devpts instance");
2104
2105 ret = strnprintf(console->name, sizeof(console->name),
2106 "/dev/pts/%d", console->pty_nr);
2107 if (ret < 0)
2108 return syserror("Failed to create console path");
2109 } else {
2110 /*
2111 * We're using a console from the host's devpts instance. Open
2112 * it again so we can later verify that the console we're
2113 * supposed to use is still the same as the one we opened on
2114 * the host.
2115 */
2116 fd_devpts_host = open_at(rootfs->dfd_host,
2117 "dev/pts",
2118 PROTECT_OPATH_DIRECTORY,
2119 PROTECT_LOOKUP_BENEATH_XDEV,
2120 0);
2121 if (fd_devpts_host < 0)
2122 return syserror("Failed to open host devpts");
2123
2124 fd_devpts = fd_devpts_host;
2125 }
2126
37c74fd1 2127 if (ttydir)
9f77617b 2128 ret = lxc_setup_ttydir_console(fd_devpts, rootfs, console, ttydir);
37c74fd1 2129 else
9f77617b 2130 ret = lxc_setup_dev_console(fd_devpts, rootfs, console);
87dfb724
CB
2131 if (ret < 0)
2132 return syserror("Failed to setup console");
2133
f3dff080
CB
2134 /*
2135 * Some init's such as busybox will set sane tty settings on stdin,
2136 * stdout, stderr which it thinks is the console. We already set them
2137 * the way we wanted on the real terminal, and we want init to do its
2138 * setup on its console ie. the pty allocated in lxc_terminal_setup() so
2139 * make sure that that pty is stdin,stdout,stderr.
2140 */
9f77617b 2141 if (console->pty >= 0) {
f3dff080 2142 if (handler->daemonize || !handler->conf->is_execute)
9f77617b 2143 ret = set_stdfds(console->pty);
f3dff080 2144 else
9f77617b 2145 ret = lxc_terminal_set_stdfds(console->pty);
f3dff080 2146 if (ret < 0)
9f77617b
CB
2147 return syserror("Failed to redirect std{in,out,err} to pty file descriptor %d", console->pty);
2148
2149 /*
2150 * If the console has been allocated from the host's devpts
2151 * we're done and we don't need to send fds to the parent.
2152 */
2153 if (fd_devpts_host >= 0)
2154 lxc_terminal_delete(console);
f3dff080
CB
2155 }
2156
37c74fd1 2157 return ret;
7c6ef2a2
SH
2158}
2159
a08bfbe3 2160static int parse_mntopt(char *opt, unsigned long *flags, char **data, size_t size)
998ac676 2161{
a08bfbe3 2162 ssize_t ret;
998ac676 2163
85c2de39
MB
2164 /* If '=' is contained in opt, the option must go into data. */
2165 if (!strchr(opt, '=')) {
a08bfbe3
CB
2166 /*
2167 * If opt is found in mount_opt, set or clear flags.
2168 * Otherwise append it to data.
2169 */
85c2de39 2170 size_t opt_len = strlen(opt);
a08bfbe3 2171 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
85c2de39 2172 size_t mo_name_len = strlen(mo->name);
a08bfbe3 2173
eed95eb0 2174 if (opt_len == mo_name_len && strnequal(opt, mo->name, mo_name_len)) {
85c2de39 2175 if (mo->clear)
1e4bce2c 2176 *flags &= ~mo->legacy_flag;
85c2de39 2177 else
1e4bce2c 2178 *flags |= mo->legacy_flag;
a08bfbe3 2179 return 0;
85c2de39 2180 }
998ac676
RT
2181 }
2182 }
2183
a08bfbe3
CB
2184 if (strlen(*data)) {
2185 ret = strlcat(*data, ",", size);
2186 if (ret < 0)
2187 return log_error_errno(ret, errno, "Failed to append \",\" to %s", *data);
2188 }
2189
2190 ret = strlcat(*data, opt, size);
2191 if (ret < 0)
2192 return log_error_errno(ret, errno, "Failed to append \"%s\" to %s", opt, *data);
efed99a4 2193
a08bfbe3 2194 return 0;
998ac676
RT
2195}
2196
d94eb390 2197int parse_mntopts_legacy(const char *mntopts, unsigned long *mntflags, char **mntdata)
998ac676 2198{
a08bfbe3
CB
2199 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
2200 char *mntopt_cur = NULL;
efed99a4 2201 size_t size;
998ac676 2202
a08bfbe3
CB
2203 if (*mntdata || *mntflags)
2204 return ret_errno(EINVAL);
911324ef
DL
2205
2206 if (!mntopts)
998ac676
RT
2207 return 0;
2208
a08bfbe3
CB
2209 mntopts_dup = strdup(mntopts);
2210 if (!mntopts_dup)
2211 return ret_errno(ENOMEM);
998ac676 2212
a08bfbe3
CB
2213 size = strlen(mntopts_dup) + 1;
2214 mntopts_new = zalloc(size);
2215 if (!mntopts_new)
2216 return ret_errno(ENOMEM);
998ac676 2217
a08bfbe3
CB
2218 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",")
2219 if (parse_mntopt(mntopt_cur, mntflags, &mntopts_new, size) < 0)
2220 return ret_errno(EINVAL);
998ac676 2221
a08bfbe3
CB
2222 if (*mntopts_new)
2223 *mntdata = move_ptr(mntopts_new);
998ac676
RT
2224
2225 return 0;
2226}
2227
1b82d721
CB
2228static int parse_vfs_attr(struct lxc_mount_options *opts, char *opt, size_t size)
2229{
2230 /*
2231 * If opt is found in mount_opt, set or clear flags.
2232 * Otherwise append it to data.
2233 */
2234 for (struct mount_opt *mo = &mount_opt[0]; mo->name != NULL; mo++) {
2235 if (!strnequal(opt, mo->name, strlen(mo->name)))
2236 continue;
2237
2238 /* This is a recursive bind-mount. */
2239 if (strequal(mo->name, "rbind")) {
3eb23230 2240 opts->bind_recursively = 1;
1b82d721 2241 opts->bind = 1;
0f43436c 2242 opts->mnt_flags |= mo->legacy_flag; /* MS_BIND | MS_REC */
1b82d721
CB
2243 return 0;
2244 }
2245
2246 /* This is a bind-mount. */
2247 if (strequal(mo->name, "bind")) {
2248 opts->bind = 1;
0f43436c 2249 opts->mnt_flags |= mo->legacy_flag; /* MS_BIND */
1b82d721
CB
2250 return 0;
2251 }
2252
2253 if (mo->flag == ~0)
2254 return log_info(0, "Ignoring %s mount option", mo->name);
2255
2256 if (mo->clear) {
2257 opts->attr.attr_clr |= mo->flag;
0f43436c 2258 opts->mnt_flags &= ~mo->legacy_flag;
1b82d721
CB
2259 TRACE("Lowering %s", mo->name);
2260 } else {
2261 opts->attr.attr_set |= mo->flag;
0f43436c 2262 opts->mnt_flags |= mo->legacy_flag;
1b82d721
CB
2263 TRACE("Raising %s", mo->name);
2264 }
2265
2266 return 0;
2267 }
2268
0f43436c 2269 for (struct mount_opt *mo = &propagation_opt[0]; mo->name != NULL; mo++) {
1b82d721
CB
2270 if (!strnequal(opt, mo->name, strlen(mo->name)))
2271 continue;
2272
6b48a575
CB
2273 if (strequal(mo->name, "rslave") ||
2274 strequal(mo->name, "rshared") ||
2275 strequal(mo->name, "runbindable") ||
2276 strequal(mo->name, "rprivate"))
2277 opts->propagate_recursively = 1;
2278
1b82d721 2279 opts->attr.propagation = mo->flag;
6b48a575 2280 opts->prop_flags |= mo->legacy_flag;
1b82d721
CB
2281 return 0;
2282 }
2283
2284 return 0;
2285}
2286
704cadd5 2287int parse_mount_attrs(struct lxc_mount_options *opts, const char *mntopts)
1b82d721
CB
2288{
2289 __do_free char *mntopts_new = NULL, *mntopts_dup = NULL;
380fcc08 2290 char *end = NULL, *mntopt_cur = NULL;
1b82d721
CB
2291 int ret;
2292 size_t size;
2293
2294 if (!opts)
2295 return ret_errno(EINVAL);
2296
2297 if (!mntopts)
2298 return 0;
2299
2300 mntopts_dup = strdup(mntopts);
2301 if (!mntopts_dup)
2302 return ret_errno(ENOMEM);
2303
2304 size = strlen(mntopts_dup) + 1;
2305 mntopts_new = zalloc(size);
2306 if (!mntopts_new)
2307 return ret_errno(ENOMEM);
2308
2309 lxc_iterate_parts(mntopt_cur, mntopts_dup, ",") {
1b82d721
CB
2310 /* This is a filesystem specific option. */
2311 if (strchr(mntopt_cur, '=')) {
2312 if (!end) {
2313 end = stpcpy(mntopts_new, mntopt_cur);
2314 } else {
2315 end = stpcpy(end, ",");
2316 end = stpcpy(end, mntopt_cur);
2317 }
2318
2319 continue;
2320 }
2321
2322 /* This is a generic vfs option. */
2323 ret = parse_vfs_attr(opts, mntopt_cur, size);
2324 if (ret < 0)
2325 return syserror("Failed to parse mount attributes: \"%s\"", mntopt_cur);
2326 }
2327
2328 if (*mntopts_new)
2329 opts->data = move_ptr(mntopts_new);
2330
2331 return 0;
2332}
2333
d840039e
YT
2334static void parse_propagationopt(char *opt, unsigned long *flags)
2335{
2336 struct mount_opt *mo;
2337
2338 /* If opt is found in propagation_opt, set or clear flags. */
d840039e 2339 for (mo = &propagation_opt[0]; mo->name != NULL; mo++) {
eed95eb0 2340 if (!strnequal(opt, mo->name, strlen(mo->name)))
0fd73091
CB
2341 continue;
2342
2343 if (mo->clear)
1e4bce2c 2344 *flags &= ~mo->legacy_flag;
0fd73091 2345 else
1e4bce2c 2346 *flags |= mo->legacy_flag;
0fd73091
CB
2347
2348 return;
d840039e
YT
2349 }
2350}
2351
8ce1abc2 2352int parse_propagationopts(const char *mntopts, unsigned long *pflags)
d840039e 2353{
dfd2e059
CB
2354 __do_free char *s = NULL;
2355 char *p;
d840039e
YT
2356
2357 if (!mntopts)
2358 return 0;
2359
2360 s = strdup(mntopts);
55022530
CB
2361 if (!s)
2362 return log_error_errno(-ENOMEM, errno, "Failed to allocate memory");
d840039e 2363
0fd73091 2364 *pflags = 0L;
8db9d26f 2365 lxc_iterate_parts(p, s, ",")
d840039e 2366 parse_propagationopt(p, pflags);
0fd73091 2367
d840039e
YT
2368 return 0;
2369}
2370
6fd5e769
SH
2371static void null_endofword(char *word)
2372{
2373 while (*word && *word != ' ' && *word != '\t')
2374 word++;
2375 *word = '\0';
2376}
2377
0fd73091 2378/* skip @nfields spaces in @src */
6fd5e769
SH
2379static char *get_field(char *src, int nfields)
2380{
6fd5e769 2381 int i;
0fd73091 2382 char *p = src;
6fd5e769
SH
2383
2384 for (i = 0; i < nfields; i++) {
2385 while (*p && *p != ' ' && *p != '\t')
2386 p++;
0fd73091 2387
6fd5e769
SH
2388 if (!*p)
2389 break;
0fd73091 2390
6fd5e769
SH
2391 p++;
2392 }
0fd73091 2393
6fd5e769
SH
2394 return p;
2395}
2396
911324ef
DL
2397static int mount_entry(const char *fsname, const char *target,
2398 const char *fstype, unsigned long mountflags,
d840039e
YT
2399 unsigned long pflags, const char *data, bool optional,
2400 bool dev, bool relative, const char *rootfs)
911324ef 2401{
0ac4b28a 2402 int ret;
6b5a54cd 2403 char srcbuf[PATH_MAX];
181437fd 2404 const char *srcpath = fsname;
614305f3 2405#ifdef HAVE_STATVFS
2938f7c8 2406 struct statvfs sb;
614305f3 2407#endif
2938f7c8 2408
181437fd 2409 if (relative) {
9bcde680
CB
2410 ret = strnprintf(srcbuf, sizeof(srcbuf), "%s/%s", rootfs ? rootfs : "/", fsname ? fsname : "");
2411 if (ret < 0)
55022530 2412 return log_error_errno(-1, errno, "source path is too long");
181437fd
YT
2413 srcpath = srcbuf;
2414 }
2415
2416 ret = safe_mount(srcpath, target, fstype, mountflags & ~MS_REMOUNT, data,
0ac4b28a
CB
2417 rootfs);
2418 if (ret < 0) {
55022530
CB
2419 if (optional)
2420 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2421 srcpath ? srcpath : "(null)", target);
0ac4b28a 2422
55022530
CB
2423 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2424 srcpath ? srcpath : "(null)", target);
911324ef
DL
2425 }
2426
2427 if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
0ac4b28a 2428
55022530
CB
2429 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
2430 srcpath ? srcpath : "(none)", target ? target : "(none)");
0ac4b28a 2431
614305f3 2432#ifdef HAVE_STATVFS
181437fd 2433 if (srcpath && statvfs(srcpath, &sb) == 0) {
94bef7e4
TA
2434 unsigned long required_flags = 0;
2435
2938f7c8
SH
2436 if (sb.f_flag & MS_NOSUID)
2437 required_flags |= MS_NOSUID;
0ac4b28a 2438
ae7a770e 2439 if (sb.f_flag & MS_NODEV && !dev)
2938f7c8 2440 required_flags |= MS_NODEV;
0ac4b28a 2441
2938f7c8
SH
2442 if (sb.f_flag & MS_RDONLY)
2443 required_flags |= MS_RDONLY;
0ac4b28a 2444
2938f7c8
SH
2445 if (sb.f_flag & MS_NOEXEC)
2446 required_flags |= MS_NOEXEC;
0ac4b28a 2447
55022530
CB
2448 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
2449 srcpath, sb.f_flag, required_flags);
0ac4b28a
CB
2450
2451 /* If this was a bind mount request, and required_flags
2938f7c8 2452 * does not have any flags which are not already in
0ac4b28a 2453 * mountflags, then skip the remount.
2938f7c8 2454 */
94bef7e4
TA
2455 if (!(mountflags & MS_REMOUNT) &&
2456 (!(required_flags & ~mountflags) && !(mountflags & MS_RDONLY))) {
15f3e22b
CB
2457 DEBUG("Mountflags already were %lu, skipping remount", mountflags);
2458 goto skipremount;
2938f7c8 2459 }
0ac4b28a 2460
2938f7c8 2461 mountflags |= required_flags;
6fd5e769 2462 }
614305f3 2463#endif
911324ef 2464
181437fd 2465 ret = mount(srcpath, target, fstype, mountflags | MS_REMOUNT, data);
0ac4b28a 2466 if (ret < 0) {
55022530
CB
2467 if (optional)
2468 return log_info_errno(0, errno, "Failed to mount \"%s\" on \"%s\" (optional)",
2469 srcpath ? srcpath : "(null)",
2470 target);
2471
2472 return log_error_errno(-1, errno, "Failed to mount \"%s\" on \"%s\"",
2473 srcpath ? srcpath : "(null)",
2474 target);
911324ef
DL
2475 }
2476 }
2477
a3ed9b81 2478#ifdef HAVE_STATVFS
2479skipremount:
2480#endif
d840039e
YT
2481 if (pflags) {
2482 ret = mount(NULL, target, NULL, pflags, NULL);
2483 if (ret < 0) {
55022530
CB
2484 if (optional)
2485 return log_info_errno(0, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
2486 else
2487 return log_error_errno(-1, errno, "Failed to change mount propagation for \"%s\" (optional)", target);
d840039e
YT
2488 }
2489 DEBUG("Changed mount propagation for \"%s\"", target);
2490 }
2491
0103eb53 2492 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
181437fd 2493 srcpath ? srcpath : "(null)", target, fstype);
911324ef
DL
2494
2495 return 0;
2496}
2497
0b932f9d
CB
2498const char *lxc_mount_options_info[LXC_MOUNT_MAX] = {
2499 "create=dir",
2500 "create=file",
2501 "optional",
2502 "relative",
f6815906 2503 "idmap=",
0b932f9d
CB
2504};
2505
c5e30de4 2506/* Remove "optional", "create=dir", and "create=file" from mntopt */
1b82d721 2507int parse_lxc_mount_attrs(struct lxc_mount_options *opts, char *mnt_opts)
4e4ca161 2508{
0b932f9d 2509 for (size_t i = LXC_MOUNT_CREATE_DIR; i < LXC_MOUNT_MAX; i++) {
8e05f350 2510 __do_close int fd_userns = -EBADF;
0b932f9d 2511 const char *opt_name = lxc_mount_options_info[i];
f6815906 2512 size_t len;
d97d9e9f 2513 char *idmap_path, *opt, *opt_next;
c5e30de4 2514
d97d9e9f
CB
2515 opt = strstr(mnt_opts, opt_name);
2516 if (!opt)
4e4ca161 2517 continue;
c5e30de4 2518
0b932f9d
CB
2519 switch (i) {
2520 case LXC_MOUNT_CREATE_DIR:
2521 opts->create_dir = 1;
2522 break;
2523 case LXC_MOUNT_CREATE_FILE:
2524 opts->create_file = 1;
2525 break;
2526 case LXC_MOUNT_OPTIONAL:
2527 opts->optional = 1;
2528 break;
2529 case LXC_MOUNT_RELATIVE:
2530 opts->relative = 1;
2531 break;
f6815906 2532 case LXC_MOUNT_IDMAP:
d97d9e9f
CB
2533 opt_next = opt;
2534 opt_next += STRLITERALLEN("idmap=");
2535 idmap_path = strchrnul(opt_next, ',');
2e5c468a 2536 len = idmap_path - opt_next + 1;
f6815906 2537
f6815906 2538 if (len >= sizeof(opts->userns_path))
16fcdacc
CB
2539 return syserror_set(-EIO, "Excessive idmap path length for \"idmap=<path>\" LXC specific mount option");
2540
1b82d721 2541 strlcpy(opts->userns_path, opt_next, len);
2e5c468a 2542
16fcdacc
CB
2543 if (is_empty_string(opts->userns_path))
2544 return syserror_set(-EINVAL, "Missing idmap path for \"idmap=<path>\" LXC specific mount option");
2545
1b82d721 2546 if (!strequal(opts->userns_path, "container")) {
4b875ef9
CB
2547 fd_userns = open(opts->userns_path, O_RDONLY | O_NOCTTY | O_CLOEXEC);
2548 if (fd_userns < 0)
1b82d721 2549 return syserror("Failed to open user namespace %s", opts->userns_path);
4b875ef9 2550 }
e26cf563
CB
2551
2552 TRACE("Parse LXC specific mount option %d->\"idmap=%s\"", fd_userns, opts->userns_path);
f6815906 2553 break;
0b932f9d 2554 default:
16fcdacc 2555 return syserror_set(-EINVAL, "Unknown LXC specific mount option");
4e4ca161 2556 }
c5e30de4 2557
d97d9e9f
CB
2558 opt_next = strchr(opt, ',');
2559 if (!opt_next)
2560 *opt = '\0'; /* no more mntopts, so just chop it here */
0b932f9d 2561 else
d97d9e9f 2562 memmove(opt, opt_next + 1, strlen(opt_next + 1) + 1);
4e4ca161 2563 }
16fcdacc
CB
2564
2565 return 0;
4e4ca161
SH
2566}
2567
4d5b72a1 2568static int mount_entry_create_dir_file(const struct mntent *mntent,
749f98d9
CB
2569 const char *path,
2570 const struct lxc_rootfs *rootfs,
0fd73091 2571 const char *lxc_name, const char *lxc_path)
0ad19a3f 2572{
7a76eeaa 2573 __do_free char *p1 = NULL;
3b7e332f 2574 int ret;
7a76eeaa 2575 char *p2;
911324ef 2576
eed95eb0 2577 if (strnequal(mntent->mnt_type, "overlay", 7)) {
749f98d9 2578 ret = ovl_mkdir(mntent, rootfs, lxc_name, lxc_path);
12e6ab5d
CB
2579 if (ret < 0)
2580 return -1;
2581 }
6e46cc0d 2582
34cfffb3 2583 if (hasmntopt(mntent, "create=dir")) {
749f98d9 2584 ret = mkdir_p(path, 0755);
55022530
CB
2585 if (ret < 0 && errno != EEXIST)
2586 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
34cfffb3
SG
2587 }
2588
0fd73091
CB
2589 if (!hasmntopt(mntent, "create=file"))
2590 return 0;
749f98d9 2591
0fd73091
CB
2592 ret = access(path, F_OK);
2593 if (ret == 0)
2594 return 0;
749f98d9 2595
0fd73091
CB
2596 p1 = strdup(path);
2597 if (!p1)
2598 return -1;
749f98d9 2599
0fd73091 2600 p2 = dirname(p1);
749f98d9 2601
0fd73091 2602 ret = mkdir_p(p2, 0755);
55022530
CB
2603 if (ret < 0 && errno != EEXIST)
2604 return log_error_errno(-1, errno, "Failed to create directory \"%s\"", path);
749f98d9 2605
3b7e332f
CB
2606 ret = mknod(path, S_IFREG | 0000, 0);
2607 if (ret < 0 && errno != EEXIST)
2608 return -errno;
0fd73091 2609
749f98d9 2610 return 0;
4d5b72a1
NC
2611}
2612
ec50007f
CB
2613/* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2614 * without a rootfs. */
db4aba38 2615static inline int mount_entry_on_generic(struct mntent *mntent,
d8b712bc
CB
2616 const char *path,
2617 const struct lxc_rootfs *rootfs,
2618 const char *lxc_name,
2619 const char *lxc_path)
4d5b72a1 2620{
fd214f37 2621 __do_free char *mntdata = NULL;
a08bfbe3
CB
2622 unsigned long mntflags = 0, pflags = 0;
2623 char *rootfs_path = NULL;
d8b712bc 2624 int ret;
181437fd 2625 bool dev, optional, relative;
0b932f9d 2626 struct lxc_mount_options opts = {};
d8b712bc
CB
2627
2628 optional = hasmntopt(mntent, "optional") != NULL;
2629 dev = hasmntopt(mntent, "dev") != NULL;
181437fd 2630 relative = hasmntopt(mntent, "relative") != NULL;
d8b712bc 2631
ec50007f
CB
2632 if (rootfs && rootfs->path)
2633 rootfs_path = rootfs->mount;
2634
d8b712bc
CB
2635 ret = mount_entry_create_dir_file(mntent, path, rootfs, lxc_name,
2636 lxc_path);
2637 if (ret < 0) {
2638 if (optional)
2639 return 0;
608e3567 2640
d8b712bc
CB
2641 return -1;
2642 }
16fcdacc 2643
1b82d721 2644 ret = parse_lxc_mount_attrs(&opts, mntent->mnt_opts);
16fcdacc
CB
2645 if (ret < 0)
2646 return ret;
4e4ca161 2647
1b82d721
CB
2648 /*
2649 * Idmapped mount entries will be setup by the parent for us. Note that
2650 * we rely on mount_entry_create_dir_file() above to have already
2651 * created the target path for us. So the parent can just open the
2652 * target and send us the target fd.
2653 */
2654 errno = EOPNOTSUPP;
fa8e75f0 2655 if (!is_empty_string(opts.userns_path))
1b82d721 2656 return systrace_ret(0, "Skipping idmapped mount entry");
fa8e75f0 2657
d840039e
YT
2658 ret = parse_propagationopts(mntent->mnt_opts, &pflags);
2659 if (ret < 0)
2660 return -1;
2661
d94eb390 2662 ret = parse_mntopts_legacy(mntent->mnt_opts, &mntflags, &mntdata);
d8b712bc 2663 if (ret < 0)
a08bfbe3 2664 return ret;
a17b1e65 2665
6e46cc0d 2666 ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags,
d840039e 2667 pflags, mntdata, optional, dev, relative, rootfs_path);
68c152ef 2668
911324ef
DL
2669 return ret;
2670}
2671
8183f09e
CB
2672static inline int mount_entry_on_systemfs(struct lxc_rootfs *rootfs,
2673 struct mntent *mntent)
db4aba38 2674{
1433c9f9
CB
2675 int ret;
2676
2677 /* For containers created without a rootfs all mounts are treated as
07667a6a
CB
2678 * absolute paths starting at / on the host.
2679 */
1433c9f9 2680 if (mntent->mnt_dir[0] != '/')
9bcde680 2681 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/%s", mntent->mnt_dir);
1433c9f9 2682 else
9bcde680
CB
2683 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s", mntent->mnt_dir);
2684 if (ret < 0)
1433c9f9 2685 return -1;
1433c9f9 2686
8183f09e 2687 return mount_entry_on_generic(mntent, rootfs->buf, NULL, NULL, NULL);
db4aba38
NC
2688}
2689
4e4ca161 2690static int mount_entry_on_absolute_rootfs(struct mntent *mntent,
9c0fd29a 2691 struct lxc_rootfs *rootfs,
0a2dddd4
CB
2692 const char *lxc_name,
2693 const char *lxc_path)
911324ef 2694{
bdd2b34c 2695 int offset;
013bd428 2696 char *aux;
67e571de 2697 const char *lxcpath;
bdd2b34c 2698 int ret = 0;
0ad19a3f 2699
593e8478 2700 lxcpath = lxc_global_config_value("lxc.lxcpath");
bdd2b34c 2701 if (!lxcpath)
2a59a681 2702 return -1;
2a59a681 2703
bdd2b34c
CB
2704 /* If rootfs->path is a blockdev path, allow container fstab to use
2705 * <lxcpath>/<name>/rootfs" as the target prefix.
2706 */
9bcde680
CB
2707 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s/rootfs", lxcpath, lxc_name);
2708 if (ret < 0)
80a881b2
SH
2709 goto skipvarlib;
2710
9c0fd29a 2711 aux = strstr(mntent->mnt_dir, rootfs->buf);
80a881b2 2712 if (aux) {
9c0fd29a 2713 offset = strlen(rootfs->buf);
80a881b2
SH
2714 goto skipabs;
2715 }
2716
2717skipvarlib:
013bd428 2718 aux = strstr(mntent->mnt_dir, rootfs->path);
55022530
CB
2719 if (!aux)
2720 return log_warn(ret, "Ignoring mount point \"%s\"", mntent->mnt_dir);
80a881b2
SH
2721 offset = strlen(rootfs->path);
2722
2723skipabs:
9bcde680
CB
2724 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, aux + offset);
2725 if (ret < 0)
a17b1e65 2726 return -1;
a17b1e65 2727
9c0fd29a 2728 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
911324ef 2729}
d330fe7b 2730
4e4ca161 2731static int mount_entry_on_relative_rootfs(struct mntent *mntent,
4806d3b9 2732 struct lxc_rootfs *rootfs,
0a2dddd4
CB
2733 const char *lxc_name,
2734 const char *lxc_path)
911324ef 2735{
911324ef 2736 int ret;
d330fe7b 2737
34cfffb3 2738 /* relative to root mount point */
9bcde680
CB
2739 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/%s", rootfs->mount, mntent->mnt_dir);
2740 if (ret < 0)
9ba8130c 2741 return -1;
911324ef 2742
4806d3b9 2743 return mount_entry_on_generic(mntent, rootfs->buf, rootfs, lxc_name, lxc_path);
911324ef
DL
2744}
2745
8183f09e 2746static int mount_file_entries(struct lxc_rootfs *rootfs, FILE *file,
1ae3c19f 2747 const char *lxc_name, const char *lxc_path)
911324ef 2748{
9d03d857 2749 char buf[PATH_MAX];
0fd73091 2750 struct mntent mntent;
e76b8764 2751
aaf901be 2752 while (getmntent_r(file, &mntent, buf, sizeof(buf))) {
9d03d857
CB
2753 int ret;
2754
1ae3c19f 2755 if (!rootfs->path)
8183f09e 2756 ret = mount_entry_on_systemfs(rootfs, &mntent);
1ae3c19f
CB
2757 else if (mntent.mnt_dir[0] != '/')
2758 ret = mount_entry_on_relative_rootfs(&mntent, rootfs,
2759 lxc_name, lxc_path);
2760 else
2761 ret = mount_entry_on_absolute_rootfs(&mntent, rootfs,
9d03d857 2762 lxc_name, lxc_path);
1ae3c19f
CB
2763 if (ret < 0)
2764 return -1;
0ad19a3f 2765 }
cd54d859 2766
55022530
CB
2767 if (!feof(file) || ferror(file))
2768 return log_error(-1, "Failed to parse mount entries");
9d03d857
CB
2769
2770 return 0;
e7938e9e
MN
2771}
2772
55022530
CB
2773static inline void __auto_endmntent__(FILE **f)
2774{
2775 if (*f)
2776 endmntent(*f);
2777}
2778
2779#define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2780
48e5dcc8 2781static int setup_mount_fstab(struct lxc_rootfs *rootfs, const char *fstab,
8183f09e 2782 const char *lxc_name, const char *lxc_path)
e7938e9e 2783{
55022530 2784 __do_endmntent FILE *f = NULL;
e7938e9e
MN
2785 int ret;
2786
2787 if (!fstab)
2788 return 0;
2789
55022530
CB
2790 f = setmntent(fstab, "re");
2791 if (!f)
2792 return log_error_errno(-1, errno, "Failed to open \"%s\"", fstab);
e7938e9e 2793
a7c6e830 2794 ret = mount_file_entries(rootfs, f, lxc_name, lxc_path);
42dff448
CB
2795 if (ret < 0)
2796 ERROR("Failed to set up mount entries");
e7938e9e 2797
0ad19a3f 2798 return ret;
2799}
2800
1800f924
WB
2801/*
2802 * In order for nested containers to be able to mount /proc and /sys they need
2803 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2804 * (like lxcfs).
2805 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2806 * apparmor rule to deny access to them. This is mostly for convenience: The
2807 * container's root user can mount them anyway and thus has access to the two
2808 * file systems. But a non-root user in the container should not be allowed to
2809 * access them as a side effect without explicitly allowing it.
2810 */
2811static const char nesting_helpers[] =
dc691e34
CB
2812"proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2813"sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
1800f924
WB
2814
2815FILE *make_anonymous_mount_file(struct lxc_list *mount,
2816 bool include_nesting_helpers)
e7938e9e 2817{
f62cf1d4 2818 __do_close int fd = -EBADF;
4110345b 2819 FILE *f;
5ef5c9a3 2820 int ret;
e7938e9e 2821 char *mount_entry;
5ef5c9a3 2822 struct lxc_list *iterator;
5ef5c9a3 2823
0fd73091 2824 fd = memfd_create(".lxc_mount_file", MFD_CLOEXEC);
5ef5c9a3 2825 if (fd < 0) {
a324e7eb
CB
2826 char template[] = P_tmpdir "/.lxc_mount_file_XXXXXX";
2827
5ef5c9a3
CB
2828 if (errno != ENOSYS)
2829 return NULL;
a324e7eb
CB
2830
2831 fd = lxc_make_tmpfile(template, true);
55022530
CB
2832 if (fd < 0)
2833 return log_error_errno(NULL, errno, "Could not create temporary mount file");
0fd73091 2834
6bd04140 2835 TRACE("Created temporary mount file");
5ef5c9a3 2836 }
e7938e9e 2837
0fd73091
CB
2838 lxc_list_for_each (iterator, mount) {
2839 size_t len;
2840
e7938e9e 2841 mount_entry = iterator->elem;
0fd73091 2842 len = strlen(mount_entry);
5ef5c9a3 2843
489f39be 2844 ret = lxc_write_nointr(fd, mount_entry, len);
0fd73091 2845 if (ret != len)
79bcf5ee 2846 return NULL;
0fd73091 2847
489f39be 2848 ret = lxc_write_nointr(fd, "\n", 1);
0fd73091 2849 if (ret != 1)
79bcf5ee 2850 return NULL;
e7938e9e
MN
2851 }
2852
1800f924
WB
2853 if (include_nesting_helpers) {
2854 ret = lxc_write_nointr(fd, nesting_helpers,
6333c915
CB
2855 STRARRAYLEN(nesting_helpers));
2856 if (ret != STRARRAYLEN(nesting_helpers))
79bcf5ee 2857 return NULL;
1800f924
WB
2858 }
2859
0fd73091
CB
2860 ret = lseek(fd, 0, SEEK_SET);
2861 if (ret < 0)
79bcf5ee 2862 return NULL;
0fd73091 2863
4110345b
CB
2864 f = fdopen(fd, "re+");
2865 if (f)
2866 move_fd(fd); /* Transfer ownership of fd. */
2867 return f;
9fc7f8c0
TA
2868}
2869
06749971 2870static int setup_mount_entries(const struct lxc_conf *conf,
48e5dcc8
CB
2871 struct lxc_rootfs *rootfs, struct lxc_list *mount,
2872 const char *lxc_name, const char *lxc_path)
9fc7f8c0 2873{
c85ced65 2874 __do_fclose FILE *f = NULL;
9fc7f8c0 2875
1800f924 2876 f = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
19b5d755 2877 if (!f)
9fc7f8c0 2878 return -1;
e7938e9e 2879
a7c6e830 2880 return mount_file_entries(rootfs, f, lxc_name, lxc_path);
e7938e9e
MN
2881}
2882
1b82d721
CB
2883static int __lxc_idmapped_mounts_child(struct lxc_handler *handler, FILE *f)
2884{
2885 struct lxc_conf *conf = handler->conf;
2886 struct lxc_rootfs *rootfs = &conf->rootfs;
5a782dca 2887 int mnt_seq = 0;
1b82d721
CB
2888 int ret;
2889 char buf[PATH_MAX];
2890 struct mntent mntent;
2891
2892 while (getmntent_r(f, &mntent, buf, sizeof(buf))) {
2893 __do_close int fd_from = -EBADF, fd_to = -EBADF,
2894 fd_userns = -EBADF;
2895 __do_free char *__data = NULL;
5a782dca 2896 int cur_mnt_seq = -1;
1b82d721
CB
2897 struct lxc_mount_options opts = {};
2898 int dfd_from;
2899 const char *source_relative, *target_relative;
6b48a575 2900 struct lxc_mount_attr attr = {};
1b82d721
CB
2901
2902 ret = parse_lxc_mount_attrs(&opts, mntent.mnt_opts);
2903 if (ret < 0)
2904 return syserror("Failed to parse LXC specific mount options");
2905 __data = opts.data;
2906
2907 ret = parse_mount_attrs(&opts, mntent.mnt_opts);
2908 if (ret < 0)
2909 return syserror("Failed to parse mount options");
2910
2911 /* No idmapped mount entry so skip it. */
2912 if (is_empty_string(opts.userns_path))
2913 continue;
2914
2915 if (!can_use_bind_mounts())
2916 return syserror_set(-EINVAL, "Kernel does not support idmapped mounts");
2917
2918 if (!opts.bind)
2919 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2920
2921 /* We don't support new filesystem mounts yet. */
2922 if (!is_empty_string(mntent.mnt_type) &&
2923 !strequal(mntent.mnt_type, "none"))
2924 return syserror_set(-EINVAL, "Only bind mounts can currently be idmapped");
2925
2926 /* Someone specified additional mount options for a bind-mount. */
2927 if (!is_empty_string(opts.data))
2928 return syserror_set(-EINVAL, "Bind mounts don't support non-generic mount options");
2929
2930 /*
2931 * The source path is supposed to be taken relative to the
2932 * container's rootfs mount or - if the container does not have
2933 * a separate rootfs - to the host's /.
2934 */
2935 source_relative = deabs(mntent.mnt_fsname);
2936 if (opts.relative || !rootfs->path)
2937 dfd_from = rootfs->dfd_mnt;
2938 else
2939 dfd_from = rootfs->dfd_host;
2940 fd_from = open_tree(dfd_from, source_relative,
2941 OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC |
3eb23230 2942 (opts.bind_recursively ? AT_RECURSIVE : 0));
1b82d721
CB
2943 if (fd_from < 0)
2944 return syserror("Failed to create detached %smount of %d/%s",
3eb23230 2945 opts.bind_recursively ? "recursive " : "",
1b82d721
CB
2946 dfd_from, source_relative);
2947
2948 if (strequal(opts.userns_path, "container"))
2949 fd_userns = openat(dfd_from, "proc/self/ns/user", O_RDONLY | O_CLOEXEC);
2950 else
2951 fd_userns = open_at(-EBADF, opts.userns_path,
2952 PROTECT_OPEN_WITH_TRAILING_SYMLINKS, 0, 0);
2953 if (fd_userns < 0) {
2954 if (opts.optional) {
2955 TRACE("Skipping optional idmapped mount");
2956 continue;
2957 }
2958
2959 return syserror("Failed to open user namespace \"%s\" for detached %smount of %d/%s",
3eb23230 2960 opts.userns_path, opts.bind_recursively ? "recursive " : "",
1b82d721
CB
2961 dfd_from, source_relative);
2962 }
2963
2964 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
2965 fd_from, fd_userns,
2966 &opts, sizeof(opts));
2967 if (ret <= 0) {
2968 if (opts.optional) {
2969 TRACE("Skipping optional idmapped mount");
2970 continue;
2971 }
2972
2973 return syserror("Failed to send file descriptor %d for detached %smount of %d/%s and file descriptor %d of user namespace \"%s\" to parent",
3eb23230 2974 fd_from, opts.bind_recursively ? "recursive " : "",
1b82d721
CB
2975 dfd_from, source_relative, fd_userns,
2976 opts.userns_path);
2977 }
2978
5a782dca
CB
2979 ret = lxc_abstract_unix_rcv_credential(handler->data_sock[0],
2980 &cur_mnt_seq,
2981 sizeof(cur_mnt_seq));
1b82d721
CB
2982 if (ret <= 0) {
2983 if (opts.optional) {
2984 TRACE("Skipping optional idmapped mount");
2985 continue;
2986 }
2987
2988 return syserror("Failed to receive notification that parent idmapped detached %smount %d/%s to user namespace %d",
3eb23230 2989 opts.bind_recursively ? "recursive " : "",
1b82d721
CB
2990 dfd_from, source_relative, fd_userns);
2991 }
2992
5a782dca
CB
2993 if (mnt_seq != cur_mnt_seq)
2994 return syserror("Expected mount sequence number and mount sequence number from parent mismatch: %d != %d",
2995 mnt_seq, cur_mnt_seq);
2996 mnt_seq++;
2997
6b48a575
CB
2998 /* Set regular mount options. */
2999 attr = opts.attr;
3000 attr.propagation = 0;
3001 ret = mount_setattr(fd_from,
3002 "",
3003 AT_EMPTY_PATH |
3eb23230 3004 (opts.bind_recursively ? AT_RECURSIVE : 0),
6b48a575
CB
3005 &attr,
3006 sizeof(attr));
1b82d721
CB
3007 if (ret < 0) {
3008 if (opts.optional) {
3009 TRACE("Skipping optional idmapped mount");
3010 continue;
3011 }
3012
6b48a575 3013 return syserror("Failed to set %smount options on detached %d/%s",
3eb23230 3014 opts.bind_recursively ? "recursive " : "",
6b48a575
CB
3015 dfd_from, source_relative);
3016 }
3017
3018 /* Set propagation mount options. */
3019 if (opts.attr.propagation) {
3020 attr = (struct lxc_mount_attr) {
3021 attr.propagation = opts.attr.propagation,
3022 };
3023
3024 ret = mount_setattr(fd_from,
3025 "",
3026 AT_EMPTY_PATH |
3027 (opts.propagate_recursively ? AT_RECURSIVE : 0),
3028 &attr,
3029 sizeof(attr));
3030 if (ret < 0) {
3031 if (opts.optional) {
3032 TRACE("Skipping optional idmapped mount");
3033 continue;
3034 }
3035
3036 return syserror("Failed to set %spropagation mount options on detached %d/%s",
3037 opts.bind_recursively ? "recursive " : "",
3038 dfd_from, source_relative);
3039 }
1b82d721
CB
3040 }
3041
6b48a575 3042
1b82d721
CB
3043 /*
3044 * In contrast to the legacy mount codepath we will simplify
3045 * our lifes and just always treat the target mountpoint to be
3046 * relative to the container's rootfs mountpoint or - if the
3047 * container does not have a separate rootfs - to the host's /.
3048 */
3049
3050 target_relative = deabs(mntent.mnt_dir);
3051 if (rootfs->path)
3052 dfd_from = rootfs->dfd_mnt;
3053 else
3054 dfd_from = rootfs->dfd_host;
3055 fd_to = open_at(dfd_from, target_relative, PROTECT_OPATH_FILE, PROTECT_LOOKUP_BENEATH_WITH_SYMLINKS, 0);
3056 if (fd_to < 0) {
3057 if (opts.optional) {
3058 TRACE("Skipping optional idmapped mount");
3059 continue;
3060 }
3061
3062 return syserror("Failed to open target mountpoint %d/%s for detached idmapped %smount %d:%d/%s",
3063 dfd_from, target_relative,
3eb23230 3064 opts.bind_recursively ? "recursive " : "",
1b82d721
CB
3065 fd_userns, dfd_from, source_relative);
3066 }
3067
3068 ret = move_detached_mount(fd_from, fd_to, "", 0, 0);
3069 if (ret) {
3070 if (opts.optional) {
3071 TRACE("Skipping optional idmapped mount");
3072 continue;
3073 }
3074
3075 return syserror("Failed to attach detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3eb23230 3076 opts.bind_recursively ? "recursive " : "",
1b82d721
CB
3077 fd_userns, dfd_from, source_relative, dfd_from, target_relative);
3078 }
3079
3080 TRACE("Attached detached idmapped %smount %d:%d/%s to target mountpoint %d/%s",
3eb23230 3081 opts.bind_recursively ? "recursive " : "", fd_userns, dfd_from,
1b82d721
CB
3082 source_relative, dfd_from, target_relative);
3083 }
3084
3085 if (!feof(f) || ferror(f))
3086 return syserror_set(-EINVAL, "Failed to parse mount entries");
3087
3088 return 0;
3089}
3090
3091static int lxc_idmapped_mounts_child(struct lxc_handler *handler)
3092{
3093 __do_fclose FILE *f_entries = NULL;
3094 int fret = -1;
3095 struct lxc_conf *conf = handler->conf;
3096 const char *fstab = conf->fstab;
3097 struct lxc_list *mount = &conf->mount_list;
3098 int ret;
3099
3100 f_entries = make_anonymous_mount_file(mount, conf->lsm_aa_allow_nesting);
3101 if (!f_entries) {
3102 SYSERROR("Failed to create anonymous mount file");
3103 goto out;
3104 }
3105
3106 ret = __lxc_idmapped_mounts_child(handler, f_entries);
3107 if (ret) {
3108 SYSERROR("Failed to setup idmapped mount entries");
3109 goto out;
3110 }
3111
3112 TRACE("Finished setting up idmapped mounts");
3113
3114 if (fstab) {
3115 __do_endmntent FILE *f_fstab = NULL;
3116
3117 f_fstab = setmntent(fstab, "re");
3118 if (!f_fstab) {
3119 SYSERROR("Failed to open fstab format file \"%s\"", fstab);
3120 goto out;
3121 }
3122
3123 ret = __lxc_idmapped_mounts_child(handler, f_fstab);
3124 if (ret) {
3125 SYSERROR("Failed to setup idmapped mount entries specified in fstab");
3126 goto out;
3127 }
3128
3129 TRACE("Finished setting up idmapped mounts specified in fstab");
3130 }
3131
3132 fret = 0;
3133
3134out:
3135 ret = lxc_abstract_unix_send_credential(handler->data_sock[0], NULL, 0);
3136 if (ret < 0)
caaa223b 3137 return syserror("Failed to inform parent that we are done setting up mounts");
1b82d721
CB
3138
3139 return fret;
3140}
3141
bab88e68
CS
3142static int parse_cap(const char *cap)
3143{
84760c11 3144 size_t i;
3145 int capid = -1;
0fd73091
CB
3146 size_t end = sizeof(caps_opt) / sizeof(caps_opt[0]);
3147 char *ptr = NULL;
bab88e68 3148
71528742 3149 if (strequal(cap, "none"))
7035407c
DE
3150 return -2;
3151
8560cd36 3152 for (i = 0; i < end; i++) {
71528742 3153 if (!strequal(cap, caps_opt[i].name))
bab88e68
CS
3154 continue;
3155
3156 capid = caps_opt[i].value;
3157 break;
3158 }
3159
3160 if (capid < 0) {
0fd73091
CB
3161 /* Try to see if it's numeric, so the user may specify
3162 * capabilities that the running kernel knows about but we
3163 * don't
3164 */
bab88e68
CS
3165 errno = 0;
3166 capid = strtol(cap, &ptr, 10);
3167 if (!ptr || *ptr != '\0' || errno != 0)
3168 /* not a valid number */
3169 capid = -1;
3170 else if (capid > lxc_caps_last_cap())
3171 /* we have a number but it's not a valid
3172 * capability */
3173 capid = -1;
3174 }
3175
3176 return capid;
3177}
3178
0769b82a
CS
3179int in_caplist(int cap, struct lxc_list *caps)
3180{
0769b82a 3181 int capid;
0fd73091 3182 struct lxc_list *iterator;
0769b82a 3183
0fd73091 3184 lxc_list_for_each (iterator, caps) {
0769b82a
CS
3185 capid = parse_cap(iterator->elem);
3186 if (capid == cap)
3187 return 1;
3188 }
3189
3190 return 0;
3191}
3192
81810dd1
DL
3193static int setup_caps(struct lxc_list *caps)
3194{
bab88e68 3195 int capid;
0fd73091
CB
3196 char *drop_entry;
3197 struct lxc_list *iterator;
81810dd1 3198
0fd73091
CB
3199 lxc_list_for_each (iterator, caps) {
3200 int ret;
81810dd1
DL
3201
3202 drop_entry = iterator->elem;
3203
bab88e68 3204 capid = parse_cap(drop_entry);
55022530
CB
3205 if (capid < 0)
3206 return log_error(-1, "unknown capability %s", drop_entry);
81810dd1 3207
b81689a1
CB
3208 ret = prctl(PR_CAPBSET_DROP, prctl_arg(capid), prctl_arg(0),
3209 prctl_arg(0), prctl_arg(0));
55022530
CB
3210 if (ret < 0)
3211 return log_error_errno(-1, errno, "Failed to remove %s capability", drop_entry);
0fd73091 3212 DEBUG("Dropped %s (%d) capability", drop_entry, capid);
81810dd1
DL
3213 }
3214
0fd73091 3215 DEBUG("Capabilities have been setup");
1fb86a7c
SH
3216 return 0;
3217}
3218
3219static int dropcaps_except(struct lxc_list *caps)
3220{
2f443e88 3221 __do_free int *caplist = NULL;
0fd73091 3222 int i, capid, numcaps;
1fb86a7c 3223 char *keep_entry;
0fd73091 3224 struct lxc_list *iterator;
1fb86a7c 3225
0fd73091 3226 numcaps = lxc_caps_last_cap() + 1;
2caf9a97
SH
3227 if (numcaps <= 0 || numcaps > 200)
3228 return -1;
0fd73091 3229 TRACE("Found %d capabilities", numcaps);
2caf9a97 3230
1a0e70ac 3231 /* caplist[i] is 1 if we keep capability i */
2f443e88 3232 caplist = must_realloc(NULL, numcaps * sizeof(int));
1fb86a7c
SH
3233 memset(caplist, 0, numcaps * sizeof(int));
3234
0fd73091 3235 lxc_list_for_each (iterator, caps) {
1fb86a7c
SH
3236 keep_entry = iterator->elem;
3237
bab88e68 3238 capid = parse_cap(keep_entry);
7035407c
DE
3239 if (capid == -2)
3240 continue;
3241
55022530
CB
3242 if (capid < 0)
3243 return log_error(-1, "Unknown capability %s", keep_entry);
1fb86a7c 3244
0fd73091 3245 DEBUG("Keep capability %s (%d)", keep_entry, capid);
1fb86a7c
SH
3246 caplist[capid] = 1;
3247 }
0fd73091
CB
3248
3249 for (i = 0; i < numcaps; i++) {
3250 int ret;
3251
1fb86a7c
SH
3252 if (caplist[i])
3253 continue;
0fd73091 3254
b81689a1
CB
3255 ret = prctl(PR_CAPBSET_DROP, prctl_arg(i), prctl_arg(0),
3256 prctl_arg(0), prctl_arg(0));
55022530
CB
3257 if (ret < 0)
3258 return log_error_errno(-1, errno, "Failed to remove capability %d", i);
1fb86a7c
SH
3259 }
3260
0fd73091 3261 DEBUG("Capabilities have been setup");
81810dd1
DL
3262 return 0;
3263}
3264
0fd73091
CB
3265static int parse_resource(const char *res)
3266{
3267 int ret;
c6d09e15
WB
3268 size_t i;
3269 int resid = -1;
3270
0fd73091 3271 for (i = 0; i < sizeof(limit_opt) / sizeof(limit_opt[0]); ++i)
71528742 3272 if (strequal(res, limit_opt[i].name))
c6d09e15 3273 return limit_opt[i].value;
c6d09e15 3274
0fd73091 3275 /* Try to see if it's numeric, so the user may specify
c6d09e15 3276 * resources that the running kernel knows about but
0fd73091
CB
3277 * we don't.
3278 */
3279 ret = lxc_safe_int(res, &resid);
3280 if (ret < 0)
3281 return -1;
3282
3283 return resid;
c6d09e15
WB
3284}
3285
223797c3 3286int setup_resource_limits(struct lxc_conf *conf, pid_t pid)
0fd73091
CB
3287{
3288 int resid;
c6d09e15 3289 struct lxc_limit *lim;
c6d09e15 3290
223797c3
CB
3291 if (list_empty(&conf->limits))
3292 return 0;
c6d09e15 3293
223797c3 3294 list_for_each_entry(lim, &conf->limits, head) {
c6d09e15 3295 resid = parse_resource(lim->resource);
55022530
CB
3296 if (resid < 0)
3297 return log_error(-1, "Unknown resource %s", lim->resource);
c6d09e15 3298
f48b5fd8 3299#if HAVE_PRLIMIT || HAVE_PRLIMIT64
55022530
CB
3300 if (prlimit(pid, resid, &lim->limit, NULL) != 0)
3301 return log_error_errno(-1, errno, "Failed to set limit %s", lim->resource);
2de12765
CB
3302
3303 TRACE("Setup \"%s\" limit", lim->resource);
f48b5fd8 3304#else
55022530 3305 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim->resource);
f48b5fd8 3306#endif
c6d09e15 3307 }
0fd73091 3308
223797c3 3309 TRACE("Setup resource limits");
c6d09e15
WB
3310 return 0;
3311}
3312
ba9f9347 3313int setup_sysctl_parameters(struct lxc_conf *conf)
7edd0540 3314{
e6f76452 3315 __do_free char *tmp = NULL;
0fd73091 3316 int ret = 0;
6b5a54cd 3317 char filename[PATH_MAX] = {0};
ba9f9347 3318 struct lxc_sysctl *sysctl, *nsysctl;
7edd0540 3319
ba9f9347
CB
3320 if (!list_empty(&conf->sysctls))
3321 return 0;
3322
3323 list_for_each_entry_safe(sysctl, nsysctl, &conf->sysctls, head) {
3324 tmp = lxc_string_replace(".", "/", sysctl->key);
55022530 3325 if (!tmp)
ba9f9347 3326 return log_error(-1, "Failed to replace key %s", sysctl->key);
7edd0540 3327
9bcde680
CB
3328 ret = strnprintf(filename, sizeof(filename), "/proc/sys/%s", tmp);
3329 if (ret < 0)
55022530 3330 return log_error(-1, "Error setting up sysctl parameters path");
7edd0540 3331
ba9f9347
CB
3332 ret = lxc_write_to_file(filename, sysctl->value,
3333 strlen(sysctl->value), false, 0666);
55022530
CB
3334 if (ret < 0)
3335 return log_error_errno(-1, errno, "Failed to setup sysctl parameters %s to %s",
ba9f9347 3336 sysctl->key, sysctl->value);
7edd0540 3337 }
0fd73091 3338
7edd0540
L
3339 return 0;
3340}
3341
91d04bf9 3342int setup_proc_filesystem(struct lxc_conf *conf, pid_t pid)
61d7a733 3343{
0c669152 3344 __do_free char *tmp = NULL;
0fd73091 3345 int ret = 0;
6b5a54cd 3346 char filename[PATH_MAX] = {0};
91d04bf9
CB
3347 struct lxc_proc *proc;
3348
3349 if (!list_empty(&conf->procs))
3350 return 0;
61d7a733 3351
91d04bf9
CB
3352 list_for_each_entry(proc, &conf->procs, head) {
3353 tmp = lxc_string_replace(".", "/", proc->filename);
55022530 3354 if (!tmp)
91d04bf9 3355 return log_error(-1, "Failed to replace key %s", proc->filename);
61d7a733 3356
9bcde680
CB
3357 ret = strnprintf(filename, sizeof(filename), "/proc/%d/%s", pid, tmp);
3358 if (ret < 0)
55022530 3359 return log_error(-1, "Error setting up proc filesystem path");
61d7a733 3360
91d04bf9
CB
3361 ret = lxc_write_to_file(filename, proc->value,
3362 strlen(proc->value), false, 0666);
55022530 3363 if (ret < 0)
91d04bf9
CB
3364 return log_error_errno(-1, errno, "Failed to setup proc filesystem %s to %s",
3365 proc->filename, proc->value);
61d7a733 3366 }
0fd73091 3367
91d04bf9 3368 TRACE("Setup /proc/%d settings", pid);
61d7a733
YT
3369 return 0;
3370}
3371
ae9242c8
SH
3372static char *default_rootfs_mount = LXCROOTFSMOUNT;
3373
7b379ab3 3374struct lxc_conf *lxc_conf_init(void)
089cd8b8 3375{
26ddeedd 3376 int i;
0fd73091 3377 struct lxc_conf *new;
7b379ab3 3378
b8e43ef0 3379 new = zalloc(sizeof(*new));
0fd73091 3380 if (!new)
7b379ab3 3381 return NULL;
7b379ab3 3382
4b73005c 3383 new->loglevel = LXC_LOG_LEVEL_NOTSET;
9c601e1f 3384 new->personality = LXC_ARCH_UNCHANGED;
124fa0a8 3385 new->autodev = 1;
3a784510 3386 new->console.buffer_size = 0;
596a818d
DE
3387 new->console.log_path = NULL;
3388 new->console.log_fd = -1;
861813e5 3389 new->console.log_size = 0;
28a4b0e5 3390 new->console.path = NULL;
63376d7d 3391 new->console.peer = -1;
fb87aa6a 3392 new->console.proxy.busy = -1;
36a94ce8 3393 new->console.proxy.ptx = -1;
41808e20 3394 new->console.proxy.pty = -1;
f3dff080
CB
3395 new->console.ptx = -EBADF;
3396 new->console.pty = -EBADF;
d926c261 3397 new->console.pty_nr = -1;
63376d7d 3398 new->console.name[0] = '\0';
7294a26d 3399 new->devpts_fd = -EBADF;
732375f5 3400 memset(&new->console.ringbuf, 0, sizeof(struct lxc_ringbuf));
d2e30e99 3401 new->maincmd_fd = -1;
258f8051 3402 new->monitor_signal_pdeath = SIGKILL;
76a26f55 3403 new->nbd_idx = -1;
54c30e29 3404 new->rootfs.mount = strdup(default_rootfs_mount);
53f3f048 3405 if (!new->rootfs.mount) {
53f3f048
SH
3406 free(new);
3407 return NULL;
3408 }
6e54330c 3409 new->rootfs.managed = true;
ea57e424 3410 new->rootfs.dfd_mnt = -EBADF;
a5a08920 3411 new->rootfs.dfd_dev = -EBADF;
ea11a215 3412 new->rootfs.dfd_host = -EBADF;
79ff643d 3413 new->rootfs.fd_path_pin = -EBADF;
4b875ef9 3414 new->rootfs.dfd_idmapped = -EBADF;
858377e4 3415 new->logfd = -1;
c9dbb8ed
CB
3416 INIT_LIST_HEAD(&new->cgroup);
3417 INIT_LIST_HEAD(&new->cgroup2);
a134099d
CB
3418 /* Block ("allowlist") all devices by default. */
3419 new->bpf_devices.list_type = LXC_BPF_DEVICE_CGROUP_ALLOWLIST;
93de768e 3420 INIT_LIST_HEAD(&(new->bpf_devices).devices);
7b379ab3 3421 lxc_list_init(&new->mount_list);
81810dd1 3422 lxc_list_init(&new->caps);
1fb86a7c 3423 lxc_list_init(&new->keepcaps);
0589d744 3424 INIT_LIST_HEAD(&new->id_map);
46ad64ab
CB
3425 new->root_nsuid_map = NULL;
3426 new->root_nsgid_map = NULL;
f979ac15 3427 lxc_list_init(&new->includes);
4184c3e1 3428 lxc_list_init(&new->aliens);
7c661726 3429 lxc_list_init(&new->environment);
223797c3 3430 INIT_LIST_HEAD(&new->limits);
ba9f9347 3431 INIT_LIST_HEAD(&new->sysctls);
91d04bf9 3432 INIT_LIST_HEAD(&new->procs);
44ae0fb6 3433 new->hooks_version = 0;
28d9e29e 3434 for (i = 0; i < NUM_LXC_HOOKS; i++)
26ddeedd 3435 lxc_list_init(&new->hooks[i]);
ee1e7aa0 3436 lxc_list_init(&new->groups);
d2e75eba 3437 INIT_LIST_HEAD(&new->state_clients);
fe4de9a6 3438 new->lsm_aa_profile = NULL;
1800f924 3439 lxc_list_init(&new->lsm_aa_raw);
fe4de9a6 3440 new->lsm_se_context = NULL;
4fef78bc 3441 new->lsm_se_keyring_context = NULL;
8f818a84 3442 new->keyring_disable_session = false;
952b5031 3443 new->transient_procfs_mnt = false;
7a41e857
LT
3444 new->shmount.path_host = NULL;
3445 new->shmount.path_cont = NULL;
7b379ab3 3446
72bb04e4
PT
3447 /* if running in a new user namespace, init and COMMAND
3448 * default to running as UID/GID 0 when using lxc-execute */
3449 new->init_uid = 0;
3450 new->init_gid = 0;
c71f64cb 3451 memset(&new->init_groups, 0, sizeof(lxc_groups_t));
43654d34 3452 memset(&new->cgroup_meta, 0, sizeof(struct lxc_cgroup));
b074bbf1 3453 memset(&new->ns_share, 0, sizeof(char *) * LXC_NS_MAX);
70fd7fc9 3454 memset(&new->timens, 0, sizeof(struct timens_offsets));
c3e3c21a 3455 seccomp_conf_init(new);
72bb04e4 3456
87d0990c
CB
3457 INIT_LIST_HEAD(&new->netdevs);
3458
7b379ab3 3459 return new;
089cd8b8
DL
3460}
3461
344c9d81 3462int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf,
a19b974f 3463 size_t buf_size)
f6d3e3e4 3464{
f62cf1d4 3465 __do_close int fd = -EBADF;
76bcd422 3466 int ret;
6b5a54cd 3467 char path[PATH_MAX];
f6d3e3e4 3468
a19b974f 3469 if (geteuid() != 0 && idtype == ID_TYPE_GID) {
f62cf1d4 3470 __do_close int setgroups_fd = -EBADF;
a19b974f 3471
9bcde680
CB
3472 ret = strnprintf(path, sizeof(path), "/proc/%d/setgroups", pid);
3473 if (ret < 0)
a19b974f 3474 return -E2BIG;
a19b974f 3475
76bcd422 3476 setgroups_fd = open(path, O_WRONLY);
55022530
CB
3477 if (setgroups_fd < 0 && errno != ENOENT)
3478 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
a19b974f 3479
76bcd422
CB
3480 if (setgroups_fd >= 0) {
3481 ret = lxc_write_nointr(setgroups_fd, "deny\n",
3482 STRLITERALLEN("deny\n"));
55022530
CB
3483 if (ret != STRLITERALLEN("deny\n"))
3484 return log_error_errno(-1, errno, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid);
395b1a3e 3485 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid);
a19b974f 3486 }
a19b974f
CB
3487 }
3488
9bcde680 3489 ret = strnprintf(path, sizeof(path), "/proc/%d/%cid_map", pid,
29053180 3490 idtype == ID_TYPE_UID ? 'u' : 'g');
9bcde680 3491 if (ret < 0)
f6d3e3e4 3492 return -E2BIG;
29053180 3493
55022530
CB
3494 fd = open(path, O_WRONLY | O_CLOEXEC);
3495 if (fd < 0)
3496 return log_error_errno(-1, errno, "Failed to open \"%s\"", path);
29053180 3497
29053180 3498 ret = lxc_write_nointr(fd, buf, buf_size);
55022530
CB
3499 if (ret != buf_size)
3500 return log_error_errno(-1, errno, "Failed to write %cid mapping to \"%s\"",
3501 idtype == ID_TYPE_UID ? 'u' : 'g', path);
29053180
CB
3502
3503 return 0;
f6d3e3e4
SH
3504}
3505
6e50e704
CB
3506/* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3507 *
3508 * @return 1 if functional binary was found
3509 * @return 0 if binary exists but is lacking privilege
3510 * @return -ENOENT if binary does not exist
3511 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
6e50e704 3512 */
df6a2945
CB
3513static int idmaptool_on_path_and_privileged(const char *binary, cap_value_t cap)
3514{
48411df2 3515 __do_free char *path = NULL;
df6a2945
CB
3516 int ret;
3517 struct stat st;
df6a2945 3518
6e50e704 3519 if (cap != CAP_SETUID && cap != CAP_SETGID)
83cb7362 3520 return ret_errno(EINVAL);
6e50e704 3521
df6a2945
CB
3522 path = on_path(binary, NULL);
3523 if (!path)
83cb7362 3524 return ret_errno(ENOENT);
df6a2945
CB
3525
3526 ret = stat(path, &st);
3275932b 3527 if (ret < 0)
83cb7362 3528 return -errno;
df6a2945
CB
3529
3530 /* Check if the binary is setuid. */
55022530
CB
3531 if (st.st_mode & S_ISUID)
3532 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path);
df6a2945 3533
0fd73091 3534#if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
df6a2945
CB
3535 /* Check if it has the CAP_SETUID capability. */
3536 if ((cap & CAP_SETUID) &&
3537 lxc_file_cap_is_set(path, CAP_SETUID, CAP_EFFECTIVE) &&
55022530
CB
3538 lxc_file_cap_is_set(path, CAP_SETUID, CAP_PERMITTED))
3539 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
df6a2945
CB
3540
3541 /* Check if it has the CAP_SETGID capability. */
3542 if ((cap & CAP_SETGID) &&
3543 lxc_file_cap_is_set(path, CAP_SETGID, CAP_EFFECTIVE) &&
55022530
CB
3544 lxc_file_cap_is_set(path, CAP_SETGID, CAP_PERMITTED))
3545 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path);
a864a2e1
CB
3546
3547 return 0;
0fd73091 3548#else
83cb7362
CB
3549 /*
3550 * If we cannot check for file capabilities we need to give the benefit
69924fff
CB
3551 * of the doubt. Otherwise we might fail even though all the necessary
3552 * file capabilities are set.
3553 */
55022530 3554 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
3275932b 3555 return 1;
a864a2e1 3556#endif
df6a2945
CB
3557}
3558
59eac805 3559static int lxc_map_ids_exec_wrapper(void *args)
986ef930
CB
3560{
3561 execl("/bin/sh", "sh", "-c", (char *)args, (char *)NULL);
3562 return -1;
3563}
3564
0589d744 3565static struct id_map *find_mapped_hostid_entry(const struct list_head *idmap,
86c78011
CB
3566 unsigned id, enum idtype idtype);
3567
0589d744 3568int lxc_map_ids(struct list_head *idmap, pid_t pid)
f6d3e3e4 3569{
0589d744 3570 int hostuid, hostgid, fill, left;
986ef930 3571 char u_or_g;
4bc3b759 3572 char *pos;
6b5a54cd 3573 char cmd_output[PATH_MAX];
0fd73091 3574 struct id_map *map;
0fd73091 3575 enum idtype type;
0fd73091 3576 int ret = 0, gidmap = 0, uidmap = 0;
c6ba8981
CB
3577 char mapbuf[STRLITERALLEN("new@idmap") + STRLITERALLEN(" ") +
3578 INTTYPE_TO_STRLEN(pid_t) + STRLITERALLEN(" ") +
3579 LXC_IDMAPLEN] = {0};
86c78011 3580 bool had_entry = false, maps_host_root = false, use_shadow = false;
c724025c
JC
3581
3582 hostuid = geteuid();
3583 hostgid = getegid();
df6a2945 3584
86c78011
CB
3585 /*
3586 * Check whether caller wants to map host root.
3587 * Due to a security fix newer kernels require CAP_SETFCAP when mapping
3588 * host root into the child userns as you would be able to write fscaps
3589 * that would be valid in the ancestor userns. Mapping host root should
3590 * rarely be the case but LXC is being clever in a bunch of cases.
3591 */
3592 if (find_mapped_hostid_entry(idmap, 0, ID_TYPE_UID))
3593 maps_host_root = true;
3594
df6a2945
CB
3595 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3596 * ranges, then insist that root also reserve ranges in subuid. This
22038de5
SH
3597 * will protected it by preventing another user from being handed the
3598 * range by shadow.
3599 */
df6a2945 3600 uidmap = idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID);
6e50e704
CB
3601 if (uidmap == -ENOENT)
3602 WARN("newuidmap binary is missing");
3603 else if (!uidmap)
3604 WARN("newuidmap is lacking necessary privileges");
3605
df6a2945 3606 gidmap = idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID);
6e50e704
CB
3607 if (gidmap == -ENOENT)
3608 WARN("newgidmap binary is missing");
3609 else if (!gidmap)
3610 WARN("newgidmap is lacking necessary privileges");
3611
86c78011
CB
3612 if (maps_host_root) {
3613 INFO("Caller maps host root. Writing mapping directly");
3614 } else if (uidmap > 0 && gidmap > 0) {
0fd73091 3615 DEBUG("Functional newuidmap and newgidmap binary found");
4bc3b759 3616 use_shadow = true;
df6a2945 3617 } else {
99d43365
CB
3618 /* In case unprivileged users run application containers via
3619 * execute() or a start*() there are valid cases where they may
3620 * only want to map their own {g,u}id. Let's not block them from
3621 * doing so by requiring geteuid() == 0.
3622 */
3623 DEBUG("No newuidmap and newgidmap binary found. Trying to "
c724025c
JC
3624 "write directly with euid %d", hostuid);
3625 }
3626
3627 /* Check if we really need to use newuidmap and newgidmap.
f48e8071 3628 * If the user is only remapping their own {g,u}id, we don't need it.
c724025c 3629 */
0589d744 3630 if (use_shadow && list_len(idmap) == 2) {
c724025c 3631 use_shadow = false;
0589d744 3632 list_for_each_entry(map, idmap, head) {
c724025c
JC
3633 if (map->idtype == ID_TYPE_UID && map->range == 1 &&
3634 map->nsid == hostuid && map->hostid == hostuid)
3635 continue;
3636 if (map->idtype == ID_TYPE_GID && map->range == 1 &&
3637 map->nsid == hostgid && map->hostid == hostgid)
3638 continue;
3639 use_shadow = true;
3640 break;
3641 }
0e6e3a41 3642 }
251d0d2a 3643
986ef930
CB
3644 for (type = ID_TYPE_UID, u_or_g = 'u'; type <= ID_TYPE_GID;
3645 type++, u_or_g = 'g') {
3646 pos = mapbuf;
3647
0e6e3a41 3648 if (use_shadow)
986ef930 3649 pos += sprintf(mapbuf, "new%cidmap %d", u_or_g, pid);
4f7521b4 3650
0589d744 3651 list_for_each_entry(map, idmap, head) {
cf3ef16d
SH
3652 if (map->idtype != type)
3653 continue;
3654
4bc3b759
CB
3655 had_entry = true;
3656
986ef930 3657 left = LXC_IDMAPLEN - (pos - mapbuf);
9bcde680 3658 fill = strnprintf(pos, left, "%s%lu %lu %lu%s",
4bc3b759
CB
3659 use_shadow ? " " : "", map->nsid,
3660 map->hostid, map->range,
0e6e3a41 3661 use_shadow ? "" : "\n");
55022530
CB
3662 /*
3663 * The kernel only takes <= 4k for writes to
3664 * /proc/<pid>/{g,u}id_map
3665 */
9bcde680 3666 if (fill <= 0)
55022530 3667 return log_error_errno(-1, errno, "Too many %cid mappings defined", u_or_g);
4bc3b759 3668
cf3ef16d 3669 pos += fill;
251d0d2a 3670 }
cf3ef16d 3671 if (!had_entry)
4f7521b4 3672 continue;
cf3ef16d 3673
d85813cd 3674 /* Try to catch the output of new{g,u}idmap to make debugging
986ef930
CB
3675 * easier.
3676 */
3677 if (use_shadow) {
3678 ret = run_command(cmd_output, sizeof(cmd_output),
3679 lxc_map_ids_exec_wrapper,
3680 (void *)mapbuf);
55022530
CB
3681 if (ret < 0)
3682 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g, cmd_output, mapbuf);
54fbbeb5 3683 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g, mapbuf);
d1838f34 3684 } else {
986ef930 3685 ret = write_id_mapping(type, pid, mapbuf, pos - mapbuf);
55022530
CB
3686 if (ret < 0)
3687 return log_error(-1, "Failed to write mapping: %s", mapbuf);
54fbbeb5 3688 TRACE("Wrote mapping \"%s\"", mapbuf);
d1838f34 3689 }
986ef930
CB
3690
3691 memset(mapbuf, 0, sizeof(mapbuf));
f6d3e3e4 3692 }
251d0d2a 3693
986ef930 3694 return 0;
f6d3e3e4
SH
3695}
3696
234998b4
CB
3697/*
3698 * Return the host uid/gid to which the container root is mapped in val.
0b3a6504 3699 * Return true if id was found, false otherwise.
cf3ef16d 3700 */
234998b4 3701static id_t get_mapped_rootid(const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3702{
4160c3a0 3703 unsigned nsid;
0fd73091 3704 struct id_map *map;
4160c3a0
CB
3705
3706 if (idtype == ID_TYPE_UID)
3707 nsid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
3708 else
3709 nsid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
cf3ef16d 3710
0589d744 3711 list_for_each_entry (map, &conf->id_map, head) {
7b50c609 3712 if (map->idtype != idtype)
cf3ef16d 3713 continue;
4160c3a0 3714 if (map->nsid != nsid)
cf3ef16d 3715 continue;
234998b4 3716 return map->hostid;
cf3ef16d 3717 }
4160c3a0 3718
234998b4
CB
3719 if (idtype == ID_TYPE_UID)
3720 return LXC_INVALID_UID;
3721
3722 return LXC_INVALID_GID;
cf3ef16d
SH
3723}
3724
facdf925 3725int mapped_hostid(unsigned id, const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3726{
cf3ef16d 3727 struct id_map *map;
0fd73091 3728
0589d744 3729 list_for_each_entry(map, &conf->id_map, head) {
2133f58c 3730 if (map->idtype != idtype)
cf3ef16d 3731 continue;
0fd73091 3732
cf3ef16d 3733 if (id >= map->hostid && id < map->hostid + map->range)
57d116ab 3734 return (id - map->hostid) + map->nsid;
cf3ef16d 3735 }
0fd73091 3736
57d116ab 3737 return -1;
cf3ef16d
SH
3738}
3739
7581a82f 3740int find_unmapped_nsid(const struct lxc_conf *conf, enum idtype idtype)
cf3ef16d 3741{
cf3ef16d 3742 struct id_map *map;
2133f58c 3743 unsigned int freeid = 0;
0fd73091 3744
cf3ef16d 3745again:
0589d744 3746 list_for_each_entry(map, &conf->id_map, head) {
2133f58c 3747 if (map->idtype != idtype)
cf3ef16d 3748 continue;
0fd73091 3749
cf3ef16d
SH
3750 if (freeid >= map->nsid && freeid < map->nsid + map->range) {
3751 freeid = map->nsid + map->range;
3752 goto again;
3753 }
3754 }
0fd73091 3755
cf3ef16d
SH
3756 return freeid;
3757}
3758
e1b9d6af
CB
3759/*
3760 * Mount a proc under @rootfs if proc self points to a pid other than
3761 * my own. This is needed to have a known-good proc mount for setting
3762 * up LSMs both at container startup and attach.
3763 *
e1b9d6af
CB
3764 * NOTE: not to be called from inside the container namespace!
3765 */
952b5031 3766static int lxc_transient_proc(struct lxc_rootfs *rootfs)
e1b9d6af 3767{
952b5031
CB
3768 __do_close int fd_proc = -EBADF;
3769 int link_to_pid, link_len, pid_self, ret;
3770 char link[INTTYPE_TO_STRLEN(pid_t) + 1];
e1b9d6af 3771
ea57e424 3772 link_len = readlinkat(rootfs->dfd_mnt, "proc/self", link, sizeof(link));
952b5031 3773 if (link_len < 0) {
ea57e424 3774 ret = mkdirat(rootfs->dfd_mnt, "proc", 0000);
952b5031 3775 if (ret < 0 && errno != EEXIST)
ea57e424 3776 return log_error_errno(-errno, errno, "Failed to create %d(proc)", rootfs->dfd_mnt);
e1b9d6af 3777
952b5031
CB
3778 goto domount;
3779 } else if (link_len >= sizeof(link)) {
3780 return log_error_errno(-EIO, EIO, "Truncated link target");
e1b9d6af 3781 }
952b5031 3782 link[link_len] = '\0';
e1b9d6af 3783
952b5031
CB
3784 pid_self = lxc_raw_getpid();
3785 INFO("Caller's PID is %d; /proc/self points to %s", pid_self, link);
e1b9d6af 3786
952b5031
CB
3787 ret = lxc_safe_int(link, &link_to_pid);
3788 if (ret)
3789 return log_error_errno(-ret, ret, "Failed to parse %s", link);
e1b9d6af 3790
952b5031
CB
3791 /* Correct procfs is already mounted. */
3792 if (link_to_pid == pid_self)
3793 return log_trace(0, "Correct procfs instance mounted");
e1b9d6af 3794
ea57e424 3795 fd_proc = open_at(rootfs->dfd_mnt, "proc", PROTECT_OPATH_DIRECTORY,
952b5031
CB
3796 PROTECT_LOOKUP_BENEATH_XDEV, 0);
3797 if (fd_proc < 0)
3798 return log_error_errno(-errno, errno, "Failed to open transient procfs mountpoint");
e1b9d6af 3799
9bcde680
CB
3800 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "/proc/self/fd/%d", fd_proc);
3801 if (ret < 0)
952b5031 3802 return ret_errno(EIO);
e1b9d6af 3803
952b5031 3804 ret = umount2(rootfs->buf, MNT_DETACH);
e1b9d6af 3805 if (ret < 0)
952b5031 3806 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", rootfs->buf);
e1b9d6af
CB
3807
3808domount:
3809 /* rootfs is NULL */
952b5031
CB
3810 if (!rootfs->path) {
3811 ret = mount("proc", rootfs->buf, "proc", 0, NULL);
3812 } else {
ea57e424 3813 ret = safe_mount_beneath_at(rootfs->dfd_mnt, "none", "proc", "proc", 0, NULL);
952b5031 3814 if (ret < 0) {
9bcde680
CB
3815 ret = strnprintf(rootfs->buf, sizeof(rootfs->buf), "%s/proc", rootfs->path ? rootfs->mount : "");
3816 if (ret < 0)
952b5031
CB
3817 return ret_errno(EIO);
3818
3819 ret = safe_mount("proc", rootfs->buf, "proc", 0, NULL, rootfs->mount);
3820 }
3821 }
e1b9d6af 3822 if (ret < 0)
952b5031 3823 return log_error_errno(-1, errno, "Failed to mount temporary procfs");
e1b9d6af 3824
952b5031 3825 INFO("Created transient procfs mount");
e1b9d6af
CB
3826 return 1;
3827}
3828
943144d9 3829/* NOTE: Must not be called from inside the container namespace! */
59eac805 3830static int lxc_create_tmp_proc_mount(struct lxc_conf *conf)
5112cd70
SH
3831{
3832 int mounted;
3833
952b5031 3834 mounted = lxc_transient_proc(&conf->rootfs);
5112cd70 3835 if (mounted == -1) {
01958b1f 3836 /* continue only if there is no rootfs */
943144d9 3837 if (conf->rootfs.path)
952b5031 3838 return log_error_errno(-EPERM, EPERM, "Failed to create transient procfs mount");
5112cd70 3839 } else if (mounted == 1) {
952b5031 3840 conf->transient_procfs_mnt = true;
5112cd70 3841 }
943144d9 3842
5112cd70
SH
3843 return 0;
3844}
3845
3846void tmp_proc_unmount(struct lxc_conf *lxc_conf)
3847{
952b5031
CB
3848 if (lxc_conf->transient_procfs_mnt) {
3849 (void)umount2("/proc", MNT_DETACH);
3850 lxc_conf->transient_procfs_mnt = false;
3851 }
5112cd70
SH
3852}
3853
9e61fb1f 3854/* Walk /proc/mounts and change any shared entries to dependent mounts. */
ed41e764 3855static void turn_into_dependent_mounts(const struct lxc_rootfs *rootfs)
e995d7a2 3856{
7969675f 3857 __do_free char *line = NULL;
003be47b 3858 __do_fclose FILE *f = NULL;
f62cf1d4 3859 __do_close int memfd = -EBADF, mntinfo_fd = -EBADF;
e995d7a2 3860 size_t len = 0;
a39fc34b
CB
3861 ssize_t copied;
3862 int ret;
e995d7a2 3863
ed41e764
CB
3864 mntinfo_fd = open_at(rootfs->dfd_host, "proc/self/mountinfo", PROTECT_OPEN,
3865 (PROTECT_LOOKUP_BENEATH_XDEV & ~RESOLVE_NO_SYMLINKS), 0);
fea3b91d 3866 if (mntinfo_fd < 0) {
ed41e764 3867 SYSERROR("Failed to open %d/proc/self/mountinfo", rootfs->dfd_host);
6a49f05e 3868 return;
fea3b91d 3869 }
6a49f05e
CB
3870
3871 memfd = memfd_create(".lxc_mountinfo", MFD_CLOEXEC);
3872 if (memfd < 0) {
3873 char template[] = P_tmpdir "/.lxc_mountinfo_XXXXXX";
3874
3875 if (errno != ENOSYS) {
fea3b91d 3876 SYSERROR("Failed to create temporary in-memory file");
6a49f05e
CB
3877 return;
3878 }
3879
3880 memfd = lxc_make_tmpfile(template, true);
fea3b91d 3881 if (memfd < 0) {
fea3b91d
DJ
3882 WARN("Failed to create temporary file");
3883 return;
3884 }
6a49f05e
CB
3885 }
3886
a39fc34b 3887 copied = fd_to_fd(mntinfo_fd, memfd);
6a49f05e 3888 if (copied < 0) {
fea3b91d 3889 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
6a49f05e
CB
3890 return;
3891 }
6a49f05e 3892
6a49f05e
CB
3893 ret = lseek(memfd, 0, SEEK_SET);
3894 if (ret < 0) {
fea3b91d 3895 SYSERROR("Failed to reset file descriptor offset");
6a49f05e
CB
3896 return;
3897 }
3898
4110345b 3899 f = fdopen(memfd, "re");
e995d7a2 3900 if (!f) {
003be47b 3901 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
e995d7a2
SH
3902 return;
3903 }
3904
003be47b
CB
3905 /*
3906 * After a successful fdopen() memfd will be closed when calling
3907 * fclose(f). Calling close(memfd) afterwards is undefined.
3908 */
3909 move_fd(memfd);
3910
e995d7a2 3911 while (getline(&line, &len, f) != -1) {
0fd73091
CB
3912 char *opts, *target;
3913
e995d7a2
SH
3914 target = get_field(line, 4);
3915 if (!target)
3916 continue;
0fd73091 3917
e995d7a2
SH
3918 opts = get_field(target, 2);
3919 if (!opts)
3920 continue;
0fd73091 3921
e995d7a2
SH
3922 null_endofword(opts);
3923 if (!strstr(opts, "shared"))
3924 continue;
0fd73091 3925
e995d7a2 3926 null_endofword(target);
0fd73091
CB
3927 ret = mount(NULL, target, NULL, MS_SLAVE, NULL);
3928 if (ret < 0) {
9e61fb1f 3929 SYSERROR("Failed to recursively turn old root mount tree into dependent mount. Continuing...");
6a49f05e 3930 continue;
e995d7a2
SH
3931 }
3932 }
9e61fb1f 3933 TRACE("Turned all mount table entries into dependent mount");
e995d7a2
SH
3934}
3935
0fd73091
CB
3936/* This does the work of remounting / if it is shared, calling the container
3937 * pre-mount hooks, and mounting the rootfs.
35120d9c 3938 */
8ce1abc2
CB
3939int lxc_setup_rootfs_prepare_root(struct lxc_conf *conf, const char *name,
3940 const char *lxcpath)
0ad19a3f 3941{
0fd73091
CB
3942 int ret;
3943
ea11a215
CB
3944 conf->rootfs.dfd_host = open_at(-EBADF, "/", PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_ABSOLUTE, 0);
3945 if (conf->rootfs.dfd_host < 0)
a370f16b
CB
3946 return log_error_errno(-errno, errno, "Failed to open \"/\"");
3947
ed41e764
CB
3948 turn_into_dependent_mounts(&conf->rootfs);
3949
35120d9c 3950 if (conf->rootfs_setup) {
35120d9c 3951 const char *path = conf->rootfs.mount;
0fd73091 3952
ed41e764
CB
3953 /*
3954 * The rootfs was set up in another namespace. bind-mount it to
0fd73091
CB
3955 * give us a mount in our own ns so we can pivot_root to it
3956 */
3957 ret = mount(path, path, "rootfs", MS_BIND, NULL);
55022530
CB
3958 if (ret < 0)
3959 return log_error(-1, "Failed to bind mount container / onto itself");
0fd73091 3960
ea57e424
CB
3961 conf->rootfs.dfd_mnt = openat(-EBADF, path, O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOCTTY);
3962 if (conf->rootfs.dfd_mnt < 0)
26ea5533
CB
3963 return log_error_errno(-errno, errno, "Failed to open file descriptor for container rootfs");
3964
55022530 3965 return log_trace(0, "Bind mounted container / onto itself");
35120d9c 3966 }
d4ef7c50 3967
0fd73091 3968 ret = run_lxc_hooks(name, "pre-mount", conf, NULL);
55022530
CB
3969 if (ret < 0)
3970 return log_error(-1, "Failed to run pre-mount hooks");
35120d9c 3971
4e86cad3 3972 ret = lxc_mount_rootfs(&conf->rootfs);
55022530
CB
3973 if (ret < 0)
3974 return log_error(-1, "Failed to setup rootfs for");
35120d9c
SH
3975
3976 conf->rootfs_setup = true;
3977 return 0;
3978}
3979
1c1c7051
SH
3980static bool verify_start_hooks(struct lxc_conf *conf)
3981{
6b5a54cd 3982 char path[PATH_MAX];
0fd73091
CB
3983 struct lxc_list *it;
3984
3985 lxc_list_for_each (it, &conf->hooks[LXCHOOK_START]) {
1c1c7051 3986 int ret;
0fd73091 3987 char *hookname = it->elem;
1c1c7051 3988
9bcde680 3989 ret = strnprintf(path, sizeof(path), "%s%s",
0fd73091
CB
3990 conf->rootfs.path ? conf->rootfs.mount : "",
3991 hookname);
9bcde680 3992 if (ret < 0)
1c1c7051 3993 return false;
0fd73091 3994
75193660 3995 ret = access(path, X_OK);
55022530
CB
3996 if (ret < 0)
3997 return log_error_errno(false, errno, "Start hook \"%s\" not found in container", hookname);
0fd73091 3998
6a0c909a 3999 return true;
1c1c7051
SH
4000 }
4001
4002 return true;
4003}
4004
20502652
CB
4005static int lxc_setup_boot_id(void)
4006{
4007 int ret;
4008 const char *boot_id_path = "/proc/sys/kernel/random/boot_id";
4009 const char *mock_boot_id_path = "/dev/.lxc-boot-id";
4010 lxc_id128_t n;
4011
4012 if (access(boot_id_path, F_OK))
4013 return 0;
4014
4015 memset(&n, 0, sizeof(n));
4016 if (lxc_id128_randomize(&n)) {
4017 SYSERROR("Failed to generate random data for uuid");
4018 return -1;
4019 }
4020
4021 ret = lxc_id128_write(mock_boot_id_path, n);
4022 if (ret < 0) {
4023 SYSERROR("Failed to write uuid to %s", mock_boot_id_path);
4024 return -1;
4025 }
4026
4027 ret = chmod(mock_boot_id_path, 0444);
4028 if (ret < 0) {
4029 SYSERROR("Failed to chown %s", mock_boot_id_path);
4030 (void)unlink(mock_boot_id_path);
4031 return -1;
4032 }
4033
4034 ret = mount(mock_boot_id_path, boot_id_path, NULL, MS_BIND, NULL);
4035 if (ret < 0) {
4036 SYSERROR("Failed to mount %s to %s", mock_boot_id_path,
4037 boot_id_path);
4038 (void)unlink(mock_boot_id_path);
4039 return -1;
4040 }
4041
4042 ret = mount(NULL, boot_id_path, NULL,
4043 (MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NOEXEC |
4044 MS_NODEV),
4045 NULL);
4046 if (ret < 0) {
4047 SYSERROR("Failed to remount %s read-only", boot_id_path);
4048 (void)unlink(mock_boot_id_path);
4049 return -1;
4050 }
4051
4052 return 0;
4053}
4054
af04d847 4055static int lxc_setup_keyring(struct lsm_ops *lsm_ops, const struct lxc_conf *conf)
d701d729
CB
4056{
4057 key_serial_t keyring;
4058 int ret = 0;
4059
4060 if (conf->lsm_se_keyring_context)
af04d847 4061 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_keyring_context);
d701d729 4062 else if (conf->lsm_se_context)
af04d847 4063 ret = lsm_ops->keyring_label_set(lsm_ops, conf->lsm_se_context);
d701d729 4064 if (ret < 0)
d2022f30 4065 return syserror("Failed to set keyring context");
d701d729
CB
4066
4067 /*
4068 * Try to allocate a new session keyring for the container to prevent
4069 * information leaks.
4070 */
4071 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, prctl_arg(0),
4072 prctl_arg(0), prctl_arg(0), prctl_arg(0));
4073 if (keyring < 0) {
4074 switch (errno) {
4075 case ENOSYS:
4076 DEBUG("The keyctl() syscall is not supported or blocked");
4077 break;
4078 case EACCES:
4079 __fallthrough;
4080 case EPERM:
4081 DEBUG("Failed to access kernel keyring. Continuing...");
4082 break;
4083 default:
d2022f30 4084 SYSWARN("Failed to create kernel keyring");
d701d729
CB
4085 break;
4086 }
4087 }
4088
4089 return ret;
4090}
4091
4b875ef9
CB
4092static int lxc_rootfs_prepare_child(struct lxc_handler *handler)
4093{
4094 struct lxc_rootfs *rootfs = &handler->conf->rootfs;
4095 int dfd_idmapped = -EBADF;
4096 int ret;
4097
0589d744 4098 if (list_empty(&handler->conf->id_map))
4b875ef9
CB
4099 return 0;
4100
4101 if (is_empty_string(rootfs->mnt_opts.userns_path))
4102 return 0;
4103
4104 if (handler->conf->rootfs_setup)
4105 return 0;
4106
4107 ret = lxc_abstract_unix_recv_one_fd(handler->data_sock[1], &dfd_idmapped, NULL, 0);
4108 if (ret < 0)
4109 return syserror("Failed to receive idmapped mount fd");
4110
4111 rootfs->dfd_idmapped = dfd_idmapped;
4112 TRACE("Received detached idmapped mount %d", rootfs->dfd_idmapped);
4113 return 0;
4114}
4115
1b82d721
CB
4116int lxc_idmapped_mounts_parent(struct lxc_handler *handler)
4117{
5a782dca
CB
4118 int mnt_seq = 0;
4119
1b82d721
CB
4120 for (;;) {
4121 __do_close int fd_from = -EBADF, fd_userns = -EBADF;
4122 struct lxc_mount_attr attr = {};
4123 struct lxc_mount_options opts = {};
4124 ssize_t ret;
4125
4126 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4127 &fd_from, &fd_userns,
4128 &opts, sizeof(opts));
4129 if (ret < 0)
4130 return syserror("Failed to receive idmapped mount file descriptors from child");
4131
4132 if (fd_from < 0 || fd_userns < 0)
4133 return log_trace(0, "Finished receiving idmapped mount file descriptors from child");
4134
4135 attr.attr_set = MOUNT_ATTR_IDMAP;
4136 attr.userns_fd = fd_userns;
4137 ret = mount_setattr(fd_from, "",
4138 AT_EMPTY_PATH |
3eb23230 4139 (opts.bind_recursively ? AT_RECURSIVE : 0),
1b82d721
CB
4140 &attr, sizeof(attr));
4141 if (ret)
4142 return syserror("Failed to idmap detached %smount %d to %d",
3eb23230 4143 opts.bind_recursively ? "recursive " : "",
1b82d721
CB
4144 fd_from, fd_userns);
4145
5a782dca
CB
4146 ret = lxc_abstract_unix_send_credential(handler->data_sock[1],
4147 &mnt_seq,
4148 sizeof(mnt_seq));
1b82d721
CB
4149 if (ret < 0)
4150 return syserror("Parent failed to notify child that detached %smount %d was idmapped to user namespace %d",
3eb23230 4151 opts.bind_recursively ? "recursive " : "",
1b82d721
CB
4152 fd_from, fd_userns);
4153
4154 TRACE("Parent idmapped detached %smount %d to user namespace %d",
3eb23230 4155 opts.bind_recursively ? "recursive " : "", fd_from, fd_userns);
5a782dca 4156 mnt_seq++;
1b82d721
CB
4157 }
4158}
4159
493ae3fe
CB
4160static int lxc_recv_ttys_from_child(struct lxc_handler *handler)
4161{
b35f8f7e 4162 call_cleaner(lxc_delete_tty) struct lxc_tty_info *info_new = &(struct lxc_tty_info){};
493ae3fe
CB
4163 int sock = handler->data_sock[1];
4164 struct lxc_conf *conf = handler->conf;
b35f8f7e
CB
4165 struct lxc_tty_info *tty_info = &conf->ttys;
4166 size_t ttys_max = tty_info->max;
4167 struct lxc_terminal_info *terminal_info;
4168 int ret;
493ae3fe 4169
b35f8f7e 4170 if (!ttys_max)
493ae3fe
CB
4171 return 0;
4172
b35f8f7e
CB
4173 info_new->tty = malloc(sizeof(*(info_new->tty)) * ttys_max);
4174 if (!info_new->tty)
4175 return ret_errno(ENOMEM);
493ae3fe 4176
b35f8f7e
CB
4177 for (int i = 0; i < ttys_max; i++) {
4178 terminal_info = &info_new->tty[i];
4179 terminal_info->busy = -1;
4180 terminal_info->ptx = -EBADF;
4181 terminal_info->pty = -EBADF;
4182 }
493ae3fe 4183
b35f8f7e
CB
4184 for (int i = 0; i < ttys_max; i++) {
4185 int ptx = -EBADF, pty = -EBADF;
4186
4187 ret = lxc_abstract_unix_recv_two_fds(sock, &ptx, &pty);
493ae3fe 4188 if (ret < 0)
b35f8f7e 4189 return syserror("Failed to receive %zu ttys from child", ttys_max);
493ae3fe 4190
b35f8f7e
CB
4191 terminal_info = &info_new->tty[i];
4192 terminal_info->ptx = ptx;
4193 terminal_info->pty = pty;
4194 TRACE("Received pty with ptx fd %d and pty fd %d from child",
4195 terminal_info->ptx, terminal_info->pty);
493ae3fe
CB
4196 }
4197
b35f8f7e
CB
4198 tty_info->tty = move_ptr(info_new->tty);
4199 TRACE("Received %zu ttys from child", ttys_max);
4200 return 0;
493ae3fe
CB
4201}
4202
9f77617b
CB
4203static int lxc_send_console_to_parent(struct lxc_handler *handler)
4204{
4205 struct lxc_terminal *console = &handler->conf->console;
4206 int ret;
4207
4208 if (!wants_console(console))
4209 return 0;
4210
4211 /* We've already allocated a console from the host's devpts instance. */
4212 if (console->pty < 0)
4213 return 0;
4214
4215 ret = __lxc_abstract_unix_send_two_fds(handler->data_sock[0],
4216 console->ptx, console->pty,
4217 console,
4218 sizeof(struct lxc_terminal));
4219 if (ret < 0)
4220 return syserror("Fail to send console to parent");
4221
4222 TRACE("Sent console to parent");
4223 return 0;
4224}
4225
4226static int lxc_recv_console_from_child(struct lxc_handler *handler)
4227{
4228 __do_close int fd_ptx = -EBADF, fd_pty = -EBADF;
4229 struct lxc_terminal *console = &handler->conf->console;
4230 int ret;
4231
4232 if (!wants_console(console))
4233 return 0;
4234
4235 /* We've already allocated a console from the host's devpts instance. */
4236 if (console->pty >= 0)
4237 return 0;
4238
4239 ret = __lxc_abstract_unix_recv_two_fds(handler->data_sock[1],
4240 &fd_ptx, &fd_pty,
4241 console,
4242 sizeof(struct lxc_terminal));
4243 if (ret < 0)
4244 return syserror("Fail to receive console from child");
4245
4246 console->ptx = move_fd(fd_ptx);
4247 console->pty = move_fd(fd_pty);
4248
4249 TRACE("Received console from child");
4250 return 0;
4251}
4252
493ae3fe
CB
4253int lxc_sync_fds_parent(struct lxc_handler *handler)
4254{
4255 int ret;
4256
4257 ret = lxc_seccomp_recv_notifier_fd(&handler->conf->seccomp, handler->data_sock[1]);
4258 if (ret < 0)
4259 return syserror_ret(ret, "Failed to receive seccomp notify fd from child");
4260
42c0d056 4261 ret = lxc_recv_devpts_from_child(handler);
493ae3fe
CB
4262 if (ret < 0)
4263 return syserror_ret(ret, "Failed to receive devpts fd from child");
4264
4265 /* Read tty fds allocated by child. */
4266 ret = lxc_recv_ttys_from_child(handler);
4267 if (ret < 0)
4268 return syserror_ret(ret, "Failed to receive tty info from child process");
4269
4270 if (handler->ns_clone_flags & CLONE_NEWNET) {
4271 ret = lxc_network_recv_name_and_ifindex_from_child(handler);
4272 if (ret < 0)
4273 return syserror_ret(ret, "Failed to receive names and ifindices for network devices from child");
4274 }
4275
9f77617b
CB
4276 ret = lxc_recv_console_from_child(handler);
4277 if (ret < 0)
4278 return syserror_ret(ret, "Failed to receive console from child");
4279
493ae3fe
CB
4280 TRACE("Finished syncing file descriptors with child");
4281 return 0;
4282}
4283
111ed96e
CB
4284int lxc_sync_fds_child(struct lxc_handler *handler)
4285{
4286 int ret;
4287
4288 ret = lxc_seccomp_send_notifier_fd(&handler->conf->seccomp, handler->data_sock[0]);
4289 if (ret < 0)
4290 return syserror_ret(ret, "Failed to send seccomp notify fd to parent");
4291
4292 ret = lxc_send_devpts_to_parent(handler);
4293 if (ret < 0)
4294 return syserror_ret(ret, "Failed to send seccomp devpts fd to parent");
4295
4296 ret = lxc_send_ttys_to_parent(handler);
4297 if (ret < 0)
4298 return syserror_ret(ret, "Failed to send tty file descriptors to parent");
4299
4300 if (handler->ns_clone_flags & CLONE_NEWNET) {
4301 ret = lxc_network_send_name_and_ifindex_to_parent(handler);
4302 if (ret < 0)
4303 return syserror_ret(ret, "Failed to send network device names and ifindices to parent");
4304 }
4305
9f77617b
CB
4306 ret = lxc_send_console_to_parent(handler);
4307 if (ret < 0)
4308 return syserror_ret(ret, "Failed to send console to parent");
4309
111ed96e
CB
4310 TRACE("Finished syncing file descriptors with parent");
4311 return 0;
4312}
4313
3b988b33 4314int lxc_setup(struct lxc_handler *handler)
35120d9c 4315{
2187efd3 4316 int ret;
0fd73091 4317 const char *lxcpath = handler->lxcpath, *name = handler->name;
35120d9c 4318 struct lxc_conf *lxc_conf = handler->conf;
35120d9c 4319
4b875ef9
CB
4320 ret = lxc_rootfs_prepare_child(handler);
4321 if (ret < 0)
4322 return syserror("Failed to prepare rootfs");
4323
8ce1abc2 4324 ret = lxc_setup_rootfs_prepare_root(lxc_conf, name, lxcpath);
55022530
CB
4325 if (ret < 0)
4326 return log_error(-1, "Failed to setup rootfs");
35120d9c 4327
b87ee312 4328 if (handler->nsfd[LXC_NS_UTS] == -EBADF) {
8353b4c9 4329 ret = setup_utsname(lxc_conf->utsname);
55022530
CB
4330 if (ret < 0)
4331 return log_error(-1, "Failed to setup the utsname %s", name);
0ad19a3f 4332 }
4333
8f818a84 4334 if (!lxc_conf->keyring_disable_session) {
d701d729 4335 ret = lxc_setup_keyring(handler->lsm_ops, lxc_conf);
8f818a84 4336 if (ret < 0)
d701d729 4337 return log_error(-1, "Failed to setup container keyring");
8f818a84 4338 }
b25291da 4339
e389f2af 4340 if (handler->ns_clone_flags & CLONE_NEWNET) {
6bc4165d
CB
4341 ret = lxc_network_recv_from_parent(handler);
4342 if (ret < 0)
4343 return log_error(-1, "Failed to receive veth names from parent");
4344
87d0990c 4345 ret = lxc_setup_network_in_child_namespaces(lxc_conf);
55022530
CB
4346 if (ret < 0)
4347 return log_error(-1, "Failed to setup network");
790255cf
CB
4348 }
4349
bc6928ff 4350 if (lxc_conf->autodev > 0) {
63012bdd 4351 ret = mount_autodev(name, &lxc_conf->rootfs, lxc_conf->autodevtmpfssize, lxcpath);
55022530
CB
4352 if (ret < 0)
4353 return log_error(-1, "Failed to mount \"/dev\"");
c6883f38
SH
4354 }
4355
8353b4c9
CB
4356 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
4357 * need to wait until other stuff has finished.
368bbc02 4358 */
6d25a524 4359 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK);
55022530
CB
4360 if (ret < 0)
4361 return log_error(-1, "Failed to setup first automatic mounts");
368bbc02 4362
48e5dcc8 4363 ret = setup_mount_fstab(&lxc_conf->rootfs, lxc_conf->fstab, name, lxcpath);
55022530
CB
4364 if (ret < 0)
4365 return log_error(-1, "Failed to setup mounts");
576f946d 4366
c631115d
FA
4367 if (!lxc_list_empty(&lxc_conf->mount_list)) {
4368 ret = setup_mount_entries(lxc_conf, &lxc_conf->rootfs,
4369 &lxc_conf->mount_list, name, lxcpath);
55022530
CB
4370 if (ret < 0)
4371 return log_error(-1, "Failed to setup mount entries");
c631115d
FA
4372 }
4373
1b82d721
CB
4374 if (!lxc_sync_wake_parent(handler, START_SYNC_IDMAPPED_MOUNTS))
4375 return -1;
4376
4377 ret = lxc_idmapped_mounts_child(handler);
4378 if (ret)
4379 return syserror("Failed to attached detached idmapped mounts");
4380
1f0a3b6e
CB
4381 lxc_conf->rootfs.dfd_dev = open_at(lxc_conf->rootfs.dfd_mnt, "dev",
4382 PROTECT_OPATH_DIRECTORY, PROTECT_LOOKUP_BENEATH_XDEV, 0);
4383 if (lxc_conf->rootfs.dfd_dev < 0 && errno != ENOENT)
4384 return log_error_errno(-errno, errno, "Failed to open \"/dev\"");
4385
8353b4c9
CB
4386 /* Now mount only cgroups, if wanted. Before, /sys could not have been
4387 * mounted. It is guaranteed to be mounted now either through
4388 * automatically or via fstab entries.
368bbc02 4389 */
6d25a524 4390 ret = lxc_mount_auto_mounts(handler, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK);
55022530
CB
4391 if (ret < 0)
4392 return log_error(-1, "Failed to setup remaining automatic mounts");
368bbc02 4393
8353b4c9 4394 ret = run_lxc_hooks(name, "mount", lxc_conf, NULL);
55022530
CB
4395 if (ret < 0)
4396 return log_error(-1, "Failed to run mount hooks");
773fb9ca 4397
bc6928ff 4398 if (lxc_conf->autodev > 0) {
8353b4c9 4399 ret = run_lxc_hooks(name, "autodev", lxc_conf, NULL);
55022530
CB
4400 if (ret < 0)
4401 return log_error(-1, "Failed to run autodev hooks");
06749971 4402
8353b4c9 4403 ret = lxc_fill_autodev(&lxc_conf->rootfs);
55022530
CB
4404 if (ret < 0)
4405 return log_error(-1, "Failed to populate \"/dev\"");
91c3830e 4406 }
368bbc02 4407
75193660 4408 /* Make sure any start hooks are in the container */
55022530
CB
4409 if (!verify_start_hooks(lxc_conf))
4410 return log_error(-1, "Failed to verify start hooks");
75193660 4411
cf68ffd9
CB
4412 ret = lxc_create_tmp_proc_mount(lxc_conf);
4413 if (ret < 0)
3dd3fc31 4414 return log_error(-1, "Failed to mount transient procfs instance for LSMs");
cf68ffd9 4415
96a980e1 4416 ret = lxc_setup_devpts_child(handler);
289b707b
CB
4417 if (ret < 0)
4418 return log_error(-1, "Failed to prepare new devpts instance");
4419
03585adc
CB
4420 ret = lxc_finish_devpts_child(handler);
4421 if (ret < 0)
4422 return log_error(-1, "Failed to finish devpts setup");
4423
f3dff080 4424 ret = lxc_setup_console(handler, &lxc_conf->rootfs, &lxc_conf->console,
37c74fd1 4425 lxc_conf->ttys.dir);
55022530
CB
4426 if (ret < 0)
4427 return log_error(-1, "Failed to setup console");
6e590161 4428
6a2ca1b4
CB
4429 ret = lxc_create_ttys(handler);
4430 if (ret < 0)
4431 return log_error(-1, "Failed to create ttys");
4432
ed8704d0 4433 ret = lxc_setup_dev_symlinks(&lxc_conf->rootfs);
55022530
CB
4434 if (ret < 0)
4435 return log_error(-1, "Failed to setup \"/dev\" symlinks");
69aa6655 4436
8ce1abc2 4437 ret = lxc_setup_rootfs_switch_root(&lxc_conf->rootfs);
55022530
CB
4438 if (ret < 0)
4439 return log_error(-1, "Failed to pivot root into rootfs");
ed502555 4440
20502652
CB
4441 /* Setting the boot-id is best-effort for now. */
4442 if (lxc_conf->autodev > 0)
4443 (void)lxc_setup_boot_id();
4444
8353b4c9 4445 ret = setup_personality(lxc_conf->personality);
55022530 4446 if (ret < 0)
9c601e1f 4447 return syserror("Failed to set personality");
cccc74b5 4448
8353b4c9
CB
4449 /* Set sysctl value to a path under /proc/sys as determined from the
4450 * key. For e.g. net.ipv4.ip_forward translated to
4451 * /proc/sys/net/ipv4/ip_forward.
7edd0540 4452 */
ba9f9347
CB
4453 ret = setup_sysctl_parameters(lxc_conf);
4454 if (ret < 0)
4455 return log_error(-1, "Failed to setup sysctl parameters");
7edd0540 4456
97a8f74f 4457 if (!lxc_list_empty(&lxc_conf->keepcaps)) {
55022530
CB
4458 if (!lxc_list_empty(&lxc_conf->caps))
4459 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 4460
55022530
CB
4461 if (dropcaps_except(&lxc_conf->keepcaps))
4462 return log_error(-1, "Failed to keep capabilities");
97a8f74f 4463 } else if (setup_caps(&lxc_conf->caps)) {
55022530 4464 return log_error(-1, "Failed to drop capabilities");
81810dd1
DL
4465 }
4466
79ff643d 4467 put_lxc_rootfs(&handler->conf->rootfs, true);
8353b4c9 4468 NOTICE("The container \"%s\" is set up", name);
cd54d859 4469
0ad19a3f 4470 return 0;
4471}
26ddeedd 4472
3f60c2f7 4473int run_lxc_hooks(const char *name, char *hookname, struct lxc_conf *conf,
14a7b0f9 4474 char *argv[])
26ddeedd 4475{
26ddeedd 4476 struct lxc_list *it;
3ea957c6
RK
4477 int which;
4478
4479 for (which = 0; which < NUM_LXC_HOOKS; which ++) {
71528742 4480 if (strequal(hookname, lxchook_names[which]))
3ea957c6
RK
4481 break;
4482 }
4483
4484 if (which >= NUM_LXC_HOOKS)
26ddeedd 4485 return -1;
3f60c2f7 4486
0fd73091 4487 lxc_list_for_each (it, &conf->hooks[which]) {
26ddeedd 4488 int ret;
3f60c2f7
CB
4489 char *hook = it->elem;
4490
4491 ret = run_script_argv(name, conf->hooks_version, "lxc", hook,
14a7b0f9 4492 hookname, argv);
3f60c2f7
CB
4493 if (ret < 0)
4494 return -1;
26ddeedd 4495 }
3f60c2f7 4496
26ddeedd
SH
4497 return 0;
4498}
72d0e1cb 4499
72d0e1cb
SG
4500int lxc_clear_config_caps(struct lxc_conf *c)
4501{
1a0e70ac 4502 struct lxc_list *it, *next;
72d0e1cb 4503
0fd73091 4504 lxc_list_for_each_safe (it, &c->caps, next) {
72d0e1cb
SG
4505 lxc_list_del(it);
4506 free(it->elem);
4507 free(it);
4508 }
0fd73091 4509
cc36133d 4510 lxc_list_init(&c->caps);
72d0e1cb
SG
4511 return 0;
4512}
4513
0589d744 4514static int lxc_free_idmap(struct list_head *id_map)
c7e345ae 4515{
0589d744 4516 struct id_map *map, *nmap;
27c27d73 4517
0589d744
CB
4518 list_for_each_entry_safe(map, nmap, id_map, head) {
4519 list_del(&map->head);
4520 free(map);
27c27d73 4521 }
c7e345ae 4522
0589d744 4523 INIT_LIST_HEAD(id_map);
27c27d73
SH
4524 return 0;
4525}
7e621263 4526
0589d744 4527static int __lxc_free_idmap(struct list_head *id_map)
7e621263
CB
4528{
4529 lxc_free_idmap(id_map);
7e621263
CB
4530 return 0;
4531}
0589d744 4532define_cleanup_function(struct list_head *, __lxc_free_idmap);
27c27d73 4533
4355ab5f
SH
4534int lxc_clear_idmaps(struct lxc_conf *c)
4535{
4536 return lxc_free_idmap(&c->id_map);
4537}
4538
1fb86a7c
SH
4539int lxc_clear_config_keepcaps(struct lxc_conf *c)
4540{
0fd73091 4541 struct lxc_list *it, *next;
1fb86a7c 4542
0fd73091 4543 lxc_list_for_each_safe (it, &c->keepcaps, next) {
1fb86a7c
SH
4544 lxc_list_del(it);
4545 free(it->elem);
4546 free(it);
4547 }
0fd73091 4548
cc36133d 4549 lxc_list_init(&c->keepcaps);
1fb86a7c
SH
4550 return 0;
4551}
4552
a3ed9b81 4553int lxc_clear_namespace(struct lxc_conf *c)
4554{
ced5587c
CB
4555 for (int i = 0; i < LXC_NS_MAX; i++)
4556 free_disarm(c->ns_share[i]);
4557
a3ed9b81 4558 return 0;
4559}
4560
54860ed0 4561int lxc_clear_cgroups(struct lxc_conf *c, const char *key, int version)
72d0e1cb 4562{
ab1a6cac 4563 const char *k = key;
54860ed0 4564 bool all = false;
c9dbb8ed
CB
4565 char *global_token, *namespaced_token;
4566 size_t namespaced_token_len;
4567 struct list_head *list;
4568 struct lxc_cgroup *cgroup, *ncgroup;
72d0e1cb 4569
54860ed0 4570 if (version == CGROUP2_SUPER_MAGIC) {
d6c06927
CB
4571 global_token = "lxc.cgroup2";
4572 namespaced_token = "lxc.cgroup2.";
4573 namespaced_token_len = STRLITERALLEN("lxc.cgroup2.");
54860ed0
CB
4574 list = &c->cgroup2;
4575 } else if (version == CGROUP_SUPER_MAGIC) {
d6c06927
CB
4576 global_token = "lxc.cgroup";
4577 namespaced_token = "lxc.cgroup.";
4578 namespaced_token_len = STRLITERALLEN("lxc.cgroup.");
54860ed0
CB
4579 list = &c->cgroup;
4580 } else {
d6c06927 4581 return ret_errno(EINVAL);
54860ed0
CB
4582 }
4583
71528742 4584 if (strequal(key, global_token))
72d0e1cb 4585 all = true;
eed95eb0 4586 else if (strnequal(key, namespaced_token, namespaced_token_len))
ab1a6cac 4587 k += namespaced_token_len;
a6390f01 4588 else
d6c06927 4589 return ret_errno(EINVAL);
72d0e1cb 4590
c9dbb8ed
CB
4591 list_for_each_entry_safe(cgroup, ncgroup, list, head) {
4592 if (!all && !strequal(cgroup->subsystem, k))
72d0e1cb 4593 continue;
54860ed0 4594
c9dbb8ed
CB
4595 list_del(&cgroup->head);
4596 free(cgroup->subsystem);
4597 free(cgroup->value);
4598 free(cgroup);
72d0e1cb 4599 }
e409b214 4600
cc36133d 4601 if (all)
c9dbb8ed 4602 INIT_LIST_HEAD(list);
cc36133d 4603
72d0e1cb
SG
4604 return 0;
4605}
4606
a7744f12 4607static inline void lxc_clear_cgroups_devices(struct lxc_conf *conf)
4bfb655e 4608{
a7744f12 4609 lxc_clear_cgroup2_devices(&conf->bpf_devices);
4bfb655e
CB
4610}
4611
c6d09e15
WB
4612int lxc_clear_limits(struct lxc_conf *c, const char *key)
4613{
c6d09e15 4614 const char *k = NULL;
0fd73091 4615 bool all = false;
223797c3 4616 struct lxc_limit *lim, *nlim;
c6d09e15 4617
71528742 4618 if (strequal(key, "lxc.limit") || strequal(key, "lxc.prlimit"))
c6d09e15 4619 all = true;
eed95eb0 4620 else if (strnequal(key, "lxc.limit.", STRLITERALLEN("lxc.limit.")))
6333c915 4621 k = key + STRLITERALLEN("lxc.limit.");
eed95eb0 4622 else if (strnequal(key, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")))
6333c915 4623 k = key + STRLITERALLEN("lxc.prlimit.");
c6d09e15 4624 else
786467cb 4625 return ret_errno(EINVAL);
c6d09e15 4626
223797c3 4627 list_for_each_entry_safe(lim, nlim, &c->limits, head) {
71528742 4628 if (!all && !strequal(lim->resource, k))
c6d09e15 4629 continue;
0fd73091 4630
223797c3 4631 list_del(&lim->head);
786467cb 4632 free_disarm(lim->resource);
c6d09e15 4633 free(lim);
c6d09e15 4634 }
b668653c 4635
786467cb 4636 if (all)
223797c3 4637 INIT_LIST_HEAD(&c->limits);
786467cb 4638
c6d09e15
WB
4639 return 0;
4640}
4641
7edd0540
L
4642int lxc_clear_sysctls(struct lxc_conf *c, const char *key)
4643{
7edd0540 4644 const char *k = NULL;
0fd73091 4645 bool all = false;
ba9f9347 4646 struct lxc_sysctl *sysctl, *nsysctl;
7edd0540 4647
71528742 4648 if (strequal(key, "lxc.sysctl"))
7edd0540 4649 all = true;
eed95eb0 4650 else if (strnequal(key, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")))
6333c915 4651 k = key + STRLITERALLEN("lxc.sysctl.");
7edd0540
L
4652 else
4653 return -1;
4654
ba9f9347
CB
4655 list_for_each_entry_safe(sysctl, nsysctl, &c->sysctls, head) {
4656 if (!all && !strequal(sysctl->key, k))
7edd0540 4657 continue;
0fd73091 4658
ba9f9347
CB
4659 list_del(&sysctl->head);
4660 free(sysctl->key);
4661 free(sysctl->value);
4662 free(sysctl);
7edd0540 4663 }
0fd73091 4664
4a2c9b40 4665 if (all)
ba9f9347 4666 INIT_LIST_HEAD(&c->sysctls);
4a2c9b40 4667
7edd0540
L
4668 return 0;
4669}
4670
61d7a733
YT
4671int lxc_clear_procs(struct lxc_conf *c, const char *key)
4672{
61d7a733 4673 const char *k = NULL;
0fd73091 4674 bool all = false;
91d04bf9 4675 struct lxc_proc *proc, *nproc;
61d7a733 4676
71528742 4677 if (strequal(key, "lxc.proc"))
61d7a733 4678 all = true;
eed95eb0 4679 else if (strnequal(key, "lxc.proc.", STRLITERALLEN("lxc.proc.")))
6333c915 4680 k = key + STRLITERALLEN("lxc.proc.");
61d7a733
YT
4681 else
4682 return -1;
4683
91d04bf9 4684 list_for_each_entry_safe(proc, nproc, &c->procs, head) {
71528742 4685 if (!all && !strequal(proc->filename, k))
61d7a733 4686 continue;
0fd73091 4687
91d04bf9 4688 list_del(&proc->head);
61d7a733
YT
4689 free(proc->filename);
4690 free(proc->value);
4691 free(proc);
61d7a733
YT
4692 }
4693
cc36133d 4694 if (all)
91d04bf9 4695 INIT_LIST_HEAD(&c->procs);
cc36133d 4696
61d7a733
YT
4697 return 0;
4698}
4699
ee1e7aa0
SG
4700int lxc_clear_groups(struct lxc_conf *c)
4701{
0fd73091 4702 struct lxc_list *it, *next;
ee1e7aa0 4703
0fd73091 4704 lxc_list_for_each_safe (it, &c->groups, next) {
ee1e7aa0
SG
4705 lxc_list_del(it);
4706 free(it->elem);
4707 free(it);
4708 }
0fd73091 4709
cc36133d 4710 lxc_list_init(&c->groups);
ee1e7aa0
SG
4711 return 0;
4712}
4713
ab799c0b
SG
4714int lxc_clear_environment(struct lxc_conf *c)
4715{
0fd73091 4716 struct lxc_list *it, *next;
ab799c0b 4717
0fd73091 4718 lxc_list_for_each_safe (it, &c->environment, next) {
ab799c0b
SG
4719 lxc_list_del(it);
4720 free(it->elem);
4721 free(it);
4722 }
0fd73091 4723
cc36133d 4724 lxc_list_init(&c->environment);
ab799c0b
SG
4725 return 0;
4726}
4727
72d0e1cb
SG
4728int lxc_clear_mount_entries(struct lxc_conf *c)
4729{
0fd73091 4730 struct lxc_list *it, *next;
72d0e1cb 4731
0fd73091 4732 lxc_list_for_each_safe (it, &c->mount_list, next) {
72d0e1cb
SG
4733 lxc_list_del(it);
4734 free(it->elem);
4735 free(it);
4736 }
0fd73091 4737
cc36133d 4738 lxc_list_init(&c->mount_list);
72d0e1cb
SG
4739 return 0;
4740}
4741
b099e9e9
SH
4742int lxc_clear_automounts(struct lxc_conf *c)
4743{
4744 c->auto_mounts = 0;
4745 return 0;
4746}
4747
12a50cc6 4748int lxc_clear_hooks(struct lxc_conf *c, const char *key)
72d0e1cb 4749{
0fd73091
CB
4750 struct lxc_list *it, *next;
4751 const char *k = NULL;
4752 bool all = false, done = false;
72d0e1cb 4753
71528742 4754 if (strequal(key, "lxc.hook"))
17ed13a3 4755 all = true;
eed95eb0 4756 else if (strnequal(key, "lxc.hook.", STRLITERALLEN("lxc.hook.")))
6333c915 4757 k = key + STRLITERALLEN("lxc.hook.");
a6390f01
WB
4758 else
4759 return -1;
17ed13a3 4760
ced5587c 4761 for (int i = 0; i < NUM_LXC_HOOKS; i++) {
71528742 4762 if (all || strequal(k, lxchook_names[i])) {
0fd73091 4763 lxc_list_for_each_safe (it, &c->hooks[i], next) {
17ed13a3
SH
4764 lxc_list_del(it);
4765 free(it->elem);
4766 free(it);
4767 }
cc36133d 4768 lxc_list_init(&c->hooks[i]);
0fd73091 4769
17ed13a3 4770 done = true;
72d0e1cb
SG
4771 }
4772 }
17ed13a3 4773
55022530
CB
4774 if (!done)
4775 return log_error(-1, "Invalid hook key: %s", key);
0fd73091 4776
72d0e1cb
SG
4777 return 0;
4778}
8eb5694b 4779
4184c3e1
SH
4780static inline void lxc_clear_aliens(struct lxc_conf *conf)
4781{
0fd73091 4782 struct lxc_list *it, *next;
4184c3e1 4783
0fd73091 4784 lxc_list_for_each_safe (it, &conf->aliens, next) {
4184c3e1
SH
4785 lxc_list_del(it);
4786 free(it->elem);
4787 free(it);
4788 }
cc36133d
CB
4789
4790 lxc_list_init(&conf->aliens);
4184c3e1
SH
4791}
4792
c7b15d1e 4793void lxc_clear_includes(struct lxc_conf *conf)
f979ac15 4794{
0fd73091 4795 struct lxc_list *it, *next;
f979ac15 4796
ced5587c 4797 lxc_list_for_each_safe(it, &conf->includes, next) {
f979ac15
SH
4798 lxc_list_del(it);
4799 free(it->elem);
4800 free(it);
4801 }
cc36133d
CB
4802
4803 lxc_list_init(&conf->includes);
f979ac15
SH
4804}
4805
1800f924
WB
4806int lxc_clear_apparmor_raw(struct lxc_conf *c)
4807{
4808 struct lxc_list *it, *next;
4809
4810 lxc_list_for_each_safe (it, &c->lsm_aa_raw, next) {
4811 lxc_list_del(it);
4812 free(it->elem);
4813 free(it);
4814 }
4815
cc36133d 4816 lxc_list_init(&c->lsm_aa_raw);
1800f924
WB
4817 return 0;
4818}
4819
8eb5694b
SH
4820void lxc_conf_free(struct lxc_conf *conf)
4821{
4822 if (!conf)
4823 return;
0fd73091 4824
858377e4
SH
4825 if (current_config == conf)
4826 current_config = NULL;
aed105d5 4827 lxc_terminal_conf_free(&conf->console);
f10fad2f 4828 free(conf->rootfs.mount);
b3b8c97f 4829 free(conf->rootfs.bdev_type);
f10fad2f 4830 free(conf->rootfs.path);
79ff643d 4831 put_lxc_rootfs(&conf->rootfs, true);
f10fad2f 4832 free(conf->logfile);
858377e4
SH
4833 if (conf->logfd != -1)
4834 close(conf->logfd);
f10fad2f 4835 free(conf->utsname);
885766f5
CB
4836 free(conf->ttys.dir);
4837 free(conf->ttys.tty_names);
f10fad2f
ME
4838 free(conf->fstab);
4839 free(conf->rcfile);
5cda27c1 4840 free(conf->execute_cmd);
f10fad2f 4841 free(conf->init_cmd);
bf31b337 4842 free(conf->init_groups.list);
3c491553 4843 free(conf->init_cwd);
6b0d5538 4844 free(conf->unexpanded_config);
76d0127f 4845 free(conf->syslog);
87d0990c 4846 lxc_free_networks(conf);
f10fad2f 4847 free(conf->lsm_aa_profile);
1800f924 4848 free(conf->lsm_aa_profile_computed);
f10fad2f 4849 free(conf->lsm_se_context);
1ed59e6d 4850 free(conf->lsm_se_keyring_context);
c3e3c21a 4851 lxc_seccomp_free(&conf->seccomp);
8eb5694b 4852 lxc_clear_config_caps(conf);
1fb86a7c 4853 lxc_clear_config_keepcaps(conf);
54860ed0
CB
4854 lxc_clear_cgroups(conf, "lxc.cgroup", CGROUP_SUPER_MAGIC);
4855 lxc_clear_cgroups(conf, "lxc.cgroup2", CGROUP2_SUPER_MAGIC);
a7744f12 4856 lxc_clear_cgroups_devices(conf);
17ed13a3 4857 lxc_clear_hooks(conf, "lxc.hook");
8eb5694b 4858 lxc_clear_mount_entries(conf);
27c27d73 4859 lxc_clear_idmaps(conf);
ee1e7aa0 4860 lxc_clear_groups(conf);
f979ac15 4861 lxc_clear_includes(conf);
761d81ca 4862 lxc_clear_aliens(conf);
ab799c0b 4863 lxc_clear_environment(conf);
240d4b74 4864 lxc_clear_limits(conf, "lxc.prlimit");
7edd0540 4865 lxc_clear_sysctls(conf, "lxc.sysctl");
61d7a733 4866 lxc_clear_procs(conf, "lxc.proc");
1800f924 4867 lxc_clear_apparmor_raw(conf);
a3ed9b81 4868 lxc_clear_namespace(conf);
43654d34 4869 free(conf->cgroup_meta.dir);
a900cbaf 4870 free(conf->cgroup_meta.monitor_dir);
eb60b564 4871 free(conf->cgroup_meta.monitor_pivot_dir);
a900cbaf
WB
4872 free(conf->cgroup_meta.container_dir);
4873 free(conf->cgroup_meta.namespace_dir);
43654d34 4874 free(conf->cgroup_meta.controllers);
7a41e857
LT
4875 free(conf->shmount.path_host);
4876 free(conf->shmount.path_cont);
8eb5694b
SH
4877 free(conf);
4878}
4355ab5f
SH
4879
4880struct userns_fn_data {
4881 int (*fn)(void *);
c9b7c33e 4882 const char *fn_name;
4355ab5f
SH
4883 void *arg;
4884 int p[2];
4885};
4886
4887static int run_userns_fn(void *data)
4888{
766c5b6d 4889 struct userns_fn_data *d = data;
adaffdd7 4890 int ret;
4355ab5f 4891 char c;
4355ab5f 4892
766c5b6d 4893 close_prot_errno_disarm(d->p[1]);
f8aa4bf3 4894
766c5b6d
CB
4895 /*
4896 * Wait for parent to finish establishing a new mapping in the user
f8aa4bf3
CB
4897 * namespace we are executing in.
4898 */
adaffdd7 4899 ret = lxc_read_nointr(d->p[0], &c, 1);
766c5b6d 4900 close_prot_errno_disarm(d->p[0]);
adaffdd7
CB
4901 if (ret != 1)
4902 return -1;
f8aa4bf3 4903
c9b7c33e 4904 if (d->fn_name)
adaffdd7 4905 TRACE("Calling function \"%s\"", d->fn_name);
0fd73091 4906
f8aa4bf3 4907 /* Call function to run. */
4355ab5f
SH
4908 return d->fn(d->arg);
4909}
4910
7581a82f 4911static struct id_map *mapped_nsid_add(const struct lxc_conf *conf, unsigned id,
db7cfe23
CB
4912 enum idtype idtype)
4913{
5173b710
CB
4914 const struct id_map *map;
4915 struct id_map *retmap;
db7cfe23
CB
4916
4917 map = find_mapped_nsid_entry(conf, id, idtype);
4918 if (!map)
4919 return NULL;
4920
b8e43ef0 4921 retmap = zalloc(sizeof(*retmap));
db7cfe23
CB
4922 if (!retmap)
4923 return NULL;
4924
4925 memcpy(retmap, map, sizeof(*retmap));
4926 return retmap;
4927}
4928
0589d744 4929static struct id_map *find_mapped_hostid_entry(const struct list_head *idmap,
c4333195 4930 unsigned id, enum idtype idtype)
f8aa4bf3 4931{
f8aa4bf3 4932 struct id_map *retmap = NULL;
0589d744 4933 struct id_map *map;
f8aa4bf3 4934
0589d744 4935 list_for_each_entry(map, idmap, head) {
f8aa4bf3
CB
4936 if (map->idtype != idtype)
4937 continue;
4938
4939 if (id >= map->hostid && id < map->hostid + map->range) {
4940 retmap = map;
4941 break;
4942 }
4943 }
4944
f8aa4bf3
CB
4945 return retmap;
4946}
4947
0fd73091 4948/* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
f8aa4bf3 4949 * existing one or establish a new one.
4355ab5f 4950 */
7581a82f 4951static struct id_map *mapped_hostid_add(const struct lxc_conf *conf, uid_t id,
0fd73091 4952 enum idtype type)
4355ab5f 4953{
55022530 4954 __do_free struct id_map *entry = NULL;
28a2d9e7 4955 int hostid_mapped;
55022530 4956 struct id_map *tmp = NULL;
c4333195 4957
b8e43ef0 4958 entry = zalloc(sizeof(*entry));
c4333195
CB
4959 if (!entry)
4960 return NULL;
f8aa4bf3 4961
28a2d9e7 4962 /* Reuse existing mapping. */
86c78011 4963 tmp = find_mapped_hostid_entry(&conf->id_map, id, type);
1758c195
CB
4964 if (tmp) {
4965 memcpy(entry, tmp, sizeof(*entry));
4966 } else {
4967 /* Find new mapping. */
4968 hostid_mapped = find_unmapped_nsid(conf, type);
4969 if (hostid_mapped < 0)
4970 return log_debug(NULL, "Failed to find free mapping for id %d", id);
4971
4972 entry->idtype = type;
4973 entry->nsid = hostid_mapped;
4974 entry->hostid = (unsigned long)id;
4975 entry->range = 1;
4976 }
4355ab5f 4977
55022530 4978 return move_ptr(entry);
4355ab5f
SH
4979}
4980
0589d744
CB
4981static int get_minimal_idmap(const struct lxc_conf *conf, uid_t *resuid,
4982 gid_t *resgid, struct list_head *head_ret)
4355ab5f 4983{
00d6cfe2
CB
4984 __do_free struct id_map *container_root_uid = NULL,
4985 *container_root_gid = NULL,
4986 *host_uid_map = NULL, *host_gid_map = NULL;
f8aa4bf3 4987 uid_t euid, egid;
4160c3a0
CB
4988 uid_t nsuid = (conf->root_nsuid_map != NULL) ? 0 : conf->init_uid;
4989 gid_t nsgid = (conf->root_nsgid_map != NULL) ? 0 : conf->init_gid;
4355ab5f 4990
db7cfe23 4991 /* Find container root mappings. */
4160c3a0 4992 container_root_uid = mapped_nsid_add(conf, nsuid, ID_TYPE_UID);
55022530 4993 if (!container_root_uid)
0589d744 4994 return sysdebug("Failed to find mapping for namespace uid %d", 0);
dcf0ffdf
CB
4995 euid = geteuid();
4996 if (euid >= container_root_uid->hostid &&
4997 euid < (container_root_uid->hostid + container_root_uid->range))
2c996219 4998 host_uid_map = move_ptr(container_root_uid);
f8aa4bf3 4999
4160c3a0 5000 container_root_gid = mapped_nsid_add(conf, nsgid, ID_TYPE_GID);
55022530 5001 if (!container_root_gid)
0589d744 5002 return sysdebug("Failed to find mapping for namespace gid %d", 0);
dcf0ffdf
CB
5003 egid = getegid();
5004 if (egid >= container_root_gid->hostid &&
5005 egid < (container_root_gid->hostid + container_root_gid->range))
2c996219 5006 host_gid_map = move_ptr(container_root_gid);
f8aa4bf3
CB
5007
5008 /* Check whether the {g,u}id of the user has a mapping. */
954b7d9b 5009 if (!host_uid_map)
c4333195 5010 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
55022530 5011 if (!host_uid_map)
0589d744 5012 return sysdebug("Failed to find mapping for uid %d", euid);
f8aa4bf3 5013
dcf0ffdf
CB
5014 if (!host_gid_map)
5015 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
55022530 5016 if (!host_gid_map)
0589d744 5017 return sysdebug("Failed to find mapping for gid %d", egid);
28a2d9e7 5018
47649d5b 5019 /* idmap will now keep track of that memory. */
0589d744
CB
5020 list_add_tail(&host_uid_map->head, head_ret);
5021 move_ptr(host_uid_map);
28a2d9e7 5022
2c996219 5023 if (container_root_uid) {
47649d5b 5024 /* idmap will now keep track of that memory. */
0589d744
CB
5025 list_add_tail(&container_root_uid->head, head_ret);
5026 move_ptr(container_root_uid);
28a2d9e7 5027 }
f8aa4bf3 5028
47649d5b 5029 /* idmap will now keep track of that memory. */
0589d744
CB
5030 list_add_tail(&host_gid_map->head, head_ret);
5031 move_ptr(host_gid_map);
28a2d9e7 5032
2c996219 5033 if (container_root_gid) {
47649d5b 5034 /* idmap will now keep track of that memory. */
0589d744
CB
5035 list_add_tail(&container_root_gid->head, head_ret);
5036 move_ptr(container_root_gid);
28a2d9e7 5037 }
f8aa4bf3 5038
dbfcdf86
CB
5039 TRACE("Allocated minimal idmapping for ns uid %d and ns gid %d", nsuid, nsgid);
5040
5041 if (resuid)
5042 *resuid = nsuid;
5043 if (resgid)
5044 *resgid = nsgid;
0589d744
CB
5045
5046 return 0;
dcf0ffdf
CB
5047}
5048
766c5b6d
CB
5049/*
5050 * Run a function in a new user namespace.
dcf0ffdf
CB
5051 * The caller's euid/egid will be mapped if it is not already.
5052 * Afaict, userns_exec_1() is only used to operate based on privileges for the
5053 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
5054 * This means we require only to establish a mapping from:
5055 * - the container root {g,u}id as seen from the host > user's host {g,u}id
5056 * - the container root -> some sub{g,u}id
915e3dbd 5057 * The former we add, if the user did not specify a mapping. The latter we
6f3fd27f 5058 * retrieve from the container's configured {g,u}id mappings as it must have been
dcf0ffdf
CB
5059 * there to start the container in the first place.
5060 */
7581a82f 5061int userns_exec_1(const struct lxc_conf *conf, int (*fn)(void *), void *data,
dcf0ffdf
CB
5062 const char *fn_name)
5063{
0589d744
CB
5064 LIST_HEAD(minimal_idmap);
5065 call_cleaner(__lxc_free_idmap) struct list_head *idmap = &minimal_idmap;
0fd73091
CB
5066 int ret = -1, status = -1;
5067 char c = '1';
46bc6f2a
CB
5068 struct userns_fn_data d = {
5069 .arg = data,
5070 .fn = fn,
5071 .fn_name = fn_name,
5072 };
766c5b6d
CB
5073 pid_t pid;
5074 int pipe_fds[2];
dcf0ffdf 5075
2b2655a8
CB
5076 if (!conf)
5077 return -EINVAL;
5078
0589d744
CB
5079 ret = get_minimal_idmap(conf, NULL, NULL, idmap);
5080 if (ret)
766c5b6d 5081 return ret_errno(ENOENT);
dcf0ffdf 5082
766c5b6d
CB
5083 ret = pipe2(pipe_fds, O_CLOEXEC);
5084 if (ret < 0)
5085 return -errno;
5086
766c5b6d
CB
5087 d.p[0] = pipe_fds[0];
5088 d.p[1] = pipe_fds[1];
dcf0ffdf
CB
5089
5090 /* Clone child in new user namespace. */
a59440be 5091 pid = lxc_raw_clone_cb(run_userns_fn, &d, CLONE_NEWUSER, NULL);
dcf0ffdf 5092 if (pid < 0) {
0fd73091 5093 ERROR("Failed to clone process in new user namespace");
dcf0ffdf
CB
5094 goto on_error;
5095 }
5096
766c5b6d 5097 close_prot_errno_disarm(pipe_fds[0]);
dcf0ffdf 5098
62fef886 5099 if (lxc_log_trace()) {
dcf0ffdf
CB
5100 struct id_map *map;
5101
0589d744 5102 list_for_each_entry(map, idmap, head)
766c5b6d
CB
5103 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5104 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
4355ab5f
SH
5105 }
5106
f8aa4bf3 5107 /* Set up {g,u}id mapping for user namespace of child process. */
4355ab5f 5108 ret = lxc_map_ids(idmap, pid);
f8aa4bf3 5109 if (ret < 0) {
0fd73091 5110 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
f8aa4bf3 5111 goto on_error;
4355ab5f
SH
5112 }
5113
f8aa4bf3 5114 /* Tell child to proceed. */
766c5b6d 5115 if (lxc_write_nointr(pipe_fds[1], &c, 1) != 1) {
dcf0ffdf 5116 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
f8aa4bf3 5117 goto on_error;
4355ab5f
SH
5118 }
5119
686dd5d1 5120on_error:
766c5b6d
CB
5121 close_prot_errno_disarm(pipe_fds[0]);
5122 close_prot_errno_disarm(pipe_fds[1]);
f8aa4bf3 5123
ee1b16bc
TA
5124 /* Wait for child to finish. */
5125 if (pid > 0)
5126 status = wait_for_pid(pid);
5127
686dd5d1
CB
5128 if (status < 0)
5129 ret = -1;
5130
f8aa4bf3 5131 return ret;
4355ab5f 5132}
97e9cfa0 5133
d1783ef4
CB
5134int userns_exec_minimal(const struct lxc_conf *conf,
5135 int (*fn_parent)(void *), void *fn_parent_data,
5136 int (*fn_child)(void *), void *fn_child_data)
edf88289 5137{
0589d744
CB
5138 LIST_HEAD(minimal_idmap);
5139 call_cleaner(__lxc_free_idmap) struct list_head *idmap = &minimal_idmap;
dbfcdf86
CB
5140 uid_t resuid = LXC_INVALID_UID;
5141 gid_t resgid = LXC_INVALID_GID;
edf88289 5142 char c = '1';
dbfcdf86 5143 ssize_t ret;
edf88289
CB
5144 pid_t pid;
5145 int sock_fds[2];
5146
d1783ef4 5147 if (!conf || !fn_child)
dbfcdf86 5148 return ret_errno(EINVAL);
edf88289 5149
0589d744
CB
5150 ret = get_minimal_idmap(conf, &resuid, &resgid, idmap);
5151 if (ret)
edf88289
CB
5152 return ret_errno(ENOENT);
5153
5154 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5155 if (ret < 0)
5156 return -errno;
5157
5158 pid = fork();
5159 if (pid < 0) {
dbfcdf86 5160 SYSERROR("Failed to create new process");
edf88289
CB
5161 goto on_error;
5162 }
5163
5164 if (pid == 0) {
5165 close_prot_errno_disarm(sock_fds[1]);
5166
5167 ret = unshare(CLONE_NEWUSER);
dbfcdf86
CB
5168 if (ret < 0) {
5169 SYSERROR("Failed to unshare new user namespace");
edf88289 5170 _exit(EXIT_FAILURE);
dbfcdf86 5171 }
edf88289 5172
dbfcdf86
CB
5173 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5174 if (ret != 1)
edf88289
CB
5175 _exit(EXIT_FAILURE);
5176
5177 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5178 if (ret != 1)
5179 _exit(EXIT_FAILURE);
5180
5181 close_prot_errno_disarm(sock_fds[0]);
5182
8917c382 5183 if (!lxc_drop_groups() && errno != EPERM)
edf88289
CB
5184 _exit(EXIT_FAILURE);
5185
dbfcdf86
CB
5186 ret = setresgid(resgid, resgid, resgid);
5187 if (ret < 0) {
5188 SYSERROR("Failed to setresgid(%d, %d, %d)",
5189 resgid, resgid, resgid);
edf88289 5190 _exit(EXIT_FAILURE);
dbfcdf86
CB
5191 }
5192
5193 ret = setresuid(resuid, resuid, resuid);
5194 if (ret < 0) {
5195 SYSERROR("Failed to setresuid(%d, %d, %d)",
5196 resuid, resuid, resuid);
5197 _exit(EXIT_FAILURE);
5198 }
edf88289 5199
d1783ef4 5200 ret = fn_child(fn_child_data);
dbfcdf86
CB
5201 if (ret) {
5202 SYSERROR("Running function in new user namespace failed");
edf88289 5203 _exit(EXIT_FAILURE);
dbfcdf86 5204 }
edf88289
CB
5205
5206 _exit(EXIT_SUCCESS);
5207 }
5208
5209 close_prot_errno_disarm(sock_fds[0]);
5210
62fef886 5211 if (lxc_log_trace()) {
edf88289 5212 struct id_map *map;
edf88289 5213
0589d744 5214 list_for_each_entry(map, idmap, head)
edf88289
CB
5215 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5216 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
edf88289
CB
5217 }
5218
5219 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5220 if (ret != 1) {
5221 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5222 goto on_error;
5223 }
5224
5225 /* Set up {g,u}id mapping for user namespace of child process. */
5226 ret = lxc_map_ids(idmap, pid);
5227 if (ret < 0) {
5228 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5229 goto on_error;
5230 }
5231
5232 /* Tell child to proceed. */
5233 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5234 if (ret != 1) {
5235 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5236 goto on_error;
5237 }
5238
d1783ef4
CB
5239 if (fn_parent && fn_parent(fn_parent_data)) {
5240 SYSERROR("Running parent function failed");
5241 _exit(EXIT_FAILURE);
5242 }
5243
edf88289
CB
5244on_error:
5245 close_prot_errno_disarm(sock_fds[0]);
5246 close_prot_errno_disarm(sock_fds[1]);
5247
5248 /* Wait for child to finish. */
dbfcdf86
CB
5249 if (pid < 0)
5250 return -1;
edf88289 5251
dbfcdf86 5252 return wait_for_pid(pid);
edf88289
CB
5253}
5254
415a8851
CB
5255int userns_exec_full(struct lxc_conf *conf, int (*fn)(void *), void *data,
5256 const char *fn_name)
5257{
0589d744
CB
5258 LIST_HEAD(full_idmap);
5259 int ret = -1;
5260 char c = '1';
5261 struct id_map *container_root_uid = NULL, *container_root_gid = NULL,
5262 *host_uid_map = NULL, *host_gid_map = NULL;
415a8851
CB
5263 pid_t pid;
5264 uid_t euid, egid;
415a8851
CB
5265 int p[2];
5266 struct id_map *map;
0fd73091 5267 struct userns_fn_data d;
415a8851 5268
2b2655a8
CB
5269 if (!conf)
5270 return -EINVAL;
5271
979f9e34 5272 ret = pipe2(p, O_CLOEXEC);
0589d744
CB
5273 if (ret < 0)
5274 return -errno;
5275
415a8851
CB
5276 d.fn = fn;
5277 d.fn_name = fn_name;
5278 d.arg = data;
5279 d.p[0] = p[0];
5280 d.p[1] = p[1];
5281
5282 /* Clone child in new user namespace. */
33258b95 5283 pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER, NULL);
415a8851 5284 if (pid < 0) {
0fd73091 5285 ERROR("Failed to clone process in new user namespace");
415a8851
CB
5286 goto on_error;
5287 }
5288
5289 close(p[0]);
5290 p[0] = -1;
5291
5292 euid = geteuid();
5293 egid = getegid();
5294
415a8851 5295 /* Find container root. */
0589d744
CB
5296 list_for_each_entry(map, &conf->id_map, head) {
5297 __do_free struct id_map *dup_map = NULL;
415a8851 5298
0589d744
CB
5299 dup_map = memdup(map, sizeof(struct id_map));
5300 if (!dup_map)
415a8851
CB
5301 goto on_error;
5302
0589d744
CB
5303 list_add_tail(&dup_map->head, &full_idmap);
5304 move_ptr(dup_map);
415a8851
CB
5305
5306 if (map->idtype == ID_TYPE_UID)
5307 if (euid >= map->hostid && euid < map->hostid + map->range)
5308 host_uid_map = map;
5309
5310 if (map->idtype == ID_TYPE_GID)
5311 if (egid >= map->hostid && egid < map->hostid + map->range)
5312 host_gid_map = map;
5313
5314 if (map->nsid != 0)
5315 continue;
5316
5317 if (map->idtype == ID_TYPE_UID)
5318 if (container_root_uid == NULL)
5319 container_root_uid = map;
5320
5321 if (map->idtype == ID_TYPE_GID)
5322 if (container_root_gid == NULL)
5323 container_root_gid = map;
5324 }
5325
5326 if (!container_root_uid || !container_root_gid) {
5327 ERROR("No mapping for container root found");
5328 goto on_error;
5329 }
5330
5331 /* Check whether the {g,u}id of the user has a mapping. */
5332 if (!host_uid_map)
c4333195 5333 host_uid_map = mapped_hostid_add(conf, euid, ID_TYPE_UID);
415a8851
CB
5334 else
5335 host_uid_map = container_root_uid;
5336
5337 if (!host_gid_map)
c4333195 5338 host_gid_map = mapped_hostid_add(conf, egid, ID_TYPE_GID);
415a8851
CB
5339 else
5340 host_gid_map = container_root_gid;
5341
5342 if (!host_uid_map) {
5343 DEBUG("Failed to find mapping for uid %d", euid);
5344 goto on_error;
5345 }
5346
5347 if (!host_gid_map) {
5348 DEBUG("Failed to find mapping for gid %d", egid);
5349 goto on_error;
5350 }
5351
5352 if (host_uid_map && (host_uid_map != container_root_uid)) {
0589d744
CB
5353 /* idmap will now keep track of that memory. */
5354 list_add_tail(&host_uid_map->head, &full_idmap);
5355 move_ptr(host_uid_map);
415a8851 5356 }
415a8851
CB
5357
5358 if (host_gid_map && (host_gid_map != container_root_gid)) {
0589d744
CB
5359 /* idmap will now keep track of that memory. */
5360 list_add_tail(&host_gid_map->head, &full_idmap);
5361 move_ptr(host_gid_map);
415a8851 5362 }
415a8851 5363
62fef886 5364 if (lxc_log_trace()) {
0589d744
CB
5365 list_for_each_entry(map, &full_idmap, head) {
5366 TRACE("establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
415a8851
CB
5367 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid,
5368 map->nsid, map->hostid, map->range);
5369 }
5370 }
5371
5372 /* Set up {g,u}id mapping for user namespace of child process. */
0589d744 5373 ret = lxc_map_ids(&full_idmap, pid);
415a8851 5374 if (ret < 0) {
0fd73091 5375 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid);
415a8851
CB
5376 goto on_error;
5377 }
5378
5379 /* Tell child to proceed. */
489f39be 5380 if (lxc_write_nointr(p[1], &c, 1) != 1) {
0fd73091 5381 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
415a8851
CB
5382 goto on_error;
5383 }
5384
686dd5d1 5385on_error:
ee1b16bc
TA
5386 if (p[0] != -1)
5387 close(p[0]);
5388 close(p[1]);
5389
415a8851 5390 /* Wait for child to finish. */
686dd5d1
CB
5391 if (pid > 0)
5392 ret = wait_for_pid(pid);
415a8851 5393
0589d744 5394 __lxc_free_idmap(&full_idmap);
80758b4b 5395
415a8851
CB
5396 if (host_uid_map && (host_uid_map != container_root_uid))
5397 free(host_uid_map);
5398 if (host_gid_map && (host_gid_map != container_root_gid))
5399 free(host_gid_map);
5400
415a8851
CB
5401 return ret;
5402}
5403
0589d744 5404static int add_idmap_entry(struct list_head *idmap_list, enum idtype idtype,
234998b4
CB
5405 unsigned long nsid, unsigned long hostid,
5406 unsigned long range)
5407{
5408 __do_free struct id_map *new_idmap = NULL;
234998b4
CB
5409
5410 new_idmap = zalloc(sizeof(*new_idmap));
5411 if (!new_idmap)
5412 return ret_errno(ENOMEM);
5413
5414 new_idmap->idtype = idtype;
5415 new_idmap->hostid = hostid;
5416 new_idmap->nsid = nsid;
5417 new_idmap->range = range;
5418
0589d744
CB
5419 list_add_tail(&new_idmap->head, idmap_list);
5420 move_ptr(new_idmap);
234998b4
CB
5421
5422 INFO("Adding id map: type %c nsid %lu hostid %lu range %lu",
5423 idtype == ID_TYPE_UID ? 'u' : 'g', nsid, hostid, range);
5424 return 0;
5425}
5426
5427int userns_exec_mapped_root(const char *path, int path_fd,
5428 const struct lxc_conf *conf)
5429{
0589d744
CB
5430 LIST_HEAD(idmap_list);
5431 call_cleaner(__lxc_free_idmap) struct list_head *idmap = &idmap_list;
234998b4
CB
5432 __do_close int fd = -EBADF;
5433 int target_fd = -EBADF;
5434 char c = '1';
5435 ssize_t ret;
5436 pid_t pid;
5437 int sock_fds[2];
5438 uid_t container_host_uid, hostuid;
5439 gid_t container_host_gid, hostgid;
5440 struct stat st;
5441
5442 if (!conf || (!path && path_fd < 0))
5443 return ret_errno(EINVAL);
5444
5445 if (!path)
5446 path = "(null)";
5447
5448 container_host_uid = get_mapped_rootid(conf, ID_TYPE_UID);
5449 if (!uid_valid(container_host_uid))
5450 return log_error(-1, "No uid mapping for container root");
5451
5452 container_host_gid = get_mapped_rootid(conf, ID_TYPE_GID);
5453 if (!gid_valid(container_host_gid))
5454 return log_error(-1, "No gid mapping for container root");
5455
cf68ffd9 5456 if (path_fd < 0) {
a72c68f7 5457 fd = open(path, O_CLOEXEC | O_NOCTTY);
234998b4
CB
5458 if (fd < 0)
5459 return log_error_errno(-errno, errno, "Failed to open \"%s\"", path);
5460 target_fd = fd;
5461 } else {
5462 target_fd = path_fd;
5463 }
5464
5465 hostuid = geteuid();
5466 /* We are root so chown directly. */
5467 if (hostuid == 0) {
5468 ret = fchown(target_fd, container_host_uid, container_host_gid);
5469 if (ret)
5470 return log_error_errno(-errno, errno,
5471 "Failed to fchown(%d(%s), %d, %d)",
5472 target_fd, path, container_host_uid,
5473 container_host_gid);
5474 return log_trace(0, "Chowned %d(%s) to uid %d and %d", target_fd, path,
5475 container_host_uid, container_host_gid);
5476 }
5477
5478 /* The container's root host id matches */
5479 if (container_host_uid == hostuid)
5480 return log_info(0, "Container root id is mapped to our uid");
5481
5482 /* Get the current ids of our target. */
5483 ret = fstat(target_fd, &st);
5484 if (ret)
5485 return log_error_errno(-errno, errno, "Failed to stat \"%s\"", path);
5486
5487 hostgid = getegid();
5488 if (st.st_uid == hostuid && mapped_hostid(st.st_gid, conf, ID_TYPE_GID) < 0) {
5489 ret = fchown(target_fd, -1, hostgid);
5490 if (ret)
5491 return log_error_errno(-errno, errno,
5492 "Failed to fchown(%d(%s), -1, %d)",
5493 target_fd, path, hostgid);
2e8013f9 5494 TRACE("Chowned %d(%s) to -1:%d", target_fd, path, hostgid);
234998b4
CB
5495 }
5496
234998b4
CB
5497 /* "u:0:rootuid:1" */
5498 ret = add_idmap_entry(idmap, ID_TYPE_UID, 0, container_host_uid, 1);
5499 if (ret < 0)
5500 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5501
5502 /* "u:hostuid:hostuid:1" */
5503 ret = add_idmap_entry(idmap, ID_TYPE_UID, hostuid, hostuid, 1);
5504 if (ret < 0)
5505 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5506
5507 /* "g:0:rootgid:1" */
5508 ret = add_idmap_entry(idmap, ID_TYPE_GID, 0, container_host_gid, 1);
5509 if (ret < 0)
5510 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5511
5512 /* "g:hostgid:hostgid:1" */
5513 ret = add_idmap_entry(idmap, ID_TYPE_GID, hostgid, hostgid, 1);
5514 if (ret < 0)
5515 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5516
5517 if (hostgid != st.st_gid) {
5518 /* "g:pathgid:rootgid+pathgid:1" */
5519 ret = add_idmap_entry(idmap, ID_TYPE_GID, st.st_gid,
5520 container_host_gid + (gid_t)st.st_gid, 1);
5521 if (ret < 0)
5522 return log_error_errno(ret, -ret, "Failed to add idmap entry");
5523 }
5524
5525 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sock_fds);
5526 if (ret < 0)
5527 return -errno;
5528
5529 pid = fork();
5530 if (pid < 0) {
5531 SYSERROR("Failed to create new process");
5532 goto on_error;
5533 }
5534
5535 if (pid == 0) {
5536 close_prot_errno_disarm(sock_fds[1]);
5537
5538 ret = unshare(CLONE_NEWUSER);
5539 if (ret < 0) {
5540 SYSERROR("Failed to unshare new user namespace");
5541 _exit(EXIT_FAILURE);
5542 }
5543
5544 ret = lxc_write_nointr(sock_fds[0], &c, 1);
5545 if (ret != 1)
5546 _exit(EXIT_FAILURE);
5547
5548 ret = lxc_read_nointr(sock_fds[0], &c, 1);
5549 if (ret != 1)
5550 _exit(EXIT_FAILURE);
5551
5552 close_prot_errno_disarm(sock_fds[0]);
5553
5554 if (!lxc_switch_uid_gid(0, 0))
5555 _exit(EXIT_FAILURE);
5556
8917c382 5557 if (!lxc_drop_groups())
234998b4
CB
5558 _exit(EXIT_FAILURE);
5559
8053a085 5560 ret = fchown(target_fd, 0, st.st_gid);
234998b4 5561 if (ret) {
8ea93a0f 5562 SYSERROR("Failed to chown %d(%s) to 0:%d", target_fd, path, st.st_gid);
234998b4
CB
5563 _exit(EXIT_FAILURE);
5564 }
5565
2e8013f9 5566 TRACE("Chowned %d(%s) to 0:%d", target_fd, path, st.st_gid);
234998b4
CB
5567 _exit(EXIT_SUCCESS);
5568 }
5569
5570 close_prot_errno_disarm(sock_fds[0]);
5571
62fef886 5572 if (lxc_log_trace()) {
234998b4 5573 struct id_map *map;
234998b4 5574
0589d744 5575 list_for_each_entry(map, idmap, head)
234998b4
CB
5576 TRACE("Establishing %cid mapping for \"%d\" in new user namespace: nsuid %lu - hostid %lu - range %lu",
5577 (map->idtype == ID_TYPE_UID) ? 'u' : 'g', pid, map->nsid, map->hostid, map->range);
234998b4
CB
5578 }
5579
5580 ret = lxc_read_nointr(sock_fds[1], &c, 1);
5581 if (ret != 1) {
5582 SYSERROR("Failed waiting for child process %d\" to tell us to proceed", pid);
5583 goto on_error;
5584 }
5585
5586 /* Set up {g,u}id mapping for user namespace of child process. */
5587 ret = lxc_map_ids(idmap, pid);
5588 if (ret < 0) {
5589 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid);
5590 goto on_error;
5591 }
5592
5593 /* Tell child to proceed. */
5594 ret = lxc_write_nointr(sock_fds[1], &c, 1);
5595 if (ret != 1) {
5596 SYSERROR("Failed telling child process \"%d\" to proceed", pid);
5597 goto on_error;
5598 }
5599
5600on_error:
5601 close_prot_errno_disarm(sock_fds[0]);
5602 close_prot_errno_disarm(sock_fds[1]);
5603
5604 /* Wait for child to finish. */
5605 if (pid < 0)
5606 return -1;
5607
5608 return wait_for_pid(pid);
5609}
5610
a96a8e8c 5611/* not thread-safe, do not use from api without first forking */
0fd73091 5612static char *getuname(void)
97e9cfa0 5613{
4f410b2a 5614 __do_free char *buf = NULL;
cb7aa5e8
DJ
5615 struct passwd pwent;
5616 struct passwd *pwentp = NULL;
cb7aa5e8
DJ
5617 size_t bufsize;
5618 int ret;
97e9cfa0 5619
cb7aa5e8
DJ
5620 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
5621 if (bufsize == -1)
5622 bufsize = 1024;
5623
b8e43ef0 5624 buf = zalloc(bufsize);
cb7aa5e8 5625 if (!buf)
97e9cfa0
SH
5626 return NULL;
5627
cb7aa5e8
DJ
5628 ret = getpwuid_r(geteuid(), &pwent, buf, bufsize, &pwentp);
5629 if (!pwentp) {
5630 if (ret == 0)
5631 WARN("Could not find matched password record.");
5632
55022530 5633 return log_error(NULL, "Failed to get password record - %u", geteuid());
cb7aa5e8
DJ
5634 }
5635
4f410b2a 5636 return strdup(pwent.pw_name);
97e9cfa0
SH
5637}
5638
a96a8e8c 5639/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
5640static char *getgname(void)
5641{
4f410b2a 5642 __do_free char *buf = NULL;
3de9fb4c
DJ
5643 struct group grent;
5644 struct group *grentp = NULL;
3de9fb4c
DJ
5645 size_t bufsize;
5646 int ret;
5647
5648 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
5649 if (bufsize == -1)
5650 bufsize = 1024;
5651
b8e43ef0 5652 buf = zalloc(bufsize);
3de9fb4c
DJ
5653 if (!buf)
5654 return NULL;
5655
5656 ret = getgrgid_r(getegid(), &grent, buf, bufsize, &grentp);
5657 if (!grentp) {
5658 if (ret == 0)
5659 WARN("Could not find matched group record");
97e9cfa0 5660
55022530 5661 return log_error(NULL, "Failed to get group record - %u", getegid());
3de9fb4c
DJ
5662 }
5663
4f410b2a 5664 return strdup(grent.gr_name);
97e9cfa0
SH
5665}
5666
a96a8e8c 5667/* not thread-safe, do not use from api without first forking */
97e9cfa0
SH
5668void suggest_default_idmap(void)
5669{
3a6e3bf5 5670 __do_free char *gname = NULL, *line = NULL, *uname = NULL;
4aae564f 5671 __do_fclose FILE *subuid_f = NULL, *subgid_f = NULL;
97e9cfa0 5672 unsigned int uid = 0, urange = 0, gid = 0, grange = 0;
97e9cfa0
SH
5673 size_t len = 0;
5674
0fd73091
CB
5675 uname = getuname();
5676 if (!uname)
97e9cfa0
SH
5677 return;
5678
0fd73091 5679 gname = getgname();
3a6e3bf5 5680 if (!gname)
97e9cfa0 5681 return;
97e9cfa0 5682
4110345b 5683 subuid_f = fopen(subuidfile, "re");
4aae564f 5684 if (!subuid_f) {
97e9cfa0 5685 ERROR("Your system is not configured with subuids");
97e9cfa0
SH
5686 return;
5687 }
0fd73091 5688
4aae564f 5689 while (getline(&line, &len, subuid_f) != -1) {
0fd73091 5690 char *p, *p2;
b7930180 5691 size_t no_newline = 0;
0fd73091
CB
5692
5693 p = strchr(line, ':');
97e9cfa0
SH
5694 if (*line == '#')
5695 continue;
5696 if (!p)
5697 continue;
5698 *p = '\0';
5699 p++;
0fd73091 5700
71528742 5701 if (!strequal(line, uname))
97e9cfa0 5702 continue;
0fd73091 5703
97e9cfa0
SH
5704 p2 = strchr(p, ':');
5705 if (!p2)
5706 continue;
5707 *p2 = '\0';
5708 p2++;
5709 if (!*p2)
5710 continue;
b7930180
CB
5711 no_newline = strcspn(p2, "\n");
5712 p2[no_newline] = '\0';
5713
b7b2fde4 5714 if (lxc_safe_uint(p, &uid) < 0)
0fd73091 5715 WARN("Could not parse UID");
b7b2fde4 5716 if (lxc_safe_uint(p2, &urange) < 0)
0fd73091 5717 WARN("Could not parse UID range");
97e9cfa0 5718 }
97e9cfa0 5719
4110345b 5720 subgid_f = fopen(subgidfile, "re");
4aae564f 5721 if (!subgid_f) {
97e9cfa0 5722 ERROR("Your system is not configured with subgids");
97e9cfa0
SH
5723 return;
5724 }
0fd73091 5725
4aae564f 5726 while (getline(&line, &len, subgid_f) != -1) {
0fd73091 5727 char *p, *p2;
b7930180 5728 size_t no_newline = 0;
0fd73091
CB
5729
5730 p = strchr(line, ':');
97e9cfa0
SH
5731 if (*line == '#')
5732 continue;
5733 if (!p)
5734 continue;
5735 *p = '\0';
5736 p++;
0fd73091 5737
71528742 5738 if (!strequal(line, uname))
97e9cfa0 5739 continue;
0fd73091 5740
97e9cfa0
SH
5741 p2 = strchr(p, ':');
5742 if (!p2)
5743 continue;
5744 *p2 = '\0';
5745 p2++;
5746 if (!*p2)
5747 continue;
b7930180
CB
5748 no_newline = strcspn(p2, "\n");
5749 p2[no_newline] = '\0';
5750
b7b2fde4 5751 if (lxc_safe_uint(p, &gid) < 0)
0fd73091 5752 WARN("Could not parse GID");
b7b2fde4 5753 if (lxc_safe_uint(p2, &grange) < 0)
0fd73091 5754 WARN("Could not parse GID range");
97e9cfa0 5755 }
97e9cfa0 5756
97e9cfa0
SH
5757 if (!urange || !grange) {
5758 ERROR("You do not have subuids or subgids allocated");
5759 ERROR("Unprivileged containers require subuids and subgids");
5760 return;
5761 }
5762
5763 ERROR("You must either run as root, or define uid mappings");
5764 ERROR("To pass uid mappings to lxc-create, you could create");
5765 ERROR("~/.config/lxc/default.conf:");
5766 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG);
bdcbb6b3
CB
5767 ERROR("lxc.idmap = u 0 %u %u", uid, urange);
5768 ERROR("lxc.idmap = g 0 %u %u", gid, grange);
97e9cfa0 5769}
aaf26830 5770
0fd73091 5771/* Return the list of cgroup_settings sorted according to the following rules
aaf26830
KT
5772 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
5773 */
c9dbb8ed 5774void sort_cgroup_settings(struct lxc_conf *conf)
aaf26830 5775{
c9dbb8ed 5776 struct lxc_cgroup *cgroup, *memsw_limit, *ncgroup;
aaf26830 5777
0fd73091 5778 /* Iterate over the cgroup settings and copy them to the output list. */
c9dbb8ed
CB
5779 list_for_each_entry_safe(cgroup, ncgroup, &conf->cgroup, head) {
5780 if (strequal(cgroup->subsystem, "memory.memsw.limit_in_bytes")) {
aaf26830 5781 /* Store the memsw_limit location */
c9dbb8ed
CB
5782 memsw_limit = cgroup;
5783 } else if (memsw_limit && strequal(cgroup->subsystem, "memory.limit_in_bytes")) {
5784 /*
5785 * lxc.cgroup.memory.memsw.limit_in_bytes is found
0fd73091 5786 * before lxc.cgroup.memory.limit_in_bytes, swap these
c9dbb8ed
CB
5787 * two items.
5788 */
5789 list_swap(&memsw_limit->head, &cgroup->head);
aaf26830 5790 }
aaf26830 5791 }
a7307747 5792}