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