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