]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/nspawn/nspawn.c
27d26f980953da4f05101e709d9543eaa51d487e
[thirdparty/systemd.git] / src / nspawn / nspawn.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <getopt.h>
4 #include <linux/loop.h>
5 #include <net/if.h>
6 #include <stdlib.h>
7 #include <sys/file.h>
8 #include <sys/ioctl.h>
9 #include <sys/mount.h>
10 #include <sys/personality.h>
11 #include <sys/prctl.h>
12 #include <sys/wait.h>
13 #include <unistd.h>
14 #include "constants.h"
15
16 #if HAVE_SELINUX
17 #include <selinux/selinux.h>
18 #endif
19
20 #include "sd-bus.h"
21 #include "sd-daemon.h"
22 #include "sd-event.h"
23 #include "sd-id128.h"
24 #include "sd-netlink.h"
25
26 #include "alloc-util.h"
27 #include "barrier.h"
28 #include "base-filesystem.h"
29 #include "btrfs-util.h"
30 #include "build.h"
31 #include "bus-error.h"
32 #include "bus-locator.h"
33 #include "bus-util.h"
34 #include "cap-list.h"
35 #include "capability-util.h"
36 #include "cgroup-setup.h"
37 #include "cgroup-util.h"
38 #include "chase.h"
39 #include "common-signal.h"
40 #include "copy.h"
41 #include "cpu-set-util.h"
42 #include "dev-setup.h"
43 #include "devnum-util.h"
44 #include "discover-image.h"
45 #include "dissect-image.h"
46 #include "env-util.h"
47 #include "escape.h"
48 #include "ether-addr-util.h"
49 #include "extract-word.h"
50 #include "fd-util.h"
51 #include "fdset.h"
52 #include "fileio.h"
53 #include "format-util.h"
54 #include "fs-util.h"
55 #include "gpt.h"
56 #include "group-record.h"
57 #include "hexdecoct.h"
58 #include "hostname-setup.h"
59 #include "hostname-util.h"
60 #include "id128-util.h"
61 #include "image-policy.h"
62 #include "in-addr-util.h"
63 #include "io-util.h"
64 #include "log.h"
65 #include "loop-util.h"
66 #include "loopback-setup.h"
67 #include "machine-credential.h"
68 #include "main-func.h"
69 #include "missing_keyctl.h"
70 #include "missing_syscall.h"
71 #include "mkdir.h"
72 #include "mount-util.h"
73 #include "mountpoint-util.h"
74 #include "namespace-util.h"
75 #include "notify-recv.h"
76 #include "nspawn-bind-user.h"
77 #include "nspawn-cgroup.h"
78 #include "nspawn-expose-ports.h"
79 #include "nspawn-mount.h"
80 #include "nspawn-network.h"
81 #include "nspawn-oci.h"
82 #include "nspawn-register.h"
83 #include "nspawn-seccomp.h"
84 #include "nspawn-settings.h"
85 #include "nspawn-setuid.h"
86 #include "nspawn-stub-pid1.h"
87 #include "nspawn.h"
88 #include "nsresource.h"
89 #include "os-util.h"
90 #include "osc-context.h"
91 #include "pager.h"
92 #include "parse-argument.h"
93 #include "parse-util.h"
94 #include "path-util.h"
95 #include "pidref.h"
96 #include "polkit-agent.h"
97 #include "pretty-print.h"
98 #include "process-util.h"
99 #include "ptyfwd.h"
100 #include "random-util.h"
101 #include "raw-clone.h"
102 #include "resolve-util.h"
103 #include "rlimit-util.h"
104 #include "rm-rf.h"
105 #include "runtime-scope.h"
106 #include "seccomp-util.h"
107 #include "shift-uid.h"
108 #include "signal-util.h"
109 #include "siphash24.h"
110 #include "socket-util.h"
111 #include "stat-util.h"
112 #include "stdio-util.h"
113 #include "string-table.h"
114 #include "string-util.h"
115 #include "strv.h"
116 #include "sysctl-util.h"
117 #include "terminal-util.h"
118 #include "tmpfile-util.h"
119 #include "uid-classification.h"
120 #include "umask-util.h"
121 #include "unit-name.h"
122 #include "user-record.h"
123 #include "user-util.h"
124 #include "vpick.h"
125
126 /* The notify socket inside the container it can use to talk to nspawn using the sd_notify(3) protocol */
127 #define NSPAWN_NOTIFY_SOCKET_PATH "/run/host/notify"
128 #define NSPAWN_MOUNT_TUNNEL "/run/host/incoming"
129
130 #define EXIT_FORCE_RESTART 133
131
132 typedef enum ContainerStatus {
133 CONTAINER_TERMINATED,
134 CONTAINER_REBOOTED,
135 } ContainerStatus;
136
137 static char *arg_directory = NULL;
138 static char *arg_template = NULL;
139 static char *arg_chdir = NULL;
140 static char *arg_pivot_root_new = NULL;
141 static char *arg_pivot_root_old = NULL;
142 static char *arg_user = NULL;
143 static uid_t arg_uid = UID_INVALID;
144 static gid_t arg_gid = GID_INVALID;
145 static gid_t* arg_supplementary_gids = NULL;
146 static size_t arg_n_supplementary_gids = 0;
147 static sd_id128_t arg_uuid = {};
148 static char *arg_machine = NULL; /* The name used by the host to refer to this */
149 static char *arg_hostname = NULL; /* The name the payload sees by default */
150 static const char *arg_selinux_context = NULL;
151 static const char *arg_selinux_apifs_context = NULL;
152 static char *arg_slice = NULL;
153 static bool arg_private_network; /* initialized depending on arg_privileged in run() */
154 static bool arg_read_only = false;
155 static StartMode arg_start_mode = START_PID1;
156 static bool arg_ephemeral = false;
157 static LinkJournal arg_link_journal = LINK_AUTO;
158 static bool arg_link_journal_try = false;
159 static uint64_t arg_caps_retain =
160 (1ULL << CAP_AUDIT_CONTROL) |
161 (1ULL << CAP_AUDIT_WRITE) |
162 (1ULL << CAP_CHOWN) |
163 (1ULL << CAP_DAC_OVERRIDE) |
164 (1ULL << CAP_DAC_READ_SEARCH) |
165 (1ULL << CAP_FOWNER) |
166 (1ULL << CAP_FSETID) |
167 (1ULL << CAP_IPC_OWNER) |
168 (1ULL << CAP_KILL) |
169 (1ULL << CAP_LEASE) |
170 (1ULL << CAP_LINUX_IMMUTABLE) |
171 (1ULL << CAP_MKNOD) |
172 (1ULL << CAP_NET_BIND_SERVICE) |
173 (1ULL << CAP_NET_BROADCAST) |
174 (1ULL << CAP_NET_RAW) |
175 (1ULL << CAP_SETFCAP) |
176 (1ULL << CAP_SETGID) |
177 (1ULL << CAP_SETPCAP) |
178 (1ULL << CAP_SETUID) |
179 (1ULL << CAP_SYS_ADMIN) |
180 (1ULL << CAP_SYS_BOOT) |
181 (1ULL << CAP_SYS_CHROOT) |
182 (1ULL << CAP_SYS_NICE) |
183 (1ULL << CAP_SYS_PTRACE) |
184 (1ULL << CAP_SYS_RESOURCE) |
185 (1ULL << CAP_SYS_TTY_CONFIG);
186 static uint64_t arg_caps_ambient = 0;
187 static CapabilityQuintet arg_full_capabilities = CAPABILITY_QUINTET_NULL;
188 static CustomMount *arg_custom_mounts = NULL;
189 static size_t arg_n_custom_mounts = 0;
190 static char **arg_setenv = NULL;
191 static bool arg_quiet = false;
192 static bool arg_register = true;
193 static bool arg_keep_unit = false;
194 static char **arg_network_interfaces = NULL;
195 static char **arg_network_macvlan = NULL;
196 static char **arg_network_ipvlan = NULL;
197 static bool arg_network_veth = false;
198 static char **arg_network_veth_extra = NULL;
199 static char *arg_network_bridge = NULL;
200 static char *arg_network_zone = NULL;
201 static char *arg_network_namespace_path = NULL;
202 struct ether_addr arg_network_provided_mac = {};
203 static PagerFlags arg_pager_flags = 0;
204 static unsigned long arg_personality = PERSONALITY_INVALID;
205 static char *arg_image = NULL;
206 static char *arg_oci_bundle = NULL;
207 static VolatileMode arg_volatile_mode = VOLATILE_NO;
208 static ExposePort *arg_expose_ports = NULL;
209 static char **arg_property = NULL;
210 static sd_bus_message *arg_property_message = NULL;
211 static UserNamespaceMode arg_userns_mode; /* initialized depending on arg_privileged in run() */
212 static uid_t arg_uid_shift = UID_INVALID, arg_uid_range = 0x10000U;
213 static UserNamespaceOwnership arg_userns_ownership = _USER_NAMESPACE_OWNERSHIP_INVALID;
214 static int arg_kill_signal = 0;
215 static SettingsMask arg_settings_mask = 0;
216 static int arg_settings_trusted = -1;
217 static char **arg_parameters = NULL;
218 static const char *arg_container_service_name = "systemd-nspawn";
219 static bool arg_notify_ready = false;
220 static bool arg_use_cgns = true;
221 static unsigned long arg_clone_ns_flags = CLONE_NEWIPC|CLONE_NEWPID|CLONE_NEWUTS;
222 static MountSettingsMask arg_mount_settings = MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_TMPFS_TMP;
223 static VeritySettings arg_verity_settings = VERITY_SETTINGS_DEFAULT;
224 static char **arg_syscall_allow_list = NULL;
225 static char **arg_syscall_deny_list = NULL;
226 #if HAVE_SECCOMP
227 static scmp_filter_ctx arg_seccomp = NULL;
228 #endif
229 static struct rlimit *arg_rlimit[_RLIMIT_MAX] = {};
230 static bool arg_no_new_privileges = false;
231 static int arg_oom_score_adjust = 0;
232 static bool arg_oom_score_adjust_set = false;
233 static CPUSet arg_cpu_set = {};
234 static ResolvConfMode arg_resolv_conf = RESOLV_CONF_AUTO;
235 static TimezoneMode arg_timezone = TIMEZONE_AUTO;
236 static unsigned arg_console_width = UINT_MAX, arg_console_height = UINT_MAX;
237 static DeviceNode* arg_extra_nodes = NULL;
238 static size_t arg_n_extra_nodes = 0;
239 static char **arg_sysctl = NULL;
240 static ConsoleMode arg_console_mode = _CONSOLE_MODE_INVALID;
241 static MachineCredentialContext arg_credentials = {};
242 static char **arg_bind_user = NULL;
243 static char *arg_bind_user_shell = NULL;
244 static bool arg_bind_user_shell_copy = false;
245 static bool arg_suppress_sync = false;
246 static char *arg_settings_filename = NULL;
247 static Architecture arg_architecture = _ARCHITECTURE_INVALID;
248 static ImagePolicy *arg_image_policy = NULL;
249 static char *arg_background = NULL;
250 static bool arg_privileged = false;
251 static bool arg_cleanup = false;
252 static bool arg_ask_password = true;
253
254 STATIC_DESTRUCTOR_REGISTER(arg_directory, freep);
255 STATIC_DESTRUCTOR_REGISTER(arg_template, freep);
256 STATIC_DESTRUCTOR_REGISTER(arg_chdir, freep);
257 STATIC_DESTRUCTOR_REGISTER(arg_pivot_root_new, freep);
258 STATIC_DESTRUCTOR_REGISTER(arg_pivot_root_old, freep);
259 STATIC_DESTRUCTOR_REGISTER(arg_user, freep);
260 STATIC_DESTRUCTOR_REGISTER(arg_supplementary_gids, freep);
261 STATIC_DESTRUCTOR_REGISTER(arg_machine, freep);
262 STATIC_DESTRUCTOR_REGISTER(arg_hostname, freep);
263 STATIC_DESTRUCTOR_REGISTER(arg_slice, freep);
264 STATIC_DESTRUCTOR_REGISTER(arg_setenv, strv_freep);
265 STATIC_DESTRUCTOR_REGISTER(arg_network_interfaces, strv_freep);
266 STATIC_DESTRUCTOR_REGISTER(arg_network_macvlan, strv_freep);
267 STATIC_DESTRUCTOR_REGISTER(arg_network_ipvlan, strv_freep);
268 STATIC_DESTRUCTOR_REGISTER(arg_network_veth_extra, strv_freep);
269 STATIC_DESTRUCTOR_REGISTER(arg_network_bridge, freep);
270 STATIC_DESTRUCTOR_REGISTER(arg_network_zone, freep);
271 STATIC_DESTRUCTOR_REGISTER(arg_network_namespace_path, freep);
272 STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
273 STATIC_DESTRUCTOR_REGISTER(arg_oci_bundle, freep);
274 STATIC_DESTRUCTOR_REGISTER(arg_property, strv_freep);
275 STATIC_DESTRUCTOR_REGISTER(arg_property_message, sd_bus_message_unrefp);
276 STATIC_DESTRUCTOR_REGISTER(arg_parameters, strv_freep);
277 STATIC_DESTRUCTOR_REGISTER(arg_verity_settings, verity_settings_done);
278 STATIC_DESTRUCTOR_REGISTER(arg_syscall_allow_list, strv_freep);
279 STATIC_DESTRUCTOR_REGISTER(arg_syscall_deny_list, strv_freep);
280 #if HAVE_SECCOMP
281 STATIC_DESTRUCTOR_REGISTER(arg_seccomp, seccomp_releasep);
282 #endif
283 STATIC_DESTRUCTOR_REGISTER(arg_credentials, machine_credential_context_done);
284 STATIC_DESTRUCTOR_REGISTER(arg_cpu_set, cpu_set_done);
285 STATIC_DESTRUCTOR_REGISTER(arg_sysctl, strv_freep);
286 STATIC_DESTRUCTOR_REGISTER(arg_bind_user, strv_freep);
287 STATIC_DESTRUCTOR_REGISTER(arg_bind_user_shell, freep);
288 STATIC_DESTRUCTOR_REGISTER(arg_settings_filename, freep);
289 STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
290 STATIC_DESTRUCTOR_REGISTER(arg_background, freep);
291
292 static int handle_arg_console(const char *arg) {
293 if (streq(arg, "help")) {
294 puts("autopipe\n"
295 "interactive\n"
296 "passive\n"
297 "pipe\n"
298 "read-only");
299 return 0;
300 }
301
302 if (streq(arg, "interactive"))
303 arg_console_mode = CONSOLE_INTERACTIVE;
304 else if (streq(arg, "read-only"))
305 arg_console_mode = CONSOLE_READ_ONLY;
306 else if (streq(arg, "passive"))
307 arg_console_mode = CONSOLE_PASSIVE;
308 else if (streq(arg, "pipe")) {
309 if (isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO))
310 log_full(arg_quiet ? LOG_DEBUG : LOG_NOTICE,
311 "Console mode 'pipe' selected, but standard input/output are connected to an interactive TTY. "
312 "Most likely you want to use 'interactive' console mode for proper interactivity and shell job control. "
313 "Proceeding anyway.");
314
315 arg_console_mode = CONSOLE_PIPE;
316 } else if (streq(arg, "autopipe")) {
317 if (isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO))
318 arg_console_mode = CONSOLE_INTERACTIVE;
319 else
320 arg_console_mode = CONSOLE_PIPE;
321 } else
322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown console mode: %s", optarg);
323
324 arg_settings_mask |= SETTING_CONSOLE_MODE;
325 return 1;
326 }
327
328 static int help(void) {
329 _cleanup_free_ char *link = NULL;
330 int r;
331
332 pager_open(arg_pager_flags);
333
334 r = terminal_urlify_man("systemd-nspawn", "1", &link);
335 if (r < 0)
336 return log_oom();
337
338 printf("%1$s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
339 "%5$sSpawn a command or OS in a lightweight container.%6$s\n\n"
340 " -h --help Show this help\n"
341 " --version Print version string\n"
342 " -q --quiet Do not show status information\n"
343 " --no-pager Do not pipe output into a pager\n"
344 " --settings=BOOLEAN Load additional settings from .nspawn file\n"
345 " --cleanup Clean up left-over mounts and underlying mount\n"
346 " points used by the container\n"
347 " --no-ask-password Do not prompt for password\n"
348 "\n%3$sImage:%4$s\n"
349 " -D --directory=PATH Root directory for the container\n"
350 " --template=PATH Initialize root directory from template directory,\n"
351 " if missing\n"
352 " -x --ephemeral Run container with snapshot of root directory, and\n"
353 " remove it after exit\n"
354 " -i --image=PATH Root file system disk image (or device node) for\n"
355 " the container\n"
356 " --image-policy=POLICY Specify disk image dissection policy\n"
357 " --oci-bundle=PATH OCI bundle directory\n"
358 " --read-only Mount the root directory read-only\n"
359 " --volatile[=MODE] Run the system in volatile mode\n"
360 " --root-hash=HASH Specify verity root hash for root disk image\n"
361 " --root-hash-sig=SIG Specify pkcs7 signature of root hash for verity\n"
362 " as a DER encoded PKCS7, either as a path to a file\n"
363 " or as an ASCII base64 encoded string prefixed by\n"
364 " 'base64:'\n"
365 " --verity-data=PATH Specify hash device for verity\n"
366 " --pivot-root=PATH[:PATH]\n"
367 " Pivot root to given directory in the container\n"
368 "\n%3$sExecution:%4$s\n"
369 " -a --as-pid2 Maintain a stub init as PID1, invoke binary as PID2\n"
370 " -b --boot Boot up full system (i.e. invoke init)\n"
371 " --chdir=PATH Set working directory in the container\n"
372 " -E --setenv=NAME[=VALUE] Pass an environment variable to PID 1\n"
373 " -u --user=USER Run the command under specified user or UID\n"
374 " --kill-signal=SIGNAL Select signal to use for shutting down PID 1\n"
375 " --notify-ready=BOOLEAN Receive notifications from the child init process\n"
376 " --suppress-sync=BOOLEAN\n"
377 " Suppress any form of disk data synchronization\n"
378 "\n%3$sSystem Identity:%4$s\n"
379 " -M --machine=NAME Set the machine name for the container\n"
380 " --hostname=NAME Override the hostname for the container\n"
381 " --uuid=UUID Set a specific machine UUID for the container\n"
382 "\n%3$sProperties:%4$s\n"
383 " -S --slice=SLICE Place the container in the specified slice\n"
384 " --property=NAME=VALUE Set scope unit property\n"
385 " --register=BOOLEAN Register container as machine\n"
386 " --keep-unit Do not register a scope for the machine, reuse\n"
387 " the service unit nspawn is running in\n"
388 "\n%3$sUser Namespacing:%4$s\n"
389 " --private-users=no Run without user namespacing\n"
390 " --private-users=yes|pick|identity|managed\n"
391 " Run within user namespace, autoselect UID/GID range\n"
392 " --private-users=UIDBASE[:NUIDS]\n"
393 " Similar, but with user configured UID/GID range\n"
394 " --private-users-ownership=MODE\n"
395 " Adjust ('chown') or map ('map') OS tree ownership\n"
396 " to private UID/GID range\n"
397 " -U Equivalent to --private-users=pick and\n"
398 " --private-users-ownership=auto\n"
399 "\n%3$sNetworking:%4$s\n"
400 " --private-network Disable network in container\n"
401 " --network-interface=HOSTIF[:CONTAINERIF]\n"
402 " Assign an existing network interface to the\n"
403 " container\n"
404 " --network-macvlan=HOSTIF[:CONTAINERIF]\n"
405 " Create a macvlan network interface based on an\n"
406 " existing network interface to the container\n"
407 " --network-ipvlan=HOSTIF[:CONTAINERIF]\n"
408 " Create an ipvlan network interface based on an\n"
409 " existing network interface to the container\n"
410 " -n --network-veth Add a virtual Ethernet connection between host\n"
411 " and container\n"
412 " --network-veth-extra=HOSTIF[:CONTAINERIF]\n"
413 " Add an additional virtual Ethernet link between\n"
414 " host and container\n"
415 " --network-bridge=INTERFACE\n"
416 " Add a virtual Ethernet connection to the container\n"
417 " and attach it to an existing bridge on the host\n"
418 " --network-zone=NAME Similar, but attach the new interface to an\n"
419 " automatically managed bridge interface\n"
420 " --network-namespace-path=PATH\n"
421 " Set network namespace to the one represented by\n"
422 " the specified kernel namespace file node\n"
423 " -p --port=[PROTOCOL:]HOSTPORT[:CONTAINERPORT]\n"
424 " Expose a container IP port on the host\n"
425 "\n%3$sSecurity:%4$s\n"
426 " --capability=CAP In addition to the default, retain specified\n"
427 " capability\n"
428 " --drop-capability=CAP Drop the specified capability from the default set\n"
429 " --ambient-capability=CAP\n"
430 " Sets the specified capability for the started\n"
431 " process. Not useful if booting a machine.\n"
432 " --no-new-privileges Set PR_SET_NO_NEW_PRIVS flag for container payload\n"
433 " --system-call-filter=LIST|~LIST\n"
434 " Permit/prohibit specific system calls\n"
435 " -Z --selinux-context=SECLABEL\n"
436 " Set the SELinux security context to be used by\n"
437 " processes in the container\n"
438 " -L --selinux-apifs-context=SECLABEL\n"
439 " Set the SELinux security context to be used by\n"
440 " API/tmpfs file systems in the container\n"
441 "\n%3$sResources:%4$s\n"
442 " --rlimit=NAME=LIMIT Set a resource limit for the payload\n"
443 " --oom-score-adjust=VALUE\n"
444 " Adjust the OOM score value for the payload\n"
445 " --cpu-affinity=CPUS Adjust the CPU affinity of the container\n"
446 " --personality=ARCH Pick personality for this container\n"
447 "\n%3$sIntegration:%4$s\n"
448 " --resolv-conf=MODE Select mode of /etc/resolv.conf initialization\n"
449 " --timezone=MODE Select mode of /etc/localtime initialization\n"
450 " --link-journal=MODE Link up guest journal, one of no, auto, guest, \n"
451 " host, try-guest, try-host\n"
452 " -j Equivalent to --link-journal=try-guest\n"
453 "\n%3$sMounts:%4$s\n"
454 " --bind=PATH[:PATH[:OPTIONS]]\n"
455 " Bind mount a file or directory from the host into\n"
456 " the container\n"
457 " --bind-ro=PATH[:PATH[:OPTIONS]\n"
458 " Similar, but creates a read-only bind mount\n"
459 " --inaccessible=PATH Over-mount file node with inaccessible node to mask\n"
460 " it\n"
461 " --tmpfs=PATH:[OPTIONS] Mount an empty tmpfs to the specified directory\n"
462 " --overlay=PATH[:PATH...]:PATH\n"
463 " Create an overlay mount from the host to \n"
464 " the container\n"
465 " --overlay-ro=PATH[:PATH...]:PATH\n"
466 " Similar, but creates a read-only overlay mount\n"
467 " --bind-user=NAME Bind user from host to container\n"
468 "\n%3$sInput/Output:%4$s\n"
469 " --console=MODE Select how stdin/stdout/stderr and /dev/console are\n"
470 " set up for the container.\n"
471 " -P --pipe Equivalent to --console=pipe\n"
472 " --background=COLOR Set ANSI color for background\n"
473 "\n%3$sCredentials:%4$s\n"
474 " --set-credential=ID:VALUE\n"
475 " Pass a credential with literal value to container.\n"
476 " --load-credential=ID:PATH\n"
477 " Load credential to pass to container from file or\n"
478 " AF_UNIX stream socket.\n"
479 "\nSee the %2$s for details.\n",
480 program_invocation_short_name,
481 link,
482 ansi_underline(),
483 ansi_normal(),
484 ansi_highlight(),
485 ansi_normal());
486
487 return 0;
488 }
489
490 static int custom_mount_check_all(void) {
491 FOREACH_ARRAY(m, arg_custom_mounts, arg_n_custom_mounts)
492 if (path_equal(m->destination, "/") && arg_userns_mode != USER_NAMESPACE_NO) {
493 if (arg_userns_ownership != USER_NAMESPACE_OWNERSHIP_OFF)
494 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
495 "--private-users-ownership=%s may not be combined with custom root mounts.",
496 user_namespace_ownership_to_string(arg_userns_ownership));
497 if (arg_uid_shift == UID_INVALID)
498 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
499 "--private-users with automatic UID shift may not be combined with custom root mounts.");
500 }
501
502 return 0;
503 }
504
505 static int parse_capability_spec(const char *spec, uint64_t *ret_mask) {
506 uint64_t mask = 0;
507 int r;
508
509 for (;;) {
510 _cleanup_free_ char *t = NULL;
511
512 r = extract_first_word(&spec, &t, ",", 0);
513 if (r < 0)
514 return log_error_errno(r, "Failed to parse capability %s.", t);
515 if (r == 0)
516 break;
517
518 if (streq(t, "help")) {
519 for (int i = 0; i < capability_list_length(); i++) {
520 const char *name;
521
522 name = capability_to_name(i);
523 if (name)
524 puts(name);
525 }
526
527 return 0; /* quit */
528 }
529
530 if (streq(t, "all"))
531 mask = UINT64_MAX;
532 else {
533 r = capability_from_name(t);
534 if (r < 0)
535 return log_error_errno(r, "Failed to parse capability %s.", t);
536
537 mask |= 1ULL << r;
538 }
539 }
540
541 *ret_mask = mask;
542 return 1; /* continue */
543 }
544
545 static int parse_share_ns_env(const char *name, unsigned long ns_flag) {
546 int r;
547
548 r = getenv_bool(name);
549 if (r == -ENXIO)
550 return 0;
551 if (r < 0)
552 return log_error_errno(r, "Failed to parse $%s: %m", name);
553
554 arg_clone_ns_flags = (arg_clone_ns_flags & ~ns_flag) | (r > 0 ? 0 : ns_flag);
555 arg_settings_mask |= SETTING_CLONE_NS_FLAGS;
556 return 0;
557 }
558
559 static int parse_mount_settings_env(void) {
560 const char *e;
561 int r;
562
563 r = getenv_bool("SYSTEMD_NSPAWN_TMPFS_TMP");
564 if (r < 0 && r != -ENXIO)
565 return log_error_errno(r, "Failed to parse $SYSTEMD_NSPAWN_TMPFS_TMP: %m");
566 if (r >= 0)
567 SET_FLAG(arg_mount_settings, MOUNT_APPLY_TMPFS_TMP, r > 0);
568
569 e = getenv("SYSTEMD_NSPAWN_API_VFS_WRITABLE");
570 if (streq_ptr(e, "network"))
571 arg_mount_settings |= MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_APIVFS_NETNS;
572 else if (e) {
573 r = parse_boolean(e);
574 if (r < 0)
575 return log_error_errno(r, "Failed to parse $SYSTEMD_NSPAWN_API_VFS_WRITABLE: %m");
576
577 SET_FLAG(arg_mount_settings, MOUNT_APPLY_APIVFS_RO, r == 0);
578 SET_FLAG(arg_mount_settings, MOUNT_APPLY_APIVFS_NETNS, false);
579 }
580
581 return 0;
582 }
583
584 static int parse_environment(void) {
585 const char *e;
586 int r;
587
588 r = parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_IPC", CLONE_NEWIPC);
589 if (r < 0)
590 return r;
591 r = parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_PID", CLONE_NEWPID);
592 if (r < 0)
593 return r;
594 r = parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_UTS", CLONE_NEWUTS);
595 if (r < 0)
596 return r;
597 r = parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_SYSTEM", CLONE_NEWIPC|CLONE_NEWPID|CLONE_NEWUTS);
598 if (r < 0)
599 return r;
600
601 r = parse_mount_settings_env();
602 if (r < 0)
603 return r;
604
605 /* SYSTEMD_NSPAWN_USE_CGNS=0 can be used to disable CLONE_NEWCGROUP use,
606 * even if it is supported. If not supported, it has no effect. */
607 if (!namespace_type_supported(NAMESPACE_CGROUP))
608 arg_use_cgns = false;
609 else {
610 r = getenv_bool("SYSTEMD_NSPAWN_USE_CGNS");
611 if (r < 0) {
612 if (r != -ENXIO)
613 return log_error_errno(r, "Failed to parse $SYSTEMD_NSPAWN_USE_CGNS: %m");
614
615 arg_use_cgns = true;
616 } else {
617 arg_use_cgns = r > 0;
618 arg_settings_mask |= SETTING_USE_CGNS;
619 }
620 }
621
622 e = getenv("SYSTEMD_NSPAWN_CONTAINER_SERVICE");
623 if (e)
624 arg_container_service_name = e;
625
626 e = getenv("SYSTEMD_NSPAWN_NETWORK_MAC");
627 if (e) {
628 r = parse_ether_addr(e, &arg_network_provided_mac);
629 if (r < 0)
630 return log_error_errno(r, "Failed to parse provided MAC address via environment variable");
631 }
632
633 r = getenv_bool("SYSTEMD_SUPPRESS_SYNC");
634 if (r >= 0)
635 arg_suppress_sync = r;
636 else if (r != -ENXIO)
637 log_debug_errno(r, "Failed to parse $SYSTEMD_SUPPRESS_SYNC, ignoring: %m");
638
639 return 0;
640 }
641
642 static int parse_argv(int argc, char *argv[]) {
643 enum {
644 ARG_VERSION = 0x100,
645 ARG_PRIVATE_NETWORK,
646 ARG_UUID,
647 ARG_READ_ONLY,
648 ARG_CAPABILITY,
649 ARG_AMBIENT_CAPABILITY,
650 ARG_DROP_CAPABILITY,
651 ARG_LINK_JOURNAL,
652 ARG_BIND,
653 ARG_BIND_RO,
654 ARG_TMPFS,
655 ARG_OVERLAY,
656 ARG_OVERLAY_RO,
657 ARG_INACCESSIBLE,
658 ARG_SHARE_SYSTEM,
659 ARG_REGISTER,
660 ARG_KEEP_UNIT,
661 ARG_NETWORK_INTERFACE,
662 ARG_NETWORK_MACVLAN,
663 ARG_NETWORK_IPVLAN,
664 ARG_NETWORK_BRIDGE,
665 ARG_NETWORK_ZONE,
666 ARG_NETWORK_VETH_EXTRA,
667 ARG_NETWORK_NAMESPACE_PATH,
668 ARG_PERSONALITY,
669 ARG_VOLATILE,
670 ARG_TEMPLATE,
671 ARG_PROPERTY,
672 ARG_PRIVATE_USERS,
673 ARG_KILL_SIGNAL,
674 ARG_SETTINGS,
675 ARG_CHDIR,
676 ARG_PIVOT_ROOT,
677 ARG_PRIVATE_USERS_CHOWN,
678 ARG_PRIVATE_USERS_OWNERSHIP,
679 ARG_NOTIFY_READY,
680 ARG_ROOT_HASH,
681 ARG_ROOT_HASH_SIG,
682 ARG_VERITY_DATA,
683 ARG_SYSTEM_CALL_FILTER,
684 ARG_RLIMIT,
685 ARG_HOSTNAME,
686 ARG_NO_NEW_PRIVILEGES,
687 ARG_OOM_SCORE_ADJUST,
688 ARG_CPU_AFFINITY,
689 ARG_RESOLV_CONF,
690 ARG_TIMEZONE,
691 ARG_CONSOLE,
692 ARG_PIPE,
693 ARG_OCI_BUNDLE,
694 ARG_NO_PAGER,
695 ARG_SET_CREDENTIAL,
696 ARG_LOAD_CREDENTIAL,
697 ARG_BIND_USER,
698 ARG_BIND_USER_SHELL,
699 ARG_SUPPRESS_SYNC,
700 ARG_IMAGE_POLICY,
701 ARG_BACKGROUND,
702 ARG_CLEANUP,
703 ARG_NO_ASK_PASSWORD,
704 };
705
706 static const struct option options[] = {
707 { "help", no_argument, NULL, 'h' },
708 { "version", no_argument, NULL, ARG_VERSION },
709 { "directory", required_argument, NULL, 'D' },
710 { "template", required_argument, NULL, ARG_TEMPLATE },
711 { "ephemeral", no_argument, NULL, 'x' },
712 { "user", required_argument, NULL, 'u' },
713 { "private-network", no_argument, NULL, ARG_PRIVATE_NETWORK },
714 { "as-pid2", no_argument, NULL, 'a' },
715 { "boot", no_argument, NULL, 'b' },
716 { "uuid", required_argument, NULL, ARG_UUID },
717 { "read-only", no_argument, NULL, ARG_READ_ONLY },
718 { "capability", required_argument, NULL, ARG_CAPABILITY },
719 { "ambient-capability", required_argument, NULL, ARG_AMBIENT_CAPABILITY },
720 { "drop-capability", required_argument, NULL, ARG_DROP_CAPABILITY },
721 { "no-new-privileges", required_argument, NULL, ARG_NO_NEW_PRIVILEGES },
722 { "link-journal", required_argument, NULL, ARG_LINK_JOURNAL },
723 { "bind", required_argument, NULL, ARG_BIND },
724 { "bind-ro", required_argument, NULL, ARG_BIND_RO },
725 { "tmpfs", required_argument, NULL, ARG_TMPFS },
726 { "overlay", required_argument, NULL, ARG_OVERLAY },
727 { "overlay-ro", required_argument, NULL, ARG_OVERLAY_RO },
728 { "inaccessible", required_argument, NULL, ARG_INACCESSIBLE },
729 { "machine", required_argument, NULL, 'M' },
730 { "hostname", required_argument, NULL, ARG_HOSTNAME },
731 { "slice", required_argument, NULL, 'S' },
732 { "setenv", required_argument, NULL, 'E' },
733 { "selinux-context", required_argument, NULL, 'Z' },
734 { "selinux-apifs-context", required_argument, NULL, 'L' },
735 { "quiet", no_argument, NULL, 'q' },
736 { "share-system", no_argument, NULL, ARG_SHARE_SYSTEM }, /* not documented */
737 { "register", required_argument, NULL, ARG_REGISTER },
738 { "keep-unit", no_argument, NULL, ARG_KEEP_UNIT },
739 { "network-interface", required_argument, NULL, ARG_NETWORK_INTERFACE },
740 { "network-macvlan", required_argument, NULL, ARG_NETWORK_MACVLAN },
741 { "network-ipvlan", required_argument, NULL, ARG_NETWORK_IPVLAN },
742 { "network-veth", no_argument, NULL, 'n' },
743 { "network-veth-extra", required_argument, NULL, ARG_NETWORK_VETH_EXTRA },
744 { "network-bridge", required_argument, NULL, ARG_NETWORK_BRIDGE },
745 { "network-zone", required_argument, NULL, ARG_NETWORK_ZONE },
746 { "network-namespace-path", required_argument, NULL, ARG_NETWORK_NAMESPACE_PATH },
747 { "personality", required_argument, NULL, ARG_PERSONALITY },
748 { "image", required_argument, NULL, 'i' },
749 { "volatile", optional_argument, NULL, ARG_VOLATILE },
750 { "port", required_argument, NULL, 'p' },
751 { "property", required_argument, NULL, ARG_PROPERTY },
752 { "private-users", optional_argument, NULL, ARG_PRIVATE_USERS },
753 { "private-users-chown", optional_argument, NULL, ARG_PRIVATE_USERS_CHOWN }, /* obsolete */
754 { "private-users-ownership",required_argument, NULL, ARG_PRIVATE_USERS_OWNERSHIP},
755 { "kill-signal", required_argument, NULL, ARG_KILL_SIGNAL },
756 { "settings", required_argument, NULL, ARG_SETTINGS },
757 { "chdir", required_argument, NULL, ARG_CHDIR },
758 { "pivot-root", required_argument, NULL, ARG_PIVOT_ROOT },
759 { "notify-ready", required_argument, NULL, ARG_NOTIFY_READY },
760 { "root-hash", required_argument, NULL, ARG_ROOT_HASH },
761 { "root-hash-sig", required_argument, NULL, ARG_ROOT_HASH_SIG },
762 { "verity-data", required_argument, NULL, ARG_VERITY_DATA },
763 { "system-call-filter", required_argument, NULL, ARG_SYSTEM_CALL_FILTER },
764 { "rlimit", required_argument, NULL, ARG_RLIMIT },
765 { "oom-score-adjust", required_argument, NULL, ARG_OOM_SCORE_ADJUST },
766 { "cpu-affinity", required_argument, NULL, ARG_CPU_AFFINITY },
767 { "resolv-conf", required_argument, NULL, ARG_RESOLV_CONF },
768 { "timezone", required_argument, NULL, ARG_TIMEZONE },
769 { "console", required_argument, NULL, ARG_CONSOLE },
770 { "pipe", no_argument, NULL, ARG_PIPE },
771 { "oci-bundle", required_argument, NULL, ARG_OCI_BUNDLE },
772 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
773 { "set-credential", required_argument, NULL, ARG_SET_CREDENTIAL },
774 { "load-credential", required_argument, NULL, ARG_LOAD_CREDENTIAL },
775 { "bind-user", required_argument, NULL, ARG_BIND_USER },
776 { "bind-user-shell", required_argument, NULL, ARG_BIND_USER_SHELL },
777 { "suppress-sync", required_argument, NULL, ARG_SUPPRESS_SYNC },
778 { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
779 { "background", required_argument, NULL, ARG_BACKGROUND },
780 { "cleanup", no_argument, NULL, ARG_CLEANUP },
781 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
782 {}
783 };
784
785 int c, r;
786 uint64_t plus = 0, minus = 0;
787 bool mask_all_settings = false, mask_no_settings = false;
788
789 assert(argc >= 0);
790 assert(argv);
791
792 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
793 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
794 optind = 0;
795 while ((c = getopt_long(argc, argv, "+hD:u:abL:M:jS:Z:qi:xp:nUE:P", options, NULL)) >= 0)
796 switch (c) {
797
798 case 'h':
799 return help();
800
801 case ARG_VERSION:
802 return version();
803
804 case 'D':
805 r = parse_path_argument(optarg, false, &arg_directory);
806 if (r < 0)
807 return r;
808
809 arg_settings_mask |= SETTING_DIRECTORY;
810 break;
811
812 case ARG_TEMPLATE:
813 r = parse_path_argument(optarg, false, &arg_template);
814 if (r < 0)
815 return r;
816
817 arg_settings_mask |= SETTING_DIRECTORY;
818 break;
819
820 case 'i':
821 r = parse_path_argument(optarg, false, &arg_image);
822 if (r < 0)
823 return r;
824
825 arg_settings_mask |= SETTING_DIRECTORY;
826 break;
827
828 case ARG_OCI_BUNDLE:
829 r = parse_path_argument(optarg, false, &arg_oci_bundle);
830 if (r < 0)
831 return r;
832
833 break;
834
835 case 'x':
836 arg_ephemeral = true;
837 arg_settings_mask |= SETTING_EPHEMERAL;
838 break;
839
840 case 'u':
841 r = free_and_strdup(&arg_user, optarg);
842 if (r < 0)
843 return log_oom();
844
845 arg_settings_mask |= SETTING_USER;
846 break;
847
848 case ARG_NETWORK_ZONE: {
849 _cleanup_free_ char *j = NULL;
850
851 j = strjoin("vz-", optarg);
852 if (!j)
853 return log_oom();
854
855 if (!ifname_valid(j))
856 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
857 "Network zone name not valid: %s", j);
858
859 free_and_replace(arg_network_zone, j);
860
861 arg_network_veth = true;
862 arg_private_network = true;
863 arg_settings_mask |= SETTING_NETWORK;
864 break;
865 }
866
867 case ARG_NETWORK_BRIDGE:
868
869 if (!ifname_valid(optarg))
870 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
871 "Bridge interface name not valid: %s", optarg);
872
873 r = free_and_strdup(&arg_network_bridge, optarg);
874 if (r < 0)
875 return log_oom();
876
877 _fallthrough_;
878 case 'n':
879 arg_network_veth = true;
880 arg_private_network = true;
881 arg_settings_mask |= SETTING_NETWORK;
882 break;
883
884 case ARG_NETWORK_VETH_EXTRA:
885 r = veth_extra_parse(&arg_network_veth_extra, optarg);
886 if (r < 0)
887 return log_error_errno(r, "Failed to parse --network-veth-extra= parameter: %s", optarg);
888
889 arg_private_network = true;
890 arg_settings_mask |= SETTING_NETWORK;
891 break;
892
893 case ARG_NETWORK_INTERFACE:
894 r = interface_pair_parse(&arg_network_interfaces, optarg);
895 if (r < 0)
896 return r;
897
898 arg_private_network = true;
899 arg_settings_mask |= SETTING_NETWORK;
900 break;
901
902 case ARG_NETWORK_MACVLAN:
903 r = macvlan_pair_parse(&arg_network_macvlan, optarg);
904 if (r < 0)
905 return r;
906
907 arg_private_network = true;
908 arg_settings_mask |= SETTING_NETWORK;
909 break;
910
911 case ARG_NETWORK_IPVLAN:
912 r = ipvlan_pair_parse(&arg_network_ipvlan, optarg);
913 if (r < 0)
914 return r;
915
916 _fallthrough_;
917 case ARG_PRIVATE_NETWORK:
918 arg_private_network = true;
919 arg_settings_mask |= SETTING_NETWORK;
920 break;
921
922 case ARG_NETWORK_NAMESPACE_PATH:
923 r = parse_path_argument(optarg, false, &arg_network_namespace_path);
924 if (r < 0)
925 return r;
926
927 arg_settings_mask |= SETTING_NETWORK;
928 break;
929
930 case 'b':
931 if (arg_start_mode == START_PID2)
932 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
933 "--boot and --as-pid2 may not be combined.");
934
935 arg_start_mode = START_BOOT;
936 arg_settings_mask |= SETTING_START_MODE;
937 break;
938
939 case 'a':
940 if (arg_start_mode == START_BOOT)
941 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
942 "--boot and --as-pid2 may not be combined.");
943
944 arg_start_mode = START_PID2;
945 arg_settings_mask |= SETTING_START_MODE;
946 break;
947
948 case ARG_UUID:
949 r = id128_from_string_nonzero(optarg, &arg_uuid);
950 if (r == -ENXIO)
951 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
952 "Machine UUID may not be all zeroes.");
953 if (r < 0)
954 return log_error_errno(r, "Invalid UUID: %s", optarg);
955
956 arg_settings_mask |= SETTING_MACHINE_ID;
957 break;
958
959 case 'S': {
960 _cleanup_free_ char *mangled = NULL;
961
962 r = unit_name_mangle_with_suffix(optarg, NULL, UNIT_NAME_MANGLE_WARN, ".slice", &mangled);
963 if (r < 0)
964 return log_oom();
965
966 free_and_replace(arg_slice, mangled);
967 arg_settings_mask |= SETTING_SLICE;
968 break;
969 }
970
971 case 'M':
972 if (isempty(optarg))
973 arg_machine = mfree(arg_machine);
974 else {
975 if (!hostname_is_valid(optarg, 0))
976 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
977 "Invalid machine name: %s", optarg);
978
979 r = free_and_strdup(&arg_machine, optarg);
980 if (r < 0)
981 return log_oom();
982 }
983 break;
984
985 case ARG_HOSTNAME:
986 if (isempty(optarg))
987 arg_hostname = mfree(arg_hostname);
988 else {
989 if (!hostname_is_valid(optarg, 0))
990 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
991 "Invalid hostname: %s", optarg);
992
993 r = free_and_strdup(&arg_hostname, optarg);
994 if (r < 0)
995 return log_oom();
996 }
997
998 arg_settings_mask |= SETTING_HOSTNAME;
999 break;
1000
1001 case 'Z':
1002 arg_selinux_context = optarg;
1003 break;
1004
1005 case 'L':
1006 arg_selinux_apifs_context = optarg;
1007 break;
1008
1009 case ARG_READ_ONLY:
1010 arg_read_only = true;
1011 arg_settings_mask |= SETTING_READ_ONLY;
1012 break;
1013
1014 case ARG_AMBIENT_CAPABILITY: {
1015 uint64_t m;
1016 r = parse_capability_spec(optarg, &m);
1017 if (r <= 0)
1018 return r;
1019 arg_caps_ambient |= m;
1020 arg_settings_mask |= SETTING_CAPABILITY;
1021 break;
1022 }
1023 case ARG_CAPABILITY:
1024 case ARG_DROP_CAPABILITY: {
1025 uint64_t m;
1026 r = parse_capability_spec(optarg, &m);
1027 if (r <= 0)
1028 return r;
1029
1030 if (c == ARG_CAPABILITY)
1031 plus |= m;
1032 else
1033 minus |= m;
1034 arg_settings_mask |= SETTING_CAPABILITY;
1035 break;
1036 }
1037 case ARG_NO_NEW_PRIVILEGES:
1038 r = parse_boolean_argument("--no-new-privileges=", optarg, &arg_no_new_privileges);
1039 if (r < 0)
1040 return r;
1041
1042 arg_settings_mask |= SETTING_NO_NEW_PRIVILEGES;
1043 break;
1044
1045 case 'j':
1046 arg_link_journal = LINK_GUEST;
1047 arg_link_journal_try = true;
1048 arg_settings_mask |= SETTING_LINK_JOURNAL;
1049 break;
1050
1051 case ARG_LINK_JOURNAL:
1052 r = parse_link_journal(optarg, &arg_link_journal, &arg_link_journal_try);
1053 if (r < 0)
1054 return log_error_errno(r, "Failed to parse link journal mode %s", optarg);
1055
1056 arg_settings_mask |= SETTING_LINK_JOURNAL;
1057 break;
1058
1059 case ARG_BIND:
1060 case ARG_BIND_RO:
1061 r = bind_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, optarg, c == ARG_BIND_RO);
1062 if (r < 0)
1063 return log_error_errno(r, "Failed to parse --bind(-ro)= argument %s: %m", optarg);
1064
1065 arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
1066 break;
1067
1068 case ARG_TMPFS:
1069 r = tmpfs_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, optarg);
1070 if (r < 0)
1071 return log_error_errno(r, "Failed to parse --tmpfs= argument %s: %m", optarg);
1072
1073 arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
1074 break;
1075
1076 case ARG_OVERLAY:
1077 case ARG_OVERLAY_RO:
1078 r = overlay_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, optarg, c == ARG_OVERLAY_RO);
1079 if (r == -EADDRNOTAVAIL)
1080 return log_error_errno(r, "--overlay(-ro)= needs at least two colon-separated directories specified.");
1081 if (r < 0)
1082 return log_error_errno(r, "Failed to parse --overlay(-ro)= argument %s: %m", optarg);
1083
1084 arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
1085 break;
1086
1087 case ARG_INACCESSIBLE:
1088 r = inaccessible_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, optarg);
1089 if (r < 0)
1090 return log_error_errno(r, "Failed to parse --inaccessible= argument %s: %m", optarg);
1091
1092 arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
1093 break;
1094
1095 case 'E':
1096 r = strv_env_replace_strdup_passthrough(&arg_setenv, optarg);
1097 if (r < 0)
1098 return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
1099
1100 arg_settings_mask |= SETTING_ENVIRONMENT;
1101 break;
1102
1103 case 'q':
1104 arg_quiet = true;
1105 break;
1106
1107 case ARG_SHARE_SYSTEM:
1108 /* We don't officially support this anymore, except for compat reasons. People should use the
1109 * $SYSTEMD_NSPAWN_SHARE_* environment variables instead. */
1110 log_warning("Please do not use --share-system anymore, use $SYSTEMD_NSPAWN_SHARE_* instead.");
1111 arg_clone_ns_flags = 0;
1112 break;
1113
1114 case ARG_REGISTER:
1115 r = parse_boolean_argument("--register=", optarg, &arg_register);
1116 if (r < 0)
1117 return r;
1118
1119 break;
1120
1121 case ARG_KEEP_UNIT:
1122 arg_keep_unit = true;
1123 break;
1124
1125 case ARG_PERSONALITY:
1126
1127 arg_personality = personality_from_string(optarg);
1128 if (arg_personality == PERSONALITY_INVALID)
1129 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1130 "Unknown or unsupported personality '%s'.", optarg);
1131
1132 arg_settings_mask |= SETTING_PERSONALITY;
1133 break;
1134
1135 case ARG_VOLATILE:
1136
1137 if (!optarg)
1138 arg_volatile_mode = VOLATILE_YES;
1139 else if (streq(optarg, "help")) {
1140 DUMP_STRING_TABLE(volatile_mode, VolatileMode, _VOLATILE_MODE_MAX);
1141 return 0;
1142 } else {
1143 VolatileMode m;
1144
1145 m = volatile_mode_from_string(optarg);
1146 if (m < 0)
1147 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1148 "Failed to parse --volatile= argument: %s", optarg);
1149 else
1150 arg_volatile_mode = m;
1151 }
1152
1153 arg_settings_mask |= SETTING_VOLATILE_MODE;
1154 break;
1155
1156 case 'p':
1157 r = expose_port_parse(&arg_expose_ports, optarg);
1158 if (r == -EEXIST)
1159 return log_error_errno(r, "Duplicate port specification: %s", optarg);
1160 if (r < 0)
1161 return log_error_errno(r, "Failed to parse host port %s: %m", optarg);
1162
1163 arg_settings_mask |= SETTING_EXPOSE_PORTS;
1164 break;
1165
1166 case ARG_PROPERTY:
1167 if (strv_extend(&arg_property, optarg) < 0)
1168 return log_oom();
1169
1170 break;
1171
1172 case ARG_PRIVATE_USERS: {
1173 int boolean;
1174
1175 if (!optarg)
1176 boolean = true;
1177 else if (!in_charset(optarg, DIGITS))
1178 /* do *not* parse numbers as booleans */
1179 boolean = parse_boolean(optarg);
1180 else
1181 boolean = -1;
1182
1183 if (boolean == 0) {
1184 /* no: User namespacing off */
1185 arg_userns_mode = USER_NAMESPACE_NO;
1186 arg_uid_shift = UID_INVALID;
1187 arg_uid_range = UINT32_C(0x10000);
1188 } else if (boolean > 0) {
1189 /* yes: User namespacing on, UID range is read from root dir */
1190 arg_userns_mode = USER_NAMESPACE_FIXED;
1191 arg_uid_shift = UID_INVALID;
1192 arg_uid_range = UINT32_C(0x10000);
1193 } else if (streq(optarg, "pick")) {
1194 /* pick: User namespacing on, UID range is picked randomly */
1195 arg_userns_mode = USER_NAMESPACE_PICK; /* Note that arg_userns_ownership is
1196 * implied by USER_NAMESPACE_PICK
1197 * further down. */
1198 arg_uid_shift = UID_INVALID;
1199 arg_uid_range = UINT32_C(0x10000);
1200
1201 } else if (streq(optarg, "identity")) {
1202 /* identity: User namespaces on, UID range is map of the 0…0xFFFF range to
1203 * itself, i.e. we don't actually map anything, but do take benefit of
1204 * isolation of capability sets. */
1205 arg_userns_mode = USER_NAMESPACE_FIXED;
1206 arg_uid_shift = 0;
1207 arg_uid_range = UINT32_C(0x10000);
1208 } else if (streq(optarg, "managed")) {
1209 /* managed: User namespace on, and acquire it from systemd-nsresourced */
1210 arg_userns_mode = USER_NAMESPACE_MANAGED;
1211 arg_uid_shift = UID_INVALID;
1212 arg_uid_range = UINT32_C(0x10000);
1213 } else {
1214 /* anything else: User namespacing on, UID range is explicitly configured */
1215 r = parse_userns_uid_range(optarg, &arg_uid_shift, &arg_uid_range);
1216 if (r < 0)
1217 return r;
1218 arg_userns_mode = USER_NAMESPACE_FIXED;
1219 }
1220
1221 arg_settings_mask |= SETTING_USERNS;
1222 break;
1223 }
1224
1225 case 'U':
1226 if (userns_supported()) {
1227 /* Note that arg_userns_ownership is implied by USER_NAMESPACE_PICK further down. */
1228 arg_userns_mode = arg_privileged ? USER_NAMESPACE_PICK : USER_NAMESPACE_MANAGED;
1229 arg_uid_shift = UID_INVALID;
1230 arg_uid_range = UINT32_C(0x10000);
1231
1232 arg_settings_mask |= SETTING_USERNS;
1233 }
1234
1235 break;
1236
1237 case ARG_PRIVATE_USERS_CHOWN:
1238 arg_userns_ownership = USER_NAMESPACE_OWNERSHIP_CHOWN;
1239
1240 arg_settings_mask |= SETTING_USERNS;
1241 break;
1242
1243 case ARG_PRIVATE_USERS_OWNERSHIP:
1244 if (streq(optarg, "help")) {
1245 DUMP_STRING_TABLE(user_namespace_ownership, UserNamespaceOwnership, _USER_NAMESPACE_OWNERSHIP_MAX);
1246 return 0;
1247 }
1248
1249 arg_userns_ownership = user_namespace_ownership_from_string(optarg);
1250 if (arg_userns_ownership < 0)
1251 return log_error_errno(arg_userns_ownership, "Cannot parse --user-namespace-ownership= value: %s", optarg);
1252
1253 arg_settings_mask |= SETTING_USERNS;
1254 break;
1255
1256 case ARG_KILL_SIGNAL:
1257 if (streq(optarg, "help")) {
1258 DUMP_STRING_TABLE(signal, int, _NSIG);
1259 return 0;
1260 }
1261
1262 arg_kill_signal = signal_from_string(optarg);
1263 if (arg_kill_signal < 0)
1264 return log_error_errno(arg_kill_signal, "Cannot parse signal: %s", optarg);
1265
1266 arg_settings_mask |= SETTING_KILL_SIGNAL;
1267 break;
1268
1269 case ARG_SETTINGS:
1270
1271 /* no → do not read files
1272 * yes → read files, do not override cmdline, trust only subset
1273 * override → read files, override cmdline, trust only subset
1274 * trusted → read files, do not override cmdline, trust all
1275 */
1276
1277 r = parse_boolean(optarg);
1278 if (r < 0) {
1279 if (streq(optarg, "trusted")) {
1280 mask_all_settings = false;
1281 mask_no_settings = false;
1282 arg_settings_trusted = true;
1283
1284 } else if (streq(optarg, "override")) {
1285 mask_all_settings = false;
1286 mask_no_settings = true;
1287 arg_settings_trusted = -1;
1288 } else
1289 return log_error_errno(r, "Failed to parse --settings= argument: %s", optarg);
1290 } else if (r > 0) {
1291 /* yes */
1292 mask_all_settings = false;
1293 mask_no_settings = false;
1294 arg_settings_trusted = -1;
1295 } else {
1296 /* no */
1297 mask_all_settings = true;
1298 mask_no_settings = false;
1299 arg_settings_trusted = false;
1300 }
1301
1302 break;
1303
1304 case ARG_CHDIR: {
1305 _cleanup_free_ char *wd = NULL;
1306
1307 if (!path_is_absolute(optarg))
1308 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1309 "Working directory %s is not an absolute path.", optarg);
1310
1311 r = path_simplify_alloc(optarg, &wd);
1312 if (r < 0)
1313 return log_error_errno(r, "Failed to simplify path %s: %m", optarg);
1314
1315 if (!path_is_normalized(wd))
1316 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Working directory path is not normalized: %s", wd);
1317
1318 if (path_below_api_vfs(wd))
1319 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Working directory is below API VFS, refusing: %s", wd);
1320
1321 free_and_replace(arg_chdir, wd);
1322 arg_settings_mask |= SETTING_WORKING_DIRECTORY;
1323 break;
1324 }
1325
1326 case ARG_PIVOT_ROOT:
1327 r = pivot_root_parse(&arg_pivot_root_new, &arg_pivot_root_old, optarg);
1328 if (r < 0)
1329 return log_error_errno(r, "Failed to parse --pivot-root= argument %s: %m", optarg);
1330
1331 arg_settings_mask |= SETTING_PIVOT_ROOT;
1332 break;
1333
1334 case ARG_NOTIFY_READY:
1335 r = parse_boolean(optarg);
1336 if (r < 0)
1337 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1338 "%s is not a valid notify mode. Valid modes are: yes, no, and ready.", optarg);
1339 arg_notify_ready = r;
1340 arg_settings_mask |= SETTING_NOTIFY_READY;
1341 break;
1342
1343 case ARG_ROOT_HASH: {
1344 _cleanup_free_ void *k = NULL;
1345 size_t l;
1346
1347 r = unhexmem(optarg, &k, &l);
1348 if (r < 0)
1349 return log_error_errno(r, "Failed to parse root hash: %s", optarg);
1350 if (l < sizeof(sd_id128_t))
1351 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Root hash must be at least 128-bit long: %s", optarg);
1352
1353 free_and_replace(arg_verity_settings.root_hash, k);
1354 arg_verity_settings.root_hash_size = l;
1355 break;
1356 }
1357
1358 case ARG_ROOT_HASH_SIG: {
1359 char *value;
1360 size_t l;
1361 void *p;
1362
1363 if ((value = startswith(optarg, "base64:"))) {
1364 r = unbase64mem(value, &p, &l);
1365 if (r < 0)
1366 return log_error_errno(r, "Failed to parse root hash signature '%s': %m", optarg);
1367
1368 } else {
1369 r = read_full_file(optarg, (char**) &p, &l);
1370 if (r < 0)
1371 return log_error_errno(r, "Failed parse root hash signature file '%s': %m", optarg);
1372 }
1373
1374 free_and_replace(arg_verity_settings.root_hash_sig, p);
1375 arg_verity_settings.root_hash_sig_size = l;
1376 break;
1377 }
1378
1379 case ARG_VERITY_DATA:
1380 r = parse_path_argument(optarg, false, &arg_verity_settings.data_path);
1381 if (r < 0)
1382 return r;
1383 break;
1384
1385 case ARG_SYSTEM_CALL_FILTER: {
1386 bool negative;
1387 const char *items;
1388
1389 negative = optarg[0] == '~';
1390 items = negative ? optarg + 1 : optarg;
1391
1392 for (;;) {
1393 _cleanup_free_ char *word = NULL;
1394
1395 r = extract_first_word(&items, &word, NULL, 0);
1396 if (r == 0)
1397 break;
1398 if (r == -ENOMEM)
1399 return log_oom();
1400 if (r < 0)
1401 return log_error_errno(r, "Failed to parse system call filter: %m");
1402
1403 if (negative)
1404 r = strv_extend(&arg_syscall_deny_list, word);
1405 else
1406 r = strv_extend(&arg_syscall_allow_list, word);
1407 if (r < 0)
1408 return log_oom();
1409 }
1410
1411 arg_settings_mask |= SETTING_SYSCALL_FILTER;
1412 break;
1413 }
1414
1415 case ARG_RLIMIT: {
1416 const char *eq;
1417 _cleanup_free_ char *name = NULL;
1418 int rl;
1419
1420 if (streq(optarg, "help")) {
1421 DUMP_STRING_TABLE(rlimit, int, _RLIMIT_MAX);
1422 return 0;
1423 }
1424
1425 eq = strchr(optarg, '=');
1426 if (!eq)
1427 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1428 "--rlimit= expects an '=' assignment.");
1429
1430 name = strndup(optarg, eq - optarg);
1431 if (!name)
1432 return log_oom();
1433
1434 rl = rlimit_from_string_harder(name);
1435 if (rl < 0)
1436 return log_error_errno(rl, "Unknown resource limit: %s", name);
1437
1438 if (!arg_rlimit[rl]) {
1439 arg_rlimit[rl] = new0(struct rlimit, 1);
1440 if (!arg_rlimit[rl])
1441 return log_oom();
1442 }
1443
1444 r = rlimit_parse(rl, eq + 1, arg_rlimit[rl]);
1445 if (r < 0)
1446 return log_error_errno(r, "Failed to parse resource limit: %s", eq + 1);
1447
1448 arg_settings_mask |= SETTING_RLIMIT_FIRST << rl;
1449 break;
1450 }
1451
1452 case ARG_OOM_SCORE_ADJUST:
1453 r = parse_oom_score_adjust(optarg, &arg_oom_score_adjust);
1454 if (r < 0)
1455 return log_error_errno(r, "Failed to parse --oom-score-adjust= parameter: %s", optarg);
1456
1457 arg_oom_score_adjust_set = true;
1458 arg_settings_mask |= SETTING_OOM_SCORE_ADJUST;
1459 break;
1460
1461 case ARG_CPU_AFFINITY: {
1462 CPUSet cpuset;
1463
1464 r = parse_cpu_set(optarg, &cpuset);
1465 if (r < 0)
1466 return log_error_errno(r, "Failed to parse CPU affinity mask %s: %m", optarg);
1467
1468 cpu_set_done_and_replace(arg_cpu_set, cpuset);
1469 arg_settings_mask |= SETTING_CPU_AFFINITY;
1470 break;
1471 }
1472
1473 case ARG_RESOLV_CONF:
1474 if (streq(optarg, "help")) {
1475 DUMP_STRING_TABLE(resolv_conf_mode, ResolvConfMode, _RESOLV_CONF_MODE_MAX);
1476 return 0;
1477 }
1478
1479 arg_resolv_conf = resolv_conf_mode_from_string(optarg);
1480 if (arg_resolv_conf < 0)
1481 return log_error_errno(arg_resolv_conf,
1482 "Failed to parse /etc/resolv.conf mode: %s", optarg);
1483
1484 arg_settings_mask |= SETTING_RESOLV_CONF;
1485 break;
1486
1487 case ARG_TIMEZONE:
1488 if (streq(optarg, "help")) {
1489 DUMP_STRING_TABLE(timezone_mode, TimezoneMode, _TIMEZONE_MODE_MAX);
1490 return 0;
1491 }
1492
1493 arg_timezone = timezone_mode_from_string(optarg);
1494 if (arg_timezone < 0)
1495 return log_error_errno(arg_timezone,
1496 "Failed to parse /etc/localtime mode: %s", optarg);
1497
1498 arg_settings_mask |= SETTING_TIMEZONE;
1499 break;
1500
1501 case ARG_CONSOLE:
1502 r = handle_arg_console(optarg);
1503 if (r <= 0)
1504 return r;
1505 break;
1506
1507 case 'P':
1508 case ARG_PIPE:
1509 r = handle_arg_console("pipe");
1510 if (r <= 0)
1511 return r;
1512 break;
1513
1514 case ARG_NO_PAGER:
1515 arg_pager_flags |= PAGER_DISABLE;
1516 break;
1517
1518 case ARG_SET_CREDENTIAL:
1519 r = machine_credential_set(&arg_credentials, optarg);
1520 if (r < 0)
1521 return r;
1522
1523 arg_settings_mask |= SETTING_CREDENTIALS;
1524 break;
1525
1526 case ARG_LOAD_CREDENTIAL:
1527 r = machine_credential_load(&arg_credentials, optarg);
1528 if (r < 0)
1529 return r;
1530
1531 arg_settings_mask |= SETTING_CREDENTIALS;
1532 break;
1533
1534 case ARG_BIND_USER:
1535 if (!valid_user_group_name(optarg, 0))
1536 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid user name to bind: %s", optarg);
1537
1538 if (strv_extend(&arg_bind_user, optarg) < 0)
1539 return log_oom();
1540
1541 arg_settings_mask |= SETTING_BIND_USER;
1542 break;
1543
1544 case ARG_BIND_USER_SHELL: {
1545 bool copy = false;
1546 char *sh = NULL;
1547 r = parse_bind_user_shell(optarg, &sh, &copy);
1548 if (r == -ENOMEM)
1549 return log_oom();
1550 if (r < 0)
1551 return log_error_errno(r, "Invalid user shell to bind: %s", optarg);
1552
1553 free_and_replace(arg_bind_user_shell, sh);
1554 arg_bind_user_shell_copy = copy;
1555
1556 arg_settings_mask |= SETTING_BIND_USER_SHELL;
1557 break;
1558 }
1559
1560 case ARG_SUPPRESS_SYNC:
1561 r = parse_boolean_argument("--suppress-sync=", optarg, &arg_suppress_sync);
1562 if (r < 0)
1563 return r;
1564
1565 arg_settings_mask |= SETTING_SUPPRESS_SYNC;
1566 break;
1567
1568 case ARG_IMAGE_POLICY:
1569 r = parse_image_policy_argument(optarg, &arg_image_policy);
1570 if (r < 0)
1571 return r;
1572 break;
1573
1574 case ARG_BACKGROUND:
1575 r = free_and_strdup_warn(&arg_background, optarg);
1576 if (r < 0)
1577 return r;
1578 break;
1579
1580 case ARG_CLEANUP:
1581 arg_cleanup = true;
1582 break;
1583
1584 case ARG_NO_ASK_PASSWORD:
1585 arg_ask_password = false;
1586 break;
1587
1588 case '?':
1589 return -EINVAL;
1590
1591 default:
1592 assert_not_reached();
1593 }
1594
1595 if (argc > optind) {
1596 strv_free(arg_parameters);
1597 arg_parameters = strv_copy(argv + optind);
1598 if (!arg_parameters)
1599 return log_oom();
1600
1601 arg_settings_mask |= SETTING_START_MODE;
1602 }
1603
1604 if (arg_ephemeral && arg_template && !arg_directory)
1605 /* User asked for ephemeral execution but specified --template= instead of --directory=. Semantically
1606 * such an invocation makes some sense, see https://github.com/systemd/systemd/issues/3667. Let's
1607 * accept this here, and silently make "--ephemeral --template=" equivalent to "--ephemeral
1608 * --directory=". */
1609 arg_directory = TAKE_PTR(arg_template);
1610
1611 arg_caps_retain |= plus;
1612 arg_caps_retain |= arg_private_network ? UINT64_C(1) << CAP_NET_ADMIN : 0;
1613 arg_caps_retain &= ~minus;
1614
1615 /* Make sure to parse environment before we reset the settings mask below */
1616 r = parse_environment();
1617 if (r < 0)
1618 return r;
1619
1620 /* Load all settings from .nspawn files */
1621 if (mask_no_settings)
1622 arg_settings_mask = 0;
1623
1624 /* Don't load any settings from .nspawn files */
1625 if (mask_all_settings)
1626 arg_settings_mask = _SETTINGS_MASK_ALL;
1627
1628 return 1;
1629 }
1630
1631 static int verify_arguments(void) {
1632 int r;
1633
1634 SET_FLAG(arg_mount_settings, MOUNT_UNMANAGED, arg_userns_mode != USER_NAMESPACE_MANAGED);
1635
1636 /* We can mount selinuxfs only if we are privileged and can do so before userns. In managed mode we
1637 * have to enter the userns earlier, hence cannot do that. */
1638 /* SET_FLAG(arg_mount_settings, MOUNT_PRIVILEGED, arg_privileged); */
1639 SET_FLAG(arg_mount_settings, MOUNT_PRIVILEGED, arg_userns_mode != USER_NAMESPACE_MANAGED);
1640
1641 SET_FLAG(arg_mount_settings, MOUNT_USE_USERNS, arg_userns_mode != USER_NAMESPACE_NO);
1642
1643 if (arg_private_network)
1644 SET_FLAG(arg_mount_settings, MOUNT_APPLY_APIVFS_NETNS, arg_private_network);
1645
1646 if (!arg_privileged && arg_userns_mode != USER_NAMESPACE_MANAGED)
1647 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unprivileged operation requires managed user namespaces, as otherwise no UID range can be acquired.");
1648
1649 if (arg_userns_mode == USER_NAMESPACE_MANAGED && !arg_private_network)
1650 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Managed user namespace operation requires private networking, as otherwise /sys/ may not be mounted.");
1651
1652 if (!(arg_clone_ns_flags & CLONE_NEWPID) ||
1653 !(arg_clone_ns_flags & CLONE_NEWUTS)) {
1654 arg_register = false;
1655 if (arg_start_mode != START_PID1)
1656 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--boot cannot be used without namespacing.");
1657 }
1658
1659 if (arg_userns_ownership < 0)
1660 arg_userns_ownership =
1661 IN_SET(arg_userns_mode, USER_NAMESPACE_PICK, USER_NAMESPACE_MANAGED) ? USER_NAMESPACE_OWNERSHIP_AUTO : USER_NAMESPACE_OWNERSHIP_OFF;
1662
1663 if (arg_start_mode == START_BOOT && arg_kill_signal <= 0)
1664 arg_kill_signal = SIGRTMIN+3;
1665
1666 if (arg_volatile_mode != VOLATILE_NO) /* Make sure all file systems contained in the image are mounted read-only if we are in volatile mode */
1667 arg_read_only = true;
1668
1669 if (has_custom_root_mount(arg_custom_mounts, arg_n_custom_mounts))
1670 arg_read_only = true;
1671
1672 if (arg_keep_unit && arg_register && cg_pid_get_owner_uid(0, NULL) >= 0)
1673 /* Save the user from accidentally registering either user-$SESSION.scope or user@.service.
1674 * The latter is not technically a user session, but we don't need to labour the point. */
1675 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--keep-unit --register=yes may not be used when invoked from a user session.");
1676
1677 if (arg_directory && arg_image)
1678 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--directory= and --image= may not be combined.");
1679
1680 if (arg_template && arg_image)
1681 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--template= and --image= may not be combined.");
1682
1683 if (arg_template && !(arg_directory || arg_machine))
1684 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--template= needs --directory= or --machine=.");
1685
1686 if (arg_ephemeral && arg_template)
1687 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--ephemeral and --template= may not be combined.");
1688
1689 /* Permit --ephemeral with --link-journal=try-* to satisfy principle of the least astonishment
1690 * (by common sense, "try" means "do not fail if not possible") */
1691 if (arg_ephemeral && !IN_SET(arg_link_journal, LINK_NO, LINK_AUTO) && !arg_link_journal_try)
1692 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--ephemeral and --link-journal={host,guest} may not be combined.");
1693
1694 if (arg_userns_mode != USER_NAMESPACE_NO && !userns_supported())
1695 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "--private-users= is not supported, kernel compiled without user namespace support.");
1696
1697 if (arg_userns_ownership == USER_NAMESPACE_OWNERSHIP_CHOWN && arg_read_only)
1698 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1699 "--read-only and --private-users-ownership=chown may not be combined.");
1700
1701 /* We don't support --private-users-ownership=chown together with any of the volatile modes since we
1702 * couldn't change the read-only part of the tree (i.e. /usr) anyway, or because it would trigger a
1703 * massive copy-up (in case of overlay) making the entire exercise pointless. */
1704 if (arg_userns_ownership == USER_NAMESPACE_OWNERSHIP_CHOWN && arg_volatile_mode != VOLATILE_NO)
1705 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--volatile= and --private-users-ownership=chown may not be combined.");
1706
1707 /* If --network-namespace-path is given with any other network-related option (except --private-network),
1708 * we need to error out, to avoid conflicts between different network options. */
1709 if (arg_network_namespace_path &&
1710 (arg_network_interfaces || arg_network_macvlan ||
1711 arg_network_ipvlan || arg_network_veth_extra ||
1712 arg_network_bridge || arg_network_zone ||
1713 arg_network_veth))
1714 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--network-namespace-path= cannot be combined with other network options.");
1715
1716 if (arg_network_bridge && arg_network_zone)
1717 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1718 "--network-bridge= and --network-zone= may not be combined.");
1719
1720 if (arg_userns_mode != USER_NAMESPACE_NO && (arg_mount_settings & MOUNT_APPLY_APIVFS_NETNS) && !arg_private_network)
1721 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid namespacing settings. Mounting sysfs with --private-users requires --private-network.");
1722
1723 if (arg_userns_mode != USER_NAMESPACE_NO && !(arg_mount_settings & MOUNT_APPLY_APIVFS_RO))
1724 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot combine --private-users with read-write API VFS mounts.");
1725
1726 if (arg_expose_ports && !arg_private_network)
1727 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot use --port= without private networking.");
1728
1729 if (arg_caps_ambient) {
1730 if (arg_caps_ambient == UINT64_MAX)
1731 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "AmbientCapability= does not support the value all.");
1732
1733 if ((arg_caps_ambient & arg_caps_retain) != arg_caps_ambient)
1734 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "AmbientCapability= setting is not fully covered by Capability= setting.");
1735
1736 if (arg_start_mode == START_BOOT)
1737 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "AmbientCapability= setting is not useful for boot mode.");
1738 }
1739
1740 if (arg_userns_mode == USER_NAMESPACE_NO && !strv_isempty(arg_bind_user))
1741 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--bind-user= requires --private-users");
1742
1743 /* Drop duplicate --bind-user= entries */
1744 strv_uniq(arg_bind_user);
1745
1746 if (arg_bind_user_shell && strv_isempty(arg_bind_user))
1747 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot use --bind-user-shell= without --bind-user=");
1748
1749 r = custom_mount_check_all();
1750 if (r < 0)
1751 return r;
1752
1753 return 0;
1754 }
1755
1756 static int verify_network_interfaces_initialized(void) {
1757 int r;
1758 r = test_network_interfaces_initialized(arg_network_interfaces);
1759 if (r < 0)
1760 return r;
1761
1762 r = test_network_interfaces_initialized(arg_network_macvlan);
1763 if (r < 0)
1764 return r;
1765
1766 r = test_network_interfaces_initialized(arg_network_ipvlan);
1767 if (r < 0)
1768 return r;
1769
1770 return 0;
1771 }
1772
1773 static int in_child_chown(void) {
1774 /* Returns true when chown()ing inodes we create inside the outer child is required. Basically, we
1775 * need the chowning when we implement userns ourselves. If userns is off we don#t need to chown(),
1776 * obviously. And if we are in managed mode we already entered the userns, and hence don#t need to
1777 * manually chown either. */
1778 return IN_SET(arg_userns_mode, USER_NAMESPACE_PICK, USER_NAMESPACE_FIXED);
1779 }
1780
1781 static int userns_chown_at(int fd, const char *fname, uid_t uid, gid_t gid, int flags) {
1782 assert(fd >= 0 || fd == AT_FDCWD);
1783
1784 if (!in_child_chown())
1785 return 0;
1786
1787 if (uid == UID_INVALID && gid == GID_INVALID)
1788 return 0;
1789
1790 if (uid != UID_INVALID) {
1791 uid += arg_uid_shift;
1792
1793 if (uid < arg_uid_shift || uid >= arg_uid_shift + arg_uid_range)
1794 return -EOVERFLOW;
1795 }
1796
1797 if (gid != GID_INVALID) {
1798 gid += (gid_t) arg_uid_shift;
1799
1800 if (gid < (gid_t) arg_uid_shift || gid >= (gid_t) (arg_uid_shift + arg_uid_range))
1801 return -EOVERFLOW;
1802 }
1803
1804 return RET_NERRNO(fchownat(fd, strempty(fname), uid, gid, flags));
1805 }
1806
1807 int userns_lchown(const char *path, uid_t uid, gid_t gid) {
1808 return userns_chown_at(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW);
1809 }
1810
1811 int userns_mkdir(const char *root, const char *path, mode_t mode, uid_t uid, gid_t gid) {
1812 int r;
1813
1814 assert(path);
1815
1816 _cleanup_close_ int parent_fd = -EBADF;
1817 _cleanup_free_ char *dname = NULL;
1818 r = chase(path, root, CHASE_PARENT|CHASE_PREFIX_ROOT|CHASE_EXTRACT_FILENAME, &dname, &parent_fd);
1819 if (r < 0)
1820 return r;
1821
1822 _cleanup_close_ int dir_fd = open_mkdir_at(parent_fd, dname, O_EXCL|O_CLOEXEC, mode);
1823 if (dir_fd == -EEXIST)
1824 return 0;
1825 if (dir_fd < 0)
1826 return dir_fd;
1827
1828 return userns_chown_at(dir_fd, /* fname= */ NULL, uid, gid, AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
1829 }
1830
1831 static const char *timezone_from_path(const char *path) {
1832 return PATH_STARTSWITH_SET(
1833 path,
1834 "../usr/share/zoneinfo/",
1835 "/usr/share/zoneinfo/");
1836 }
1837
1838 static bool etc_writable(void) {
1839 return !arg_read_only || IN_SET(arg_volatile_mode, VOLATILE_YES, VOLATILE_OVERLAY);
1840 }
1841
1842 static int setup_timezone(const char *dest) {
1843 _cleanup_free_ char *p = NULL, *etc = NULL;
1844 const char *where, *check;
1845 TimezoneMode m;
1846 int r;
1847
1848 assert(dest);
1849
1850 if (IN_SET(arg_timezone, TIMEZONE_AUTO, TIMEZONE_SYMLINK)) {
1851 r = readlink_malloc("/etc/localtime", &p);
1852 if (r == -ENOENT && arg_timezone == TIMEZONE_AUTO)
1853 m = etc_writable() ? TIMEZONE_DELETE : TIMEZONE_OFF;
1854 else if (r == -EINVAL && arg_timezone == TIMEZONE_AUTO) /* regular file? */
1855 m = etc_writable() ? TIMEZONE_COPY : TIMEZONE_BIND;
1856 else if (r < 0) {
1857 log_warning_errno(r, "Failed to read host's /etc/localtime symlink, not updating container timezone: %m");
1858 /* To handle warning, delete /etc/localtime and replace it with a symbolic link to a time zone data
1859 * file.
1860 *
1861 * Example:
1862 * ln -s /usr/share/zoneinfo/UTC /etc/localtime
1863 */
1864 return 0;
1865 } else if (arg_timezone == TIMEZONE_AUTO)
1866 m = etc_writable() ? TIMEZONE_SYMLINK : TIMEZONE_BIND;
1867 else
1868 m = arg_timezone;
1869 } else
1870 m = arg_timezone;
1871
1872 if (m == TIMEZONE_OFF)
1873 return 0;
1874
1875 r = chase("/etc", dest, CHASE_PREFIX_ROOT, &etc, NULL);
1876 if (r < 0) {
1877 log_warning_errno(r, "Failed to resolve /etc path in container, ignoring: %m");
1878 return 0;
1879 }
1880
1881 where = strjoina(etc, "/localtime");
1882
1883 switch (m) {
1884
1885 case TIMEZONE_DELETE:
1886 if (unlink(where) < 0)
1887 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno, "Failed to remove '%s', ignoring: %m", where);
1888
1889 return 0;
1890
1891 case TIMEZONE_SYMLINK: {
1892 _cleanup_free_ char *q = NULL;
1893 const char *z, *what;
1894
1895 z = timezone_from_path(p);
1896 if (!z) {
1897 log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
1898 return 0;
1899 }
1900
1901 r = readlink_malloc(where, &q);
1902 if (r >= 0 && streq_ptr(timezone_from_path(q), z))
1903 return 0; /* Already pointing to the right place? Then do nothing .. */
1904
1905 check = strjoina(dest, "/usr/share/zoneinfo/", z);
1906 r = chase(check, dest, 0, NULL, NULL);
1907 if (r < 0)
1908 log_debug_errno(r, "Timezone %s does not exist (or is not accessible) in container, not creating symlink: %m", z);
1909 else {
1910 if (unlink(where) < 0 && errno != ENOENT) {
1911 log_full_errno(IN_SET(errno, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING, /* Don't complain on read-only images */
1912 errno, "Failed to remove existing timezone info %s in container, ignoring: %m", where);
1913 return 0;
1914 }
1915
1916 what = strjoina("../usr/share/zoneinfo/", z);
1917 if (symlink(what, where) < 0) {
1918 log_full_errno(IN_SET(errno, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING,
1919 errno, "Failed to correct timezone of container, ignoring: %m");
1920 return 0;
1921 }
1922
1923 break;
1924 }
1925
1926 _fallthrough_;
1927 }
1928
1929 case TIMEZONE_BIND: {
1930 _cleanup_free_ char *resolved = NULL;
1931 int found;
1932
1933 found = chase(where, dest, CHASE_NONEXISTENT, &resolved, NULL);
1934 if (found < 0) {
1935 log_warning_errno(found, "Failed to resolve /etc/localtime path in container, ignoring: %m");
1936 return 0;
1937 }
1938
1939 if (found == 0) /* missing? */
1940 (void) touch(resolved);
1941
1942 r = mount_nofollow_verbose(LOG_WARNING, "/etc/localtime", resolved, NULL, MS_BIND, NULL);
1943 if (r >= 0)
1944 return mount_nofollow_verbose(LOG_ERR, NULL, resolved, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NODEV, NULL);
1945
1946 _fallthrough_;
1947 }
1948
1949 case TIMEZONE_COPY:
1950 /* If mounting failed, try to copy */
1951 r = copy_file_atomic("/etc/localtime", where, 0644, COPY_REFLINK|COPY_REPLACE);
1952 if (r < 0) {
1953 log_full_errno(IN_SET(r, -EROFS, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
1954 "Failed to copy /etc/localtime to %s, ignoring: %m", where);
1955 return 0;
1956 }
1957
1958 break;
1959
1960 default:
1961 assert_not_reached();
1962 }
1963
1964 /* Fix permissions of the symlink or file copy we just created */
1965 r = userns_lchown(where, 0, 0);
1966 if (r < 0)
1967 log_warning_errno(r, "Failed to chown /etc/localtime, ignoring: %m");
1968
1969 return 0;
1970 }
1971
1972 static int have_resolv_conf(const char *path) {
1973 assert(path);
1974
1975 if (access(path, F_OK) < 0) {
1976 if (errno == ENOENT)
1977 return 0;
1978
1979 return log_debug_errno(errno, "Failed to determine whether '%s' is available: %m", path);
1980 }
1981
1982 return 1;
1983 }
1984
1985 static int resolved_listening(void) {
1986 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1987 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1988 _cleanup_free_ char *dns_stub_listener_mode = NULL;
1989 int r;
1990
1991 /* Check if resolved is listening */
1992
1993 r = sd_bus_open_system(&bus);
1994 if (r < 0)
1995 return log_debug_errno(r, "Failed to open system bus: %m");
1996
1997 r = bus_name_has_owner(bus, "org.freedesktop.resolve1", NULL);
1998 if (r < 0)
1999 return log_debug_errno(r, "Failed to check whether the 'org.freedesktop.resolve1' bus name is taken: %m");
2000 if (r == 0)
2001 return 0;
2002
2003 r = bus_get_property_string(bus, bus_resolve_mgr, "DNSStubListener", &error, &dns_stub_listener_mode);
2004 if (r < 0)
2005 return log_debug_errno(r, "Failed to query DNSStubListener property: %s", bus_error_message(&error, r));
2006
2007 return STR_IN_SET(dns_stub_listener_mode, "udp", "yes");
2008 }
2009
2010 static int setup_resolv_conf(const char *dest) {
2011 _cleanup_free_ char *etc = NULL;
2012 const char *where, *what;
2013 ResolvConfMode m;
2014 int r;
2015
2016 assert(dest);
2017
2018 if (arg_resolv_conf == RESOLV_CONF_AUTO) {
2019 if (arg_private_network)
2020 m = RESOLV_CONF_OFF;
2021 else if (have_resolv_conf(PRIVATE_STUB_RESOLV_CONF) > 0 && resolved_listening() > 0)
2022 m = etc_writable() ? RESOLV_CONF_COPY_STUB : RESOLV_CONF_BIND_STUB;
2023 else if (have_resolv_conf("/etc/resolv.conf") > 0)
2024 m = etc_writable() ? RESOLV_CONF_COPY_HOST : RESOLV_CONF_BIND_HOST;
2025 else
2026 m = etc_writable() ? RESOLV_CONF_DELETE : RESOLV_CONF_OFF;
2027
2028 } else
2029 m = arg_resolv_conf;
2030
2031 if (m == RESOLV_CONF_OFF)
2032 return 0;
2033
2034 r = chase("/etc", dest, CHASE_PREFIX_ROOT, &etc, NULL);
2035 if (r < 0) {
2036 log_warning_errno(r, "Failed to resolve /etc path in container, ignoring: %m");
2037 return 0;
2038 }
2039
2040 where = strjoina(etc, "/resolv.conf");
2041
2042 if (m == RESOLV_CONF_DELETE) {
2043 if (unlink(where) < 0)
2044 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno, "Failed to remove '%s', ignoring: %m", where);
2045
2046 return 0;
2047 }
2048
2049 if (IN_SET(m, RESOLV_CONF_BIND_STATIC, RESOLV_CONF_REPLACE_STATIC, RESOLV_CONF_COPY_STATIC))
2050 what = PRIVATE_STATIC_RESOLV_CONF;
2051 else if (IN_SET(m, RESOLV_CONF_BIND_UPLINK, RESOLV_CONF_REPLACE_UPLINK, RESOLV_CONF_COPY_UPLINK))
2052 what = PRIVATE_UPLINK_RESOLV_CONF;
2053 else if (IN_SET(m, RESOLV_CONF_BIND_STUB, RESOLV_CONF_REPLACE_STUB, RESOLV_CONF_COPY_STUB))
2054 what = PRIVATE_STUB_RESOLV_CONF;
2055 else
2056 what = "/etc/resolv.conf";
2057
2058 if (IN_SET(m, RESOLV_CONF_BIND_HOST, RESOLV_CONF_BIND_STATIC, RESOLV_CONF_BIND_UPLINK, RESOLV_CONF_BIND_STUB)) {
2059 _cleanup_free_ char *resolved = NULL;
2060 int found;
2061
2062 found = chase(where, dest, CHASE_NONEXISTENT|CHASE_NOFOLLOW, &resolved, NULL);
2063 if (found < 0) {
2064 log_warning_errno(found, "Failed to resolve /etc/resolv.conf path in container, ignoring: %m");
2065 return 0;
2066 }
2067
2068 if (found == 0) /* missing? */
2069 (void) touch(resolved);
2070
2071 r = mount_nofollow_verbose(LOG_WARNING, what, resolved, NULL, MS_BIND, NULL);
2072 if (r >= 0)
2073 return mount_nofollow_verbose(LOG_ERR, NULL, resolved, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NODEV, NULL);
2074
2075 /* If that didn't work, let's copy the file */
2076 }
2077
2078 if (IN_SET(m, RESOLV_CONF_REPLACE_HOST, RESOLV_CONF_REPLACE_STATIC, RESOLV_CONF_REPLACE_UPLINK, RESOLV_CONF_REPLACE_STUB))
2079 r = copy_file_atomic(what, where, 0644, COPY_REFLINK|COPY_REPLACE);
2080 else
2081 r = copy_file(what, where, O_TRUNC|O_NOFOLLOW, 0644, COPY_REFLINK);
2082 if (r < 0) {
2083 /* If the file already exists as symlink, let's suppress the warning, under the assumption that
2084 * resolved or something similar runs inside and the symlink points there.
2085 *
2086 * If the disk image is read-only, there's also no point in complaining.
2087 */
2088 log_full_errno(!IN_SET(RESOLV_CONF_COPY_HOST, RESOLV_CONF_COPY_STATIC, RESOLV_CONF_COPY_UPLINK, RESOLV_CONF_COPY_STUB) &&
2089 IN_SET(r, -ELOOP, -EROFS, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
2090 "Failed to copy /etc/resolv.conf to %s, ignoring: %m", where);
2091 return 0;
2092 }
2093
2094 r = userns_lchown(where, 0, 0);
2095 if (r < 0)
2096 log_warning_errno(r, "Failed to chown /etc/resolv.conf, ignoring: %m");
2097
2098 return 0;
2099 }
2100
2101 static int setup_boot_id(void) {
2102 _cleanup_(unlink_and_freep) char *from = NULL;
2103 _cleanup_free_ char *path = NULL;
2104 sd_id128_t rnd = SD_ID128_NULL;
2105 const char *to;
2106 int r;
2107
2108 /* Generate a new randomized boot ID, so that each boot-up of the container gets a new one */
2109
2110 r = tempfn_random_child("/run", "proc-sys-kernel-random-boot-id", &path);
2111 if (r < 0)
2112 return log_error_errno(r, "Failed to generate random boot ID path: %m");
2113
2114 r = sd_id128_randomize(&rnd);
2115 if (r < 0)
2116 return log_error_errno(r, "Failed to generate random boot id: %m");
2117
2118 r = id128_write(path, ID128_FORMAT_UUID, rnd);
2119 if (r < 0)
2120 return log_error_errno(r, "Failed to write boot id: %m");
2121
2122 from = TAKE_PTR(path);
2123 to = "/proc/sys/kernel/random/boot_id";
2124
2125 r = mount_nofollow_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
2126 if (r < 0)
2127 return r;
2128
2129 return mount_nofollow_verbose(LOG_ERR, NULL, to, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
2130 }
2131
2132 static int bind_mount_devnode(const char *from, const char *to) {
2133 int r;
2134
2135 assert(from);
2136 assert(to);
2137
2138 r = touch(to);
2139 if (r < 0)
2140 return log_debug_errno(r, "Failed to touch %s: %m", to);
2141
2142 r = mount_nofollow_verbose(LOG_DEBUG, from, to, NULL, MS_BIND, NULL);
2143 if (r < 0) {
2144 (void) unlink(to);
2145 return log_error_errno(r, "Failed to bind mount %s to %s: %m", from, to);
2146 }
2147
2148 return 0;
2149 }
2150
2151 static int copy_devnode_one(const char *dest, const char *node, bool check) {
2152 int r;
2153
2154 assert(dest);
2155 assert(!isempty(node));
2156
2157 BLOCK_WITH_UMASK(0000);
2158
2159 _cleanup_free_ char *from = path_join("/dev/", node);
2160 if (!from)
2161 return log_oom();
2162
2163 if (check) {
2164 /* If 'check' is true, create /dev/fuse only when it is accessible. The check is necessary,
2165 * as some custom service units that invoke systemd-nspawn may enable DevicePolicy= without
2166 * DeviceAllow= for the device node. */
2167 _cleanup_close_ int fd = open(from, O_CLOEXEC|O_RDWR);
2168 if (fd < 0) {
2169 log_debug_errno(errno,
2170 "Failed to open %s, skipping creation of the device node in the container, ignoring: %m",
2171 from);
2172 return 0;
2173 }
2174 }
2175
2176 _cleanup_free_ char *to = path_join(dest, from);
2177 if (!to)
2178 return log_oom();
2179
2180 struct stat st;
2181 if (stat(from, &st) < 0) {
2182 if (errno != ENOENT)
2183 return log_error_errno(errno, "Failed to stat %s: %m", from);
2184
2185 log_debug_errno(errno, "Device node %s does not exist, ignoring.", from);
2186 return 0;
2187 }
2188 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode))
2189 return log_error_errno(SYNTHETIC_ERRNO(ESTALE), "%s is not a device node.", from);
2190
2191 /* Create the parent directory of the device node. Here, we assume that the path has at most one
2192 * subdirectory under /dev/, e.g. /dev/net/tun. */
2193 _cleanup_free_ char *parent = NULL;
2194 r = path_extract_directory(from, &parent);
2195 if (r < 0)
2196 return log_error_errno(r, "Failed to extract directory from %s: %m", from);
2197 r = userns_mkdir(dest, parent, 0755, 0, 0);
2198 if (r < 0)
2199 return log_error_errno(r, "Failed to create directory %s: %m", parent);
2200
2201 r = RET_NERRNO(mknod(to, st.st_mode, st.st_rdev));
2202 if (r < 0) {
2203 /* Explicitly warn the user when /dev/ is already populated. */
2204 if (r == -EEXIST)
2205 log_notice("%s/dev/ is pre-mounted and pre-populated. If a pre-mounted /dev/ is provided it needs to be an unpopulated file system.", dest);
2206
2207 /* If arg_uid_shift != 0, then we cannot fall back to use bind mount. */
2208 if (!(arg_userns_mode == USER_NAMESPACE_NO ||
2209 (arg_userns_mode == USER_NAMESPACE_FIXED && arg_uid_shift == 0))) {
2210
2211 if (arg_userns_mode != USER_NAMESPACE_MANAGED || !ERRNO_IS_NEG_PRIVILEGE(r))
2212 return log_error_errno(r, "Failed to mknod(%s): %m", to);
2213
2214 log_debug_errno(r, "Failed to create device node '%s' and running in managed mode, resorting to bind mount: %m", to);
2215 }
2216
2217 /* Some systems abusively restrict mknod but allow bind mounts. */
2218 if (bind_mount_devnode(from, to) < 0)
2219 /* use the original error code. */
2220 return log_error_errno(r, "Both mknod() and bind mount %s failed: %m", to);
2221 } else {
2222 /* mknod() succeeds, chown() it if necessary. */
2223 r = userns_lchown(to, 0, 0);
2224 if (r < 0)
2225 return log_error_errno(r, "chown() of device node %s failed: %m", to);
2226 }
2227
2228 _cleanup_free_ char *dn = path_join("/dev", S_ISCHR(st.st_mode) ? "char" : "block");
2229 if (!dn)
2230 return log_oom();
2231
2232 r = userns_mkdir(dest, dn, 0755, 0, 0);
2233 if (r < 0)
2234 return log_error_errno(r, "Failed to create '%s': %m", dn);
2235
2236 _cleanup_free_ char *sl = NULL;
2237 if (asprintf(&sl, "%s/" DEVNUM_FORMAT_STR, dn, DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
2238 return log_oom();
2239
2240 _cleanup_free_ char *prefixed = path_join(dest, sl);
2241 if (!prefixed)
2242 return log_oom();
2243
2244 _cleanup_free_ char *t = path_join("..", node);
2245 if (!t)
2246 return log_oom();
2247
2248 if (symlink(t, prefixed) < 0)
2249 log_debug_errno(errno, "Failed to symlink '%s' to '%s', ignoring: %m", t, prefixed);
2250
2251 return 0;
2252 }
2253
2254 static int copy_devnodes(const char *dest) {
2255 int r = 0;
2256
2257 assert(dest);
2258
2259 /* Required basic device nodes. */
2260 FOREACH_STRING(node, "null", "zero", "full", "random", "urandom", "tty") {
2261 r = copy_devnode_one(dest, node, /* check = */ false);
2262 if (r < 0)
2263 return r;
2264 }
2265
2266 /* Optional device nodes. */
2267 FOREACH_STRING(node, "fuse", "net/tun") {
2268 r = copy_devnode_one(dest, node, /* check = */ true);
2269 if (r < 0)
2270 return r;
2271 }
2272
2273 return 0;
2274 }
2275
2276 static int make_extra_nodes(const char *dest) {
2277 int r;
2278
2279 BLOCK_WITH_UMASK(0000);
2280
2281 FOREACH_ARRAY(node, arg_extra_nodes, arg_n_extra_nodes) {
2282 _cleanup_free_ char *path = NULL;
2283
2284 path = path_join(dest, node->path);
2285 if (!path)
2286 return log_oom();
2287
2288 dev_t dev = S_ISCHR(node->mode) || S_ISBLK(node->mode) ? makedev(node->major, node->minor) : 0;
2289 if (mknod(path, node->mode, dev) < 0)
2290 return log_error_errno(errno, "Failed to create device node '%s': %m", path);
2291
2292 r = chmod_and_chown(path, node->mode, node->uid, node->gid);
2293 if (r < 0)
2294 return log_error_errno(r, "Failed to adjust device node ownership of '%s': %m", path);
2295 }
2296
2297 return 0;
2298 }
2299
2300 static int setup_pts(const char *dest, uid_t chown_uid) {
2301 _cleanup_free_ char *options = NULL;
2302 int r;
2303
2304 #if HAVE_SELINUX
2305 if (arg_selinux_apifs_context)
2306 (void) asprintf(&options,
2307 "newinstance,ptmxmode=0666,mode=" STRINGIFY(TTY_MODE) ",gid=" GID_FMT ",context=\"%s\"",
2308 chown_uid + TTY_GID,
2309 arg_selinux_apifs_context);
2310 else
2311 #endif
2312 (void) asprintf(&options,
2313 "newinstance,ptmxmode=0666,mode=" STRINGIFY(TTY_MODE) ",gid=" GID_FMT,
2314 chown_uid + TTY_GID);
2315
2316 if (!options)
2317 return log_oom();
2318
2319 /* Mount /dev/pts itself */
2320 _cleanup_free_ char *p = path_join(dest, "/dev/pts");
2321 if (!p)
2322 return log_oom();
2323
2324 r = RET_NERRNO(mkdir(p, 0755));
2325 if (r < 0)
2326 return log_error_errno(r, "Failed to create /dev/pts: %m");
2327
2328 r = mount_nofollow_verbose(LOG_ERR, "devpts", p, "devpts", MS_NOSUID|MS_NOEXEC, options);
2329 if (r < 0)
2330 return r;
2331 r = userns_lchown(p, 0, 0);
2332 if (r < 0)
2333 return log_error_errno(r, "Failed to chown /dev/pts: %m");
2334
2335 /* Create /dev/ptmx symlink */
2336 free(p);
2337 p = path_join(dest, "/dev/ptmx");
2338 if (!p)
2339 return log_oom();
2340
2341 if (symlink("pts/ptmx", p) < 0)
2342 return log_error_errno(errno, "Failed to create /dev/ptmx symlink: %m");
2343 r = userns_lchown(p, 0, 0);
2344 if (r < 0)
2345 return log_error_errno(r, "Failed to chown /dev/ptmx: %m");
2346
2347 /* And fix /dev/pts/ptmx ownership */
2348 free(p);
2349 p = path_join(dest, "/dev/pts/ptmx");
2350 if (!p)
2351 return log_oom();
2352
2353 r = userns_lchown(p, 0, 0);
2354 if (r < 0)
2355 return log_error_errno(r, "Failed to chown /dev/pts/ptmx: %m");
2356
2357 return 0;
2358 }
2359
2360 static int setup_stdio_as_dev_console(void) {
2361 _cleanup_close_ int terminal = -EBADF;
2362 int r;
2363
2364 /* We open the TTY in O_NOCTTY mode, so that we do not become controller yet. We'll do that later
2365 * explicitly, if we are configured to. */
2366 terminal = open_terminal("/dev/console", O_RDWR|O_NOCTTY);
2367 if (terminal < 0)
2368 return log_error_errno(terminal, "Failed to open console: %m");
2369
2370 /* Make sure we can continue logging to the original stderr, even if
2371 * stderr points elsewhere now */
2372 r = log_dup_console();
2373 if (r < 0)
2374 return log_error_errno(r, "Failed to duplicate stderr: %m");
2375
2376 /* invalidates 'terminal' on success and failure */
2377 r = rearrange_stdio(terminal, terminal, terminal);
2378 TAKE_FD(terminal);
2379 if (r < 0)
2380 return log_error_errno(r, "Failed to move console to stdin/stdout/stderr: %m");
2381
2382 return 0;
2383 }
2384
2385 static int setup_dev_console(const char *console) {
2386 _cleanup_free_ char *p = NULL;
2387 int r;
2388
2389 /* Create /dev/console symlink */
2390 r = path_make_relative("/dev", console, &p);
2391 if (r < 0)
2392 return log_error_errno(r, "Failed to create relative path: %m");
2393
2394 if (symlink(p, "/dev/console") < 0)
2395 return log_error_errno(errno, "Failed to create /dev/console symlink: %m");
2396
2397 return 0;
2398 }
2399
2400 static int setup_keyring(void) {
2401 key_serial_t keyring;
2402
2403 /* Allocate a new session keyring for the container. This makes sure the keyring of the session
2404 * systemd-nspawn was invoked from doesn't leak into the container. Note that by default we block
2405 * keyctl() and request_key() anyway via seccomp so doing this operation isn't strictly necessary,
2406 * but in case people explicitly allow-list these system calls let's make sure we don't leak anything
2407 * into the container. */
2408
2409 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
2410 if (keyring == -1) {
2411 if (errno == ENOSYS)
2412 log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
2413 else if (ERRNO_IS_PRIVILEGE(errno))
2414 log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
2415 else
2416 return log_error_errno(errno, "Setting up kernel keyring failed: %m");
2417 }
2418
2419 return 0;
2420 }
2421
2422 int make_run_host(const char *root) {
2423 int r;
2424
2425 assert(root);
2426
2427 r = userns_mkdir(root, "/run/host", 0755, 0, 0);
2428 if (r < 0)
2429 return log_error_errno(r, "Failed to create /run/host/: %m");
2430
2431 return 0;
2432 }
2433
2434 static int setup_credentials(const char *root) {
2435 bool world_readable = false;
2436 int r;
2437
2438 if (arg_credentials.n_credentials == 0)
2439 return 0;
2440
2441 /* If starting a single-process container as a non-root user, the uid will only be resolved after we
2442 * are inside the inner child, when credential directories and files are already read-only, so they
2443 * are unusable as the single process won't have access to them. We also don't have access to the
2444 * uid that will actually be used from here, as we are setting credentials up from the outer child.
2445 * In order to make them usable as requested by the configuration, make them world readable in that
2446 * case, as by definition there are no other processes in that case besides the one being started,
2447 * which is being configured to be able to access credentials, and any of its children which will
2448 * inherit its privileges anyway. To ensure this, also enforce (and document) that
2449 * --no-new-privileges is necessary for this combination to work. */
2450 if (arg_no_new_privileges && !isempty(arg_user) && !STR_IN_SET(arg_user, "root", "0") &&
2451 arg_start_mode == START_PID1)
2452 world_readable = true;
2453
2454 r = make_run_host(root);
2455 if (r < 0)
2456 return r;
2457
2458 r = userns_mkdir(root, "/run/host/credentials", world_readable ? 0777 : 0700, 0, 0);
2459 if (r < 0)
2460 return log_error_errno(r, "Failed to create /run/host/credentials: %m");
2461
2462 _cleanup_free_ char *q = path_join(root, "/run/host/credentials");
2463 if (!q)
2464 return log_oom();
2465
2466 r = mount_nofollow_verbose(LOG_ERR, NULL, q, "ramfs", MS_NOSUID|MS_NOEXEC|MS_NODEV, "mode=0700");
2467 if (r < 0)
2468 return r;
2469
2470 FOREACH_ARRAY(cred, arg_credentials.credentials, arg_credentials.n_credentials) {
2471 _cleanup_free_ char *j = NULL;
2472 _cleanup_close_ int fd = -EBADF;
2473
2474 j = path_join(q, cred->id);
2475 if (!j)
2476 return log_oom();
2477
2478 fd = open(j, O_CREAT|O_EXCL|O_WRONLY|O_CLOEXEC|O_NOFOLLOW, world_readable ? 0666 : 0600);
2479 if (fd < 0)
2480 return log_error_errno(errno, "Failed to create credential file %s: %m", j);
2481
2482 r = loop_write(fd, cred->data, cred->size);
2483 if (r < 0)
2484 return log_error_errno(r, "Failed to write credential to file %s: %m", j);
2485
2486 if (fchmod(fd, world_readable ? 0444 : 0400) < 0)
2487 return log_error_errno(errno, "Failed to adjust access mode of %s: %m", j);
2488
2489 if (arg_userns_mode != USER_NAMESPACE_NO)
2490 if (fchown(fd, arg_uid_shift, arg_uid_shift) < 0)
2491 return log_error_errno(errno, "Failed to adjust ownership of %s: %m", j);
2492 }
2493
2494 if (chmod(q, world_readable ? 0555 : 0500) < 0)
2495 return log_error_errno(errno, "Failed to adjust access mode of %s: %m", q);
2496
2497 r = userns_lchown(q, 0, 0);
2498 if (r < 0)
2499 return r;
2500
2501 /* Make both mount and superblock read-only now */
2502 r = mount_nofollow_verbose(LOG_ERR, NULL, q, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
2503 if (r < 0)
2504 return r;
2505
2506 return mount_nofollow_verbose(LOG_ERR, NULL, q, NULL, MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, "mode=0500");
2507 }
2508
2509 static int setup_kmsg(int fd_inner_socket) {
2510 _cleanup_(unlink_and_freep) char *from = NULL;
2511 _cleanup_free_ char *fifo = NULL;
2512 _cleanup_close_ int fd = -EBADF;
2513 int r;
2514
2515 assert(fd_inner_socket >= 0);
2516
2517 BLOCK_WITH_UMASK(0000);
2518
2519 /* We create the kmsg FIFO as a temporary file in /run, but immediately delete it after bind mounting it to
2520 * /proc/kmsg. While FIFOs on the reading side behave very similar to /proc/kmsg, their writing side behaves
2521 * differently from /dev/kmsg in that writing blocks when nothing is reading. In order to avoid any problems
2522 * with containers deadlocking due to this we simply make /dev/kmsg unavailable to the container. */
2523
2524 r = tempfn_random_child("/run", "proc-kmsg", &fifo);
2525 if (r < 0)
2526 return log_error_errno(r, "Failed to generate kmsg path: %m");
2527
2528 if (mkfifo(fifo, 0600) < 0)
2529 return log_error_errno(errno, "mkfifo() for /run/kmsg failed: %m");
2530
2531 from = TAKE_PTR(fifo);
2532
2533 r = mount_nofollow_verbose(LOG_ERR, from, "/proc/kmsg", NULL, MS_BIND, NULL);
2534 if (r < 0)
2535 return r;
2536
2537 fd = open(from, O_RDWR|O_NONBLOCK|O_CLOEXEC);
2538 if (fd < 0)
2539 return log_error_errno(errno, "Failed to open fifo: %m");
2540
2541 /* Store away the fd in the socket, so that it stays open as long as we run the child */
2542 r = send_one_fd(fd_inner_socket, fd, 0);
2543 if (r < 0)
2544 return log_error_errno(r, "Failed to send FIFO fd: %m");
2545
2546 return 0;
2547 }
2548
2549 struct ExposeArgs {
2550 union in_addr_union address4;
2551 union in_addr_union address6;
2552 struct FirewallContext *fw_ctx;
2553 };
2554
2555 static int on_address_change(sd_netlink *rtnl, sd_netlink_message *m, void *userdata) {
2556 struct ExposeArgs *args = ASSERT_PTR(userdata);
2557
2558 assert(rtnl);
2559 assert(m);
2560
2561 (void) expose_port_execute(rtnl, &args->fw_ctx, arg_expose_ports, AF_INET, &args->address4);
2562 (void) expose_port_execute(rtnl, &args->fw_ctx, arg_expose_ports, AF_INET6, &args->address6);
2563 return 0;
2564 }
2565
2566 static int setup_hostname(void) {
2567 int r;
2568
2569 if ((arg_clone_ns_flags & CLONE_NEWUTS) == 0)
2570 return 0;
2571
2572 r = sethostname_idempotent(arg_hostname ?: arg_machine);
2573 if (r < 0)
2574 return log_error_errno(r, "Failed to set hostname: %m");
2575
2576 return 0;
2577 }
2578
2579 static int setup_journal(const char *directory) {
2580 _cleanup_free_ char *d = NULL;
2581 sd_id128_t this_id;
2582 bool try;
2583 int r;
2584
2585 /* Don't link journals in ephemeral mode */
2586 if (arg_ephemeral)
2587 return 0;
2588
2589 if (arg_link_journal == LINK_NO)
2590 return 0;
2591
2592 try = arg_link_journal_try || arg_link_journal == LINK_AUTO;
2593
2594 r = sd_id128_get_machine(&this_id);
2595 if (r < 0)
2596 return log_error_errno(r, "Failed to retrieve machine ID: %m");
2597
2598 if (sd_id128_equal(arg_uuid, this_id)) {
2599 log_full(try ? LOG_WARNING : LOG_ERR,
2600 "Host and machine ids are equal (%s): refusing to link journals", SD_ID128_TO_STRING(arg_uuid));
2601 if (try)
2602 return 0;
2603 return -EEXIST;
2604 }
2605
2606 FOREACH_STRING(dirname, "/var", "/var/log", "/var/log/journal") {
2607 r = userns_mkdir(directory, dirname, 0755, 0, 0);
2608 if (r < 0) {
2609 bool ignore = r == -EROFS && try;
2610 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, r,
2611 "Failed to create %s%s: %m", dirname, ignore ? ", ignoring" : "");
2612 return ignore ? 0 : r;
2613 }
2614 }
2615
2616 _cleanup_free_ char *p = path_join("/var/log/journal/", SD_ID128_TO_STRING(arg_uuid));
2617 if (!p)
2618 return log_oom();
2619
2620 _cleanup_free_ char *q = path_join(directory, p);
2621 if (!q)
2622 return log_oom();
2623
2624 if (path_is_mount_point(p) > 0) {
2625 if (try)
2626 return 0;
2627
2628 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
2629 "%s: already a mount point, refusing to use for journal", p);
2630 }
2631
2632 if (path_is_mount_point(q) > 0) {
2633 if (try)
2634 return 0;
2635
2636 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
2637 "%s: already a mount point, refusing to use for journal", q);
2638 }
2639
2640 r = readlink_and_make_absolute(p, &d);
2641 if (r >= 0) {
2642 if (IN_SET(arg_link_journal, LINK_GUEST, LINK_AUTO) &&
2643 path_equal(d, q)) {
2644
2645 r = userns_mkdir(directory, p, 0755, 0, 0);
2646 if (r < 0)
2647 log_warning_errno(r, "Failed to create directory %s: %m", q);
2648 return 0;
2649 }
2650
2651 if (unlink(p) < 0)
2652 return log_error_errno(errno, "Failed to remove symlink %s: %m", p);
2653 } else if (r == -EINVAL) {
2654
2655 if (arg_link_journal == LINK_GUEST &&
2656 rmdir(p) < 0) {
2657
2658 if (errno == ENOTDIR) {
2659 log_error("%s already exists and is neither a symlink nor a directory", p);
2660 return r;
2661 } else
2662 return log_error_errno(errno, "Failed to remove %s: %m", p);
2663 }
2664 } else if (r != -ENOENT)
2665 return log_error_errno(r, "readlink(%s) failed: %m", p);
2666
2667 if (arg_link_journal == LINK_GUEST) {
2668
2669 if (symlink(q, p) < 0) {
2670 if (try) {
2671 log_debug_errno(errno, "Failed to symlink %s to %s, skipping journal setup: %m", q, p);
2672 return 0;
2673 } else
2674 return log_error_errno(errno, "Failed to symlink %s to %s: %m", q, p);
2675 }
2676
2677 r = userns_mkdir(directory, p, 0755, 0, 0);
2678 if (r < 0)
2679 log_warning_errno(r, "Failed to create directory %s: %m", q);
2680 return 0;
2681 }
2682
2683 if (arg_link_journal == LINK_HOST) {
2684 /* don't create parents here — if the host doesn't have
2685 * permanent journal set up, don't force it here */
2686
2687 r = RET_NERRNO(mkdir(p, 0755));
2688 if (r < 0 && r != -EEXIST) {
2689 if (try) {
2690 log_debug_errno(r, "Failed to create %s, skipping journal setup: %m", p);
2691 return 0;
2692 } else
2693 return log_error_errno(r, "Failed to create %s: %m", p);
2694 }
2695
2696 } else if (access(p, F_OK) < 0)
2697 return 0;
2698
2699 if (dir_is_empty(q, /* ignore_hidden_or_backup= */ false) == 0)
2700 log_warning("%s is not empty, proceeding anyway.", q);
2701
2702 r = userns_mkdir(directory, p, 0755, 0, 0);
2703 if (r < 0)
2704 return log_error_errno(r, "Failed to create %s: %m", q);
2705
2706 r = mount_nofollow_verbose(LOG_DEBUG, p, q, NULL, MS_BIND, NULL);
2707 if (r < 0)
2708 return log_error_errno(r, "Failed to bind mount journal from host into guest: %m");
2709
2710 return 0;
2711 }
2712
2713 static int drop_capabilities(uid_t uid) {
2714 CapabilityQuintet q;
2715
2716 /* Let's initialize all five capability sets to something valid. If the quintet was configured via
2717 * OCI use that, but fill in missing bits. If it wasn't then derive the quintet in full from
2718 * arg_caps_retain. */
2719
2720 if (capability_quintet_is_set(&arg_full_capabilities)) {
2721 q = arg_full_capabilities;
2722
2723 if (q.bounding == UINT64_MAX)
2724 q.bounding = uid == 0 ? arg_caps_retain : 0;
2725
2726 if (q.effective == UINT64_MAX)
2727 q.effective = uid == 0 ? q.bounding : 0;
2728
2729 if (q.inheritable == UINT64_MAX)
2730 q.inheritable = uid == 0 ? q.bounding : arg_caps_ambient;
2731
2732 if (q.permitted == UINT64_MAX)
2733 q.permitted = uid == 0 ? q.bounding : arg_caps_ambient;
2734
2735 if (q.ambient == UINT64_MAX)
2736 q.ambient = arg_caps_ambient;
2737
2738 if (capability_quintet_mangle(&q))
2739 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Cannot set capabilities that are not in the current bounding set.");
2740
2741 } else {
2742 q = (CapabilityQuintet) {
2743 .bounding = arg_caps_retain,
2744 .effective = uid == 0 ? arg_caps_retain : 0,
2745 .inheritable = uid == 0 ? arg_caps_retain : arg_caps_ambient,
2746 .permitted = uid == 0 ? arg_caps_retain : arg_caps_ambient,
2747 .ambient = arg_caps_ambient,
2748 };
2749
2750 /* If we're not using OCI, proceed with mangled capabilities (so we don't error out)
2751 * in order to maintain the same behavior as systemd < 242. */
2752 if (capability_quintet_mangle(&q))
2753 log_full(arg_quiet ? LOG_DEBUG : LOG_WARNING,
2754 "Some capabilities will not be set because they are not in the current bounding set.");
2755
2756 }
2757
2758 return capability_quintet_enforce(&q);
2759 }
2760
2761 static int reset_audit_loginuid(void) {
2762 _cleanup_free_ char *p = NULL;
2763 int r;
2764
2765 if ((arg_clone_ns_flags & CLONE_NEWPID) == 0)
2766 return 0;
2767
2768 /* if we are in managed userns mode, then we are already in our userns, hence we cannot reset the
2769 * loginuid anyway, hence don't bother */
2770 if (arg_userns_mode == USER_NAMESPACE_MANAGED)
2771 return 0;
2772
2773 r = read_virtual_file("/proc/self/loginuid", SIZE_MAX, &p, /* ret_size= */ NULL);
2774 if (r == -ENOENT)
2775 return 0;
2776 if (r < 0)
2777 return log_error_errno(r, "Failed to read /proc/self/loginuid: %m");
2778
2779 /* Already reset? */
2780 if (streq(p, "4294967295"))
2781 return 0;
2782
2783 r = write_string_file("/proc/self/loginuid", "4294967295", WRITE_STRING_FILE_DISABLE_BUFFER);
2784 if (r < 0) {
2785 log_error_errno(r,
2786 "Failed to reset audit login UID. This probably means that your kernel is too\n"
2787 "old and you have audit enabled. Note that the auditing subsystem is known to\n"
2788 "be incompatible with containers on old kernels. Please make sure to upgrade\n"
2789 "your kernel or to off auditing with 'audit=0' on the kernel command line before\n"
2790 "using systemd-nspawn. Sleeping for 5s... (%m)");
2791
2792 sleep(5);
2793 }
2794
2795 return 0;
2796 }
2797
2798 static int mount_tunnel_dig(const char *root) {
2799 int r;
2800
2801 if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
2802 log_debug("Not digging mount tunnel, because running in managed user namespace mode.");
2803 return 0;
2804 }
2805
2806 (void) mkdir_p("/run/systemd/nspawn/", 0755);
2807 (void) mkdir_p("/run/systemd/nspawn/propagate", 0600);
2808 _cleanup_free_ char *p = path_join("/run/systemd/nspawn/propagate/", arg_machine);
2809 if (!p)
2810 return log_oom();
2811
2812 (void) mkdir_p(p, 0600);
2813
2814 r = make_run_host(root);
2815 if (r < 0)
2816 return r;
2817
2818 r = userns_mkdir(root, NSPAWN_MOUNT_TUNNEL, 0600, 0, 0);
2819 if (r < 0)
2820 return log_error_errno(r, "Failed to create "NSPAWN_MOUNT_TUNNEL": %m");
2821
2822 _cleanup_free_ char *q = path_join(root, NSPAWN_MOUNT_TUNNEL);
2823 if (!q)
2824 return log_oom();
2825
2826 r = mount_nofollow_verbose(LOG_ERR, p, q, NULL, MS_BIND, NULL);
2827 if (r < 0)
2828 return r;
2829
2830 r = mount_nofollow_verbose(LOG_ERR, NULL, q, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
2831 if (r < 0)
2832 return r;
2833
2834 return 0;
2835 }
2836
2837 static int mount_tunnel_open(void) {
2838 int r;
2839
2840 if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
2841 log_debug("Not opening up mount tunnel, because running in managed user namespace mode.");
2842 return 0;
2843 }
2844
2845 r = mount_follow_verbose(LOG_ERR, NULL, NSPAWN_MOUNT_TUNNEL, NULL, MS_SLAVE, NULL);
2846 if (r < 0)
2847 return r;
2848
2849 return 0;
2850 }
2851
2852 static int setup_machine_id(const char *directory) {
2853 int r;
2854
2855 /* If the UUID in the container is already set, then that's what counts, and we use. If it isn't set, and the
2856 * caller passed --uuid=, then we'll pass it in the $container_uuid env var to PID 1 of the container. The
2857 * assumption is that PID 1 will then write it to /etc/machine-id to make it persistent. If --uuid= is not
2858 * passed we generate a random UUID, and pass it via $container_uuid. In effect this means that /etc/machine-id
2859 * in the container and our idea of the container UUID will always be in sync (at least if PID 1 in the
2860 * container behaves nicely). */
2861
2862 r = id128_get_machine(directory, &arg_uuid);
2863 if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) {
2864 /* If the file is missing, empty, or uninitialized, we don't mind */
2865 if (sd_id128_is_null(arg_uuid)) {
2866 r = sd_id128_randomize(&arg_uuid);
2867 if (r < 0)
2868 return log_error_errno(r, "Failed to acquire randomized machine UUID: %m");
2869 }
2870 } else if (r < 0)
2871 return log_error_errno(r, "Failed to read machine ID from container image: %m");
2872
2873 return 0;
2874 }
2875
2876 static int recursive_chown(const char *directory, uid_t shift, uid_t range) {
2877 int r;
2878
2879 assert(directory);
2880
2881 if (arg_userns_mode == USER_NAMESPACE_NO || arg_userns_ownership != USER_NAMESPACE_OWNERSHIP_CHOWN)
2882 return 0;
2883
2884 r = path_patch_uid(directory, arg_uid_shift, arg_uid_range);
2885 if (r == -EOPNOTSUPP)
2886 return log_error_errno(r, "Automatic UID/GID adjusting is only supported for UID/GID ranges starting at multiples of 2^16 with a range of 2^16.");
2887 if (r == -EBADE)
2888 return log_error_errno(r, "Upper 16 bits of root directory UID and GID do not match.");
2889 if (r < 0)
2890 return log_error_errno(r, "Failed to adjust UID/GID shift of OS tree: %m");
2891 if (r == 0)
2892 log_debug("Root directory of image is already owned by the right UID/GID range, skipping recursive chown operation.");
2893 else
2894 log_debug("Patched directory tree to match UID/GID range.");
2895
2896 return r;
2897 }
2898
2899 /*
2900 * Return values:
2901 * < 0 : wait_for_terminate() failed to get the state of the
2902 * container, the container was terminated by a signal, or
2903 * failed for an unknown reason. No change is made to the
2904 * container argument.
2905 * > 0 : The program executed in the container terminated with an
2906 * error. The exit code of the program executed in the
2907 * container is returned. The container argument has been set
2908 * to CONTAINER_TERMINATED.
2909 * 0 : The container is being rebooted, has been shut down or exited
2910 * successfully. The container argument has been set to either
2911 * CONTAINER_TERMINATED or CONTAINER_REBOOTED.
2912 *
2913 * That is, success is indicated by a return value of zero, and an
2914 * error is indicated by a non-zero value.
2915 */
2916 static int wait_for_container(PidRef *pid, ContainerStatus *container) {
2917 siginfo_t status;
2918 int r;
2919
2920 assert(pidref_is_set(pid));
2921
2922 r = pidref_wait_for_terminate(pid, &status);
2923 if (r < 0)
2924 return log_warning_errno(r, "Failed to wait for container: %m");
2925
2926 pidref_done(pid);
2927
2928 switch (status.si_code) {
2929
2930 case CLD_EXITED:
2931 if (status.si_status == 0)
2932 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s exited successfully.", arg_machine);
2933 else
2934 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s failed with error code %i.", arg_machine, status.si_status);
2935
2936 *container = CONTAINER_TERMINATED;
2937 return status.si_status;
2938
2939 case CLD_KILLED:
2940 if (status.si_status == SIGINT) {
2941 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s has been shut down.", arg_machine);
2942 *container = CONTAINER_TERMINATED;
2943 return 0;
2944
2945 } else if (status.si_status == SIGHUP) {
2946 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s is being rebooted.", arg_machine);
2947 *container = CONTAINER_REBOOTED;
2948 return 0;
2949 }
2950
2951 _fallthrough_;
2952 case CLD_DUMPED:
2953 return log_error_errno(SYNTHETIC_ERRNO(EIO),
2954 "Container %s terminated by signal %s.", arg_machine, signal_to_string(status.si_status));
2955
2956 default:
2957 return log_error_errno(SYNTHETIC_ERRNO(EIO),
2958 "Container %s failed due to unknown reason.", arg_machine);
2959 }
2960 }
2961
2962 static int on_orderly_shutdown(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
2963 PidRef *pid = ASSERT_PTR(userdata);
2964
2965 if (pidref_is_set(pid))
2966 if (pidref_kill(pid, arg_kill_signal) >= 0) {
2967 log_info("Trying to halt container. Send SIGTERM again to trigger immediate termination.");
2968 sd_event_source_set_userdata(s, NULL);
2969 return 0;
2970 }
2971
2972 sd_event_exit(sd_event_source_get_event(s), 0);
2973 return 0;
2974 }
2975
2976 static int on_sigchld(sd_event_source *s, const struct signalfd_siginfo *ssi, void *userdata) {
2977
2978 assert(s);
2979 assert(ssi);
2980
2981 PidRef *pid = ASSERT_PTR(userdata);
2982 for (;;) {
2983 siginfo_t si = {};
2984
2985 if (waitid(P_ALL, 0, &si, WNOHANG|WNOWAIT|WEXITED) < 0)
2986 return log_error_errno(errno, "Failed to waitid(): %m");
2987 if (si.si_pid == 0) /* No pending children. */
2988 break;
2989 if (si.si_pid == pid->pid) {
2990 /* The main process we care for has exited. Return from
2991 * signal handler but leave the zombie. */
2992 sd_event_exit(sd_event_source_get_event(s), 0);
2993 break;
2994 }
2995
2996 /* Reap all other children. */
2997 (void) waitid(P_PID, si.si_pid, &si, WNOHANG|WEXITED);
2998 }
2999
3000 return 0;
3001 }
3002
3003 static int on_request_stop(sd_bus_message *m, void *userdata, sd_bus_error *error) {
3004 PidRef *pid = ASSERT_PTR(userdata);
3005
3006 assert(m);
3007
3008 if (arg_kill_signal > 0) {
3009 log_info("Container termination requested. Attempting to halt container.");
3010 (void) pidref_kill(pid, arg_kill_signal);
3011 } else {
3012 log_info("Container termination requested. Exiting.");
3013 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), 0);
3014 }
3015
3016 return 0;
3017 }
3018
3019 static int pick_paths(void) {
3020 int r;
3021
3022 if (arg_directory) {
3023 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3024 PickFilter filter = pick_filter_image_dir;
3025
3026 filter.architecture = arg_architecture;
3027
3028 r = path_pick_update_warn(
3029 &arg_directory,
3030 &filter,
3031 PICK_ARCHITECTURE|PICK_TRIES,
3032 &result);
3033 if (r < 0) {
3034 /* Accept ENOENT here so that the --template= logic can work */
3035 if (r != -ENOENT)
3036 return r;
3037 } else
3038 arg_architecture = result.architecture;
3039 }
3040
3041 if (arg_image) {
3042 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3043 PickFilter filter = pick_filter_image_raw;
3044
3045 filter.architecture = arg_architecture;
3046
3047 r = path_pick_update_warn(
3048 &arg_image,
3049 &filter,
3050 PICK_ARCHITECTURE|PICK_TRIES,
3051 &result);
3052 if (r < 0)
3053 return r;
3054
3055 arg_architecture = result.architecture;
3056 }
3057
3058 if (arg_template) {
3059 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3060 PickFilter filter = pick_filter_image_dir;
3061
3062 filter.architecture = arg_architecture;
3063
3064 r = path_pick_update_warn(
3065 &arg_template,
3066 &filter,
3067 PICK_ARCHITECTURE,
3068 &result);
3069 if (r < 0)
3070 return r;
3071
3072 arg_architecture = result.architecture;
3073 }
3074
3075 return 0;
3076 }
3077
3078 static int determine_names(void) {
3079 int r;
3080
3081 if (arg_template && !arg_directory && arg_machine) {
3082
3083 /* If --template= was specified then we should not search for a machine, but instead create a
3084 * new one in /var/lib/machine. */
3085
3086 arg_directory = path_join("/var/lib/machines", arg_machine);
3087 if (!arg_directory)
3088 return log_oom();
3089 }
3090
3091 if (!arg_image && !arg_directory) {
3092 if (arg_machine) {
3093 _cleanup_(image_unrefp) Image *i = NULL;
3094
3095 r = image_find(arg_privileged ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER,
3096 IMAGE_MACHINE, arg_machine, NULL, &i);
3097 if (r == -ENOENT)
3098 return log_error_errno(r, "No image for machine '%s'.", arg_machine);
3099 if (r < 0)
3100 return log_error_errno(r, "Failed to find image for machine '%s': %m", arg_machine);
3101
3102 if (IN_SET(i->type, IMAGE_RAW, IMAGE_BLOCK))
3103 r = free_and_strdup(&arg_image, i->path);
3104 else
3105 r = free_and_strdup(&arg_directory, i->path);
3106 if (r < 0)
3107 return log_oom();
3108
3109 if (!arg_ephemeral)
3110 arg_read_only = arg_read_only || i->read_only;
3111 } else {
3112 r = safe_getcwd(&arg_directory);
3113 if (r < 0)
3114 return log_error_errno(r, "Failed to determine current directory: %m");
3115 }
3116
3117 if (!arg_directory && !arg_image)
3118 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine path, please use -D or -i.");
3119 }
3120
3121 if (!arg_machine) {
3122 if (arg_directory && path_equal(arg_directory, "/")) {
3123 arg_machine = gethostname_malloc();
3124 if (!arg_machine)
3125 return log_oom();
3126 } else if (arg_image) {
3127 char *e;
3128
3129 r = path_extract_filename(arg_image, &arg_machine);
3130 if (r < 0)
3131 return log_error_errno(r, "Failed to extract file name from '%s': %m", arg_image);
3132
3133 /* Truncate suffix if there is one */
3134 e = endswith(arg_machine, ".raw");
3135 if (e)
3136 *e = 0;
3137 } else {
3138 r = path_extract_filename(arg_directory, &arg_machine);
3139 if (r < 0)
3140 return log_error_errno(r, "Failed to extract file name from '%s': %m", arg_directory);
3141 }
3142
3143 hostname_cleanup(arg_machine);
3144 if (!hostname_is_valid(arg_machine, 0))
3145 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine machine name automatically, please use -M.");
3146
3147 /* Copy the machine name before the random suffix is added below, otherwise we won't be able
3148 * to match fixed config file names. */
3149 arg_settings_filename = strjoin(arg_machine, ".nspawn");
3150 if (!arg_settings_filename)
3151 return log_oom();
3152
3153 /* Add a random suffix when this is an ephemeral machine, so that we can run many
3154 * instances at once without manually having to specify -M each time. */
3155 if (arg_ephemeral)
3156 if (strextendf(&arg_machine, "-%016" PRIx64, random_u64()) < 0)
3157 return log_oom();
3158 } else {
3159 arg_settings_filename = strjoin(arg_machine, ".nspawn");
3160 if (!arg_settings_filename)
3161 return log_oom();
3162 }
3163
3164 return 0;
3165 }
3166
3167 static int chase_and_update(char **p, unsigned flags) {
3168 char *chased;
3169 int r;
3170
3171 assert(p);
3172
3173 if (!*p)
3174 return 0;
3175
3176 r = chase(*p, NULL, flags, &chased, NULL);
3177 if (r < 0)
3178 return log_error_errno(r, "Failed to resolve path %s: %m", *p);
3179
3180 return free_and_replace(*p, chased);
3181 }
3182
3183 static int determine_uid_shift(const char *directory) {
3184 assert(directory);
3185
3186 if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
3187 /* In managed mode we should already know the UID shift */
3188 assert(uid_is_valid(arg_uid_shift));
3189 return 0;
3190 }
3191
3192 if (arg_userns_mode == USER_NAMESPACE_NO) {
3193 arg_uid_shift = 0;
3194 return 0;
3195 }
3196
3197 if (arg_uid_shift == UID_INVALID) {
3198 struct stat st;
3199
3200 /* Read the UID shift off the image. Maybe we can reuse this to avoid chowning. */
3201
3202 if (stat(directory, &st) < 0)
3203 return log_error_errno(errno, "Failed to determine UID base of %s: %m", directory);
3204
3205 arg_uid_shift = st.st_uid & UINT32_C(0xffff0000);
3206
3207 if (arg_uid_shift != (st.st_gid & UINT32_C(0xffff0000)))
3208 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3209 "UID and GID base of %s don't match.", directory);
3210
3211 arg_uid_range = UINT32_C(0x10000);
3212
3213 if (arg_uid_shift != 0) {
3214 /* If the image is shifted already, then we'll fall back to classic chowning, for
3215 * compatibility (and simplicity), or refuse if mapping is explicitly requested. */
3216
3217 if (arg_userns_ownership == USER_NAMESPACE_OWNERSHIP_AUTO) {
3218 log_debug("UID base of %s is non-zero, not using UID mapping.", directory);
3219 arg_userns_ownership = USER_NAMESPACE_OWNERSHIP_CHOWN;
3220 } else if (arg_userns_ownership == USER_NAMESPACE_OWNERSHIP_MAP)
3221 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3222 "UID base of %s is not zero, UID mapping not supported.", directory);
3223 }
3224 }
3225
3226 if (!userns_shift_range_valid(arg_uid_shift, arg_uid_range))
3227 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "UID base too high for UID range.");
3228
3229 return 0;
3230 }
3231
3232 static unsigned long effective_clone_ns_flags(void) {
3233 unsigned long flags = arg_clone_ns_flags;
3234
3235 if (arg_private_network)
3236 flags |= CLONE_NEWNET;
3237 if (arg_use_cgns)
3238 flags |= CLONE_NEWCGROUP;
3239 if (arg_userns_mode != USER_NAMESPACE_NO)
3240 flags |= CLONE_NEWUSER;
3241
3242 return flags;
3243 }
3244
3245 static int patch_sysctl(void) {
3246
3247 /* This table is inspired by runc's sysctl() function */
3248 static const struct {
3249 const char *key;
3250 bool prefix;
3251 unsigned long clone_flags;
3252 } safe_sysctl[] = {
3253 { "kernel.hostname", false, CLONE_NEWUTS },
3254 { "kernel.domainname", false, CLONE_NEWUTS },
3255 { "kernel.msgmax", false, CLONE_NEWIPC },
3256 { "kernel.msgmnb", false, CLONE_NEWIPC },
3257 { "kernel.msgmni", false, CLONE_NEWIPC },
3258 { "kernel.sem", false, CLONE_NEWIPC },
3259 { "kernel.shmall", false, CLONE_NEWIPC },
3260 { "kernel.shmmax", false, CLONE_NEWIPC },
3261 { "kernel.shmmni", false, CLONE_NEWIPC },
3262 { "fs.mqueue.", true, CLONE_NEWIPC },
3263 { "net.", true, CLONE_NEWNET },
3264 };
3265
3266 unsigned long flags;
3267 int r;
3268
3269 flags = effective_clone_ns_flags();
3270
3271 STRV_FOREACH_PAIR(k, v, arg_sysctl) {
3272 bool good = false;
3273
3274 FOREACH_ELEMENT(i, safe_sysctl) {
3275 if (!FLAGS_SET(flags, i->clone_flags))
3276 continue;
3277
3278 if (i->prefix)
3279 good = startswith(*k, i->key);
3280 else
3281 good = streq(*k, i->key);
3282
3283 if (good)
3284 break;
3285 }
3286
3287 if (!good)
3288 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Refusing to write to sysctl '%s', as it is not safe in the selected namespaces.", *k);
3289
3290 r = sysctl_write(*k, *v);
3291 if (r < 0)
3292 return log_error_errno(r, "Failed to write sysctl '%s': %m", *k);
3293 }
3294
3295 return 0;
3296 }
3297
3298 static int inner_child(
3299 Barrier *barrier,
3300 int fd_inner_socket,
3301 FDSet *fds,
3302 char **os_release_pairs) {
3303
3304 _cleanup_free_ char *home = NULL;
3305 size_t n_env = 1;
3306 char *envp[] = {
3307 (char*) "PATH=" DEFAULT_PATH_COMPAT,
3308 NULL, /* container */
3309 NULL, /* TERM */
3310 NULL, /* COLORTERM */
3311 NULL, /* NO_COLOR */
3312 NULL, /* HOME */
3313 NULL, /* USER */
3314 NULL, /* LOGNAME */
3315 NULL, /* container_uuid */
3316 NULL, /* LISTEN_FDS */
3317 NULL, /* LISTEN_PID */
3318 NULL, /* NOTIFY_SOCKET */
3319 NULL, /* CREDENTIALS_DIRECTORY */
3320 NULL, /* LANG */
3321 NULL
3322 };
3323 const char *exec_target;
3324 _cleanup_strv_free_ char **env_use = NULL;
3325 int r, which_failed;
3326
3327 /* This is the "inner" child process, i.e. the one forked off by the "outer" child process, which is the one
3328 * the container manager itself forked off. At the time of clone() it gained its own CLONE_NEWNS, CLONE_NEWPID,
3329 * CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER namespaces. Note that it has its own CLONE_NEWNS namespace,
3330 * separate from the CLONE_NEWNS created for the "outer" child, and also separate from the host's CLONE_NEWNS
3331 * namespace. The reason for having two levels of CLONE_NEWNS namespaces is that the "inner" one is owned by
3332 * the CLONE_NEWUSER namespace of the container, while the "outer" one is owned by the host's CLONE_NEWUSER
3333 * namespace.
3334 *
3335 * Note at this point we have no CLONE_NEWNET namespace yet. We'll acquire that one later through
3336 * unshare(). See below. */
3337
3338 assert(barrier);
3339 assert(fd_inner_socket >= 0);
3340
3341 log_debug("Inner child is initializing.");
3342
3343 if (arg_userns_mode != USER_NAMESPACE_NO) {
3344 /* Tell the parent, that it now can write the UID map. */
3345 (void) barrier_place(barrier); /* #1 */
3346
3347 /* Wait until the parent wrote the UID map */
3348 if (!barrier_place_and_sync(barrier)) /* #2 */
3349 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "Parent died too early");
3350
3351 /* Become the new root user inside our namespace */
3352 r = reset_uid_gid();
3353 if (r < 0)
3354 return log_error_errno(r, "Couldn't become new root: %m");
3355
3356 /* Creating a new user namespace means all MS_SHARED mounts become MS_SLAVE. Let's put them
3357 * back to MS_SHARED here, since that's what we want as defaults. (This will not reconnect
3358 * propagation, but simply create new peer groups for all our mounts). */
3359 r = mount_follow_verbose(LOG_ERR, NULL, "/", NULL, MS_SHARED|MS_REC, NULL);
3360 if (r < 0)
3361 return r;
3362 }
3363
3364 r = mount_all(/* dest= */ NULL,
3365 arg_mount_settings | MOUNT_IN_USERNS,
3366 arg_uid_shift,
3367 arg_selinux_apifs_context);
3368 if (r < 0)
3369 return r;
3370
3371 if (!arg_network_namespace_path && arg_private_network) {
3372 _cleanup_close_ int netns_fd = -EBADF;
3373
3374 if (arg_userns_mode != USER_NAMESPACE_MANAGED)
3375 if (unshare(CLONE_NEWNET) < 0)
3376 return log_error_errno(errno, "Failed to unshare network namespace: %m");
3377
3378 netns_fd = namespace_open_by_type(NAMESPACE_NET);
3379 if (netns_fd < 0)
3380 return log_error_errno(netns_fd, "Failed to open newly allocate network namespace: %m");
3381
3382 r = send_one_fd(fd_inner_socket, netns_fd, 0);
3383 if (r < 0)
3384 return log_error_errno(r, "Failed to send network namespace to supervisor: %m");
3385
3386 /* Tell the parent that it can setup network interfaces. */
3387 (void) barrier_place(barrier); /* #3 */
3388 }
3389
3390 if (arg_userns_mode != USER_NAMESPACE_MANAGED) {
3391 r = mount_sysfs(NULL, arg_mount_settings | MOUNT_IN_USERNS);
3392 if (r < 0)
3393 return r;
3394 }
3395
3396 /* Wait until we are cgroup-ified, so that we can mount the right cgroup path writable */
3397 if (!barrier_place_and_sync(barrier)) /* #4 */
3398 return log_error_errno(SYNTHETIC_ERRNO(ESRCH),
3399 "Parent died too early");
3400
3401 if (arg_use_cgns) {
3402 r = unshare(CLONE_NEWCGROUP);
3403 if (r < 0)
3404 return log_error_errno(errno, "Failed to unshare cgroup namespace: %m");
3405
3406 r = mount_cgroups(/* dest = */ NULL, /* accept_existing = */ false);
3407 } else
3408 r = bind_mount_cgroup_hierarchy();
3409 if (r < 0)
3410 return r;
3411
3412 r = setup_boot_id();
3413 if (r < 0)
3414 return r;
3415
3416 r = setup_kmsg(fd_inner_socket);
3417 if (r < 0)
3418 return r;
3419
3420 r = mount_custom(
3421 "/",
3422 arg_custom_mounts,
3423 arg_n_custom_mounts,
3424 0,
3425 0,
3426 arg_selinux_apifs_context,
3427 MOUNT_NON_ROOT_ONLY | MOUNT_IN_USERNS);
3428 if (r < 0)
3429 return r;
3430
3431 if (setsid() < 0)
3432 return log_error_errno(errno, "setsid() failed: %m");
3433
3434 if (arg_private_network)
3435 (void) loopback_setup();
3436
3437 if (arg_expose_ports) {
3438 r = expose_port_send_rtnl(fd_inner_socket);
3439 if (r < 0)
3440 return r;
3441 }
3442
3443 if (arg_console_mode != CONSOLE_PIPE) {
3444 _cleanup_close_ int master = -EBADF;
3445 _cleanup_free_ char *console = NULL;
3446
3447 /* Allocate a pty and make it available as /dev/console. */
3448 master = openpt_allocate(O_RDWR|O_NONBLOCK, &console);
3449 if (master < 0)
3450 return log_error_errno(master, "Failed to allocate a pty: %m");
3451
3452 r = setup_dev_console(console);
3453 if (r < 0)
3454 return log_error_errno(r, "Failed to set up /dev/console: %m");
3455
3456 r = send_one_fd(fd_inner_socket, master, 0);
3457 if (r < 0)
3458 return log_error_errno(r, "Failed to send master fd: %m");
3459
3460 r = setup_stdio_as_dev_console();
3461 if (r < 0)
3462 return r;
3463 }
3464
3465 r = patch_sysctl();
3466 if (r < 0)
3467 return r;
3468
3469 if (arg_oom_score_adjust_set) {
3470 r = set_oom_score_adjust(arg_oom_score_adjust);
3471 if (r < 0)
3472 return log_error_errno(r, "Failed to adjust OOM score: %m");
3473 }
3474
3475 if (arg_cpu_set.set)
3476 if (sched_setaffinity(0, arg_cpu_set.allocated, arg_cpu_set.set) < 0)
3477 return log_error_errno(errno, "Failed to set CPU affinity: %m");
3478
3479 (void) setup_hostname();
3480
3481 if (arg_personality != PERSONALITY_INVALID) {
3482 r = safe_personality(arg_personality);
3483 if (r < 0)
3484 return log_error_errno(r, "personality() failed: %m");
3485 #ifdef ARCHITECTURE_SECONDARY
3486 } else if (arg_architecture == ARCHITECTURE_SECONDARY) {
3487 r = safe_personality(PER_LINUX32);
3488 if (r < 0)
3489 return log_error_errno(r, "personality() failed: %m");
3490 #endif
3491 } else if (!arg_quiet && arg_architecture >= 0 && arg_architecture != native_architecture())
3492 log_notice("Selected architecture '%s' not supported natively on the local CPU, assuming "
3493 "invocation with qemu userspace emulator (or equivalent) in effect.",
3494 architecture_to_string(arg_architecture));
3495
3496 r = setrlimit_closest_all((const struct rlimit *const*) arg_rlimit, &which_failed);
3497 if (r < 0)
3498 return log_error_errno(r, "Failed to apply resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
3499
3500 #if HAVE_SECCOMP
3501 if (arg_seccomp) {
3502
3503 if (is_seccomp_available()) {
3504 r = seccomp_load(arg_seccomp);
3505 if (ERRNO_IS_NEG_SECCOMP_FATAL(r))
3506 return log_error_errno(r, "Failed to install seccomp filter: %m");
3507 if (r < 0)
3508 log_debug_errno(r, "Failed to install seccomp filter: %m");
3509 }
3510 } else
3511 #endif
3512 {
3513 r = setup_seccomp(arg_caps_retain, arg_syscall_allow_list, arg_syscall_deny_list);
3514 if (r < 0)
3515 return r;
3516 }
3517
3518 if (arg_suppress_sync) {
3519 #if HAVE_SECCOMP
3520 r = seccomp_suppress_sync();
3521 if (r < 0)
3522 log_debug_errno(r, "Failed to install sync() suppression seccomp filter, ignoring: %m");
3523 #else
3524 log_debug("systemd is built without SECCOMP support. Ignoring --suppress-sync= command line option and SuppressSync= setting.");
3525 #endif
3526 }
3527
3528 #if HAVE_SELINUX
3529 if (arg_selinux_context)
3530 if (setexeccon(arg_selinux_context) < 0)
3531 return log_error_errno(errno, "setexeccon(\"%s\") failed: %m", arg_selinux_context);
3532 #endif
3533
3534 /* Make sure we keep the caps across the uid/gid dropping, so that we can retain some selected caps
3535 * if we need to later on. */
3536 if (prctl(PR_SET_KEEPCAPS, 1) < 0)
3537 return log_error_errno(errno, "Failed to set PR_SET_KEEPCAPS: %m");
3538
3539 if (uid_is_valid(arg_uid) || gid_is_valid(arg_gid))
3540 r = change_uid_gid_raw(arg_uid, arg_gid, arg_supplementary_gids, arg_n_supplementary_gids, arg_console_mode != CONSOLE_PIPE);
3541 else
3542 r = change_uid_gid(arg_user, arg_console_mode != CONSOLE_PIPE, &home);
3543 if (r < 0)
3544 return r;
3545
3546 r = drop_capabilities(getuid());
3547 if (r < 0)
3548 return log_error_errno(r, "Dropping capabilities failed: %m");
3549
3550 if (arg_no_new_privileges)
3551 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)
3552 return log_error_errno(errno, "Failed to disable new privileges: %m");
3553
3554 /* LXC sets container=lxc, so follow the scheme here */
3555 envp[n_env++] = strjoina("container=", arg_container_service_name);
3556
3557 /* Propagate $TERM & Co. unless we are invoked in pipe mode and stdin/stdout/stderr don't refer to a TTY */
3558 if (arg_console_mode != CONSOLE_PIPE || on_tty()) {
3559 FOREACH_STRING(v, "TERM=", "COLORTERM=", "NO_COLOR=") {
3560 char *t = strv_find_prefix(environ, v);
3561 if (!t)
3562 continue;
3563
3564 envp[n_env++] = t;
3565 }
3566 } else
3567 envp[n_env++] = (char*) "TERM=dumb";
3568
3569 if (home || !uid_is_valid(arg_uid) || arg_uid == 0)
3570 if (asprintf(envp + n_env++, "HOME=%s", home ?: "/root") < 0)
3571 return log_oom();
3572
3573 if (arg_user || !uid_is_valid(arg_uid) || arg_uid == 0)
3574 if (asprintf(envp + n_env++, "USER=%s", arg_user ?: "root") < 0 ||
3575 asprintf(envp + n_env++, "LOGNAME=%s", arg_user ?: "root") < 0)
3576 return log_oom();
3577
3578 assert(!sd_id128_is_null(arg_uuid));
3579
3580 if (asprintf(envp + n_env++, "container_uuid=%s", SD_ID128_TO_UUID_STRING(arg_uuid)) < 0)
3581 return log_oom();
3582
3583 if (!fdset_isempty(fds)) {
3584 r = fdset_cloexec(fds, false);
3585 if (r < 0)
3586 return log_error_errno(r, "Failed to unset O_CLOEXEC for file descriptors.");
3587
3588 if ((asprintf(envp + n_env++, "LISTEN_FDS=%u", fdset_size(fds)) < 0) ||
3589 (asprintf(envp + n_env++, "LISTEN_PID=1") < 0))
3590 return log_oom();
3591 }
3592 if (asprintf(envp + n_env++, "NOTIFY_SOCKET=%s", NSPAWN_NOTIFY_SOCKET_PATH) < 0)
3593 return log_oom();
3594
3595 if (arg_credentials.n_credentials > 0) {
3596 envp[n_env] = strdup("CREDENTIALS_DIRECTORY=/run/host/credentials");
3597 if (!envp[n_env])
3598 return log_oom();
3599 n_env++;
3600 }
3601
3602 if (arg_start_mode != START_BOOT) {
3603 envp[n_env] = strdup("LANG=" SYSTEMD_NSPAWN_LOCALE);
3604 if (!envp[n_env])
3605 return log_oom();
3606 n_env++;
3607 }
3608
3609 env_use = strv_env_merge(envp, os_release_pairs, arg_setenv);
3610 if (!env_use)
3611 return log_oom();
3612
3613 /* Let the parent know that we are ready and wait until the parent is ready with the setup, too... */
3614 if (!barrier_place_and_sync(barrier)) /* #5 */
3615 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "Parent died too early");
3616
3617 /* Note, this should be done this late (💣 and not moved earlier! 💣), so that all namespacing
3618 * changes are already in effect by now, so that any resolved paths here definitely reference
3619 * resources inside the container, and not outside of them. */
3620 if (arg_chdir)
3621 if (chdir(arg_chdir) < 0)
3622 return log_error_errno(errno, "Failed to change to specified working directory %s: %m", arg_chdir);
3623
3624 if (arg_start_mode == START_PID2) {
3625 r = stub_pid1(arg_uuid);
3626 if (r < 0)
3627 return r;
3628 }
3629
3630 if (arg_console_mode != CONSOLE_PIPE) {
3631 /* So far our pty wasn't controlled by any process. Finally, it's time to change that, if we
3632 * are configured for that. Acquire it as controlling tty. */
3633 if (ioctl(STDIN_FILENO, TIOCSCTTY) < 0)
3634 return log_error_errno(errno, "Failed to acquire controlling TTY: %m");
3635 }
3636
3637 log_debug("Inner child finished, invoking payload.");
3638
3639 /* Now, explicitly close the log, so that we then can close all remaining fds. Closing the log explicitly first
3640 * has the benefit that the logging subsystem knows about it, and is thus ready to be reopened should we need
3641 * it again. Note that the other fds closed here are at least the locking and barrier fds. */
3642 log_close();
3643 log_set_open_when_needed(true);
3644 log_settle_target();
3645
3646 (void) fdset_close_others(fds);
3647
3648 if (arg_start_mode == START_BOOT) {
3649 char **a;
3650 size_t m;
3651
3652 /* Automatically search for the init system */
3653
3654 m = strv_length(arg_parameters);
3655 a = newa(char*, m + 2);
3656 memcpy_safe(a + 1, arg_parameters, m * sizeof(char*));
3657 a[1 + m] = NULL;
3658
3659 FOREACH_STRING(init,
3660 "/usr/lib/systemd/systemd",
3661 "/lib/systemd/systemd",
3662 "/sbin/init") {
3663 a[0] = (char*) init;
3664 execve(a[0], a, env_use);
3665 }
3666
3667 exec_target = "/usr/lib/systemd/systemd, /lib/systemd/systemd, /sbin/init";
3668 } else if (!strv_isempty(arg_parameters)) {
3669 const char *dollar_path;
3670
3671 exec_target = arg_parameters[0];
3672
3673 /* Use the user supplied search $PATH if there is one, or DEFAULT_PATH_COMPAT if not to search the
3674 * binary. */
3675 dollar_path = strv_env_get(env_use, "PATH");
3676 if (dollar_path) {
3677 if (setenv("PATH", dollar_path, 1) < 0)
3678 return log_error_errno(errno, "Failed to update $PATH: %m");
3679 }
3680
3681 execvpe(arg_parameters[0], arg_parameters, env_use);
3682 } else {
3683 if (!arg_chdir)
3684 /* If we cannot change the directory, we'll end up in /, that is expected. */
3685 (void) chdir(home ?: "/root");
3686
3687 execle(DEFAULT_USER_SHELL, "-" DEFAULT_USER_SHELL_NAME, NULL, env_use);
3688 if (!streq(DEFAULT_USER_SHELL, "/bin/bash"))
3689 execle("/bin/bash", "-bash", NULL, env_use);
3690 if (!streq(DEFAULT_USER_SHELL, "/bin/sh"))
3691 execle("/bin/sh", "-sh", NULL, env_use);
3692
3693 exec_target = DEFAULT_USER_SHELL ", /bin/bash, /bin/sh";
3694 }
3695
3696 return log_error_errno(errno, "execv(%s) failed: %m", exec_target);
3697 }
3698
3699 static int setup_notify_child(const void *directory) {
3700 _cleanup_close_ int fd = -EBADF;
3701 _cleanup_free_ char *j = NULL;
3702 union sockaddr_union sa = {
3703 .un.sun_family = AF_UNIX,
3704 };
3705 int r;
3706
3707 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
3708 if (fd < 0)
3709 return log_error_errno(errno, "Failed to allocate notification socket: %m");
3710
3711 if (directory) {
3712 j = path_join(directory, NSPAWN_NOTIFY_SOCKET_PATH);
3713 if (!j)
3714 return log_oom();
3715 }
3716
3717 r = sockaddr_un_set_path(&sa.un, j ?: NSPAWN_NOTIFY_SOCKET_PATH);
3718 if (r < 0)
3719 return log_error_errno(r, "Failed to set AF_UNIX path to %s: %m", j ?: NSPAWN_NOTIFY_SOCKET_PATH);
3720
3721 (void) mkdir_parents(sa.un.sun_path, 0755);
3722 (void) sockaddr_un_unlink(&sa.un);
3723
3724 WITH_UMASK(0577) { /* only set "w" bit, which is all that's necessary for connecting from the container */
3725 r = bind(fd, &sa.sa, sockaddr_un_len(&sa.un));
3726 if (r < 0)
3727 return log_error_errno(errno, "bind(" NSPAWN_NOTIFY_SOCKET_PATH ") failed: %m");
3728 }
3729
3730 r = userns_lchown(sa.un.sun_path, 0, 0);
3731 if (r < 0)
3732 return log_error_errno(r, "Failed to chown " NSPAWN_NOTIFY_SOCKET_PATH ": %m");
3733
3734 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
3735 if (r < 0)
3736 return log_error_errno(r, "Failed to enable SO_PASSCRED: %m");
3737
3738 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSPIDFD, true);
3739 if (r < 0)
3740 log_debug_errno(r, "Failed to enable SO_PASSPIDFD, ignoring: %m");
3741
3742 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSRIGHTS, false);
3743 if (r < 0)
3744 log_debug_errno(r, "Failed to turn off SO_PASSRIGHTS, ignoring: %m");
3745
3746 return TAKE_FD(fd);
3747 }
3748
3749 static int setup_unix_export_dir_outside(char **ret) {
3750 int r;
3751
3752 assert(ret);
3753
3754 if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
3755 log_debug("Not digging socket tunnel, because running in managed user namespace mode.");
3756 return 0;
3757 }
3758
3759 _cleanup_free_ char *p = NULL;
3760 p = path_join("/run/systemd/nspawn/unix-export", arg_machine);
3761 if (!p)
3762 return log_oom();
3763
3764 r = path_is_mount_point(p);
3765 if (r > 0)
3766 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Mount point '%s' exists already, refusing.", p);
3767 if (r < 0 && r != -ENOENT)
3768 return log_error_errno(r, "Failed to detect if '%s' is a mount point: %m", p);
3769
3770 r = mkdir_p(p, 0755);
3771 if (r < 0)
3772 return log_error_errno(r, "Failed to create '%s': %m", p);
3773
3774 _cleanup_(rmdir_and_freep) char *q = TAKE_PTR(p);
3775
3776 /* Mount the "unix export" directory really tiny, just 64 inodes. We mark the superblock writable
3777 * (since the container shall bind sockets into it). */
3778 r = mount_nofollow_verbose(
3779 LOG_ERR,
3780 "tmpfs",
3781 q,
3782 "tmpfs",
3783 MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported(),
3784 "size=4M,nr_inodes=64,mode=0755");
3785 if (r < 0)
3786 return r;
3787
3788 _cleanup_(umount_and_rmdir_and_freep) char *w = TAKE_PTR(q);
3789
3790 /* After creating the superblock we change the bind mount to be read-only. This means that the fs
3791 * itself is writable, but not through the mount accessible from the host. */
3792 r = mount_nofollow_verbose(
3793 LOG_ERR,
3794 /* what= */ NULL,
3795 w,
3796 /* fstype= */ NULL,
3797 MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported(),
3798 /* options= */ NULL);
3799 if (r < 0)
3800 return r;
3801
3802 *ret = TAKE_PTR(w);
3803 return 0;
3804 }
3805
3806 static int setup_unix_export_host_inside(const char *directory, const char *unix_export_path) {
3807 int r;
3808
3809 assert(directory);
3810
3811 if (arg_userns_mode == USER_NAMESPACE_MANAGED)
3812 return 0;
3813
3814 assert(unix_export_path);
3815
3816 r = make_run_host(directory);
3817 if (r < 0)
3818 return r;
3819
3820 _cleanup_free_ char *p = path_join(directory, "run/host/unix-export");
3821 if (!p)
3822 return log_oom();
3823
3824 if (mkdir(p, 0755) < 0)
3825 return log_error_errno(errno, "Failed to create '%s': %m", p);
3826
3827 r = mount_nofollow_verbose(
3828 LOG_ERR,
3829 unix_export_path,
3830 p,
3831 /* fstype= */ NULL,
3832 MS_BIND,
3833 /* options= */ NULL);
3834 if (r < 0)
3835 return r;
3836
3837 r = mount_nofollow_verbose(
3838 LOG_ERR,
3839 /* what= */ NULL,
3840 p,
3841 /* fstype= */ NULL,
3842 MS_BIND|MS_REMOUNT|MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported(),
3843 /* options= */ NULL);
3844 if (r < 0)
3845 return r;
3846
3847 r = userns_lchown(p, 0, 0);
3848 if (r < 0)
3849 return log_error_errno(r, "Failed to chown '%s': %m", p);
3850
3851 return 0;
3852 }
3853
3854 static DissectImageFlags determine_dissect_image_flags(void) {
3855 return
3856 DISSECT_IMAGE_GENERIC_ROOT |
3857 DISSECT_IMAGE_REQUIRE_ROOT |
3858 DISSECT_IMAGE_RELAX_VAR_CHECK |
3859 DISSECT_IMAGE_USR_NO_ROOT |
3860 DISSECT_IMAGE_DISCARD_ON_LOOP |
3861 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
3862 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
3863 (arg_read_only ? DISSECT_IMAGE_READ_ONLY : DISSECT_IMAGE_FSCK|DISSECT_IMAGE_GROWFS) |
3864 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY |
3865 (arg_console_mode == CONSOLE_INTERACTIVE && arg_ask_password ? DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH : 0) |
3866 ((arg_userns_ownership == USER_NAMESPACE_OWNERSHIP_FOREIGN) ? DISSECT_IMAGE_FOREIGN_UID :
3867 (arg_userns_ownership != USER_NAMESPACE_OWNERSHIP_AUTO) ? DISSECT_IMAGE_IDENTITY_UID : 0);
3868 }
3869
3870 static int outer_child(
3871 Barrier *barrier,
3872 const char *directory,
3873 int mount_fd,
3874 DissectedImage *dissected_image,
3875 int fd_outer_socket,
3876 int fd_inner_socket,
3877 FDSet *fds,
3878 int netns_fd,
3879 const char *unix_export_path) {
3880
3881 _cleanup_(bind_user_context_freep) BindUserContext *bind_user_context = NULL;
3882 _cleanup_strv_free_ char **os_release_pairs = NULL;
3883 bool idmap = false;
3884 ssize_t l;
3885 int r;
3886
3887 /* This is the "outer" child process, i.e the one forked off by the container manager itself. Its
3888 * namespace situation is:
3889 *
3890 * - CLONE_NEWUSER : if not in USER_NAMESPACE_MANAGED mode: still in the host's
3891 * if USER_NAMESPACE_MANAGED mode: already has its own (created by nsresource_allocate_userns()->setns(userns_fd))
3892 * - CLONE_NEWNS : already has its own (created by clone() if not USER_NAMESPACE_MANAGED, or unshare() otherwise)
3893 * - CLONE_NEWPID : still in the host's
3894 * - CLONE_NEWUTS : still in the host's
3895 * - CLONE_NEWIPC : still in the host's
3896 * - CLONE_NEWNET : still in the host's
3897 *
3898 * After it completed a number of initializations a second child (the "inner" one) is forked off it,
3899 * and it exits. */
3900
3901 assert(barrier);
3902 assert(directory);
3903 assert(fd_outer_socket >= 0);
3904 assert(fd_inner_socket >= 0);
3905
3906 log_debug("Outer child is initializing.");
3907
3908 r = load_os_release_pairs_with_prefix("/", "container_host_", &os_release_pairs);
3909 if (r < 0)
3910 log_debug_errno(r, "Failed to read os-release from host for container, ignoring: %m");
3911
3912 if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0)
3913 return log_error_errno(errno, "PR_SET_PDEATHSIG failed: %m");
3914
3915 r = reset_audit_loginuid();
3916 if (r < 0)
3917 return r;
3918
3919 /* Mark everything as slave, so that we still receive mounts from the real root, but don't propagate
3920 * mounts to the real root. */
3921 r = mount_follow_verbose(LOG_ERR, NULL, "/", NULL, MS_SLAVE|MS_REC, NULL);
3922 if (r < 0)
3923 return r;
3924
3925 /* Put the root dir into the target directory now. One of three mechanisms is provided: either we
3926 * have a single mount fd (typically unprivileged --directory= mode) or we have a fully dissected
3927 * image (--image= mode), or we have a regular path. */
3928 if (mount_fd >= 0) {
3929 assert(arg_directory);
3930 assert(!arg_image);
3931
3932 if (move_mount(mount_fd, "", AT_FDCWD, directory, MOVE_MOUNT_F_EMPTY_PATH) < 0)
3933 return log_error_errno(errno, "Failed to attach root directory: %m");
3934
3935 mount_fd = safe_close(mount_fd);
3936 log_debug("Successfully attached root directory to '%s'.", directory);
3937
3938 } else if (dissected_image) {
3939 assert(!arg_directory);
3940 assert(arg_image);
3941
3942 /* If we are operating on a disk image, then mount its root directory now, but leave out the
3943 * rest. We can read the UID shift from it if we need to. Further down we'll mount the rest,
3944 * but then with the uid shift known. That way we can mount VFAT file systems shifted to the
3945 * right place right away. This makes sure ESP partitions and userns are compatible. */
3946
3947 r = dissected_image_mount_and_warn(
3948 dissected_image,
3949 directory,
3950 arg_uid_shift,
3951 arg_uid_range,
3952 /* userns_fd= */ -EBADF,
3953 determine_dissect_image_flags()|
3954 DISSECT_IMAGE_MOUNT_ROOT_ONLY|
3955 (arg_start_mode == START_BOOT ? DISSECT_IMAGE_VALIDATE_OS : 0));
3956 if (r < 0)
3957 return r;
3958 } else {
3959 assert(arg_directory);
3960 assert(!arg_image);
3961
3962 r = mount_nofollow_verbose(LOG_ERR, arg_directory, directory, /* fstype= */ NULL, MS_BIND|MS_REC, /* options= */ NULL);
3963 if (r < 0)
3964 return r;
3965 }
3966
3967 r = determine_uid_shift(directory);
3968 if (r < 0)
3969 return r;
3970
3971 /* If we do userns on our own, we need to chown() all files ourselves before. Otherwise, if userns is
3972 * off or we are in managed mode we already have the userns applied, hence don't need to chown
3973 * anything */
3974 uid_t chown_uid, chown_range;
3975 if (in_child_chown()) {
3976 chown_uid = arg_uid_shift;
3977 chown_range = arg_uid_range;
3978 } else {
3979 chown_uid = 0;
3980 chown_range = UINT32_C(0x10000);
3981 }
3982
3983 if (arg_userns_mode != USER_NAMESPACE_NO) {
3984 _cleanup_close_ int mntns_fd = -EBADF;
3985
3986 mntns_fd = namespace_open_by_type(NAMESPACE_MOUNT);
3987 if (mntns_fd < 0)
3988 return log_error_errno(mntns_fd, "Failed to pin outer mount namespace: %m");
3989
3990 l = send_one_fd(fd_outer_socket, mntns_fd, 0);
3991 if (l < 0)
3992 return log_error_errno(l, "Failed to send outer mount namespace fd: %m");
3993 mntns_fd = safe_close(mntns_fd);
3994
3995 /* Let the parent know which UID shift we read from the image */
3996 l = send(fd_outer_socket, &arg_uid_shift, sizeof(arg_uid_shift), MSG_NOSIGNAL);
3997 if (l < 0)
3998 return log_error_errno(errno, "Failed to send UID shift: %m");
3999 if (l != sizeof(arg_uid_shift))
4000 return log_error_errno(SYNTHETIC_ERRNO(EIO),
4001 "Short write while sending UID shift.");
4002
4003 if (arg_userns_mode == USER_NAMESPACE_PICK) {
4004 /* When we are supposed to pick the UID shift, the parent will check now whether the
4005 * UID shift we just read from the image is available. If yes, it will send the UID
4006 * shift back to us, if not it will pick a different one, and send it back to us. */
4007
4008 l = recv(fd_outer_socket, &arg_uid_shift, sizeof(arg_uid_shift), 0);
4009 if (l < 0)
4010 return log_error_errno(errno, "Failed to recv UID shift: %m");
4011 if (l != sizeof(arg_uid_shift))
4012 return log_error_errno(SYNTHETIC_ERRNO(EIO),
4013 "Short read while receiving UID shift.");
4014
4015 if (in_child_chown())
4016 chown_uid = arg_uid_shift;
4017 }
4018
4019 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
4020 "Selected user namespace base " UID_FMT " and range " UID_FMT ".", arg_uid_shift, arg_uid_range);
4021 }
4022
4023 /* So the whole tree is now MS_SLAVE, i.e. we'll still receive mount/umount events from the host
4024 * mount namespace. For the directory we are going to run our container let's turn this off, so that
4025 * we'll live in our own little world from now on, and propagation from the host may only happen via
4026 * the mount tunnel dir, or not at all. */
4027 r = mount_follow_verbose(LOG_ERR, NULL, directory, NULL, MS_PRIVATE|MS_REC, NULL);
4028 if (r < 0)
4029 return r;
4030
4031 r = setup_pivot_root(
4032 directory,
4033 arg_pivot_root_new,
4034 arg_pivot_root_old);
4035 if (r < 0)
4036 return r;
4037
4038 r = setup_volatile_mode(
4039 directory,
4040 arg_volatile_mode,
4041 chown_uid,
4042 arg_selinux_apifs_context);
4043 if (r < 0)
4044 return r;
4045
4046 r = bind_user_prepare(
4047 directory,
4048 arg_bind_user,
4049 arg_bind_user_shell,
4050 arg_bind_user_shell_copy,
4051 chown_uid,
4052 chown_range,
4053 &arg_custom_mounts, &arg_n_custom_mounts,
4054 &bind_user_context);
4055 if (r < 0)
4056 return r;
4057
4058 if (arg_userns_mode != USER_NAMESPACE_NO && bind_user_context) {
4059 /* Send the user maps we determined to the parent, so that it installs it in our user
4060 * namespace UID map table */
4061
4062 FOREACH_ARRAY(d, bind_user_context->data, bind_user_context->n_data) {
4063 uid_t map[] = {
4064 d->payload_user->uid,
4065 d->host_user->uid,
4066 (uid_t) d->payload_group->gid,
4067 (uid_t) d->host_group->gid,
4068 };
4069
4070 l = send(fd_outer_socket, map, sizeof(map), MSG_NOSIGNAL);
4071 if (l < 0)
4072 return log_error_errno(errno, "Failed to send user UID map: %m");
4073 if (l != sizeof(map))
4074 return log_error_errno(SYNTHETIC_ERRNO(EIO),
4075 "Short write while sending user UID map.");
4076 }
4077 }
4078
4079 r = mount_custom(
4080 directory,
4081 arg_custom_mounts,
4082 arg_n_custom_mounts,
4083 chown_uid,
4084 chown_range,
4085 arg_selinux_apifs_context,
4086 MOUNT_ROOT_ONLY);
4087 if (r < 0)
4088 return r;
4089
4090 if (!IN_SET(arg_userns_mode, USER_NAMESPACE_NO, USER_NAMESPACE_MANAGED) &&
4091 IN_SET(arg_userns_ownership, USER_NAMESPACE_OWNERSHIP_MAP, USER_NAMESPACE_OWNERSHIP_FOREIGN, USER_NAMESPACE_OWNERSHIP_AUTO) &&
4092 chown_uid != 0) {
4093 _cleanup_strv_free_ char **dirs = NULL;
4094 RemountIdmapping mapping;
4095
4096 switch (arg_userns_ownership) {
4097 case USER_NAMESPACE_OWNERSHIP_MAP:
4098 mapping = REMOUNT_IDMAPPING_HOST_ROOT;
4099 break;
4100
4101 case USER_NAMESPACE_OWNERSHIP_FOREIGN:
4102 mapping = REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT;
4103 break;
4104
4105 case USER_NAMESPACE_OWNERSHIP_AUTO: {
4106 struct stat st;
4107
4108 if (lstat(directory, &st) < 0)
4109 return log_error_errno(errno, "Failed to stat() container root directory '%s': %m", directory);
4110
4111 r = stat_verify_directory(&st);
4112 if (r < 0)
4113 return log_error_errno(r, "Container root directory '%s' is not a directory: %m", directory);
4114
4115 mapping = uid_is_foreign(st.st_uid) ?
4116 REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT :
4117 REMOUNT_IDMAPPING_HOST_ROOT;
4118 break;
4119 }
4120
4121 default:
4122 assert_not_reached();
4123 }
4124
4125 if (arg_volatile_mode != VOLATILE_YES) {
4126 r = strv_extend(&dirs, directory);
4127 if (r < 0)
4128 return log_oom();
4129 }
4130
4131 if ((dissected_image && dissected_image->partitions[PARTITION_USR].found) ||
4132 arg_volatile_mode == VOLATILE_YES) {
4133 char *s = path_join(directory, "/usr");
4134 if (!s)
4135 return log_oom();
4136
4137 r = strv_consume(&dirs, s);
4138 if (r < 0)
4139 return log_oom();
4140 }
4141
4142 r = remount_idmap(
4143 dirs,
4144 chown_uid,
4145 chown_range,
4146 /* host_owner= */ UID_INVALID,
4147 /* dest_owner= */ UID_INVALID,
4148 mapping);
4149 if (r == -EINVAL || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
4150 /* This might fail because the kernel or file system doesn't support idmapping. We
4151 * can't really distinguish this nicely, nor do we have any guarantees about the
4152 * error codes we see, could be EOPNOTSUPP or EINVAL. */
4153 if (arg_userns_ownership != USER_NAMESPACE_OWNERSHIP_AUTO)
4154 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4155 "ID mapped mounts are apparently not available, sorry.");
4156
4157 log_debug("ID mapped mounts are apparently not available on this kernel or for the selected file system, reverting to recursive chown()ing.");
4158 arg_userns_ownership = USER_NAMESPACE_OWNERSHIP_CHOWN;
4159 } else if (r < 0)
4160 return log_error_errno(r, "Failed to set up ID mapped mounts: %m");
4161 else {
4162 log_debug("ID mapped mounts available, making use of them.");
4163 idmap = true;
4164 }
4165 }
4166
4167 r = setup_volatile_mode_after_remount_idmap(
4168 directory,
4169 arg_volatile_mode,
4170 chown_uid,
4171 arg_selinux_apifs_context);
4172 if (r < 0)
4173 return r;
4174
4175 if (dissected_image) {
4176 /* Now we know the uid shift, let's now mount everything else that might be in the image. */
4177 r = dissected_image_mount_and_warn(
4178 dissected_image,
4179 directory,
4180 chown_uid,
4181 chown_range,
4182 /* userns_fd= */ -EBADF,
4183 determine_dissect_image_flags()|
4184 DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY|
4185 (idmap ? DISSECT_IMAGE_MOUNT_IDMAPPED : 0));
4186 if (r < 0)
4187 return r;
4188 }
4189
4190 r = recursive_chown(directory, chown_uid, chown_range);
4191 if (r < 0)
4192 return r;
4193
4194 r = base_filesystem_create(directory, chown_uid, (gid_t) chown_uid);
4195 if (r < 0)
4196 return r;
4197
4198 if (arg_read_only && arg_volatile_mode == VOLATILE_NO &&
4199 !has_custom_root_mount(arg_custom_mounts, arg_n_custom_mounts)) {
4200 r = bind_remount_recursive(directory, MS_RDONLY, MS_RDONLY, NULL);
4201 if (r < 0)
4202 return log_error_errno(r, "Failed to make tree read-only: %m");
4203 }
4204
4205 r = mount_all(directory,
4206 arg_mount_settings,
4207 chown_uid,
4208 arg_selinux_apifs_context);
4209 if (r < 0)
4210 return r;
4211
4212 r = copy_devnodes(directory);
4213 if (r < 0)
4214 return r;
4215
4216 r = make_extra_nodes(directory);
4217 if (r < 0)
4218 return r;
4219
4220 (void) dev_setup(directory, chown_uid, chown_uid);
4221
4222 _cleanup_free_ char *p = path_join(directory, "/run/host");
4223 if (!p)
4224 return log_oom();
4225
4226 (void) make_inaccessible_nodes(p, chown_uid, chown_uid);
4227
4228 r = setup_unix_export_host_inside(directory, unix_export_path);
4229 if (r < 0)
4230 return r;
4231
4232 r = setup_pts(directory, chown_uid);
4233 if (r < 0)
4234 return r;
4235
4236 r = mount_tunnel_dig(directory);
4237 if (r < 0)
4238 return r;
4239
4240 r = setup_keyring();
4241 if (r < 0)
4242 return r;
4243
4244 r = setup_credentials(directory);
4245 if (r < 0)
4246 return r;
4247
4248 r = bind_user_setup(bind_user_context, directory);
4249 if (r < 0)
4250 return r;
4251
4252 r = mount_custom(
4253 directory,
4254 arg_custom_mounts,
4255 arg_n_custom_mounts,
4256 chown_uid,
4257 chown_range,
4258 arg_selinux_apifs_context,
4259 MOUNT_NON_ROOT_ONLY);
4260 if (r < 0)
4261 return r;
4262
4263 r = setup_timezone(directory);
4264 if (r < 0)
4265 return r;
4266
4267 r = setup_resolv_conf(directory);
4268 if (r < 0)
4269 return r;
4270
4271 r = setup_machine_id(directory);
4272 if (r < 0)
4273 return r;
4274
4275 r = setup_journal(directory);
4276 if (r < 0)
4277 return r;
4278
4279 /* The same stuff as the $container env var, but nicely readable for the entire payload */
4280 free(p);
4281 p = path_join(directory, "/run/host/container-manager");
4282 if (!p)
4283 return log_oom();
4284
4285 (void) write_string_file(p, arg_container_service_name, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MODE_0444);
4286
4287 /* The same stuff as the $container_uuid env var */
4288 free(p);
4289 p = path_join(directory, "/run/host/container-uuid");
4290 if (!p)
4291 return log_oom();
4292
4293 (void) write_string_filef(p, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MODE_0444, SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(arg_uuid));
4294
4295 if (!arg_use_cgns) {
4296 r = mount_cgroups(directory, /* accept_existing = */ true);
4297 if (r < 0)
4298 return r;
4299 }
4300
4301 /* We have different codepaths here for privileged and non-privileged mode. In privileged mode we'll
4302 * now switch into the target directory, and then do the final setup from there. If a user namespace
4303 * is then allocated for the container, the root mount and everything else will be out of reach for
4304 * it. For unprivileged containers we cannot do that however, since we couldn't mount a sysfs and
4305 * procfs then anymore, since that only works if there's an unobstructed instance currently
4306 * visible. Hence there we do it the other way round: we first allocate a new set of namespaces
4307 * (and fork for it) for which we then mount sysfs/procfs, and only then switch root. */
4308
4309 _cleanup_close_ int notify_fd = -EBADF;
4310 if (arg_userns_mode != USER_NAMESPACE_MANAGED) {
4311 /* Mark everything as shared so our mounts get propagated down. This is required to make new
4312 * bind mounts available in systemd services inside the container that create a new mount
4313 * namespace. See https://github.com/systemd/systemd/issues/3860 Further submounts (such as
4314 * /dev/) done after this will inherit the shared propagation mode.
4315 *
4316 * IMPORTANT: Do not overmount the root directory anymore from now on to enable moving the root
4317 * directory mount to root later on.
4318 * https://github.com/systemd/systemd/issues/3847#issuecomment-562735251
4319 */
4320 r = mount_switch_root(directory, MS_SHARED);
4321 if (r < 0)
4322 return log_error_errno(r, "Failed to move root directory: %m");
4323
4324 /* We finished setting up the rootfs which is a shared mount. The mount tunnel needs to be a
4325 * dependent mount otherwise we can't MS_MOVE mounts that were propagated from the host into
4326 * the container. */
4327 r = mount_tunnel_open();
4328 if (r < 0)
4329 return r;
4330
4331 if (arg_userns_mode != USER_NAMESPACE_NO) {
4332 /* In order to mount procfs and sysfs in an unprivileged container the kernel
4333 * requires that a fully visible instance is already present in the target mount
4334 * namespace. Mount one here so the inner child can mount its own instances. Later
4335 * we umount the temporary instances created here before we actually exec the
4336 * payload. Since the rootfs is shared the umount will propagate into the container.
4337 * Note, the inner child wouldn't be able to unmount the instances on its own since
4338 * it doesn't own the originating mount namespace. IOW, the outer child needs to do
4339 * this. */
4340 r = pin_fully_visible_api_fs();
4341 if (r < 0)
4342 return r;
4343 }
4344
4345 notify_fd = setup_notify_child(NULL);
4346 } else
4347 notify_fd = setup_notify_child(directory);
4348 if (notify_fd < 0)
4349 return notify_fd;
4350
4351 pid_t pid = raw_clone(SIGCHLD|CLONE_NEWNS|
4352 arg_clone_ns_flags |
4353 (IN_SET(arg_userns_mode, USER_NAMESPACE_FIXED, USER_NAMESPACE_PICK) ? CLONE_NEWUSER : 0) |
4354 ((arg_private_network && arg_userns_mode == USER_NAMESPACE_MANAGED) ? CLONE_NEWNET : 0));
4355 if (pid < 0)
4356 return log_error_errno(errno, "Failed to fork inner child: %m");
4357 if (pid == 0) {
4358 fd_outer_socket = safe_close(fd_outer_socket);
4359
4360 /* The inner child has all namespaces that are requested, so that we all are owned by the
4361 * user if user namespaces are turned on. */
4362
4363 if (arg_network_namespace_path) {
4364 r = namespace_enter(/* pidns_fd = */ -EBADF,
4365 /* mntns_fd = */ -EBADF,
4366 netns_fd,
4367 /* userns_fd = */ -EBADF,
4368 /* root_fd = */ -EBADF);
4369 if (r < 0)
4370 return log_error_errno(r, "Failed to join network namespace: %m");
4371 }
4372
4373 if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
4374 /* In managed usernamespace operation, sysfs + procfs are special, we'll have to
4375 * mount them inside the inner namespaces, but before we switch root. Hence do so
4376 * here. */
4377 _cleanup_free_ char *j = path_join(directory, "/proc");
4378 if (!j)
4379 return log_oom();
4380
4381 r = mount_follow_verbose(LOG_ERR, "proc", j, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
4382 if (r < 0)
4383 return r;
4384
4385 r = mount_sysfs(directory, arg_mount_settings);
4386 if (r < 0)
4387 return r;
4388
4389 r = mount_switch_root(directory, MS_SHARED);
4390 if (r < 0)
4391 return log_error_errno(r, "Failed to move root directory: %m");
4392 }
4393
4394 r = inner_child(barrier, fd_inner_socket, fds, os_release_pairs);
4395 if (r < 0)
4396 _exit(EXIT_FAILURE);
4397
4398 _exit(EXIT_SUCCESS);
4399 }
4400
4401 l = send(fd_outer_socket, &pid, sizeof(pid), MSG_NOSIGNAL);
4402 if (l < 0)
4403 return log_error_errno(errno, "Failed to send PID: %m");
4404 if (l != sizeof(pid))
4405 return log_error_errno(SYNTHETIC_ERRNO(EIO),
4406 "Short write while sending PID.");
4407
4408 l = send(fd_outer_socket, &arg_uuid, sizeof(arg_uuid), MSG_NOSIGNAL);
4409 if (l < 0)
4410 return log_error_errno(errno, "Failed to send machine ID: %m");
4411 if (l != sizeof(arg_uuid))
4412 return log_error_errno(SYNTHETIC_ERRNO(EIO),
4413 "Short write while sending machine ID.");
4414
4415 l = send_one_fd(fd_outer_socket, notify_fd, 0);
4416 if (l < 0)
4417 return log_error_errno(l, "Failed to send notify fd: %m");
4418
4419 fd_outer_socket = safe_close(fd_outer_socket);
4420 fd_inner_socket = safe_close(fd_inner_socket);
4421 netns_fd = safe_close(netns_fd);
4422
4423 return 0;
4424 }
4425
4426 static int uid_shift_pick(uid_t *shift, LockFile *ret_lock_file) {
4427 bool tried_hashed = false;
4428 unsigned n_tries = 100;
4429 uid_t candidate;
4430 int r;
4431
4432 assert(shift);
4433 assert(ret_lock_file);
4434 assert(arg_userns_mode == USER_NAMESPACE_PICK);
4435 assert(arg_uid_range == 0x10000U);
4436
4437 candidate = *shift;
4438
4439 (void) mkdir("/run/systemd/nspawn-uid", 0755);
4440
4441 for (;;) {
4442 char lock_path[STRLEN("/run/systemd/nspawn-uid/") + DECIMAL_STR_MAX(uid_t) + 1];
4443 _cleanup_(release_lock_file) LockFile lf = LOCK_FILE_INIT;
4444
4445 if (--n_tries <= 0)
4446 return -EBUSY;
4447
4448 if (candidate < CONTAINER_UID_BASE_MIN || candidate > CONTAINER_UID_BASE_MAX)
4449 goto next;
4450 if ((candidate & UINT32_C(0xFFFF)) != 0)
4451 goto next;
4452
4453 xsprintf(lock_path, "/run/systemd/nspawn-uid/" UID_FMT, candidate);
4454 r = make_lock_file(lock_path, LOCK_EX|LOCK_NB, &lf);
4455 if (r == -EBUSY) /* Range already taken by another nspawn instance */
4456 goto next;
4457 if (r < 0)
4458 return r;
4459
4460 /* Make some superficial checks whether the range is currently known in the user database */
4461 if (getpwuid_malloc(candidate, /* ret= */ NULL) >= 0)
4462 goto next;
4463 if (getpwuid_malloc(candidate + UINT32_C(0xFFFE), /* ret= */ NULL) >= 0)
4464 goto next;
4465 if (getgrgid_malloc(candidate, /* ret= */ NULL) >= 0)
4466 goto next;
4467 if (getgrgid_malloc(candidate + UINT32_C(0xFFFE), /* ret= */ NULL) >= 0)
4468 goto next;
4469
4470 *ret_lock_file = lf;
4471 lf = (struct LockFile) LOCK_FILE_INIT;
4472 *shift = candidate;
4473 return 0;
4474
4475 next:
4476 if (arg_machine && !tried_hashed) {
4477 /* Try to hash the base from the container name */
4478
4479 static const uint8_t hash_key[] = {
4480 0xe1, 0x56, 0xe0, 0xf0, 0x4a, 0xf0, 0x41, 0xaf,
4481 0x96, 0x41, 0xcf, 0x41, 0x33, 0x94, 0xff, 0x72
4482 };
4483
4484 candidate = (uid_t) siphash24(arg_machine, strlen(arg_machine), hash_key);
4485
4486 tried_hashed = true;
4487 } else
4488 random_bytes(&candidate, sizeof(candidate));
4489
4490 candidate = (candidate % (CONTAINER_UID_BASE_MAX - CONTAINER_UID_BASE_MIN)) + CONTAINER_UID_BASE_MIN;
4491 candidate &= (uid_t) UINT32_C(0xFFFF0000);
4492 }
4493 }
4494
4495 static int add_one_uid_map(
4496 char **p,
4497 uid_t container_uid,
4498 uid_t host_uid,
4499 uid_t range) {
4500
4501 return strextendf(p,
4502 UID_FMT " " UID_FMT " " UID_FMT "\n",
4503 container_uid, host_uid, range);
4504 }
4505
4506 static int make_uid_map_string(
4507 const uid_t bind_user_uid[],
4508 size_t n_bind_user_uid,
4509 size_t offset,
4510 char **ret) {
4511
4512 _cleanup_free_ char *s = NULL;
4513 uid_t previous_uid = 0;
4514 int r;
4515
4516 assert(n_bind_user_uid == 0 || bind_user_uid);
4517 assert(IN_SET(offset, 0, 2)); /* used to switch between UID and GID map */
4518 assert(ret);
4519
4520 /* The bind_user_uid[] array is a series of 4 uid_t values, for each --bind-user= entry one
4521 * quadruplet, consisting of host and container UID + GID. */
4522
4523 for (size_t i = 0; i < n_bind_user_uid; i++) {
4524 uid_t payload_uid = bind_user_uid[i*4+offset],
4525 host_uid = bind_user_uid[i*4+offset+1];
4526
4527 assert(previous_uid <= payload_uid);
4528 assert(payload_uid < arg_uid_range);
4529
4530 /* Add a range to close the gap to previous entry */
4531 if (payload_uid > previous_uid) {
4532 r = add_one_uid_map(&s, previous_uid, arg_uid_shift + previous_uid, payload_uid - previous_uid);
4533 if (r < 0)
4534 return r;
4535 }
4536
4537 /* Map this specific user */
4538 r = add_one_uid_map(&s, payload_uid, host_uid, 1);
4539 if (r < 0)
4540 return r;
4541
4542 previous_uid = payload_uid + 1;
4543 }
4544
4545 /* And add a range to close the gap to finish the range */
4546 if (arg_uid_range > previous_uid) {
4547 r = add_one_uid_map(&s, previous_uid, arg_uid_shift + previous_uid, arg_uid_range - previous_uid);
4548 if (r < 0)
4549 return r;
4550 }
4551
4552 assert(s);
4553
4554 *ret = TAKE_PTR(s);
4555 return 0;
4556 }
4557
4558 static int setup_uid_map(
4559 const PidRef *pid,
4560 const uid_t bind_user_uid[],
4561 size_t n_bind_user_uid) {
4562
4563 char uid_map[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(uid_t) + 1];
4564 _cleanup_free_ char *s = NULL;
4565 int r;
4566
4567 assert(pidref_is_set(pid));
4568 assert(pid->pid > 1);
4569
4570 /* Build the UID map string */
4571 if (make_uid_map_string(bind_user_uid, n_bind_user_uid, 0, &s) < 0) /* offset=0 contains the UID pair */
4572 return log_oom();
4573
4574 xsprintf(uid_map, "/proc/" PID_FMT "/uid_map", pid->pid);
4575 r = write_string_file(uid_map, s, WRITE_STRING_FILE_DISABLE_BUFFER);
4576 if (r < 0)
4577 return log_error_errno(r, "Failed to write UID map: %m");
4578
4579 /* And now build the GID map string */
4580 s = mfree(s);
4581 if (make_uid_map_string(bind_user_uid, n_bind_user_uid, 2, &s) < 0) /* offset=2 contains the GID pair */
4582 return log_oom();
4583
4584 xsprintf(uid_map, "/proc/" PID_FMT "/gid_map", pid->pid);
4585 r = write_string_file(uid_map, s, WRITE_STRING_FILE_DISABLE_BUFFER);
4586 if (r < 0)
4587 return log_error_errno(r, "Failed to write GID map: %m");
4588
4589 return 0;
4590 }
4591
4592 static int nspawn_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
4593 PidRef *inner_child_pid = ASSERT_PTR(userdata);
4594 int r;
4595
4596 assert(userdata);
4597
4598 _cleanup_(pidref_done) PidRef sender_pid = PIDREF_NULL;
4599 _cleanup_strv_free_ char **tags = NULL;
4600 r = notify_recv_strv(fd, &tags, /* ret_ucred= */ NULL, &sender_pid);
4601 if (r == -EAGAIN)
4602 return 0;
4603 if (r < 0)
4604 return r;
4605
4606 if (!pidref_equal(&sender_pid, inner_child_pid)) {
4607 log_debug("Received notify message from process that is not the payload's PID 1. Ignoring.");
4608 return 0;
4609 }
4610
4611 if (DEBUG_LOGGING) {
4612 _cleanup_free_ char *joined = strv_join(tags, " ");
4613
4614 if (joined) {
4615 _cleanup_free_ char *j = cescape(joined);
4616 free_and_replace(joined, j);
4617 }
4618
4619 log_debug("Got sd_notify() message: %s", strnull(joined));
4620 }
4621
4622 if (strv_contains(tags, "READY=1")) {
4623 r = sd_notify(false, "READY=1\n");
4624 if (r < 0)
4625 log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
4626 }
4627
4628 char *p = strv_find_startswith(tags, "STATUS=");
4629 if (p)
4630 (void) sd_notifyf(false, "STATUS=Container running: %s", p);
4631
4632 return 0;
4633 }
4634
4635 static int setup_notify_parent(sd_event *event, int fd, PidRef *inner_child_pid, sd_event_source **notify_event_source) {
4636 int r;
4637
4638 if (fd < 0)
4639 return 0;
4640
4641 r = sd_event_add_io(event, notify_event_source, fd, EPOLLIN, nspawn_dispatch_notify_fd, inner_child_pid);
4642 if (r < 0)
4643 return log_error_errno(r, "Failed to allocate notify event source: %m");
4644
4645 (void) sd_event_source_set_description(*notify_event_source, "nspawn-notify");
4646
4647 return 0;
4648 }
4649
4650 static int ptyfwd_hotkey(PTYForward *f, char c, void *userdata) {
4651 PidRef *pid = ASSERT_PTR(userdata);
4652 const char *word;
4653 int sig = 0, r;
4654
4655 assert(f);
4656
4657 switch (c) {
4658 case 'p':
4659 sig = SIGRTMIN+4;
4660 word = "power off";
4661 break;
4662
4663 case 'r':
4664 sig = SIGRTMIN+5;
4665 word = "reboot";
4666 break;
4667
4668 default:
4669 log_info("Unknown hotkey sequence ^]^]%c, ignoring.", c);
4670 return 0;
4671 }
4672
4673 r = pidref_kill(pid, sig);
4674 if (r < 0)
4675 log_error_errno(r, "Failed to send %s (%s request) to PID 1 of container: %m", signal_to_string(sig), word);
4676 else
4677 log_info("Sent %s (%s request) to PID 1 of container.", signal_to_string(sig), word);
4678
4679 return 0;
4680 }
4681
4682 static int merge_settings(Settings *settings, const char *path) {
4683 int rl;
4684
4685 assert(settings);
4686 assert(path);
4687
4688 /* Copy over bits from the settings, unless they have been explicitly masked by command line switches. Note
4689 * that this steals the fields of the Settings* structure, and hence modifies it. */
4690
4691 if ((arg_settings_mask & SETTING_START_MODE) == 0 &&
4692 settings->start_mode >= 0) {
4693 arg_start_mode = settings->start_mode;
4694 strv_free_and_replace(arg_parameters, settings->parameters);
4695 }
4696
4697 if ((arg_settings_mask & SETTING_EPHEMERAL) == 0 &&
4698 settings->ephemeral >= 0)
4699 arg_ephemeral = settings->ephemeral;
4700
4701 if ((arg_settings_mask & SETTING_DIRECTORY) == 0 &&
4702 settings->root) {
4703
4704 if (!arg_settings_trusted)
4705 log_warning("Ignoring root directory setting, file %s is not trusted.", path);
4706 else
4707 free_and_replace(arg_directory, settings->root);
4708 }
4709
4710 if ((arg_settings_mask & SETTING_PIVOT_ROOT) == 0 &&
4711 settings->pivot_root_new) {
4712 free_and_replace(arg_pivot_root_new, settings->pivot_root_new);
4713 free_and_replace(arg_pivot_root_old, settings->pivot_root_old);
4714 }
4715
4716 if ((arg_settings_mask & SETTING_WORKING_DIRECTORY) == 0 &&
4717 settings->working_directory)
4718 free_and_replace(arg_chdir, settings->working_directory);
4719
4720 if ((arg_settings_mask & SETTING_ENVIRONMENT) == 0 &&
4721 settings->environment)
4722 strv_free_and_replace(arg_setenv, settings->environment);
4723
4724 if ((arg_settings_mask & SETTING_USER) == 0) {
4725
4726 if (settings->user)
4727 free_and_replace(arg_user, settings->user);
4728
4729 if (uid_is_valid(settings->uid))
4730 arg_uid = settings->uid;
4731 if (gid_is_valid(settings->gid))
4732 arg_gid = settings->gid;
4733 if (settings->n_supplementary_gids > 0) {
4734 free_and_replace(arg_supplementary_gids, settings->supplementary_gids);
4735 arg_n_supplementary_gids = settings->n_supplementary_gids;
4736 }
4737 }
4738
4739 if ((arg_settings_mask & SETTING_CAPABILITY) == 0) {
4740 uint64_t plus, minus;
4741 uint64_t network_minus = 0;
4742 uint64_t ambient;
4743
4744 /* Note that we copy both the simple plus/minus caps here, and the full quintet from the
4745 * Settings structure */
4746
4747 plus = settings->capability;
4748 minus = settings->drop_capability;
4749
4750 if ((arg_settings_mask & SETTING_NETWORK) == 0 &&
4751 settings_network_configured(settings)) {
4752 if (settings_private_network(settings))
4753 plus |= UINT64_C(1) << CAP_NET_ADMIN;
4754 else
4755 network_minus |= UINT64_C(1) << CAP_NET_ADMIN;
4756 }
4757
4758 if (!arg_settings_trusted && plus != 0) {
4759 if (settings->capability != 0)
4760 log_warning("Ignoring Capability= setting, file %s is not trusted.", path);
4761 } else {
4762 arg_caps_retain &= ~network_minus;
4763 arg_caps_retain |= plus;
4764 }
4765
4766 arg_caps_retain &= ~minus;
4767
4768 /* Copy the full capabilities over too */
4769 if (capability_quintet_is_set(&settings->full_capabilities)) {
4770 if (!arg_settings_trusted)
4771 log_warning("Ignoring capability settings, file %s is not trusted.", path);
4772 else
4773 arg_full_capabilities = settings->full_capabilities;
4774 }
4775
4776 ambient = settings->ambient_capability;
4777 if (!arg_settings_trusted && ambient != 0)
4778 log_warning("Ignoring AmbientCapability= setting, file %s is not trusted.", path);
4779 else
4780 arg_caps_ambient |= ambient;
4781 }
4782
4783 if ((arg_settings_mask & SETTING_KILL_SIGNAL) == 0 &&
4784 settings->kill_signal > 0)
4785 arg_kill_signal = settings->kill_signal;
4786
4787 if ((arg_settings_mask & SETTING_PERSONALITY) == 0 &&
4788 settings->personality != PERSONALITY_INVALID)
4789 arg_personality = settings->personality;
4790
4791 if ((arg_settings_mask & SETTING_MACHINE_ID) == 0 &&
4792 !sd_id128_is_null(settings->machine_id)) {
4793
4794 if (!arg_settings_trusted)
4795 log_warning("Ignoring MachineID= setting, file %s is not trusted.", path);
4796 else
4797 arg_uuid = settings->machine_id;
4798 }
4799
4800 if ((arg_settings_mask & SETTING_READ_ONLY) == 0 &&
4801 settings->read_only >= 0)
4802 arg_read_only = settings->read_only;
4803
4804 if ((arg_settings_mask & SETTING_VOLATILE_MODE) == 0 &&
4805 settings->volatile_mode != _VOLATILE_MODE_INVALID)
4806 arg_volatile_mode = settings->volatile_mode;
4807
4808 if ((arg_settings_mask & SETTING_CUSTOM_MOUNTS) == 0 &&
4809 settings->n_custom_mounts > 0) {
4810
4811 if (!arg_settings_trusted)
4812 log_warning("Ignoring TemporaryFileSystem=, Bind= and BindReadOnly= settings, file %s is not trusted.", path);
4813 else {
4814 custom_mount_free_all(arg_custom_mounts, arg_n_custom_mounts);
4815 arg_custom_mounts = TAKE_PTR(settings->custom_mounts);
4816 arg_n_custom_mounts = settings->n_custom_mounts;
4817 settings->n_custom_mounts = 0;
4818 }
4819 }
4820
4821 if ((arg_settings_mask & SETTING_NETWORK) == 0 &&
4822 settings_network_configured(settings)) {
4823
4824 if (!arg_settings_trusted)
4825 log_warning("Ignoring network settings, file %s is not trusted.", path);
4826 else {
4827 arg_network_veth = settings_network_veth(settings);
4828 arg_private_network = settings_private_network(settings);
4829
4830 strv_free_and_replace(arg_network_interfaces, settings->network_interfaces);
4831 strv_free_and_replace(arg_network_macvlan, settings->network_macvlan);
4832 strv_free_and_replace(arg_network_ipvlan, settings->network_ipvlan);
4833 strv_free_and_replace(arg_network_veth_extra, settings->network_veth_extra);
4834
4835 free_and_replace(arg_network_bridge, settings->network_bridge);
4836 free_and_replace(arg_network_zone, settings->network_zone);
4837
4838 free_and_replace(arg_network_namespace_path, settings->network_namespace_path);
4839 }
4840 }
4841
4842 if ((arg_settings_mask & SETTING_EXPOSE_PORTS) == 0 &&
4843 settings->expose_ports) {
4844
4845 if (!arg_settings_trusted)
4846 log_warning("Ignoring Port= setting, file %s is not trusted.", path);
4847 else {
4848 expose_port_free_all(arg_expose_ports);
4849 arg_expose_ports = TAKE_PTR(settings->expose_ports);
4850 }
4851 }
4852
4853 if ((arg_settings_mask & SETTING_USERNS) == 0 &&
4854 settings->userns_mode != _USER_NAMESPACE_MODE_INVALID) {
4855
4856 if (!arg_settings_trusted)
4857 log_warning("Ignoring PrivateUsers= and PrivateUsersChown= settings, file %s is not trusted.", path);
4858 else {
4859 arg_userns_mode = settings->userns_mode;
4860 arg_uid_shift = settings->uid_shift;
4861 arg_uid_range = settings->uid_range;
4862 arg_userns_ownership = settings->userns_ownership;
4863 }
4864 }
4865
4866 if ((arg_settings_mask & SETTING_BIND_USER) == 0 &&
4867 !strv_isempty(settings->bind_user))
4868 strv_free_and_replace(arg_bind_user, settings->bind_user);
4869
4870 if (!FLAGS_SET(arg_settings_mask, SETTING_BIND_USER_SHELL) &&
4871 settings->bind_user_shell_set) {
4872 free_and_replace(arg_bind_user_shell, settings->bind_user_shell);
4873 arg_bind_user_shell_copy = settings->bind_user_shell_copy;
4874 }
4875
4876 if ((arg_settings_mask & SETTING_NOTIFY_READY) == 0 &&
4877 settings->notify_ready >= 0)
4878 arg_notify_ready = settings->notify_ready;
4879
4880 if ((arg_settings_mask & SETTING_SYSCALL_FILTER) == 0) {
4881
4882 if (!strv_isempty(settings->syscall_allow_list) || !strv_isempty(settings->syscall_deny_list)) {
4883 if (!arg_settings_trusted && !strv_isempty(settings->syscall_allow_list))
4884 log_warning("Ignoring SystemCallFilter= settings, file %s is not trusted.", path);
4885 else {
4886 strv_free_and_replace(arg_syscall_allow_list, settings->syscall_allow_list);
4887 strv_free_and_replace(arg_syscall_deny_list, settings->syscall_deny_list);
4888 }
4889 }
4890
4891 #if HAVE_SECCOMP
4892 if (settings->seccomp) {
4893 if (!arg_settings_trusted)
4894 log_warning("Ignoring SECCOMP filter, file %s is not trusted.", path);
4895 else {
4896 seccomp_release(arg_seccomp);
4897 arg_seccomp = TAKE_PTR(settings->seccomp);
4898 }
4899 }
4900 #endif
4901 }
4902
4903 for (rl = 0; rl < _RLIMIT_MAX; rl++) {
4904 if ((arg_settings_mask & (SETTING_RLIMIT_FIRST << rl)))
4905 continue;
4906
4907 if (!settings->rlimit[rl])
4908 continue;
4909
4910 if (!arg_settings_trusted) {
4911 log_warning("Ignoring Limit%s= setting, file '%s' is not trusted.", rlimit_to_string(rl), path);
4912 continue;
4913 }
4914
4915 free_and_replace(arg_rlimit[rl], settings->rlimit[rl]);
4916 }
4917
4918 if ((arg_settings_mask & SETTING_HOSTNAME) == 0 &&
4919 settings->hostname)
4920 free_and_replace(arg_hostname, settings->hostname);
4921
4922 if ((arg_settings_mask & SETTING_NO_NEW_PRIVILEGES) == 0 &&
4923 settings->no_new_privileges >= 0)
4924 arg_no_new_privileges = settings->no_new_privileges;
4925
4926 if ((arg_settings_mask & SETTING_OOM_SCORE_ADJUST) == 0 &&
4927 settings->oom_score_adjust_set) {
4928
4929 if (!arg_settings_trusted)
4930 log_warning("Ignoring OOMScoreAdjust= setting, file '%s' is not trusted.", path);
4931 else {
4932 arg_oom_score_adjust = settings->oom_score_adjust;
4933 arg_oom_score_adjust_set = true;
4934 }
4935 }
4936
4937 if ((arg_settings_mask & SETTING_CPU_AFFINITY) == 0 &&
4938 settings->cpu_set.set) {
4939
4940 if (!arg_settings_trusted)
4941 log_warning("Ignoring CPUAffinity= setting, file '%s' is not trusted.", path);
4942 else
4943 cpu_set_done_and_replace(arg_cpu_set, settings->cpu_set);
4944 }
4945
4946 if ((arg_settings_mask & SETTING_RESOLV_CONF) == 0 &&
4947 settings->resolv_conf != _RESOLV_CONF_MODE_INVALID)
4948 arg_resolv_conf = settings->resolv_conf;
4949
4950 if ((arg_settings_mask & SETTING_LINK_JOURNAL) == 0 &&
4951 settings->link_journal != _LINK_JOURNAL_INVALID) {
4952
4953 if (!arg_settings_trusted)
4954 log_warning("Ignoring journal link setting, file '%s' is not trusted.", path);
4955 else {
4956 arg_link_journal = settings->link_journal;
4957 arg_link_journal_try = settings->link_journal_try;
4958 }
4959 }
4960
4961 if ((arg_settings_mask & SETTING_TIMEZONE) == 0 &&
4962 settings->timezone != _TIMEZONE_MODE_INVALID)
4963 arg_timezone = settings->timezone;
4964
4965 if ((arg_settings_mask & SETTING_SLICE) == 0 &&
4966 settings->slice) {
4967
4968 if (!arg_settings_trusted)
4969 log_warning("Ignoring slice setting, file '%s' is not trusted.", path);
4970 else
4971 free_and_replace(arg_slice, settings->slice);
4972 }
4973
4974 if ((arg_settings_mask & SETTING_USE_CGNS) == 0 &&
4975 settings->use_cgns >= 0) {
4976
4977 if (!arg_settings_trusted)
4978 log_warning("Ignoring cgroup namespace setting, file '%s' is not trusted.", path);
4979 else
4980 arg_use_cgns = settings->use_cgns;
4981 }
4982
4983 if ((arg_settings_mask & SETTING_CLONE_NS_FLAGS) == 0 &&
4984 settings->clone_ns_flags != ULONG_MAX) {
4985
4986 if (!arg_settings_trusted)
4987 log_warning("Ignoring namespace setting, file '%s' is not trusted.", path);
4988 else
4989 arg_clone_ns_flags = settings->clone_ns_flags;
4990 }
4991
4992 if ((arg_settings_mask & SETTING_CONSOLE_MODE) == 0 &&
4993 settings->console_mode >= 0) {
4994
4995 if (!arg_settings_trusted)
4996 log_warning("Ignoring console mode setting, file '%s' is not trusted.", path);
4997 else
4998 arg_console_mode = settings->console_mode;
4999 }
5000
5001 if ((arg_settings_mask & SETTING_SUPPRESS_SYNC) == 0 &&
5002 settings->suppress_sync >= 0)
5003 arg_suppress_sync = settings->suppress_sync;
5004
5005 /* The following properties can only be set through the OCI settings logic, not from the command line, hence we
5006 * don't consult arg_settings_mask for them. */
5007
5008 sd_bus_message_unref(arg_property_message);
5009 arg_property_message = TAKE_PTR(settings->properties);
5010
5011 arg_console_width = settings->console_width;
5012 arg_console_height = settings->console_height;
5013
5014 device_node_array_free(arg_extra_nodes, arg_n_extra_nodes);
5015 arg_extra_nodes = TAKE_PTR(settings->extra_nodes);
5016 arg_n_extra_nodes = settings->n_extra_nodes;
5017 settings->n_extra_nodes = 0;
5018
5019 return 0;
5020 }
5021
5022 static int load_settings(void) {
5023 _cleanup_(settings_freep) Settings *settings = NULL;
5024 _cleanup_fclose_ FILE *f = NULL;
5025 _cleanup_free_ char *p = NULL;
5026 int r;
5027
5028 if (arg_oci_bundle)
5029 return 0;
5030
5031 /* If all settings are masked, there's no point in looking for
5032 * the settings file */
5033 if (FLAGS_SET(arg_settings_mask, _SETTINGS_MASK_ALL))
5034 return 0;
5035
5036 /* We first look in the admin's directories in /etc and /run */
5037 if (arg_privileged)
5038 FOREACH_STRING(i, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
5039 _cleanup_free_ char *j = NULL;
5040
5041 j = path_join(i, arg_settings_filename);
5042 if (!j)
5043 return log_oom();
5044
5045 f = fopen(j, "re");
5046 if (f) {
5047 p = TAKE_PTR(j);
5048
5049 /* By default, we trust configuration from /etc and /run */
5050 if (arg_settings_trusted < 0)
5051 arg_settings_trusted = true;
5052
5053 break;
5054 }
5055
5056 if (errno != ENOENT)
5057 return log_error_errno(errno, "Failed to open %s: %m", j);
5058 }
5059
5060 if (!f) {
5061 /* After that, let's look for a file next to the
5062 * actual image we shall boot. */
5063
5064 if (arg_image) {
5065 r = file_in_same_dir(arg_image, arg_settings_filename, &p);
5066 if (r < 0)
5067 return log_error_errno(r, "Failed to generate settings path from image path: %m");
5068 } else if (arg_directory) {
5069 r = file_in_same_dir(arg_directory, arg_settings_filename, &p);
5070 if (r < 0 && r != -EADDRNOTAVAIL) /* if directory is root fs, don't complain */
5071 return log_error_errno(r, "Failed to generate settings path from directory path: %m");
5072 }
5073
5074 if (p) {
5075 f = fopen(p, "re");
5076 if (!f && errno != ENOENT)
5077 return log_error_errno(errno, "Failed to open %s: %m", p);
5078
5079 /* By default, we do not trust configuration from /var/lib/machines */
5080 if (arg_settings_trusted < 0)
5081 arg_settings_trusted = false;
5082 }
5083 }
5084
5085 if (!f)
5086 return 0;
5087
5088 log_debug("Settings are trusted: %s", yes_no(arg_settings_trusted));
5089
5090 r = settings_load(f, p, &settings);
5091 if (r < 0)
5092 return r;
5093
5094 return merge_settings(settings, p);
5095 }
5096
5097 static int load_oci_bundle(void) {
5098 _cleanup_(settings_freep) Settings *settings = NULL;
5099 int r;
5100
5101 if (!arg_oci_bundle)
5102 return 0;
5103
5104 /* By default let's trust OCI bundles */
5105 if (arg_settings_trusted < 0)
5106 arg_settings_trusted = true;
5107
5108 r = oci_load(NULL, arg_oci_bundle, &settings);
5109 if (r < 0)
5110 return r;
5111
5112 return merge_settings(settings, arg_oci_bundle);
5113 }
5114
5115 static int run_container(
5116 const char *directory,
5117 int mount_fd,
5118 DissectedImage *dissected_image,
5119 int userns_fd,
5120 FDSet *fds,
5121 char veth_name[IFNAMSIZ],
5122 bool *veth_created,
5123 struct ExposeArgs *expose_args,
5124 int *master,
5125 PidRef *pid,
5126 int *ret) {
5127
5128 _cleanup_(release_lock_file) LockFile uid_shift_lock = LOCK_FILE_INIT;
5129 _cleanup_close_ int etc_passwd_lock = -EBADF;
5130 _cleanup_close_pair_ int
5131 fd_inner_socket_pair[2] = EBADF_PAIR,
5132 fd_outer_socket_pair[2] = EBADF_PAIR;
5133
5134 _cleanup_close_ int notify_socket = -EBADF, mntns_fd = -EBADF, fd_kmsg_fifo = -EBADF;
5135 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
5136 _cleanup_(sd_event_source_unrefp) sd_event_source *notify_event_source = NULL;
5137 _cleanup_(umount_and_rmdir_and_freep) char *unix_export_host_dir = NULL;
5138 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
5139 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
5140 _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
5141 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
5142 _cleanup_free_ uid_t *bind_user_uid = NULL;
5143 size_t n_bind_user_uid = 0;
5144 ContainerStatus container_status = 0;
5145 int ifi = 0, r;
5146 ssize_t l;
5147 sigset_t mask_chld;
5148 _cleanup_close_ int child_netns_fd = -EBADF;
5149
5150 assert_se(sigemptyset(&mask_chld) == 0);
5151 assert_se(sigaddset(&mask_chld, SIGCHLD) == 0);
5152
5153 /* Set up the unix export host directory on the host first */
5154 r = setup_unix_export_dir_outside(&unix_export_host_dir);
5155 if (r < 0)
5156 return r;
5157
5158 if (arg_userns_mode == USER_NAMESPACE_PICK) {
5159 /* When we shall pick the UID/GID range, let's first lock /etc/passwd, so that we can safely
5160 * check with getpwuid() if the specific user already exists. Note that /etc might be
5161 * read-only, in which case this will fail with EROFS. But that's really OK, as in that case we
5162 * can be reasonably sure that no users are going to be added. Note that getpwuid() checks are
5163 * really just an extra safety net. We kinda assume that the UID range we allocate from is
5164 * really ours. */
5165
5166 etc_passwd_lock = take_etc_passwd_lock(NULL);
5167 if (etc_passwd_lock < 0 && etc_passwd_lock != -EROFS)
5168 return log_error_errno(etc_passwd_lock, "Failed to take /etc/passwd lock: %m");
5169 }
5170
5171 r = barrier_create(&barrier);
5172 if (r < 0)
5173 return log_error_errno(r, "Cannot initialize IPC barrier: %m");
5174
5175 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, fd_inner_socket_pair) < 0)
5176 return log_error_errno(errno, "Failed to create inner socket pair: %m");
5177
5178 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, fd_outer_socket_pair) < 0)
5179 return log_error_errno(errno, "Failed to create outer socket pair: %m");
5180
5181 /* Child can be killed before execv(), so handle SIGCHLD in order to interrupt
5182 * parent's blocking calls and give it a chance to call wait() and terminate. */
5183 r = sigprocmask(SIG_UNBLOCK, &mask_chld, NULL);
5184 if (r < 0)
5185 return log_error_errno(errno, "Failed to change the signal mask: %m");
5186
5187 r = sigaction(SIGCHLD, &sigaction_nop_nocldstop, NULL);
5188 if (r < 0)
5189 return log_error_errno(errno, "Failed to install SIGCHLD handler: %m");
5190
5191 if (arg_network_namespace_path) {
5192 child_netns_fd = open(arg_network_namespace_path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5193 if (child_netns_fd < 0)
5194 return log_error_errno(errno, "Cannot open file %s: %m", arg_network_namespace_path);
5195
5196 r = fd_is_namespace(child_netns_fd, NAMESPACE_NET);
5197 if (r < 0)
5198 return log_error_errno(r, "Failed to check %s fs type: %m", arg_network_namespace_path);
5199 if (r == 0)
5200 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5201 "Path %s doesn't refer to a network namespace, refusing.", arg_network_namespace_path);
5202 }
5203
5204 bool in_child;
5205 if (arg_userns_mode != USER_NAMESPACE_MANAGED) {
5206 assert(userns_fd < 0);
5207 /* If we have no user namespace then we'll clone and create a new mount namespace right-away. */
5208
5209 pid_t _pid = raw_clone(SIGCHLD|CLONE_NEWNS);
5210 if (_pid < 0)
5211 return log_error_errno(errno, "clone() failed%s: %m",
5212 errno == EINVAL ?
5213 ", do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in)" : "");
5214 if (_pid != 0) {
5215 r = pidref_set_pid(pid, _pid);
5216 if (r < 0)
5217 return log_error_errno(r, "Failed to allocate pidfd: %m");
5218 }
5219
5220 in_child = _pid == 0;
5221 } else {
5222 assert(userns_fd >= 0);
5223 /* If we have a user namespace then we'll clone() first, and then join the user namespace,
5224 * and then open the mount namespace, so that it is owned by the user namespace */
5225
5226 pid_t _pid = raw_clone(SIGCHLD);
5227 if (_pid < 0)
5228 return log_error_errno(errno, "clone() failed: %m");
5229
5230 if (_pid != 0) {
5231 r = pidref_set_pid(pid, _pid);
5232 if (r < 0)
5233 return log_error_errno(r, "Failed to allocate pidfd: %m");
5234 }
5235
5236 in_child = _pid == 0;
5237 if (in_child) {
5238 if (setns(userns_fd, CLONE_NEWUSER) < 0) {
5239 log_error_errno(errno, "Failed to join allocate user namespace: %m");
5240 _exit(EXIT_FAILURE);
5241 }
5242
5243 r = reset_uid_gid();
5244 if (r < 0) {
5245 log_error_errno(r, "Failed to reset UID/GID to root: %m");
5246 _exit(EXIT_FAILURE);
5247 }
5248
5249 if (unshare(CLONE_NEWNS) < 0) {
5250 log_error_errno(errno, "Failed to unshare file system namespace: %m");
5251 _exit(EXIT_FAILURE);
5252 }
5253 }
5254 }
5255
5256 if (in_child) {
5257 /* The outer child only has a file system namespace. */
5258 barrier_set_role(&barrier, BARRIER_CHILD);
5259
5260 fd_inner_socket_pair[0] = safe_close(fd_inner_socket_pair[0]);
5261 fd_outer_socket_pair[0] = safe_close(fd_outer_socket_pair[0]);
5262
5263 (void) reset_all_signal_handlers();
5264 (void) reset_signal_mask();
5265
5266 r = outer_child(&barrier,
5267 directory,
5268 mount_fd,
5269 dissected_image,
5270 fd_outer_socket_pair[1],
5271 fd_inner_socket_pair[1],
5272 fds,
5273 child_netns_fd,
5274 unix_export_host_dir);
5275 if (r < 0)
5276 _exit(EXIT_FAILURE);
5277
5278 _exit(EXIT_SUCCESS);
5279 }
5280
5281 barrier_set_role(&barrier, BARRIER_PARENT);
5282
5283 fdset_close(fds, /* async= */ false);
5284
5285 fd_inner_socket_pair[1] = safe_close(fd_inner_socket_pair[1]);
5286 fd_outer_socket_pair[1] = safe_close(fd_outer_socket_pair[1]);
5287
5288 if (arg_userns_mode != USER_NAMESPACE_NO) {
5289 mntns_fd = receive_one_fd(fd_outer_socket_pair[0], 0);
5290 if (mntns_fd < 0)
5291 return log_error_errno(mntns_fd, "Failed to receive mount namespace fd from outer child: %m");
5292
5293 /* The child just let us know the UID shift it might have read from the image. */
5294 l = recv(fd_outer_socket_pair[0], &arg_uid_shift, sizeof arg_uid_shift, 0);
5295 if (l < 0)
5296 return log_error_errno(errno, "Failed to read UID shift: %m");
5297 if (l != sizeof arg_uid_shift)
5298 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short read while reading UID shift.");
5299
5300 if (arg_userns_mode == USER_NAMESPACE_PICK) {
5301 /* If we are supposed to pick the UID shift, let's try to use the shift read from the
5302 * image, but if that's already in use, pick a new one, and report back to the child,
5303 * which one we now picked. */
5304
5305 r = uid_shift_pick(&arg_uid_shift, &uid_shift_lock);
5306 if (r < 0)
5307 return log_error_errno(r, "Failed to pick suitable UID/GID range: %m");
5308
5309 l = send(fd_outer_socket_pair[0], &arg_uid_shift, sizeof arg_uid_shift, MSG_NOSIGNAL);
5310 if (l < 0)
5311 return log_error_errno(errno, "Failed to send UID shift: %m");
5312 if (l != sizeof arg_uid_shift)
5313 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing UID shift.");
5314 }
5315
5316 n_bind_user_uid = strv_length(arg_bind_user);
5317 if (n_bind_user_uid > 0) {
5318 /* Right after the UID shift, we'll receive the list of UID mappings for the
5319 * --bind-user= logic. Always a quadruplet of payload and host UID + GID. */
5320
5321 bind_user_uid = new(uid_t, n_bind_user_uid*4);
5322 if (!bind_user_uid)
5323 return log_oom();
5324
5325 for (size_t i = 0; i < n_bind_user_uid; i++) {
5326 l = recv(fd_outer_socket_pair[0], bind_user_uid + i*4, sizeof(uid_t)*4, 0);
5327 if (l < 0)
5328 return log_error_errno(errno, "Failed to read user UID map pair: %m");
5329 if (l != sizeof(uid_t)*4)
5330 return log_full_errno(l == 0 ? LOG_DEBUG : LOG_WARNING,
5331 SYNTHETIC_ERRNO(EIO),
5332 "Short read while reading bind user UID pairs.");
5333 }
5334 }
5335 }
5336
5337 /* Wait for the outer child. */
5338 r = pidref_wait_for_terminate_and_check("(sd-namespace)", pid, WAIT_LOG_ABNORMAL);
5339 if (r < 0)
5340 return r;
5341 pidref_done(pid);
5342 if (r != EXIT_SUCCESS)
5343 return -EIO;
5344
5345 /* And now retrieve the PID of the inner child. */
5346 pid_t _pid;
5347 l = recv(fd_outer_socket_pair[0], &_pid, sizeof _pid, 0);
5348 if (l < 0)
5349 return log_error_errno(errno, "Failed to read inner child PID: %m");
5350 if (l != sizeof _pid)
5351 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short read while reading inner child PID.");
5352
5353 r = pidref_set_pid(pid, _pid);
5354 if (r < 0)
5355 return log_error_errno(r, "Failed to allocate pidfd: %m");
5356
5357 /* We also retrieve container UUID in case it was generated by outer child */
5358 l = recv(fd_outer_socket_pair[0], &arg_uuid, sizeof arg_uuid, 0);
5359 if (l < 0)
5360 return log_error_errno(errno, "Failed to read container machine ID: %m");
5361 if (l != sizeof(arg_uuid))
5362 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short read while reading container machined ID.");
5363
5364 /* We also retrieve the socket used for notifications generated by outer child */
5365 notify_socket = receive_one_fd(fd_outer_socket_pair[0], 0);
5366 if (notify_socket < 0)
5367 return log_error_errno(notify_socket,
5368 "Failed to receive notification socket from the outer child: %m");
5369
5370 log_debug("Init process invoked as PID "PID_FMT, pid->pid);
5371
5372 if (arg_userns_mode != USER_NAMESPACE_NO) {
5373 if (!barrier_place_and_sync(&barrier)) /* #1 */
5374 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "Child died too early.");
5375
5376 if (arg_userns_mode != USER_NAMESPACE_MANAGED) {
5377 r = setup_uid_map(pid, bind_user_uid, n_bind_user_uid);
5378 if (r < 0)
5379 return r;
5380 }
5381
5382 (void) barrier_place(&barrier); /* #2 */
5383 }
5384
5385 if (arg_private_network) {
5386 if (!arg_network_namespace_path) {
5387 /* Wait until the child has unshared its network namespace. */
5388 if (!barrier_place_and_sync(&barrier)) /* #3 */
5389 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "Child died too early");
5390
5391 /* Make sure we have an open file descriptor to the child's network namespace so it
5392 * stays alive even if the child exits. */
5393 assert(child_netns_fd < 0);
5394 child_netns_fd = receive_one_fd(fd_inner_socket_pair[0], 0);
5395 if (child_netns_fd < 0)
5396 return log_error_errno(r, "Failed to receive child network namespace: %m");
5397 }
5398
5399 r = move_network_interfaces(child_netns_fd, arg_network_interfaces);
5400 if (r < 0)
5401 return r;
5402
5403 if (arg_network_veth) {
5404 if (arg_userns_mode != USER_NAMESPACE_MANAGED) {
5405 r = setup_veth(arg_machine, pid, veth_name,
5406 arg_network_bridge || arg_network_zone, &arg_network_provided_mac);
5407 if (r < 0)
5408 return r;
5409 else if (r > 0)
5410 ifi = r;
5411 } else {
5412 _cleanup_free_ char *host_ifname = NULL;
5413
5414 r = nsresource_add_netif_veth(userns_fd, child_netns_fd, /* namespace_ifname= */ NULL, &host_ifname, /* ret_namespace_ifname= */ NULL);
5415 if (r < 0)
5416 return log_error_errno(r, "Failed to add network interface to container: %m");
5417
5418 ifi = if_nametoindex(host_ifname);
5419 if (ifi == 0)
5420 return log_error_errno(errno, "Failed to resolve interface '%s': %m", host_ifname);
5421
5422 if (strlen(host_ifname) >= IFNAMSIZ)
5423 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Host interface name too long?");
5424
5425 strcpy(veth_name, host_ifname);
5426 }
5427
5428 if (arg_network_bridge) {
5429 /* Add the interface to a bridge */
5430 r = setup_bridge(veth_name, arg_network_bridge, false);
5431 if (r < 0)
5432 return r;
5433 if (r > 0)
5434 ifi = r;
5435 } else if (arg_network_zone) {
5436 /* Add the interface to a bridge, possibly creating it */
5437 r = setup_bridge(veth_name, arg_network_zone, true);
5438 if (r < 0)
5439 return r;
5440 if (r > 0)
5441 ifi = r;
5442 }
5443 }
5444
5445 r = setup_veth_extra(arg_machine, pid, arg_network_veth_extra);
5446 if (r < 0)
5447 return r;
5448
5449 /* We created the primary and extra veth links now; let's remember this, so that we know to
5450 remove them later on. Note that we don't bother with removing veth links that were created
5451 here when their setup failed half-way, because in that case the kernel should be able to
5452 remove them on its own, since they cannot be referenced by anything yet. */
5453 *veth_created = true;
5454
5455 r = setup_macvlan(arg_machine, pid, arg_network_macvlan);
5456 if (r < 0)
5457 return r;
5458
5459 r = setup_ipvlan(arg_machine, pid, arg_network_ipvlan);
5460 if (r < 0)
5461 return r;
5462 }
5463
5464 if (arg_register || !arg_keep_unit) {
5465 if (arg_privileged || arg_register)
5466 r = sd_bus_default_system(&bus);
5467 else
5468 r = sd_bus_default_user(&bus);
5469 if (r < 0)
5470 return log_error_errno(r, "Failed to open bus: %m");
5471
5472 r = sd_bus_set_close_on_exit(bus, false);
5473 if (r < 0)
5474 return log_error_errno(r, "Failed to disable close-on-exit behaviour: %m");
5475
5476 (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
5477 }
5478
5479 if (!arg_keep_unit) {
5480 /* When a new scope is created for this container, then we'll be registered as its controller, in which
5481 * case PID 1 will send us a friendly RequestStop signal, when it is asked to terminate the
5482 * scope. Let's hook into that, and cleanly shut down the container, and print a friendly message. */
5483
5484 r = sd_bus_match_signal_async(
5485 bus,
5486 NULL,
5487 "org.freedesktop.systemd1",
5488 NULL,
5489 "org.freedesktop.systemd1.Scope",
5490 "RequestStop",
5491 on_request_stop,
5492 NULL,
5493 pid);
5494 if (r < 0)
5495 return log_error_errno(r, "Failed to request RequestStop match: %m");
5496 }
5497
5498 if (arg_register) {
5499 RegisterMachineFlags flags = 0;
5500 SET_FLAG(flags, REGISTER_MACHINE_KEEP_UNIT, arg_keep_unit);
5501 r = register_machine(
5502 bus,
5503 arg_machine,
5504 pid,
5505 arg_directory,
5506 arg_uuid,
5507 ifi,
5508 arg_slice,
5509 arg_custom_mounts, arg_n_custom_mounts,
5510 arg_kill_signal,
5511 arg_property,
5512 arg_property_message,
5513 arg_container_service_name,
5514 arg_start_mode,
5515 flags);
5516 if (r < 0)
5517 return r;
5518
5519 } else if (!arg_keep_unit) {
5520 AllocateScopeFlags flags = ALLOCATE_SCOPE_ALLOW_PIDFD;
5521 r = allocate_scope(
5522 bus,
5523 arg_machine,
5524 pid,
5525 arg_slice,
5526 arg_custom_mounts, arg_n_custom_mounts,
5527 arg_kill_signal,
5528 arg_property,
5529 arg_property_message,
5530 arg_start_mode,
5531 flags);
5532 if (r < 0)
5533 return r;
5534
5535 } else if (arg_slice || arg_property)
5536 log_notice("Machine and scope registration turned off, --slice= and --property= settings will have no effect.");
5537
5538 r = create_subcgroup(
5539 pid,
5540 arg_keep_unit,
5541 arg_uid_shift,
5542 userns_fd,
5543 arg_userns_mode);
5544 if (r < 0)
5545 return r;
5546
5547 /* Notify the child that the parent is ready with all its setup (including cgroup-ification), and
5548 * that the child can now hand over control to the code to run inside the container. */
5549 (void) barrier_place(&barrier); /* #4 */
5550
5551 /* Block SIGCHLD here, before notifying child.
5552 * process_pty() will handle it with the other signals. */
5553 assert_se(sigprocmask(SIG_BLOCK, &mask_chld, NULL) >= 0);
5554
5555 /* Reset signal to default */
5556 r = default_signals(SIGCHLD);
5557 if (r < 0)
5558 return log_error_errno(r, "Failed to reset SIGCHLD: %m");
5559
5560 r = sd_event_new(&event);
5561 if (r < 0)
5562 return log_error_errno(r, "Failed to get default event source: %m");
5563
5564 (void) sd_event_set_watchdog(event, true);
5565
5566 if (bus) {
5567 r = sd_bus_attach_event(bus, event, 0);
5568 if (r < 0)
5569 return log_error_errno(r, "Failed to attach bus to event loop: %m");
5570 }
5571
5572 r = setup_notify_parent(event, notify_socket, pid, &notify_event_source);
5573 if (r < 0)
5574 return r;
5575
5576 /* Wait that the child is completely ready now, and has mounted their own copies of procfs and so on,
5577 * before we take the fully visible instances away. */
5578 if (!barrier_sync(&barrier)) /* #5.1 */
5579 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "Child died too early.");
5580
5581 if (!IN_SET(arg_userns_mode, USER_NAMESPACE_NO, USER_NAMESPACE_MANAGED)) {
5582 r = wipe_fully_visible_api_fs(mntns_fd);
5583 if (r < 0)
5584 return r;
5585 mntns_fd = safe_close(mntns_fd);
5586 }
5587
5588 /* And now let the child know that we completed removing the procfs instances, and it can start the
5589 * payload. */
5590 if (!barrier_place(&barrier)) /* #5.2 */
5591 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "Child died too early.");
5592
5593 /* At this point we have made use of the UID we picked, and thus nss-systemd/systemd-machined.service
5594 * will make them appear in getpwuid(), thus we can release the /etc/passwd lock. */
5595 etc_passwd_lock = safe_close(etc_passwd_lock);
5596
5597 (void) sd_notifyf(false,
5598 "STATUS=Container running.\n"
5599 "X_NSPAWN_LEADER_PID=" PID_FMT, pid->pid);
5600 if (!arg_notify_ready) {
5601 r = sd_notify(false, "READY=1\n");
5602 if (r < 0)
5603 log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
5604 }
5605
5606 /* All operations that might need Polkit authorizations (i.e. userns registration, mounts, and
5607 * machine registration are complete now, get rid of the agent again, so that we retain exclusive
5608 * control of the TTY from now on. */
5609 polkit_agent_close();
5610
5611 /* Note: we do not use SD_EVENT_SIGNAL_PROCMASK or sd_event_set_signal_exit(), since we want the
5612 * signals to be block continuously, even if we destroy the event loop and allocate a new one on
5613 * container reboot. */
5614
5615 if (arg_kill_signal > 0) {
5616 /* Try to kill the init system on SIGINT or SIGTERM */
5617 (void) sd_event_add_signal(event, NULL, SIGINT, on_orderly_shutdown, pid);
5618 (void) sd_event_add_signal(event, NULL, SIGTERM, on_orderly_shutdown, pid);
5619 } else {
5620 /* Immediately exit */
5621 (void) sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
5622 (void) sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
5623 }
5624
5625 (void) sd_event_add_signal(event, NULL, SIGRTMIN+18, sigrtmin18_handler, NULL);
5626
5627 r = sd_event_add_memory_pressure(event, NULL, NULL, NULL);
5628 if (r < 0)
5629 log_debug_errno(r, "Failed allocate memory pressure event source, ignoring: %m");
5630
5631 /* Exit when the child exits */
5632 (void) sd_event_add_signal(event, NULL, SIGCHLD, on_sigchld, pid);
5633
5634 /* Retrieve the kmsg fifo allocated by inner child */
5635 fd_kmsg_fifo = receive_one_fd(fd_inner_socket_pair[0], 0);
5636 if (fd_kmsg_fifo < 0)
5637 return log_error_errno(fd_kmsg_fifo, "Failed to receive kmsg fifo from inner child: %m");
5638
5639 if (arg_expose_ports) {
5640 r = expose_port_watch_rtnl(event, fd_inner_socket_pair[0], on_address_change, expose_args, &rtnl);
5641 if (r < 0)
5642 return r;
5643
5644 (void) expose_port_execute(rtnl, &expose_args->fw_ctx, arg_expose_ports, AF_INET, &expose_args->address4);
5645 (void) expose_port_execute(rtnl, &expose_args->fw_ctx, arg_expose_ports, AF_INET6, &expose_args->address6);
5646 }
5647
5648 _cleanup_(osc_context_closep) sd_id128_t osc_context_id = SD_ID128_NULL;
5649 if (IN_SET(arg_console_mode, CONSOLE_INTERACTIVE, CONSOLE_READ_ONLY) && !terminal_is_dumb()) {
5650 r = osc_context_open_container(arg_machine, /* ret_seq= */ NULL, &osc_context_id);
5651 if (r < 0)
5652 return r;
5653 }
5654
5655 if (arg_console_mode != CONSOLE_PIPE) {
5656 _cleanup_close_ int fd = -EBADF;
5657 PTYForwardFlags flags = 0;
5658
5659 /* Retrieve the master pty allocated by inner child */
5660 fd = receive_one_fd(fd_inner_socket_pair[0], 0);
5661 if (fd < 0)
5662 return log_error_errno(fd, "Failed to receive master pty from the inner child: %m");
5663
5664 switch (arg_console_mode) {
5665
5666 case CONSOLE_READ_ONLY:
5667 flags |= PTY_FORWARD_READ_ONLY;
5668
5669 _fallthrough_;
5670
5671 case CONSOLE_INTERACTIVE:
5672 flags |= PTY_FORWARD_IGNORE_VHANGUP;
5673
5674 r = pty_forward_new(event, fd, flags, &forward);
5675 if (r < 0)
5676 return log_error_errno(r, "Failed to create PTY forwarder: %m");
5677
5678 if (arg_console_width != UINT_MAX || arg_console_height != UINT_MAX)
5679 (void) pty_forward_set_width_height(
5680 forward,
5681 arg_console_width,
5682 arg_console_height);
5683
5684 if (!arg_background && shall_tint_background()) {
5685 _cleanup_free_ char *bg = NULL;
5686
5687 r = terminal_tint_color(220 /* blue */, &bg);
5688 if (r < 0)
5689 log_debug_errno(r, "Failed to determine terminal background color, not tinting.");
5690 else
5691 (void) pty_forward_set_background_color(forward, bg);
5692 } else if (!isempty(arg_background))
5693 (void) pty_forward_set_background_color(forward, arg_background);
5694
5695 (void) pty_forward_set_window_title(forward, GLYPH_BLUE_CIRCLE, /* hostname = */ NULL,
5696 STRV_MAKE("Container", arg_machine));
5697
5698 pty_forward_set_hotkey_handler(forward, ptyfwd_hotkey, pid);
5699 break;
5700
5701 default:
5702 assert(arg_console_mode == CONSOLE_PASSIVE);
5703 }
5704
5705 *master = TAKE_FD(fd);
5706 }
5707
5708 fd_inner_socket_pair[0] = safe_close(fd_inner_socket_pair[0]);
5709
5710 r = sd_event_loop(event);
5711 if (r < 0)
5712 return log_error_errno(r, "Failed to run event loop: %m");
5713
5714 /* Kill if it is not dead yet anyway */
5715 if (!arg_register && !arg_keep_unit && bus)
5716 terminate_scope(bus, arg_machine);
5717
5718 /* Normally redundant, but better safe than sorry */
5719 (void) pidref_kill(pid, SIGKILL);
5720
5721 fd_kmsg_fifo = safe_close(fd_kmsg_fifo);
5722
5723 if (arg_private_network && arg_userns_mode != USER_NAMESPACE_MANAGED) {
5724 r = move_back_network_interfaces(child_netns_fd, arg_network_interfaces);
5725 if (r < 0)
5726 return r;
5727
5728 r = remove_macvlan(child_netns_fd, arg_network_macvlan);
5729 if (r < 0)
5730 return r;
5731 }
5732
5733 r = wait_for_container(pid, &container_status);
5734
5735 /* Tell machined that we are gone. */
5736 if (arg_register && bus)
5737 (void) unregister_machine(bus, arg_machine);
5738
5739 if (r < 0)
5740 /* We failed to wait for the container, or the container exited abnormally. */
5741 return r;
5742 if (r > 0 || container_status == CONTAINER_TERMINATED) {
5743 /* r > 0 → The container exited with a non-zero status.
5744 * As a special case, we need to replace 133 with a different value,
5745 * because 133 is special-cased in the service file to reboot the container.
5746 * otherwise → The container exited with zero status and a reboot was not requested.
5747 */
5748 if (r == EXIT_FORCE_RESTART)
5749 r = EXIT_FAILURE; /* replace 133 with the general failure code */
5750 *ret = r;
5751 return 0; /* finito */
5752 }
5753
5754 /* CONTAINER_REBOOTED, loop again */
5755
5756 if (arg_keep_unit) {
5757 /* Special handling if we are running as a service: instead of simply
5758 * restarting the machine we want to restart the entire service, so let's
5759 * inform systemd about this with the special exit code 133. The service
5760 * file uses RestartForceExitStatus=133 so that this results in a full
5761 * nspawn restart. This is necessary since we might have cgroup parameters
5762 * set we want to have flushed out. */
5763 *ret = EXIT_FORCE_RESTART;
5764 return 0; /* finito */
5765 }
5766
5767 expose_port_flush(&expose_args->fw_ctx, arg_expose_ports, AF_INET, &expose_args->address4);
5768 expose_port_flush(&expose_args->fw_ctx, arg_expose_ports, AF_INET6, &expose_args->address6);
5769
5770 (void) remove_veth_links(veth_name, arg_network_veth_extra);
5771 *veth_created = false;
5772 return 1; /* loop again */
5773 }
5774
5775 static int initialize_rlimits(void) {
5776 /* The default resource limits the kernel passes to PID 1, as per kernel 5.16. Let's pass our container payload
5777 * the same values as the kernel originally passed to PID 1, in order to minimize differences between host and
5778 * container execution environments. */
5779
5780 static const struct rlimit kernel_defaults[_RLIMIT_MAX] = {
5781 [RLIMIT_AS] = { RLIM_INFINITY, RLIM_INFINITY },
5782 [RLIMIT_CORE] = { 0, RLIM_INFINITY },
5783 [RLIMIT_CPU] = { RLIM_INFINITY, RLIM_INFINITY },
5784 [RLIMIT_DATA] = { RLIM_INFINITY, RLIM_INFINITY },
5785 [RLIMIT_FSIZE] = { RLIM_INFINITY, RLIM_INFINITY },
5786 [RLIMIT_LOCKS] = { RLIM_INFINITY, RLIM_INFINITY },
5787 [RLIMIT_MEMLOCK] = { DEFAULT_RLIMIT_MEMLOCK, DEFAULT_RLIMIT_MEMLOCK },
5788 [RLIMIT_MSGQUEUE] = { 819200, 819200 },
5789 [RLIMIT_NICE] = { 0, 0 },
5790 [RLIMIT_NOFILE] = { 1024, 4096 },
5791 [RLIMIT_RSS] = { RLIM_INFINITY, RLIM_INFINITY },
5792 [RLIMIT_RTPRIO] = { 0, 0 },
5793 [RLIMIT_RTTIME] = { RLIM_INFINITY, RLIM_INFINITY },
5794 [RLIMIT_STACK] = { 8388608, RLIM_INFINITY },
5795
5796 /* The kernel scales the default for RLIMIT_NPROC and RLIMIT_SIGPENDING based on the system's amount of
5797 * RAM. To provide best compatibility we'll read these limits off PID 1 instead of hardcoding them
5798 * here. This is safe as we know that PID 1 doesn't change these two limits and thus the original
5799 * kernel's initialization should still be valid during runtime — at least if PID 1 is systemd. Note
5800 * that PID 1 changes a number of other resource limits during early initialization which is why we
5801 * don't read the other limits from PID 1 but prefer the static table above. */
5802 };
5803
5804 int rl, r;
5805
5806 for (rl = 0; rl < _RLIMIT_MAX; rl++) {
5807 /* Let's only fill in what the user hasn't explicitly configured anyway */
5808 if ((arg_settings_mask & (SETTING_RLIMIT_FIRST << rl)) == 0) {
5809 const struct rlimit *v;
5810 struct rlimit buffer;
5811
5812 if (IN_SET(rl, RLIMIT_NPROC, RLIMIT_SIGPENDING)) {
5813 /* For these two let's read the limits off PID 1. See above for an explanation. */
5814
5815 r = pid_getrlimit(1, rl, &buffer);
5816 if (r < 0)
5817 return log_error_errno(r, "Failed to read resource limit RLIMIT_%s of PID 1: %m", rlimit_to_string(rl));
5818
5819 v = &buffer;
5820 } else if (rl == RLIMIT_NOFILE) {
5821 /* We nowadays bump RLIMIT_NOFILE's hard limit early in PID 1 for all
5822 * userspace. Given that nspawn containers are often run without our PID 1,
5823 * let's grant the containers a raised RLIMIT_NOFILE hard limit by default,
5824 * so that container userspace gets similar resources as host userspace
5825 * gets. */
5826 buffer = kernel_defaults[rl];
5827 buffer.rlim_max = MIN((rlim_t) read_nr_open(), (rlim_t) HIGH_RLIMIT_NOFILE);
5828 v = &buffer;
5829 } else
5830 v = kernel_defaults + rl;
5831
5832 arg_rlimit[rl] = newdup(struct rlimit, v, 1);
5833 if (!arg_rlimit[rl])
5834 return log_oom();
5835 }
5836
5837 if (DEBUG_LOGGING) {
5838 _cleanup_free_ char *k = NULL;
5839
5840 (void) rlimit_format(arg_rlimit[rl], &k);
5841 log_debug("Setting RLIMIT_%s to %s.", rlimit_to_string(rl), k);
5842 }
5843 }
5844
5845 return 0;
5846 }
5847
5848 static int cant_be_in_netns(void) {
5849 _cleanup_close_ int fd = -EBADF;
5850 struct ucred ucred;
5851 int r;
5852
5853 /* Check if we are in the same netns as udev. If we aren't, then device monitoring (and thus waiting
5854 * for loopback block devices) won't work, and we will hang. Detect this case and exit early with a
5855 * nice message. */
5856
5857 if (!arg_image) /* only matters if --image= us used, i.e. we actually need to use loopback devices */
5858 return 0;
5859
5860 fd = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
5861 if (fd < 0)
5862 return log_error_errno(errno, "Failed to allocate udev control socket: %m");
5863
5864 r = connect_unix_path(fd, AT_FDCWD, "/run/udev/control");
5865 if (r == -ENOENT || ERRNO_IS_NEG_DISCONNECT(r))
5866 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
5867 "Sorry, but --image= requires access to the host's /run/ hierarchy, since we need access to udev.");
5868 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
5869 log_debug_errno(r, "Can't connect to udev control socket, assuming we are in same netns.");
5870 return 0;
5871 }
5872 if (r < 0)
5873 return log_error_errno(r, "Failed to connect socket to udev control socket: %m");
5874
5875 r = getpeercred(fd, &ucred);
5876 if (r < 0)
5877 return log_error_errno(r, "Failed to determine peer of udev control socket: %m");
5878
5879 r = in_same_namespace(ucred.pid, 0, NAMESPACE_NET);
5880 if (r < 0)
5881 return log_error_errno(r, "Failed to determine network namespace of udev: %m");
5882 if (r == 0)
5883 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
5884 "Sorry, but --image= is only supported in the main network namespace, since we need access to udev/AF_NETLINK.");
5885 return 0;
5886 }
5887
5888 static void initialize_defaults(void) {
5889 arg_privileged = getuid() == 0;
5890
5891 /* If running unprivileged default to systemd-nsresourced operation */
5892 arg_userns_mode = arg_privileged ? USER_NAMESPACE_NO : USER_NAMESPACE_MANAGED;
5893
5894 /* Imply private networking for unprivileged operation, since kernel otherwise refuses mounting sysfs */
5895 arg_private_network = !arg_privileged;
5896 }
5897
5898 static void cleanup_propagation_and_export_directories(void) {
5899 const char *p;
5900
5901 if (!arg_machine || !arg_privileged)
5902 return;
5903
5904 p = strjoina("/run/systemd/nspawn/propagate/", arg_machine);
5905 (void) rm_rf(p, REMOVE_ROOT);
5906
5907 p = strjoina("/run/systemd/nspawn/unix-export/", arg_machine);
5908 (void) umount2(p, MNT_DETACH|UMOUNT_NOFOLLOW);
5909 (void) rmdir(p);
5910 }
5911
5912 static int do_cleanup(void) {
5913 int r;
5914
5915 if (arg_ephemeral)
5916 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot specify --ephemeral with --cleanup.");
5917
5918 r = determine_names();
5919 if (r < 0)
5920 return r;
5921
5922 cleanup_propagation_and_export_directories();
5923 return 0;
5924 }
5925
5926 static int run(int argc, char *argv[]) {
5927 bool remove_directory = false, remove_image = false, veth_created = false;
5928 _cleanup_close_ int master = -EBADF, userns_fd = -EBADF, mount_fd = -EBADF;
5929 _cleanup_fdset_free_ FDSet *fds = NULL;
5930 int r, ret = EXIT_SUCCESS;
5931 char veth_name[IFNAMSIZ] = "";
5932 struct ExposeArgs expose_args = {};
5933 _cleanup_(release_lock_file) LockFile tree_global_lock = LOCK_FILE_INIT, tree_local_lock = LOCK_FILE_INIT;
5934 _cleanup_(rmdir_and_freep) char *rootdir = NULL;
5935 _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
5936 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
5937 _cleanup_(fw_ctx_freep) FirewallContext *fw_ctx = NULL;
5938 _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
5939
5940 log_setup();
5941
5942 initialize_defaults();
5943
5944 r = parse_argv(argc, argv);
5945 if (r <= 0)
5946 goto finish;
5947
5948 if (arg_cleanup)
5949 return do_cleanup();
5950
5951 r = cg_has_legacy();
5952 if (r < 0)
5953 goto finish;
5954 if (r > 0) {
5955 r = log_error_errno(SYNTHETIC_ERRNO(EPROTO),
5956 "Detected host uses legacy cgroup v1 hierarchy, refusing.");
5957 goto finish;
5958 }
5959
5960 r = cant_be_in_netns();
5961 if (r < 0)
5962 goto finish;
5963
5964 r = initialize_rlimits();
5965 if (r < 0)
5966 goto finish;
5967
5968 r = load_oci_bundle();
5969 if (r < 0)
5970 goto finish;
5971
5972 r = pick_paths();
5973 if (r < 0)
5974 goto finish;
5975
5976 r = determine_names();
5977 if (r < 0)
5978 goto finish;
5979
5980 r = load_settings();
5981 if (r < 0)
5982 goto finish;
5983
5984 /* If we're not unsharing the network namespace and are unsharing the user namespace, we won't have
5985 * permissions to bind ports in the container, so let's drop the CAP_NET_BIND_SERVICE capability to
5986 * indicate that. */
5987 if (!arg_private_network && arg_userns_mode != USER_NAMESPACE_NO && arg_uid_shift > 0)
5988 arg_caps_retain &= ~(UINT64_C(1) << CAP_NET_BIND_SERVICE);
5989
5990 r = verify_arguments();
5991 if (r < 0)
5992 goto finish;
5993
5994 r = resolve_network_interface_names(arg_network_interfaces);
5995 if (r < 0)
5996 goto finish;
5997
5998 r = verify_network_interfaces_initialized();
5999 if (r < 0)
6000 goto finish;
6001
6002 /* Ignore SIGPIPE here, because we use splice() on the ptyfwd stuff and that will generate SIGPIPE if
6003 * the result is closed. Note that the container payload child will reset signal mask+handler anyway,
6004 * so just turning this off here means we only turn it off in nspawn itself, not any children. */
6005 (void) ignore_signals(SIGPIPE);
6006
6007 r = fdset_new_listen_fds(&fds, /* unset = */ false);
6008 if (r < 0) {
6009 log_error_errno(r, "Failed to collect file descriptors: %m");
6010 goto finish;
6011 }
6012
6013 /* The "default" umask. This is appropriate for most file and directory
6014 * operations performed by nspawn, and is the umask that will be used for
6015 * the child. Functions like copy_devnodes() change the umask temporarily. */
6016 umask(0022);
6017
6018 if (arg_console_mode < 0)
6019 arg_console_mode = isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO) ?
6020 CONSOLE_INTERACTIVE : CONSOLE_READ_ONLY;
6021
6022 if (arg_console_mode == CONSOLE_PIPE) /* if we pass STDERR on to the container, don't add our own logs into it too */
6023 arg_quiet = true;
6024
6025 polkit_agent_open();
6026
6027 if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
6028 /* Let's allocate a 64K userns first, if managed mode is chosen */
6029
6030 _cleanup_free_ char *userns_name = NULL;
6031 if (asprintf(&userns_name, "nspawn-" PID_FMT "-%s", getpid_cached(), arg_machine) < 0) {
6032 r = log_oom();
6033 goto finish;
6034 }
6035
6036 userns_fd = nsresource_allocate_userns(userns_name, UINT64_C(0x10000));
6037 if (userns_fd < 0) {
6038 r = log_error_errno(userns_fd, "Failed to allocate user namespace with 64K users: %m");
6039 goto finish;
6040 }
6041
6042 r = userns_get_base_uid(userns_fd, &arg_uid_shift, /* ret_gid= */ NULL);
6043 if (r < 0) {
6044 log_error_errno(r, "Failed to determine UID shift from userns: %m");
6045 goto finish;
6046 }
6047
6048 arg_uid_range = UINT32_C(0x10000);
6049 }
6050
6051 if (arg_directory) {
6052 assert(!arg_image);
6053
6054 /* Safety precaution: let's not allow running images from the live host OS image, as long as
6055 * /var from the host will propagate into container dynamically (because bad things happen if
6056 * two systems write to the same /var). Let's allow it for the special cases where /var is
6057 * either copied (i.e. --ephemeral) or replaced (i.e. --volatile=yes|state). */
6058 if (path_equal(arg_directory, "/") && !(arg_ephemeral || IN_SET(arg_volatile_mode, VOLATILE_YES, VOLATILE_STATE))) {
6059 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6060 "Spawning container on root directory is not supported. Consider using --ephemeral, --volatile=yes or --volatile=state.");
6061 goto finish;
6062 }
6063
6064 if (arg_ephemeral) {
6065 _cleanup_free_ char *np = NULL;
6066
6067 r = chase_and_update(&arg_directory, 0);
6068 if (r < 0)
6069 goto finish;
6070
6071 /* If the specified path is a mount point we generate the new snapshot immediately
6072 * inside it under a random name. However if the specified is not a mount point we
6073 * create the new snapshot in the parent directory, just next to it. */
6074 r = path_is_mount_point(arg_directory);
6075 if (r < 0) {
6076 log_error_errno(r, "Failed to determine whether directory %s is mount point: %m", arg_directory);
6077 goto finish;
6078 }
6079 if (r > 0)
6080 r = tempfn_random_child(arg_directory, "machine.", &np);
6081 else
6082 r = tempfn_random(arg_directory, "machine.", &np);
6083 if (r < 0) {
6084 log_error_errno(r, "Failed to generate name for directory snapshot: %m");
6085 goto finish;
6086 }
6087
6088 /* We take an exclusive lock on this image, since it's our private, ephemeral copy
6089 * only owned by us and no one else. */
6090 r = image_path_lock(
6091 np,
6092 LOCK_EX|LOCK_NB,
6093 arg_privileged ? &tree_global_lock : NULL,
6094 &tree_local_lock);
6095 if (r < 0) {
6096 log_error_errno(r, "Failed to lock %s: %m", np);
6097 goto finish;
6098 }
6099
6100 {
6101 BLOCK_SIGNALS(SIGINT);
6102 r = btrfs_subvol_snapshot_at(AT_FDCWD, arg_directory, AT_FDCWD, np,
6103 (arg_read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
6104 BTRFS_SNAPSHOT_FALLBACK_COPY |
6105 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
6106 BTRFS_SNAPSHOT_RECURSIVE |
6107 BTRFS_SNAPSHOT_QUOTA |
6108 BTRFS_SNAPSHOT_SIGINT);
6109 }
6110 if (r == -EINTR) {
6111 log_error_errno(r, "Interrupted while copying file system tree to %s, removed again.", np);
6112 goto finish;
6113 }
6114 if (r < 0) {
6115 log_error_errno(r, "Failed to create snapshot %s from %s: %m", np, arg_directory);
6116 goto finish;
6117 }
6118
6119 free_and_replace(arg_directory, np);
6120 remove_directory = true;
6121 } else {
6122 r = chase_and_update(&arg_directory, arg_template ? CHASE_NONEXISTENT : 0);
6123 if (r < 0)
6124 goto finish;
6125
6126 r = image_path_lock(
6127 arg_directory,
6128 (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB,
6129 arg_privileged ? &tree_global_lock : NULL,
6130 &tree_local_lock);
6131 if (r == -EBUSY) {
6132 log_error_errno(r, "Directory tree %s is currently busy.", arg_directory);
6133 goto finish;
6134 }
6135 if (r < 0) {
6136 log_error_errno(r, "Failed to lock %s: %m", arg_directory);
6137 goto finish;
6138 }
6139
6140 if (arg_template) {
6141 r = chase_and_update(&arg_template, 0);
6142 if (r < 0)
6143 goto finish;
6144
6145 {
6146 BLOCK_SIGNALS(SIGINT);
6147 r = btrfs_subvol_snapshot_at(AT_FDCWD, arg_template, AT_FDCWD, arg_directory,
6148 (arg_read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
6149 BTRFS_SNAPSHOT_FALLBACK_COPY |
6150 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
6151 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE |
6152 BTRFS_SNAPSHOT_RECURSIVE |
6153 BTRFS_SNAPSHOT_QUOTA |
6154 BTRFS_SNAPSHOT_SIGINT);
6155 }
6156 if (r == -EEXIST)
6157 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
6158 "Directory %s already exists, not populating from template %s.", arg_directory, arg_template);
6159 else if (r == -EINTR) {
6160 log_error_errno(r, "Interrupted while copying file system tree to %s, removed again.", arg_directory);
6161 goto finish;
6162 } else if (r < 0) {
6163 log_error_errno(r, "Couldn't create snapshot %s from %s: %m", arg_directory, arg_template);
6164 goto finish;
6165 } else
6166 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
6167 "Populated %s from template %s.", arg_directory, arg_template);
6168 }
6169 }
6170
6171 if (arg_start_mode == START_BOOT) {
6172 _cleanup_free_ char *b = NULL;
6173 const char *p;
6174 int check_os_release, is_os_tree;
6175
6176 if (arg_pivot_root_new) {
6177 b = path_join(arg_directory, arg_pivot_root_new);
6178 if (!b) {
6179 r = log_oom();
6180 goto finish;
6181 }
6182
6183 p = b;
6184 } else
6185 p = arg_directory;
6186
6187 check_os_release = getenv_bool("SYSTEMD_NSPAWN_CHECK_OS_RELEASE");
6188 if (check_os_release < 0 && check_os_release != -ENXIO) {
6189 r = log_error_errno(check_os_release, "Failed to parse $SYSTEMD_NSPAWN_CHECK_OS_RELEASE: %m");
6190 goto finish;
6191 }
6192
6193 is_os_tree = path_is_os_tree(p);
6194 if (is_os_tree == 0 && check_os_release == 0)
6195 log_debug("Directory %s is missing an os-release file, continuing anyway.", p);
6196 else if (is_os_tree <= 0) {
6197 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6198 "Directory %s doesn't look like an OS root directory (os-release file is missing). Refusing.", p);
6199 goto finish;
6200 }
6201 } else {
6202 _cleanup_free_ char *p = NULL;
6203
6204 if (arg_pivot_root_new)
6205 p = path_join(arg_directory, arg_pivot_root_new, "/usr/");
6206 else
6207 p = path_join(arg_directory, "/usr/");
6208 if (!p) {
6209 r = log_oom();
6210 goto finish;
6211 }
6212
6213 r = access_nofollow(p, F_OK);
6214 if (r == -ENOENT) {
6215 log_error_errno(r, "Directory %s doesn't look like it has an OS tree (/usr/ directory is missing). Refusing.", arg_directory);
6216 goto finish;
6217 } else if (r < 0) {
6218 log_error_errno(r, "Unable to determine if %s looks like it has an OS tree (i.e. whether /usr/ exists): %m", arg_directory);
6219 goto finish;
6220 }
6221 }
6222
6223 if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
6224 r = mountfsd_mount_directory(
6225 arg_directory,
6226 userns_fd,
6227 determine_dissect_image_flags(),
6228 &mount_fd);
6229 if (r < 0)
6230 goto finish;
6231 }
6232 } else {
6233 DissectImageFlags dissect_image_flags =
6234 determine_dissect_image_flags();
6235
6236 assert(arg_image);
6237 assert(!arg_template);
6238
6239 r = chase_and_update(&arg_image, 0);
6240 if (r < 0)
6241 goto finish;
6242
6243 if (arg_ephemeral) {
6244 _cleanup_free_ char *np = NULL;
6245
6246 r = tempfn_random(arg_image, "machine.", &np);
6247 if (r < 0) {
6248 log_error_errno(r, "Failed to generate name for image snapshot: %m");
6249 goto finish;
6250 }
6251
6252 /* Always take an exclusive lock on our own ephemeral copy. */
6253 r = image_path_lock(
6254 np,
6255 LOCK_EX|LOCK_NB,
6256 arg_privileged ? &tree_global_lock : NULL,
6257 &tree_local_lock);
6258 if (r < 0) {
6259 log_error_errno(r, "Failed to create image lock: %m");
6260 goto finish;
6261 }
6262
6263 {
6264 BLOCK_SIGNALS(SIGINT);
6265 r = copy_file(arg_image, np, O_EXCL, arg_read_only ? 0400 : 0600,
6266 COPY_REFLINK|COPY_CRTIME|COPY_SIGINT|COPY_NOCOW_AFTER);
6267 }
6268 if (r == -EINTR) {
6269 log_error_errno(r, "Interrupted while copying image file to %s, removed again.", np);
6270 goto finish;
6271 }
6272 if (r < 0) {
6273 r = log_error_errno(r, "Failed to copy image file: %m");
6274 goto finish;
6275 }
6276
6277 free_and_replace(arg_image, np);
6278 remove_image = true;
6279 } else {
6280 r = image_path_lock(
6281 arg_image,
6282 (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB,
6283 arg_privileged ? &tree_global_lock : NULL,
6284 &tree_local_lock);
6285 if (r == -EBUSY) {
6286 log_error_errno(r, "Disk image %s is currently busy.", arg_image);
6287 goto finish;
6288 }
6289 if (r < 0) {
6290 log_error_errno(r, "Failed to create image lock: %m");
6291 goto finish;
6292 }
6293
6294 r = verity_settings_load(
6295 &arg_verity_settings,
6296 arg_image, NULL, NULL);
6297 if (r < 0) {
6298 log_error_errno(r, "Failed to read verity artefacts for %s: %m", arg_image);
6299 goto finish;
6300 }
6301
6302 if (arg_verity_settings.data_path)
6303 dissect_image_flags |= DISSECT_IMAGE_NO_PARTITION_TABLE;
6304 }
6305
6306 if (arg_userns_mode != USER_NAMESPACE_MANAGED) {
6307 r = loop_device_make_by_path(
6308 arg_image,
6309 arg_read_only ? O_RDONLY : O_RDWR,
6310 /* sector_size= */ UINT32_MAX,
6311 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
6312 LOCK_SH,
6313 &loop);
6314 if (r < 0) {
6315 log_error_errno(r, "Failed to set up loopback block device: %m");
6316 goto finish;
6317 }
6318
6319 r = dissect_loop_device_and_warn(
6320 loop,
6321 &arg_verity_settings,
6322 /* mount_options= */ NULL,
6323 arg_image_policy ?: &image_policy_container,
6324 /* image_filter= */ NULL,
6325 dissect_image_flags,
6326 &dissected_image);
6327 if (r == -ENOPKG) {
6328 /* dissected_image_and_warn() already printed a brief error message. Extend on that with more details */
6329 log_notice("Note that the disk image needs to\n"
6330 " a) either contain only a single MBR partition of type 0x83 that is marked bootable\n"
6331 " b) or contain a single GPT partition of type 0FC63DAF-8483-4772-8E79-3D69D8477DE4\n"
6332 " c) or follow https://uapi-group.org/specifications/specs/discoverable_partitions_specification\n"
6333 " d) or contain a file system without a partition table\n"
6334 "in order to be bootable with systemd-nspawn.");
6335 goto finish;
6336 }
6337 if (r < 0)
6338 goto finish;
6339
6340 r = dissected_image_load_verity_sig_partition(
6341 dissected_image,
6342 loop->fd,
6343 &arg_verity_settings);
6344 if (r < 0) {
6345 log_error_errno(r, "Failed to load Verity signature partition: %m");
6346 goto finish;
6347 }
6348
6349 r = dissected_image_guess_verity_roothash(
6350 dissected_image,
6351 &arg_verity_settings);
6352 if (r < 0) {
6353 log_error_errno(r, "Failed to guess Verity root hash: %m");
6354 goto finish;
6355 }
6356
6357 if (dissected_image->has_verity && !arg_verity_settings.root_hash)
6358 log_notice("Note: image %s contains verity information, but no root hash specified and no embedded "
6359 "root hash signature found! Proceeding without integrity checking.", arg_image);
6360
6361 r = dissected_image_decrypt_interactively(
6362 dissected_image,
6363 NULL,
6364 &arg_verity_settings,
6365 dissect_image_flags);
6366 if (r < 0)
6367 goto finish;
6368 } else {
6369 r = mountfsd_mount_image(
6370 arg_image,
6371 userns_fd,
6372 arg_image_policy,
6373 dissect_image_flags,
6374 &dissected_image);
6375 if (r < 0)
6376 goto finish;
6377 }
6378
6379 /* Now that we mounted the image, let's try to remove it again, if it is ephemeral */
6380 if (remove_image && unlink(arg_image) >= 0)
6381 remove_image = false;
6382
6383 if (arg_architecture < 0)
6384 arg_architecture = dissected_image_architecture(dissected_image);
6385 }
6386
6387 /* Create a temporary place to mount stuff. */
6388 r = mkdtemp_malloc("/tmp/nspawn-root-XXXXXX", &rootdir);
6389 if (r < 0) {
6390 log_error_errno(r, "Failed to create temporary directory: %m");
6391 goto finish;
6392 }
6393
6394 r = custom_mount_prepare_all(rootdir, arg_custom_mounts, arg_n_custom_mounts);
6395 if (r < 0)
6396 goto finish;
6397
6398 if (!arg_quiet) {
6399 const char *t = arg_image ?: arg_directory;
6400 _cleanup_free_ char *u = NULL;
6401 (void) terminal_urlify_path(t, t, &u);
6402
6403 log_info("%s %sSpawning container %s on %s.%s",
6404 glyph(GLYPH_LIGHT_SHADE), ansi_grey(), arg_machine, u ?: t, ansi_normal());
6405
6406 if (arg_console_mode == CONSOLE_INTERACTIVE)
6407 log_info("%s %sPress %sCtrl-]%s three times within 1s to kill container; two times followed by %sr%s\n"
6408 "%s %sto reboot container; two times followed by %sp%s to poweroff container.%s",
6409 glyph(GLYPH_LIGHT_SHADE), ansi_grey(), ansi_highlight(), ansi_grey(), ansi_highlight(), ansi_normal(),
6410 glyph(GLYPH_LIGHT_SHADE), ansi_grey(), ansi_highlight(), ansi_grey(), ansi_normal());
6411 }
6412
6413 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, SIGWINCH, SIGTERM, SIGINT, SIGRTMIN+18) >= 0);
6414
6415 r = make_reaper_process(true);
6416 if (r < 0) {
6417 log_error_errno(r, "Failed to become subreaper: %m");
6418 goto finish;
6419 }
6420
6421 if (arg_expose_ports) {
6422 r = fw_ctx_new(&fw_ctx);
6423 if (r < 0) {
6424 log_error_errno(r, "Cannot expose configured ports, firewall initialization failed: %m");
6425 goto finish;
6426 }
6427 expose_args.fw_ctx = fw_ctx;
6428 }
6429
6430 for (;;) {
6431 r = run_container(
6432 rootdir,
6433 mount_fd,
6434 dissected_image,
6435 userns_fd,
6436 fds,
6437 veth_name, &veth_created,
6438 &expose_args, &master,
6439 &pid, &ret);
6440 if (r <= 0)
6441 break;
6442 }
6443
6444 finish:
6445 (void) sd_notify(false,
6446 r == 0 && ret == EXIT_FORCE_RESTART ? "STOPPING=1\nSTATUS=Restarting..." :
6447 "STOPPING=1\nSTATUS=Terminating...");
6448
6449 if (pidref_is_set(&pid))
6450 (void) pidref_kill(&pid, SIGKILL);
6451
6452 /* Try to flush whatever is still queued in the pty */
6453 if (master >= 0) {
6454 (void) copy_bytes(master, STDOUT_FILENO, UINT64_MAX, 0);
6455 master = safe_close(master);
6456 }
6457
6458 if (pidref_is_set(&pid)) {
6459 (void) pidref_wait_for_terminate(&pid, NULL);
6460 pidref_done(&pid);
6461 }
6462
6463 pager_close();
6464
6465 if (remove_directory && arg_directory) {
6466 int k;
6467
6468 k = rm_rf(arg_directory, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
6469 if (k < 0)
6470 log_warning_errno(k, "Cannot remove '%s', ignoring: %m", arg_directory);
6471 }
6472
6473 if (remove_image && arg_image) {
6474 if (unlink(arg_image) < 0)
6475 log_warning_errno(errno, "Can't remove image file '%s', ignoring: %m", arg_image);
6476 }
6477
6478 if (arg_machine && arg_userns_mode != USER_NAMESPACE_MANAGED) {
6479 const char *p;
6480
6481 p = strjoina("/run/systemd/nspawn/propagate/", arg_machine);
6482 (void) rm_rf(p, REMOVE_ROOT);
6483
6484 p = strjoina("/run/systemd/nspawn/unix-export/", arg_machine);
6485 (void) umount2(p, MNT_DETACH|UMOUNT_NOFOLLOW);
6486 (void) rmdir(p);
6487 }
6488
6489 cleanup_propagation_and_export_directories();
6490
6491 expose_port_flush(&fw_ctx, arg_expose_ports, AF_INET, &expose_args.address4);
6492 expose_port_flush(&fw_ctx, arg_expose_ports, AF_INET6, &expose_args.address6);
6493
6494 if (arg_userns_mode != USER_NAMESPACE_MANAGED) {
6495 if (veth_created)
6496 (void) remove_veth_links(veth_name, arg_network_veth_extra);
6497 (void) remove_bridge(arg_network_zone);
6498 }
6499
6500 custom_mount_free_all(arg_custom_mounts, arg_n_custom_mounts);
6501 expose_port_free_all(arg_expose_ports);
6502 rlimit_free_all(arg_rlimit);
6503 device_node_array_free(arg_extra_nodes, arg_n_extra_nodes);
6504
6505 if (r < 0)
6506 return r;
6507
6508 return ret;
6509 }
6510
6511 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);