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