1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/loop.h>
10 #include <sys/personality.h>
11 #include <sys/prctl.h>
14 #include "constants.h"
17 #include <selinux/selinux.h>
21 #include "sd-daemon.h"
24 #include "sd-netlink.h"
26 #include "alloc-util.h"
28 #include "base-filesystem.h"
29 #include "btrfs-util.h"
31 #include "bus-error.h"
32 #include "bus-locator.h"
35 #include "capability-util.h"
36 #include "cgroup-setup.h"
37 #include "cgroup-util.h"
39 #include "common-signal.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"
48 #include "ether-addr-util.h"
49 #include "extract-word.h"
53 #include "format-util.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"
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"
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"
88 #include "nsresource.h"
90 #include "osc-context.h"
92 #include "parse-argument.h"
93 #include "parse-util.h"
94 #include "path-util.h"
96 #include "polkit-agent.h"
97 #include "pretty-print.h"
98 #include "process-util.h"
100 #include "random-util.h"
101 #include "raw-clone.h"
102 #include "resolve-util.h"
103 #include "rlimit-util.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"
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"
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"
130 #define EXIT_FORCE_RESTART 133
132 typedef enum ContainerStatus
{
133 CONTAINER_TERMINATED
,
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
) |
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
;
227 static scmp_filter_ctx arg_seccomp
= NULL
;
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;
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
);
281 STATIC_DESTRUCTOR_REGISTER(arg_seccomp
, seccomp_releasep
);
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
);
292 static int handle_arg_console(const char *arg
) {
293 if (streq(arg
, "help")) {
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.");
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
;
320 arg_console_mode
= CONSOLE_PIPE
;
322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown console mode: %s", optarg
);
324 arg_settings_mask
|= SETTING_CONSOLE_MODE
;
328 static int help(void) {
329 _cleanup_free_
char *link
= NULL
;
332 pager_open(arg_pager_flags
);
334 r
= terminal_urlify_man("systemd-nspawn", "1", &link
);
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"
349 " -D --directory=PATH Root directory for the container\n"
350 " --template=PATH Initialize root directory from template directory,\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"
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"
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"
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"
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"
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"
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"
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"
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
,
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.");
505 static int parse_capability_spec(const char *spec
, uint64_t *ret_mask
) {
510 _cleanup_free_
char *t
= NULL
;
512 r
= extract_first_word(&spec
, &t
, ",", 0);
514 return log_error_errno(r
, "Failed to parse capability %s.", t
);
518 if (streq(t
, "help")) {
519 for (int i
= 0; i
< capability_list_length(); i
++) {
522 name
= capability_to_name(i
);
533 r
= capability_from_name(t
);
535 return log_error_errno(r
, "Failed to parse capability %s.", t
);
542 return 1; /* continue */
545 static int parse_share_ns_env(const char *name
, unsigned long ns_flag
) {
548 r
= getenv_bool(name
);
552 return log_error_errno(r
, "Failed to parse $%s: %m", name
);
554 arg_clone_ns_flags
= (arg_clone_ns_flags
& ~ns_flag
) | (r
> 0 ? 0 : ns_flag
);
555 arg_settings_mask
|= SETTING_CLONE_NS_FLAGS
;
559 static int parse_mount_settings_env(void) {
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");
567 SET_FLAG(arg_mount_settings
, MOUNT_APPLY_TMPFS_TMP
, r
> 0);
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
;
573 r
= parse_boolean(e
);
575 return log_error_errno(r
, "Failed to parse $SYSTEMD_NSPAWN_API_VFS_WRITABLE: %m");
577 SET_FLAG(arg_mount_settings
, MOUNT_APPLY_APIVFS_RO
, r
== 0);
578 SET_FLAG(arg_mount_settings
, MOUNT_APPLY_APIVFS_NETNS
, false);
584 static int parse_environment(void) {
588 r
= parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_IPC", CLONE_NEWIPC
);
591 r
= parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_PID", CLONE_NEWPID
);
594 r
= parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_UTS", CLONE_NEWUTS
);
597 r
= parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_SYSTEM", CLONE_NEWIPC
|CLONE_NEWPID
|CLONE_NEWUTS
);
601 r
= parse_mount_settings_env();
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;
610 r
= getenv_bool("SYSTEMD_NSPAWN_USE_CGNS");
613 return log_error_errno(r
, "Failed to parse $SYSTEMD_NSPAWN_USE_CGNS: %m");
617 arg_use_cgns
= r
> 0;
618 arg_settings_mask
|= SETTING_USE_CGNS
;
622 e
= getenv("SYSTEMD_NSPAWN_CONTAINER_SERVICE");
624 arg_container_service_name
= e
;
626 e
= getenv("SYSTEMD_NSPAWN_NETWORK_MAC");
628 r
= parse_ether_addr(e
, &arg_network_provided_mac
);
630 return log_error_errno(r
, "Failed to parse provided MAC address via environment variable");
633 r
= getenv_bool("SYSTEMD_SUPPRESS_SYNC");
635 arg_suppress_sync
= r
;
636 else if (r
!= -ENXIO
)
637 log_debug_errno(r
, "Failed to parse $SYSTEMD_SUPPRESS_SYNC, ignoring: %m");
642 static int parse_argv(int argc
, char *argv
[]) {
649 ARG_AMBIENT_CAPABILITY
,
661 ARG_NETWORK_INTERFACE
,
666 ARG_NETWORK_VETH_EXTRA
,
667 ARG_NETWORK_NAMESPACE_PATH
,
677 ARG_PRIVATE_USERS_CHOWN
,
678 ARG_PRIVATE_USERS_OWNERSHIP
,
683 ARG_SYSTEM_CALL_FILTER
,
686 ARG_NO_NEW_PRIVILEGES
,
687 ARG_OOM_SCORE_ADJUST
,
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
},
786 uint64_t plus
= 0, minus
= 0;
787 bool mask_all_settings
= false, mask_no_settings
= false;
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). */
795 while ((c
= getopt_long(argc
, argv
, "+hD:u:abL:M:jS:Z:qi:xp:nUE:P", options
, NULL
)) >= 0)
805 r
= parse_path_argument(optarg
, false, &arg_directory
);
809 arg_settings_mask
|= SETTING_DIRECTORY
;
813 r
= parse_path_argument(optarg
, false, &arg_template
);
817 arg_settings_mask
|= SETTING_DIRECTORY
;
821 r
= parse_path_argument(optarg
, false, &arg_image
);
825 arg_settings_mask
|= SETTING_DIRECTORY
;
829 r
= parse_path_argument(optarg
, false, &arg_oci_bundle
);
836 arg_ephemeral
= true;
837 arg_settings_mask
|= SETTING_EPHEMERAL
;
841 r
= free_and_strdup(&arg_user
, optarg
);
845 arg_settings_mask
|= SETTING_USER
;
848 case ARG_NETWORK_ZONE
: {
849 _cleanup_free_
char *j
= NULL
;
851 j
= strjoin("vz-", optarg
);
855 if (!ifname_valid(j
))
856 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
857 "Network zone name not valid: %s", j
);
859 free_and_replace(arg_network_zone
, j
);
861 arg_network_veth
= true;
862 arg_private_network
= true;
863 arg_settings_mask
|= SETTING_NETWORK
;
867 case ARG_NETWORK_BRIDGE
:
869 if (!ifname_valid(optarg
))
870 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
871 "Bridge interface name not valid: %s", optarg
);
873 r
= free_and_strdup(&arg_network_bridge
, optarg
);
879 arg_network_veth
= true;
880 arg_private_network
= true;
881 arg_settings_mask
|= SETTING_NETWORK
;
884 case ARG_NETWORK_VETH_EXTRA
:
885 r
= veth_extra_parse(&arg_network_veth_extra
, optarg
);
887 return log_error_errno(r
, "Failed to parse --network-veth-extra= parameter: %s", optarg
);
889 arg_private_network
= true;
890 arg_settings_mask
|= SETTING_NETWORK
;
893 case ARG_NETWORK_INTERFACE
:
894 r
= interface_pair_parse(&arg_network_interfaces
, optarg
);
898 arg_private_network
= true;
899 arg_settings_mask
|= SETTING_NETWORK
;
902 case ARG_NETWORK_MACVLAN
:
903 r
= macvlan_pair_parse(&arg_network_macvlan
, optarg
);
907 arg_private_network
= true;
908 arg_settings_mask
|= SETTING_NETWORK
;
911 case ARG_NETWORK_IPVLAN
:
912 r
= ipvlan_pair_parse(&arg_network_ipvlan
, optarg
);
917 case ARG_PRIVATE_NETWORK
:
918 arg_private_network
= true;
919 arg_settings_mask
|= SETTING_NETWORK
;
922 case ARG_NETWORK_NAMESPACE_PATH
:
923 r
= parse_path_argument(optarg
, false, &arg_network_namespace_path
);
927 arg_settings_mask
|= SETTING_NETWORK
;
931 if (arg_start_mode
== START_PID2
)
932 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
933 "--boot and --as-pid2 may not be combined.");
935 arg_start_mode
= START_BOOT
;
936 arg_settings_mask
|= SETTING_START_MODE
;
940 if (arg_start_mode
== START_BOOT
)
941 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
942 "--boot and --as-pid2 may not be combined.");
944 arg_start_mode
= START_PID2
;
945 arg_settings_mask
|= SETTING_START_MODE
;
949 r
= id128_from_string_nonzero(optarg
, &arg_uuid
);
951 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
952 "Machine UUID may not be all zeroes.");
954 return log_error_errno(r
, "Invalid UUID: %s", optarg
);
956 arg_settings_mask
|= SETTING_MACHINE_ID
;
960 _cleanup_free_
char *mangled
= NULL
;
962 r
= unit_name_mangle_with_suffix(optarg
, NULL
, UNIT_NAME_MANGLE_WARN
, ".slice", &mangled
);
966 free_and_replace(arg_slice
, mangled
);
967 arg_settings_mask
|= SETTING_SLICE
;
973 arg_machine
= mfree(arg_machine
);
975 if (!hostname_is_valid(optarg
, 0))
976 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
977 "Invalid machine name: %s", optarg
);
979 r
= free_and_strdup(&arg_machine
, optarg
);
987 arg_hostname
= mfree(arg_hostname
);
989 if (!hostname_is_valid(optarg
, 0))
990 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
991 "Invalid hostname: %s", optarg
);
993 r
= free_and_strdup(&arg_hostname
, optarg
);
998 arg_settings_mask
|= SETTING_HOSTNAME
;
1002 arg_selinux_context
= optarg
;
1006 arg_selinux_apifs_context
= optarg
;
1010 arg_read_only
= true;
1011 arg_settings_mask
|= SETTING_READ_ONLY
;
1014 case ARG_AMBIENT_CAPABILITY
: {
1016 r
= parse_capability_spec(optarg
, &m
);
1019 arg_caps_ambient
|= m
;
1020 arg_settings_mask
|= SETTING_CAPABILITY
;
1023 case ARG_CAPABILITY
:
1024 case ARG_DROP_CAPABILITY
: {
1026 r
= parse_capability_spec(optarg
, &m
);
1030 if (c
== ARG_CAPABILITY
)
1034 arg_settings_mask
|= SETTING_CAPABILITY
;
1037 case ARG_NO_NEW_PRIVILEGES
:
1038 r
= parse_boolean_argument("--no-new-privileges=", optarg
, &arg_no_new_privileges
);
1042 arg_settings_mask
|= SETTING_NO_NEW_PRIVILEGES
;
1046 arg_link_journal
= LINK_GUEST
;
1047 arg_link_journal_try
= true;
1048 arg_settings_mask
|= SETTING_LINK_JOURNAL
;
1051 case ARG_LINK_JOURNAL
:
1052 r
= parse_link_journal(optarg
, &arg_link_journal
, &arg_link_journal_try
);
1054 return log_error_errno(r
, "Failed to parse link journal mode %s", optarg
);
1056 arg_settings_mask
|= SETTING_LINK_JOURNAL
;
1061 r
= bind_mount_parse(&arg_custom_mounts
, &arg_n_custom_mounts
, optarg
, c
== ARG_BIND_RO
);
1063 return log_error_errno(r
, "Failed to parse --bind(-ro)= argument %s: %m", optarg
);
1065 arg_settings_mask
|= SETTING_CUSTOM_MOUNTS
;
1069 r
= tmpfs_mount_parse(&arg_custom_mounts
, &arg_n_custom_mounts
, optarg
);
1071 return log_error_errno(r
, "Failed to parse --tmpfs= argument %s: %m", optarg
);
1073 arg_settings_mask
|= SETTING_CUSTOM_MOUNTS
;
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.");
1082 return log_error_errno(r
, "Failed to parse --overlay(-ro)= argument %s: %m", optarg
);
1084 arg_settings_mask
|= SETTING_CUSTOM_MOUNTS
;
1087 case ARG_INACCESSIBLE
:
1088 r
= inaccessible_mount_parse(&arg_custom_mounts
, &arg_n_custom_mounts
, optarg
);
1090 return log_error_errno(r
, "Failed to parse --inaccessible= argument %s: %m", optarg
);
1092 arg_settings_mask
|= SETTING_CUSTOM_MOUNTS
;
1096 r
= strv_env_replace_strdup_passthrough(&arg_setenv
, optarg
);
1098 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
1100 arg_settings_mask
|= SETTING_ENVIRONMENT
;
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;
1115 r
= parse_boolean_argument("--register=", optarg
, &arg_register
);
1122 arg_keep_unit
= true;
1125 case ARG_PERSONALITY
:
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
);
1132 arg_settings_mask
|= SETTING_PERSONALITY
;
1138 arg_volatile_mode
= VOLATILE_YES
;
1139 else if (streq(optarg
, "help")) {
1140 DUMP_STRING_TABLE(volatile_mode
, VolatileMode
, _VOLATILE_MODE_MAX
);
1145 m
= volatile_mode_from_string(optarg
);
1147 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1148 "Failed to parse --volatile= argument: %s", optarg
);
1150 arg_volatile_mode
= m
;
1153 arg_settings_mask
|= SETTING_VOLATILE_MODE
;
1157 r
= expose_port_parse(&arg_expose_ports
, optarg
);
1159 return log_error_errno(r
, "Duplicate port specification: %s", optarg
);
1161 return log_error_errno(r
, "Failed to parse host port %s: %m", optarg
);
1163 arg_settings_mask
|= SETTING_EXPOSE_PORTS
;
1167 if (strv_extend(&arg_property
, optarg
) < 0)
1172 case ARG_PRIVATE_USERS
: {
1177 else if (!in_charset(optarg
, DIGITS
))
1178 /* do *not* parse numbers as booleans */
1179 boolean
= parse_boolean(optarg
);
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
1198 arg_uid_shift
= UID_INVALID
;
1199 arg_uid_range
= UINT32_C(0x10000);
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
;
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);
1214 /* anything else: User namespacing on, UID range is explicitly configured */
1215 r
= parse_userns_uid_range(optarg
, &arg_uid_shift
, &arg_uid_range
);
1218 arg_userns_mode
= USER_NAMESPACE_FIXED
;
1221 arg_settings_mask
|= SETTING_USERNS
;
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);
1232 arg_settings_mask
|= SETTING_USERNS
;
1237 case ARG_PRIVATE_USERS_CHOWN
:
1238 arg_userns_ownership
= USER_NAMESPACE_OWNERSHIP_CHOWN
;
1240 arg_settings_mask
|= SETTING_USERNS
;
1243 case ARG_PRIVATE_USERS_OWNERSHIP
:
1244 if (streq(optarg
, "help")) {
1245 DUMP_STRING_TABLE(user_namespace_ownership
, UserNamespaceOwnership
, _USER_NAMESPACE_OWNERSHIP_MAX
);
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
);
1253 arg_settings_mask
|= SETTING_USERNS
;
1256 case ARG_KILL_SIGNAL
:
1257 if (streq(optarg
, "help")) {
1258 DUMP_STRING_TABLE(signal
, int, _NSIG
);
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
);
1266 arg_settings_mask
|= SETTING_KILL_SIGNAL
;
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
1277 r
= parse_boolean(optarg
);
1279 if (streq(optarg
, "trusted")) {
1280 mask_all_settings
= false;
1281 mask_no_settings
= false;
1282 arg_settings_trusted
= true;
1284 } else if (streq(optarg
, "override")) {
1285 mask_all_settings
= false;
1286 mask_no_settings
= true;
1287 arg_settings_trusted
= -1;
1289 return log_error_errno(r
, "Failed to parse --settings= argument: %s", optarg
);
1292 mask_all_settings
= false;
1293 mask_no_settings
= false;
1294 arg_settings_trusted
= -1;
1297 mask_all_settings
= true;
1298 mask_no_settings
= false;
1299 arg_settings_trusted
= false;
1305 _cleanup_free_
char *wd
= NULL
;
1307 if (!path_is_absolute(optarg
))
1308 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1309 "Working directory %s is not an absolute path.", optarg
);
1311 r
= path_simplify_alloc(optarg
, &wd
);
1313 return log_error_errno(r
, "Failed to simplify path %s: %m", optarg
);
1315 if (!path_is_normalized(wd
))
1316 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Working directory path is not normalized: %s", wd
);
1318 if (path_below_api_vfs(wd
))
1319 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Working directory is below API VFS, refusing: %s", wd
);
1321 free_and_replace(arg_chdir
, wd
);
1322 arg_settings_mask
|= SETTING_WORKING_DIRECTORY
;
1326 case ARG_PIVOT_ROOT
:
1327 r
= pivot_root_parse(&arg_pivot_root_new
, &arg_pivot_root_old
, optarg
);
1329 return log_error_errno(r
, "Failed to parse --pivot-root= argument %s: %m", optarg
);
1331 arg_settings_mask
|= SETTING_PIVOT_ROOT
;
1334 case ARG_NOTIFY_READY
:
1335 r
= parse_boolean(optarg
);
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
;
1343 case ARG_ROOT_HASH
: {
1344 _cleanup_free_
void *k
= NULL
;
1347 r
= unhexmem(optarg
, &k
, &l
);
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
);
1353 free_and_replace(arg_verity_settings
.root_hash
, k
);
1354 arg_verity_settings
.root_hash_size
= l
;
1358 case ARG_ROOT_HASH_SIG
: {
1363 if ((value
= startswith(optarg
, "base64:"))) {
1364 r
= unbase64mem(value
, &p
, &l
);
1366 return log_error_errno(r
, "Failed to parse root hash signature '%s': %m", optarg
);
1369 r
= read_full_file(optarg
, (char**) &p
, &l
);
1371 return log_error_errno(r
, "Failed parse root hash signature file '%s': %m", optarg
);
1374 free_and_replace(arg_verity_settings
.root_hash_sig
, p
);
1375 arg_verity_settings
.root_hash_sig_size
= l
;
1379 case ARG_VERITY_DATA
:
1380 r
= parse_path_argument(optarg
, false, &arg_verity_settings
.data_path
);
1385 case ARG_SYSTEM_CALL_FILTER
: {
1389 negative
= optarg
[0] == '~';
1390 items
= negative
? optarg
+ 1 : optarg
;
1393 _cleanup_free_
char *word
= NULL
;
1395 r
= extract_first_word(&items
, &word
, NULL
, 0);
1401 return log_error_errno(r
, "Failed to parse system call filter: %m");
1404 r
= strv_extend(&arg_syscall_deny_list
, word
);
1406 r
= strv_extend(&arg_syscall_allow_list
, word
);
1411 arg_settings_mask
|= SETTING_SYSCALL_FILTER
;
1417 _cleanup_free_
char *name
= NULL
;
1420 if (streq(optarg
, "help")) {
1421 DUMP_STRING_TABLE(rlimit
, int, _RLIMIT_MAX
);
1425 eq
= strchr(optarg
, '=');
1427 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1428 "--rlimit= expects an '=' assignment.");
1430 name
= strndup(optarg
, eq
- optarg
);
1434 rl
= rlimit_from_string_harder(name
);
1436 return log_error_errno(rl
, "Unknown resource limit: %s", name
);
1438 if (!arg_rlimit
[rl
]) {
1439 arg_rlimit
[rl
] = new0(struct rlimit
, 1);
1440 if (!arg_rlimit
[rl
])
1444 r
= rlimit_parse(rl
, eq
+ 1, arg_rlimit
[rl
]);
1446 return log_error_errno(r
, "Failed to parse resource limit: %s", eq
+ 1);
1448 arg_settings_mask
|= SETTING_RLIMIT_FIRST
<< rl
;
1452 case ARG_OOM_SCORE_ADJUST
:
1453 r
= parse_oom_score_adjust(optarg
, &arg_oom_score_adjust
);
1455 return log_error_errno(r
, "Failed to parse --oom-score-adjust= parameter: %s", optarg
);
1457 arg_oom_score_adjust_set
= true;
1458 arg_settings_mask
|= SETTING_OOM_SCORE_ADJUST
;
1461 case ARG_CPU_AFFINITY
: {
1464 r
= parse_cpu_set(optarg
, &cpuset
);
1466 return log_error_errno(r
, "Failed to parse CPU affinity mask %s: %m", optarg
);
1468 cpu_set_done_and_replace(arg_cpu_set
, cpuset
);
1469 arg_settings_mask
|= SETTING_CPU_AFFINITY
;
1473 case ARG_RESOLV_CONF
:
1474 if (streq(optarg
, "help")) {
1475 DUMP_STRING_TABLE(resolv_conf_mode
, ResolvConfMode
, _RESOLV_CONF_MODE_MAX
);
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
);
1484 arg_settings_mask
|= SETTING_RESOLV_CONF
;
1488 if (streq(optarg
, "help")) {
1489 DUMP_STRING_TABLE(timezone_mode
, TimezoneMode
, _TIMEZONE_MODE_MAX
);
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
);
1498 arg_settings_mask
|= SETTING_TIMEZONE
;
1502 r
= handle_arg_console(optarg
);
1509 r
= handle_arg_console("pipe");
1515 arg_pager_flags
|= PAGER_DISABLE
;
1518 case ARG_SET_CREDENTIAL
:
1519 r
= machine_credential_set(&arg_credentials
, optarg
);
1523 arg_settings_mask
|= SETTING_CREDENTIALS
;
1526 case ARG_LOAD_CREDENTIAL
:
1527 r
= machine_credential_load(&arg_credentials
, optarg
);
1531 arg_settings_mask
|= SETTING_CREDENTIALS
;
1535 if (!valid_user_group_name(optarg
, 0))
1536 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid user name to bind: %s", optarg
);
1538 if (strv_extend(&arg_bind_user
, optarg
) < 0)
1541 arg_settings_mask
|= SETTING_BIND_USER
;
1544 case ARG_BIND_USER_SHELL
: {
1547 r
= parse_bind_user_shell(optarg
, &sh
, ©
);
1551 return log_error_errno(r
, "Invalid user shell to bind: %s", optarg
);
1553 free_and_replace(arg_bind_user_shell
, sh
);
1554 arg_bind_user_shell_copy
= copy
;
1556 arg_settings_mask
|= SETTING_BIND_USER_SHELL
;
1560 case ARG_SUPPRESS_SYNC
:
1561 r
= parse_boolean_argument("--suppress-sync=", optarg
, &arg_suppress_sync
);
1565 arg_settings_mask
|= SETTING_SUPPRESS_SYNC
;
1568 case ARG_IMAGE_POLICY
:
1569 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
1574 case ARG_BACKGROUND
:
1575 r
= free_and_strdup_warn(&arg_background
, optarg
);
1584 case ARG_NO_ASK_PASSWORD
:
1585 arg_ask_password
= false;
1592 assert_not_reached();
1595 if (argc
> optind
) {
1596 strv_free(arg_parameters
);
1597 arg_parameters
= strv_copy(argv
+ optind
);
1598 if (!arg_parameters
)
1601 arg_settings_mask
|= SETTING_START_MODE
;
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
1609 arg_directory
= TAKE_PTR(arg_template
);
1611 arg_caps_retain
|= plus
;
1612 arg_caps_retain
|= arg_private_network
? UINT64_C(1) << CAP_NET_ADMIN
: 0;
1613 arg_caps_retain
&= ~minus
;
1615 /* Make sure to parse environment before we reset the settings mask below */
1616 r
= parse_environment();
1620 /* Load all settings from .nspawn files */
1621 if (mask_no_settings
)
1622 arg_settings_mask
= 0;
1624 /* Don't load any settings from .nspawn files */
1625 if (mask_all_settings
)
1626 arg_settings_mask
= _SETTINGS_MASK_ALL
;
1631 static int verify_arguments(void) {
1634 SET_FLAG(arg_mount_settings
, MOUNT_UNMANAGED
, arg_userns_mode
!= USER_NAMESPACE_MANAGED
);
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
);
1641 SET_FLAG(arg_mount_settings
, MOUNT_USE_USERNS
, arg_userns_mode
!= USER_NAMESPACE_NO
);
1643 if (arg_private_network
)
1644 SET_FLAG(arg_mount_settings
, MOUNT_APPLY_APIVFS_NETNS
, arg_private_network
);
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.");
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.");
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.");
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
;
1663 if (arg_start_mode
== START_BOOT
&& arg_kill_signal
<= 0)
1664 arg_kill_signal
= SIGRTMIN
+3;
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;
1669 if (has_custom_root_mount(arg_custom_mounts
, arg_n_custom_mounts
))
1670 arg_read_only
= true;
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.");
1677 if (arg_directory
&& arg_image
)
1678 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--directory= and --image= may not be combined.");
1680 if (arg_template
&& arg_image
)
1681 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--template= and --image= may not be combined.");
1683 if (arg_template
&& !(arg_directory
|| arg_machine
))
1684 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--template= needs --directory= or --machine=.");
1686 if (arg_ephemeral
&& arg_template
)
1687 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--ephemeral and --template= may not be combined.");
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.");
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.");
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.");
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.");
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
||
1714 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "--network-namespace-path= cannot be combined with other network options.");
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.");
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.");
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.");
1726 if (arg_expose_ports
&& !arg_private_network
)
1727 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot use --port= without private networking.");
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.");
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.");
1736 if (arg_start_mode
== START_BOOT
)
1737 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "AmbientCapability= setting is not useful for boot mode.");
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");
1743 /* Drop duplicate --bind-user= entries */
1744 strv_uniq(arg_bind_user
);
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=");
1749 r
= custom_mount_check_all();
1756 static int verify_network_interfaces_initialized(void) {
1758 r
= test_network_interfaces_initialized(arg_network_interfaces
);
1762 r
= test_network_interfaces_initialized(arg_network_macvlan
);
1766 r
= test_network_interfaces_initialized(arg_network_ipvlan
);
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
);
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
);
1784 if (!in_child_chown())
1787 if (uid
== UID_INVALID
&& gid
== GID_INVALID
)
1790 if (uid
!= UID_INVALID
) {
1791 uid
+= arg_uid_shift
;
1793 if (uid
< arg_uid_shift
|| uid
>= arg_uid_shift
+ arg_uid_range
)
1797 if (gid
!= GID_INVALID
) {
1798 gid
+= (gid_t
) arg_uid_shift
;
1800 if (gid
< (gid_t
) arg_uid_shift
|| gid
>= (gid_t
) (arg_uid_shift
+ arg_uid_range
))
1804 return RET_NERRNO(fchownat(fd
, strempty(fname
), uid
, gid
, flags
));
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
);
1811 int userns_mkdir(const char *root
, const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
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
);
1822 _cleanup_close_
int dir_fd
= open_mkdir_at(parent_fd
, dname
, O_EXCL
|O_CLOEXEC
, mode
);
1823 if (dir_fd
== -EEXIST
)
1828 return userns_chown_at(dir_fd
, /* fname= */ NULL
, uid
, gid
, AT_SYMLINK_NOFOLLOW
|AT_EMPTY_PATH
);
1831 static const char *timezone_from_path(const char *path
) {
1832 return PATH_STARTSWITH_SET(
1834 "../usr/share/zoneinfo/",
1835 "/usr/share/zoneinfo/");
1838 static bool etc_writable(void) {
1839 return !arg_read_only
|| IN_SET(arg_volatile_mode
, VOLATILE_YES
, VOLATILE_OVERLAY
);
1842 static int setup_timezone(const char *dest
) {
1843 _cleanup_free_
char *p
= NULL
, *etc
= NULL
;
1844 const char *where
, *check
;
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
;
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
1862 * ln -s /usr/share/zoneinfo/UTC /etc/localtime
1865 } else if (arg_timezone
== TIMEZONE_AUTO
)
1866 m
= etc_writable() ? TIMEZONE_SYMLINK
: TIMEZONE_BIND
;
1872 if (m
== TIMEZONE_OFF
)
1875 r
= chase("/etc", dest
, CHASE_PREFIX_ROOT
, &etc
, NULL
);
1877 log_warning_errno(r
, "Failed to resolve /etc path in container, ignoring: %m");
1881 where
= strjoina(etc
, "/localtime");
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
);
1891 case TIMEZONE_SYMLINK
: {
1892 _cleanup_free_
char *q
= NULL
;
1893 const char *z
, *what
;
1895 z
= timezone_from_path(p
);
1897 log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
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 .. */
1905 check
= strjoina(dest
, "/usr/share/zoneinfo/", z
);
1906 r
= chase(check
, dest
, 0, NULL
, NULL
);
1908 log_debug_errno(r
, "Timezone %s does not exist (or is not accessible) in container, not creating symlink: %m", z
);
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
);
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");
1929 case TIMEZONE_BIND
: {
1930 _cleanup_free_
char *resolved
= NULL
;
1933 found
= chase(where
, dest
, CHASE_NONEXISTENT
, &resolved
, NULL
);
1935 log_warning_errno(found
, "Failed to resolve /etc/localtime path in container, ignoring: %m");
1939 if (found
== 0) /* missing? */
1940 (void) touch(resolved
);
1942 r
= mount_nofollow_verbose(LOG_WARNING
, "/etc/localtime", resolved
, NULL
, MS_BIND
, NULL
);
1944 return mount_nofollow_verbose(LOG_ERR
, NULL
, resolved
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
|MS_NOSUID
|MS_NODEV
, NULL
);
1950 /* If mounting failed, try to copy */
1951 r
= copy_file_atomic("/etc/localtime", where
, 0644, COPY_REFLINK
|COPY_REPLACE
);
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
);
1961 assert_not_reached();
1964 /* Fix permissions of the symlink or file copy we just created */
1965 r
= userns_lchown(where
, 0, 0);
1967 log_warning_errno(r
, "Failed to chown /etc/localtime, ignoring: %m");
1972 static int have_resolv_conf(const char *path
) {
1975 if (access(path
, F_OK
) < 0) {
1976 if (errno
== ENOENT
)
1979 return log_debug_errno(errno
, "Failed to determine whether '%s' is available: %m", path
);
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
;
1991 /* Check if resolved is listening */
1993 r
= sd_bus_open_system(&bus
);
1995 return log_debug_errno(r
, "Failed to open system bus: %m");
1997 r
= bus_name_has_owner(bus
, "org.freedesktop.resolve1", NULL
);
1999 return log_debug_errno(r
, "Failed to check whether the 'org.freedesktop.resolve1' bus name is taken: %m");
2003 r
= bus_get_property_string(bus
, bus_resolve_mgr
, "DNSStubListener", &error
, &dns_stub_listener_mode
);
2005 return log_debug_errno(r
, "Failed to query DNSStubListener property: %s", bus_error_message(&error
, r
));
2007 return STR_IN_SET(dns_stub_listener_mode
, "udp", "yes");
2010 static int setup_resolv_conf(const char *dest
) {
2011 _cleanup_free_
char *etc
= NULL
;
2012 const char *where
, *what
;
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
;
2026 m
= etc_writable() ? RESOLV_CONF_DELETE
: RESOLV_CONF_OFF
;
2029 m
= arg_resolv_conf
;
2031 if (m
== RESOLV_CONF_OFF
)
2034 r
= chase("/etc", dest
, CHASE_PREFIX_ROOT
, &etc
, NULL
);
2036 log_warning_errno(r
, "Failed to resolve /etc path in container, ignoring: %m");
2040 where
= strjoina(etc
, "/resolv.conf");
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
);
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
;
2056 what
= "/etc/resolv.conf";
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
;
2062 found
= chase(where
, dest
, CHASE_NONEXISTENT
|CHASE_NOFOLLOW
, &resolved
, NULL
);
2064 log_warning_errno(found
, "Failed to resolve /etc/resolv.conf path in container, ignoring: %m");
2068 if (found
== 0) /* missing? */
2069 (void) touch(resolved
);
2071 r
= mount_nofollow_verbose(LOG_WARNING
, what
, resolved
, NULL
, MS_BIND
, NULL
);
2073 return mount_nofollow_verbose(LOG_ERR
, NULL
, resolved
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
|MS_NOSUID
|MS_NODEV
, NULL
);
2075 /* If that didn't work, let's copy the file */
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
);
2081 r
= copy_file(what
, where
, O_TRUNC
|O_NOFOLLOW
, 0644, COPY_REFLINK
);
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.
2086 * If the disk image is read-only, there's also no point in complaining.
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
);
2094 r
= userns_lchown(where
, 0, 0);
2096 log_warning_errno(r
, "Failed to chown /etc/resolv.conf, ignoring: %m");
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
;
2108 /* Generate a new randomized boot ID, so that each boot-up of the container gets a new one */
2110 r
= tempfn_random_child("/run", "proc-sys-kernel-random-boot-id", &path
);
2112 return log_error_errno(r
, "Failed to generate random boot ID path: %m");
2114 r
= sd_id128_randomize(&rnd
);
2116 return log_error_errno(r
, "Failed to generate random boot id: %m");
2118 r
= id128_write(path
, ID128_FORMAT_UUID
, rnd
);
2120 return log_error_errno(r
, "Failed to write boot id: %m");
2122 from
= TAKE_PTR(path
);
2123 to
= "/proc/sys/kernel/random/boot_id";
2125 r
= mount_nofollow_verbose(LOG_ERR
, from
, to
, NULL
, MS_BIND
, NULL
);
2129 return mount_nofollow_verbose(LOG_ERR
, NULL
, to
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
|MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, NULL
);
2132 static int bind_mount_devnode(const char *from
, const char *to
) {
2140 return log_debug_errno(r
, "Failed to touch %s: %m", to
);
2142 r
= mount_nofollow_verbose(LOG_DEBUG
, from
, to
, NULL
, MS_BIND
, NULL
);
2145 return log_error_errno(r
, "Failed to bind mount %s to %s: %m", from
, to
);
2151 static int copy_devnode_one(const char *dest
, const char *node
, bool check
) {
2155 assert(!isempty(node
));
2157 BLOCK_WITH_UMASK(0000);
2159 _cleanup_free_
char *from
= path_join("/dev/", node
);
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
);
2169 log_debug_errno(errno
,
2170 "Failed to open %s, skipping creation of the device node in the container, ignoring: %m",
2176 _cleanup_free_
char *to
= path_join(dest
, from
);
2181 if (stat(from
, &st
) < 0) {
2182 if (errno
!= ENOENT
)
2183 return log_error_errno(errno
, "Failed to stat %s: %m", from
);
2185 log_debug_errno(errno
, "Device node %s does not exist, ignoring.", from
);
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
);
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
);
2196 return log_error_errno(r
, "Failed to extract directory from %s: %m", from
);
2197 r
= userns_mkdir(dest
, parent
, 0755, 0, 0);
2199 return log_error_errno(r
, "Failed to create directory %s: %m", parent
);
2201 r
= RET_NERRNO(mknod(to
, st
.st_mode
, st
.st_rdev
));
2203 /* Explicitly warn the user when /dev/ is already populated. */
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
);
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))) {
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
);
2214 log_debug_errno(r
, "Failed to create device node '%s' and running in managed mode, resorting to bind mount: %m", to
);
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
);
2222 /* mknod() succeeds, chown() it if necessary. */
2223 r
= userns_lchown(to
, 0, 0);
2225 return log_error_errno(r
, "chown() of device node %s failed: %m", to
);
2228 _cleanup_free_
char *dn
= path_join("/dev", S_ISCHR(st
.st_mode
) ? "char" : "block");
2232 r
= userns_mkdir(dest
, dn
, 0755, 0, 0);
2234 return log_error_errno(r
, "Failed to create '%s': %m", dn
);
2236 _cleanup_free_
char *sl
= NULL
;
2237 if (asprintf(&sl
, "%s/" DEVNUM_FORMAT_STR
, dn
, DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0)
2240 _cleanup_free_
char *prefixed
= path_join(dest
, sl
);
2244 _cleanup_free_
char *t
= path_join("..", node
);
2248 if (symlink(t
, prefixed
) < 0)
2249 log_debug_errno(errno
, "Failed to symlink '%s' to '%s', ignoring: %m", t
, prefixed
);
2254 static int copy_devnodes(const char *dest
) {
2259 /* Required basic device nodes. */
2260 FOREACH_STRING(node
, "null", "zero", "full", "random", "urandom", "tty") {
2261 r
= copy_devnode_one(dest
, node
, /* check = */ false);
2266 /* Optional device nodes. */
2267 FOREACH_STRING(node
, "fuse", "net/tun") {
2268 r
= copy_devnode_one(dest
, node
, /* check = */ true);
2276 static int make_extra_nodes(const char *dest
) {
2279 BLOCK_WITH_UMASK(0000);
2281 FOREACH_ARRAY(node
, arg_extra_nodes
, arg_n_extra_nodes
) {
2282 _cleanup_free_
char *path
= NULL
;
2284 path
= path_join(dest
, node
->path
);
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
);
2292 r
= chmod_and_chown(path
, node
->mode
, node
->uid
, node
->gid
);
2294 return log_error_errno(r
, "Failed to adjust device node ownership of '%s': %m", path
);
2300 static int setup_pts(const char *dest
, uid_t chown_uid
) {
2301 _cleanup_free_
char *options
= NULL
;
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
);
2312 (void) asprintf(&options
,
2313 "newinstance,ptmxmode=0666,mode=" STRINGIFY(TTY_MODE
) ",gid=" GID_FMT
,
2314 chown_uid
+ TTY_GID
);
2319 /* Mount /dev/pts itself */
2320 _cleanup_free_
char *p
= path_join(dest
, "/dev/pts");
2324 r
= RET_NERRNO(mkdir(p
, 0755));
2326 return log_error_errno(r
, "Failed to create /dev/pts: %m");
2328 r
= mount_nofollow_verbose(LOG_ERR
, "devpts", p
, "devpts", MS_NOSUID
|MS_NOEXEC
, options
);
2331 r
= userns_lchown(p
, 0, 0);
2333 return log_error_errno(r
, "Failed to chown /dev/pts: %m");
2335 /* Create /dev/ptmx symlink */
2337 p
= path_join(dest
, "/dev/ptmx");
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);
2345 return log_error_errno(r
, "Failed to chown /dev/ptmx: %m");
2347 /* And fix /dev/pts/ptmx ownership */
2349 p
= path_join(dest
, "/dev/pts/ptmx");
2353 r
= userns_lchown(p
, 0, 0);
2355 return log_error_errno(r
, "Failed to chown /dev/pts/ptmx: %m");
2360 static int setup_stdio_as_dev_console(void) {
2361 _cleanup_close_
int terminal
= -EBADF
;
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
);
2368 return log_error_errno(terminal
, "Failed to open console: %m");
2370 /* Make sure we can continue logging to the original stderr, even if
2371 * stderr points elsewhere now */
2372 r
= log_dup_console();
2374 return log_error_errno(r
, "Failed to duplicate stderr: %m");
2376 /* invalidates 'terminal' on success and failure */
2377 r
= rearrange_stdio(terminal
, terminal
, terminal
);
2380 return log_error_errno(r
, "Failed to move console to stdin/stdout/stderr: %m");
2385 static int setup_dev_console(const char *console
) {
2386 _cleanup_free_
char *p
= NULL
;
2389 /* Create /dev/console symlink */
2390 r
= path_make_relative("/dev", console
, &p
);
2392 return log_error_errno(r
, "Failed to create relative path: %m");
2394 if (symlink(p
, "/dev/console") < 0)
2395 return log_error_errno(errno
, "Failed to create /dev/console symlink: %m");
2400 static int setup_keyring(void) {
2401 key_serial_t keyring
;
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. */
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.");
2416 return log_error_errno(errno
, "Setting up kernel keyring failed: %m");
2422 int make_run_host(const char *root
) {
2427 r
= userns_mkdir(root
, "/run/host", 0755, 0, 0);
2429 return log_error_errno(r
, "Failed to create /run/host/: %m");
2434 static int setup_credentials(const char *root
) {
2435 bool world_readable
= false;
2438 if (arg_credentials
.n_credentials
== 0)
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;
2454 r
= make_run_host(root
);
2458 r
= userns_mkdir(root
, "/run/host/credentials", world_readable
? 0777 : 0700, 0, 0);
2460 return log_error_errno(r
, "Failed to create /run/host/credentials: %m");
2462 _cleanup_free_
char *q
= path_join(root
, "/run/host/credentials");
2466 r
= mount_nofollow_verbose(LOG_ERR
, NULL
, q
, "ramfs", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, "mode=0700");
2470 FOREACH_ARRAY(cred
, arg_credentials
.credentials
, arg_credentials
.n_credentials
) {
2471 _cleanup_free_
char *j
= NULL
;
2472 _cleanup_close_
int fd
= -EBADF
;
2474 j
= path_join(q
, cred
->id
);
2478 fd
= open(j
, O_CREAT
|O_EXCL
|O_WRONLY
|O_CLOEXEC
|O_NOFOLLOW
, world_readable
? 0666 : 0600);
2480 return log_error_errno(errno
, "Failed to create credential file %s: %m", j
);
2482 r
= loop_write(fd
, cred
->data
, cred
->size
);
2484 return log_error_errno(r
, "Failed to write credential to file %s: %m", j
);
2486 if (fchmod(fd
, world_readable
? 0444 : 0400) < 0)
2487 return log_error_errno(errno
, "Failed to adjust access mode of %s: %m", j
);
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
);
2494 if (chmod(q
, world_readable
? 0555 : 0500) < 0)
2495 return log_error_errno(errno
, "Failed to adjust access mode of %s: %m", q
);
2497 r
= userns_lchown(q
, 0, 0);
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
);
2506 return mount_nofollow_verbose(LOG_ERR
, NULL
, q
, NULL
, MS_REMOUNT
|MS_RDONLY
|MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, "mode=0500");
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
;
2515 assert(fd_inner_socket
>= 0);
2517 BLOCK_WITH_UMASK(0000);
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. */
2524 r
= tempfn_random_child("/run", "proc-kmsg", &fifo
);
2526 return log_error_errno(r
, "Failed to generate kmsg path: %m");
2528 if (mkfifo(fifo
, 0600) < 0)
2529 return log_error_errno(errno
, "mkfifo() for /run/kmsg failed: %m");
2531 from
= TAKE_PTR(fifo
);
2533 r
= mount_nofollow_verbose(LOG_ERR
, from
, "/proc/kmsg", NULL
, MS_BIND
, NULL
);
2537 fd
= open(from
, O_RDWR
|O_NONBLOCK
|O_CLOEXEC
);
2539 return log_error_errno(errno
, "Failed to open fifo: %m");
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);
2544 return log_error_errno(r
, "Failed to send FIFO fd: %m");
2550 union in_addr_union address4
;
2551 union in_addr_union address6
;
2552 struct FirewallContext
*fw_ctx
;
2555 static int on_address_change(sd_netlink
*rtnl
, sd_netlink_message
*m
, void *userdata
) {
2556 struct ExposeArgs
*args
= ASSERT_PTR(userdata
);
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
);
2566 static int setup_hostname(void) {
2569 if ((arg_clone_ns_flags
& CLONE_NEWUTS
) == 0)
2572 r
= sethostname_idempotent(arg_hostname
?: arg_machine
);
2574 return log_error_errno(r
, "Failed to set hostname: %m");
2579 static int setup_journal(const char *directory
) {
2580 _cleanup_free_
char *d
= NULL
;
2585 /* Don't link journals in ephemeral mode */
2589 if (arg_link_journal
== LINK_NO
)
2592 try = arg_link_journal_try
|| arg_link_journal
== LINK_AUTO
;
2594 r
= sd_id128_get_machine(&this_id
);
2596 return log_error_errno(r
, "Failed to retrieve machine ID: %m");
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
));
2606 FOREACH_STRING(dirname
, "/var", "/var/log", "/var/log/journal") {
2607 r
= userns_mkdir(directory
, dirname
, 0755, 0, 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
;
2616 _cleanup_free_
char *p
= path_join("/var/log/journal/", SD_ID128_TO_STRING(arg_uuid
));
2620 _cleanup_free_
char *q
= path_join(directory
, p
);
2624 if (path_is_mount_point(p
) > 0) {
2628 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
2629 "%s: already a mount point, refusing to use for journal", p
);
2632 if (path_is_mount_point(q
) > 0) {
2636 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
2637 "%s: already a mount point, refusing to use for journal", q
);
2640 r
= readlink_and_make_absolute(p
, &d
);
2642 if (IN_SET(arg_link_journal
, LINK_GUEST
, LINK_AUTO
) &&
2645 r
= userns_mkdir(directory
, p
, 0755, 0, 0);
2647 log_warning_errno(r
, "Failed to create directory %s: %m", q
);
2652 return log_error_errno(errno
, "Failed to remove symlink %s: %m", p
);
2653 } else if (r
== -EINVAL
) {
2655 if (arg_link_journal
== LINK_GUEST
&&
2658 if (errno
== ENOTDIR
) {
2659 log_error("%s already exists and is neither a symlink nor a directory", p
);
2662 return log_error_errno(errno
, "Failed to remove %s: %m", p
);
2664 } else if (r
!= -ENOENT
)
2665 return log_error_errno(r
, "readlink(%s) failed: %m", p
);
2667 if (arg_link_journal
== LINK_GUEST
) {
2669 if (symlink(q
, p
) < 0) {
2671 log_debug_errno(errno
, "Failed to symlink %s to %s, skipping journal setup: %m", q
, p
);
2674 return log_error_errno(errno
, "Failed to symlink %s to %s: %m", q
, p
);
2677 r
= userns_mkdir(directory
, p
, 0755, 0, 0);
2679 log_warning_errno(r
, "Failed to create directory %s: %m", q
);
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 */
2687 r
= RET_NERRNO(mkdir(p
, 0755));
2688 if (r
< 0 && r
!= -EEXIST
) {
2690 log_debug_errno(r
, "Failed to create %s, skipping journal setup: %m", p
);
2693 return log_error_errno(r
, "Failed to create %s: %m", p
);
2696 } else if (access(p
, F_OK
) < 0)
2699 if (dir_is_empty(q
, /* ignore_hidden_or_backup= */ false) == 0)
2700 log_warning("%s is not empty, proceeding anyway.", q
);
2702 r
= userns_mkdir(directory
, p
, 0755, 0, 0);
2704 return log_error_errno(r
, "Failed to create %s: %m", q
);
2706 r
= mount_nofollow_verbose(LOG_DEBUG
, p
, q
, NULL
, MS_BIND
, NULL
);
2708 return log_error_errno(r
, "Failed to bind mount journal from host into guest: %m");
2713 static int drop_capabilities(uid_t uid
) {
2714 CapabilityQuintet q
;
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. */
2720 if (capability_quintet_is_set(&arg_full_capabilities
)) {
2721 q
= arg_full_capabilities
;
2723 if (q
.bounding
== UINT64_MAX
)
2724 q
.bounding
= uid
== 0 ? arg_caps_retain
: 0;
2726 if (q
.effective
== UINT64_MAX
)
2727 q
.effective
= uid
== 0 ? q
.bounding
: 0;
2729 if (q
.inheritable
== UINT64_MAX
)
2730 q
.inheritable
= uid
== 0 ? q
.bounding
: arg_caps_ambient
;
2732 if (q
.permitted
== UINT64_MAX
)
2733 q
.permitted
= uid
== 0 ? q
.bounding
: arg_caps_ambient
;
2735 if (q
.ambient
== UINT64_MAX
)
2736 q
.ambient
= arg_caps_ambient
;
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.");
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
,
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.");
2758 return capability_quintet_enforce(&q
);
2761 static int reset_audit_loginuid(void) {
2762 _cleanup_free_
char *p
= NULL
;
2765 if ((arg_clone_ns_flags
& CLONE_NEWPID
) == 0)
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
)
2773 r
= read_virtual_file("/proc/self/loginuid", SIZE_MAX
, &p
, /* ret_size= */ NULL
);
2777 return log_error_errno(r
, "Failed to read /proc/self/loginuid: %m");
2779 /* Already reset? */
2780 if (streq(p
, "4294967295"))
2783 r
= write_string_file("/proc/self/loginuid", "4294967295", WRITE_STRING_FILE_DISABLE_BUFFER
);
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)");
2798 static int mount_tunnel_dig(const char *root
) {
2801 if (arg_userns_mode
== USER_NAMESPACE_MANAGED
) {
2802 log_debug("Not digging mount tunnel, because running in managed user namespace mode.");
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
);
2812 (void) mkdir_p(p
, 0600);
2814 r
= make_run_host(root
);
2818 r
= userns_mkdir(root
, NSPAWN_MOUNT_TUNNEL
, 0600, 0, 0);
2820 return log_error_errno(r
, "Failed to create "NSPAWN_MOUNT_TUNNEL
": %m");
2822 _cleanup_free_
char *q
= path_join(root
, NSPAWN_MOUNT_TUNNEL
);
2826 r
= mount_nofollow_verbose(LOG_ERR
, p
, q
, NULL
, MS_BIND
, NULL
);
2830 r
= mount_nofollow_verbose(LOG_ERR
, NULL
, q
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
, NULL
);
2837 static int mount_tunnel_open(void) {
2840 if (arg_userns_mode
== USER_NAMESPACE_MANAGED
) {
2841 log_debug("Not opening up mount tunnel, because running in managed user namespace mode.");
2845 r
= mount_follow_verbose(LOG_ERR
, NULL
, NSPAWN_MOUNT_TUNNEL
, NULL
, MS_SLAVE
, NULL
);
2852 static int setup_machine_id(const char *directory
) {
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). */
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
);
2868 return log_error_errno(r
, "Failed to acquire randomized machine UUID: %m");
2871 return log_error_errno(r
, "Failed to read machine ID from container image: %m");
2876 static int recursive_chown(const char *directory
, uid_t shift
, uid_t range
) {
2881 if (arg_userns_mode
== USER_NAMESPACE_NO
|| arg_userns_ownership
!= USER_NAMESPACE_OWNERSHIP_CHOWN
)
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.");
2888 return log_error_errno(r
, "Upper 16 bits of root directory UID and GID do not match.");
2890 return log_error_errno(r
, "Failed to adjust UID/GID shift of OS tree: %m");
2892 log_debug("Root directory of image is already owned by the right UID/GID range, skipping recursive chown operation.");
2894 log_debug("Patched directory tree to match UID/GID range.");
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.
2913 * That is, success is indicated by a return value of zero, and an
2914 * error is indicated by a non-zero value.
2916 static int wait_for_container(PidRef
*pid
, ContainerStatus
*container
) {
2920 assert(pidref_is_set(pid
));
2922 r
= pidref_wait_for_terminate(pid
, &status
);
2924 return log_warning_errno(r
, "Failed to wait for container: %m");
2928 switch (status
.si_code
) {
2931 if (status
.si_status
== 0)
2932 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
, "Container %s exited successfully.", arg_machine
);
2934 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
, "Container %s failed with error code %i.", arg_machine
, status
.si_status
);
2936 *container
= CONTAINER_TERMINATED
;
2937 return status
.si_status
;
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
;
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
;
2953 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
2954 "Container %s terminated by signal %s.", arg_machine
, signal_to_string(status
.si_status
));
2957 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
2958 "Container %s failed due to unknown reason.", arg_machine
);
2962 static int on_orderly_shutdown(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
2963 PidRef
*pid
= ASSERT_PTR(userdata
);
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
);
2972 sd_event_exit(sd_event_source_get_event(s
), 0);
2976 static int on_sigchld(sd_event_source
*s
, const struct signalfd_siginfo
*ssi
, void *userdata
) {
2981 PidRef
*pid
= ASSERT_PTR(userdata
);
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. */
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);
2996 /* Reap all other children. */
2997 (void) waitid(P_PID
, si
.si_pid
, &si
, WNOHANG
|WEXITED
);
3003 static int on_request_stop(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
3004 PidRef
*pid
= ASSERT_PTR(userdata
);
3008 if (arg_kill_signal
> 0) {
3009 log_info("Container termination requested. Attempting to halt container.");
3010 (void) pidref_kill(pid
, arg_kill_signal
);
3012 log_info("Container termination requested. Exiting.");
3013 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), 0);
3019 static int pick_paths(void) {
3022 if (arg_directory
) {
3023 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
3024 PickFilter filter
= pick_filter_image_dir
;
3026 filter
.architecture
= arg_architecture
;
3028 r
= path_pick_update_warn(
3031 PICK_ARCHITECTURE
|PICK_TRIES
,
3034 /* Accept ENOENT here so that the --template= logic can work */
3038 arg_architecture
= result
.architecture
;
3042 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
3043 PickFilter filter
= pick_filter_image_raw
;
3045 filter
.architecture
= arg_architecture
;
3047 r
= path_pick_update_warn(
3050 PICK_ARCHITECTURE
|PICK_TRIES
,
3055 arg_architecture
= result
.architecture
;
3059 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
3060 PickFilter filter
= pick_filter_image_dir
;
3062 filter
.architecture
= arg_architecture
;
3064 r
= path_pick_update_warn(
3072 arg_architecture
= result
.architecture
;
3078 static int determine_names(void) {
3081 if (arg_template
&& !arg_directory
&& arg_machine
) {
3083 /* If --template= was specified then we should not search for a machine, but instead create a
3084 * new one in /var/lib/machine. */
3086 arg_directory
= path_join("/var/lib/machines", arg_machine
);
3091 if (!arg_image
&& !arg_directory
) {
3093 _cleanup_(image_unrefp
) Image
*i
= NULL
;
3095 r
= image_find(arg_privileged
? RUNTIME_SCOPE_SYSTEM
: RUNTIME_SCOPE_USER
,
3096 IMAGE_MACHINE
, arg_machine
, NULL
, &i
);
3098 return log_error_errno(r
, "No image for machine '%s'.", arg_machine
);
3100 return log_error_errno(r
, "Failed to find image for machine '%s': %m", arg_machine
);
3102 if (IN_SET(i
->type
, IMAGE_RAW
, IMAGE_BLOCK
))
3103 r
= free_and_strdup(&arg_image
, i
->path
);
3105 r
= free_and_strdup(&arg_directory
, i
->path
);
3110 arg_read_only
= arg_read_only
|| i
->read_only
;
3112 r
= safe_getcwd(&arg_directory
);
3114 return log_error_errno(r
, "Failed to determine current directory: %m");
3117 if (!arg_directory
&& !arg_image
)
3118 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to determine path, please use -D or -i.");
3122 if (arg_directory
&& path_equal(arg_directory
, "/")) {
3123 arg_machine
= gethostname_malloc();
3126 } else if (arg_image
) {
3129 r
= path_extract_filename(arg_image
, &arg_machine
);
3131 return log_error_errno(r
, "Failed to extract file name from '%s': %m", arg_image
);
3133 /* Truncate suffix if there is one */
3134 e
= endswith(arg_machine
, ".raw");
3138 r
= path_extract_filename(arg_directory
, &arg_machine
);
3140 return log_error_errno(r
, "Failed to extract file name from '%s': %m", arg_directory
);
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.");
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
)
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. */
3156 if (strextendf(&arg_machine
, "-%016" PRIx64
, random_u64()) < 0)
3159 arg_settings_filename
= strjoin(arg_machine
, ".nspawn");
3160 if (!arg_settings_filename
)
3167 static int chase_and_update(char **p
, unsigned flags
) {
3176 r
= chase(*p
, NULL
, flags
, &chased
, NULL
);
3178 return log_error_errno(r
, "Failed to resolve path %s: %m", *p
);
3180 return free_and_replace(*p
, chased
);
3183 static int determine_uid_shift(const char *directory
) {
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
));
3192 if (arg_userns_mode
== USER_NAMESPACE_NO
) {
3197 if (arg_uid_shift
== UID_INVALID
) {
3200 /* Read the UID shift off the image. Maybe we can reuse this to avoid chowning. */
3202 if (stat(directory
, &st
) < 0)
3203 return log_error_errno(errno
, "Failed to determine UID base of %s: %m", directory
);
3205 arg_uid_shift
= st
.st_uid
& UINT32_C(0xffff0000);
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
);
3211 arg_uid_range
= UINT32_C(0x10000);
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. */
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
);
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.");
3232 static unsigned long effective_clone_ns_flags(void) {
3233 unsigned long flags
= arg_clone_ns_flags
;
3235 if (arg_private_network
)
3236 flags
|= CLONE_NEWNET
;
3238 flags
|= CLONE_NEWCGROUP
;
3239 if (arg_userns_mode
!= USER_NAMESPACE_NO
)
3240 flags
|= CLONE_NEWUSER
;
3245 static int patch_sysctl(void) {
3247 /* This table is inspired by runc's sysctl() function */
3248 static const struct {
3251 unsigned long clone_flags
;
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
},
3266 unsigned long flags
;
3269 flags
= effective_clone_ns_flags();
3271 STRV_FOREACH_PAIR(k
, v
, arg_sysctl
) {
3274 FOREACH_ELEMENT(i
, safe_sysctl
) {
3275 if (!FLAGS_SET(flags
, i
->clone_flags
))
3279 good
= startswith(*k
, i
->key
);
3281 good
= streq(*k
, i
->key
);
3288 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Refusing to write to sysctl '%s', as it is not safe in the selected namespaces.", *k
);
3290 r
= sysctl_write(*k
, *v
);
3292 return log_error_errno(r
, "Failed to write sysctl '%s': %m", *k
);
3298 static int inner_child(
3300 int fd_inner_socket
,
3302 char **os_release_pairs
) {
3304 _cleanup_free_
char *home
= NULL
;
3307 (char*) "PATH=" DEFAULT_PATH_COMPAT
,
3308 NULL
, /* container */
3310 NULL
, /* COLORTERM */
3311 NULL
, /* NO_COLOR */
3315 NULL
, /* container_uuid */
3316 NULL
, /* LISTEN_FDS */
3317 NULL
, /* LISTEN_PID */
3318 NULL
, /* NOTIFY_SOCKET */
3319 NULL
, /* CREDENTIALS_DIRECTORY */
3323 const char *exec_target
;
3324 _cleanup_strv_free_
char **env_use
= NULL
;
3325 int r
, which_failed
;
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
3335 * Note at this point we have no CLONE_NEWNET namespace yet. We'll acquire that one later through
3336 * unshare(). See below. */
3339 assert(fd_inner_socket
>= 0);
3341 log_debug("Inner child is initializing.");
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 */
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");
3351 /* Become the new root user inside our namespace */
3352 r
= reset_uid_gid();
3354 return log_error_errno(r
, "Couldn't become new root: %m");
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
);
3364 r
= mount_all(/* dest= */ NULL
,
3365 arg_mount_settings
| MOUNT_IN_USERNS
,
3367 arg_selinux_apifs_context
);
3371 if (!arg_network_namespace_path
&& arg_private_network
) {
3372 _cleanup_close_
int netns_fd
= -EBADF
;
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");
3378 netns_fd
= namespace_open_by_type(NAMESPACE_NET
);
3380 return log_error_errno(netns_fd
, "Failed to open newly allocate network namespace: %m");
3382 r
= send_one_fd(fd_inner_socket
, netns_fd
, 0);
3384 return log_error_errno(r
, "Failed to send network namespace to supervisor: %m");
3386 /* Tell the parent that it can setup network interfaces. */
3387 (void) barrier_place(barrier
); /* #3 */
3390 if (arg_userns_mode
!= USER_NAMESPACE_MANAGED
) {
3391 r
= mount_sysfs(NULL
, arg_mount_settings
| MOUNT_IN_USERNS
);
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");
3402 r
= unshare(CLONE_NEWCGROUP
);
3404 return log_error_errno(errno
, "Failed to unshare cgroup namespace: %m");
3406 r
= mount_cgroups(/* dest = */ NULL
, /* accept_existing = */ false);
3408 r
= bind_mount_cgroup_hierarchy();
3412 r
= setup_boot_id();
3416 r
= setup_kmsg(fd_inner_socket
);
3423 arg_n_custom_mounts
,
3426 arg_selinux_apifs_context
,
3427 MOUNT_NON_ROOT_ONLY
| MOUNT_IN_USERNS
);
3432 return log_error_errno(errno
, "setsid() failed: %m");
3434 if (arg_private_network
)
3435 (void) loopback_setup();
3437 if (arg_expose_ports
) {
3438 r
= expose_port_send_rtnl(fd_inner_socket
);
3443 if (arg_console_mode
!= CONSOLE_PIPE
) {
3444 _cleanup_close_
int master
= -EBADF
;
3445 _cleanup_free_
char *console
= NULL
;
3447 /* Allocate a pty and make it available as /dev/console. */
3448 master
= openpt_allocate(O_RDWR
|O_NONBLOCK
, &console
);
3450 return log_error_errno(master
, "Failed to allocate a pty: %m");
3452 r
= setup_dev_console(console
);
3454 return log_error_errno(r
, "Failed to set up /dev/console: %m");
3456 r
= send_one_fd(fd_inner_socket
, master
, 0);
3458 return log_error_errno(r
, "Failed to send master fd: %m");
3460 r
= setup_stdio_as_dev_console();
3469 if (arg_oom_score_adjust_set
) {
3470 r
= set_oom_score_adjust(arg_oom_score_adjust
);
3472 return log_error_errno(r
, "Failed to adjust OOM score: %m");
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");
3479 (void) setup_hostname();
3481 if (arg_personality
!= PERSONALITY_INVALID
) {
3482 r
= safe_personality(arg_personality
);
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
);
3489 return log_error_errno(r
, "personality() failed: %m");
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
));
3496 r
= setrlimit_closest_all((const struct rlimit
*const*) arg_rlimit
, &which_failed
);
3498 return log_error_errno(r
, "Failed to apply resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed
));
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");
3508 log_debug_errno(r
, "Failed to install seccomp filter: %m");
3513 r
= setup_seccomp(arg_caps_retain
, arg_syscall_allow_list
, arg_syscall_deny_list
);
3518 if (arg_suppress_sync
) {
3520 r
= seccomp_suppress_sync();
3522 log_debug_errno(r
, "Failed to install sync() suppression seccomp filter, ignoring: %m");
3524 log_debug("systemd is built without SECCOMP support. Ignoring --suppress-sync= command line option and SuppressSync= setting.");
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
);
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");
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
);
3542 r
= change_uid_gid(arg_user
, arg_console_mode
!= CONSOLE_PIPE
, &home
);
3546 r
= drop_capabilities(getuid());
3548 return log_error_errno(r
, "Dropping capabilities failed: %m");
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");
3554 /* LXC sets container=lxc, so follow the scheme here */
3555 envp
[n_env
++] = strjoina("container=", arg_container_service_name
);
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
);
3567 envp
[n_env
++] = (char*) "TERM=dumb";
3569 if (home
|| !uid_is_valid(arg_uid
) || arg_uid
== 0)
3570 if (asprintf(envp
+ n_env
++, "HOME=%s", home
?: "/root") < 0)
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)
3578 assert(!sd_id128_is_null(arg_uuid
));
3580 if (asprintf(envp
+ n_env
++, "container_uuid=%s", SD_ID128_TO_UUID_STRING(arg_uuid
)) < 0)
3583 if (!fdset_isempty(fds
)) {
3584 r
= fdset_cloexec(fds
, false);
3586 return log_error_errno(r
, "Failed to unset O_CLOEXEC for file descriptors.");
3588 if ((asprintf(envp
+ n_env
++, "LISTEN_FDS=%u", fdset_size(fds
)) < 0) ||
3589 (asprintf(envp
+ n_env
++, "LISTEN_PID=1") < 0))
3592 if (asprintf(envp
+ n_env
++, "NOTIFY_SOCKET=%s", NSPAWN_NOTIFY_SOCKET_PATH
) < 0)
3595 if (arg_credentials
.n_credentials
> 0) {
3596 envp
[n_env
] = strdup("CREDENTIALS_DIRECTORY=/run/host/credentials");
3602 if (arg_start_mode
!= START_BOOT
) {
3603 envp
[n_env
] = strdup("LANG=" SYSTEMD_NSPAWN_LOCALE
);
3609 env_use
= strv_env_merge(envp
, os_release_pairs
, arg_setenv
);
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");
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. */
3621 if (chdir(arg_chdir
) < 0)
3622 return log_error_errno(errno
, "Failed to change to specified working directory %s: %m", arg_chdir
);
3624 if (arg_start_mode
== START_PID2
) {
3625 r
= stub_pid1(arg_uuid
);
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");
3637 log_debug("Inner child finished, invoking payload.");
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. */
3643 log_set_open_when_needed(true);
3644 log_settle_target();
3646 (void) fdset_close_others(fds
);
3648 if (arg_start_mode
== START_BOOT
) {
3652 /* Automatically search for the init system */
3654 m
= strv_length(arg_parameters
);
3655 a
= newa(char*, m
+ 2);
3656 memcpy_safe(a
+ 1, arg_parameters
, m
* sizeof(char*));
3659 FOREACH_STRING(init
,
3660 "/usr/lib/systemd/systemd",
3661 "/lib/systemd/systemd",
3663 a
[0] = (char*) init
;
3664 execve(a
[0], a
, env_use
);
3667 exec_target
= "/usr/lib/systemd/systemd, /lib/systemd/systemd, /sbin/init";
3668 } else if (!strv_isempty(arg_parameters
)) {
3669 const char *dollar_path
;
3671 exec_target
= arg_parameters
[0];
3673 /* Use the user supplied search $PATH if there is one, or DEFAULT_PATH_COMPAT if not to search the
3675 dollar_path
= strv_env_get(env_use
, "PATH");
3677 if (setenv("PATH", dollar_path
, 1) < 0)
3678 return log_error_errno(errno
, "Failed to update $PATH: %m");
3681 execvpe(arg_parameters
[0], arg_parameters
, env_use
);
3684 /* If we cannot change the directory, we'll end up in /, that is expected. */
3685 (void) chdir(home
?: "/root");
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
);
3693 exec_target
= DEFAULT_USER_SHELL
", /bin/bash, /bin/sh";
3696 return log_error_errno(errno
, "execv(%s) failed: %m", exec_target
);
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
,
3707 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
3709 return log_error_errno(errno
, "Failed to allocate notification socket: %m");
3712 j
= path_join(directory
, NSPAWN_NOTIFY_SOCKET_PATH
);
3717 r
= sockaddr_un_set_path(&sa
.un
, j
?: NSPAWN_NOTIFY_SOCKET_PATH
);
3719 return log_error_errno(r
, "Failed to set AF_UNIX path to %s: %m", j
?: NSPAWN_NOTIFY_SOCKET_PATH
);
3721 (void) mkdir_parents(sa
.un
.sun_path
, 0755);
3722 (void) sockaddr_un_unlink(&sa
.un
);
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
));
3727 return log_error_errno(errno
, "bind(" NSPAWN_NOTIFY_SOCKET_PATH
") failed: %m");
3730 r
= userns_lchown(sa
.un
.sun_path
, 0, 0);
3732 return log_error_errno(r
, "Failed to chown " NSPAWN_NOTIFY_SOCKET_PATH
": %m");
3734 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
3736 return log_error_errno(r
, "Failed to enable SO_PASSCRED: %m");
3738 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSPIDFD
, true);
3740 log_debug_errno(r
, "Failed to enable SO_PASSPIDFD, ignoring: %m");
3742 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSRIGHTS
, false);
3744 log_debug_errno(r
, "Failed to turn off SO_PASSRIGHTS, ignoring: %m");
3749 static int setup_unix_export_dir_outside(char **ret
) {
3754 if (arg_userns_mode
== USER_NAMESPACE_MANAGED
) {
3755 log_debug("Not digging socket tunnel, because running in managed user namespace mode.");
3759 _cleanup_free_
char *p
= NULL
;
3760 p
= path_join("/run/systemd/nspawn/unix-export", arg_machine
);
3764 r
= path_is_mount_point(p
);
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
);
3770 r
= mkdir_p(p
, 0755);
3772 return log_error_errno(r
, "Failed to create '%s': %m", p
);
3774 _cleanup_(rmdir_and_freep
) char *q
= TAKE_PTR(p
);
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(
3783 MS_NODEV
|MS_NOEXEC
|MS_NOSUID
|ms_nosymfollow_supported(),
3784 "size=4M,nr_inodes=64,mode=0755");
3788 _cleanup_(umount_and_rmdir_and_freep
) char *w
= TAKE_PTR(q
);
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(
3797 MS_BIND
|MS_REMOUNT
|MS_RDONLY
|MS_NODEV
|MS_NOEXEC
|MS_NOSUID
|ms_nosymfollow_supported(),
3798 /* options= */ NULL
);
3806 static int setup_unix_export_host_inside(const char *directory
, const char *unix_export_path
) {
3811 if (arg_userns_mode
== USER_NAMESPACE_MANAGED
)
3814 assert(unix_export_path
);
3816 r
= make_run_host(directory
);
3820 _cleanup_free_
char *p
= path_join(directory
, "run/host/unix-export");
3824 if (mkdir(p
, 0755) < 0)
3825 return log_error_errno(errno
, "Failed to create '%s': %m", p
);
3827 r
= mount_nofollow_verbose(
3833 /* options= */ NULL
);
3837 r
= mount_nofollow_verbose(
3842 MS_BIND
|MS_REMOUNT
|MS_NODEV
|MS_NOEXEC
|MS_NOSUID
|ms_nosymfollow_supported(),
3843 /* options= */ NULL
);
3847 r
= userns_lchown(p
, 0, 0);
3849 return log_error_errno(r
, "Failed to chown '%s': %m", p
);
3854 static DissectImageFlags
determine_dissect_image_flags(void) {
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);
3870 static int outer_child(
3872 const char *directory
,
3874 DissectedImage
*dissected_image
,
3875 int fd_outer_socket
,
3876 int fd_inner_socket
,
3879 const char *unix_export_path
) {
3881 _cleanup_(bind_user_context_freep
) BindUserContext
*bind_user_context
= NULL
;
3882 _cleanup_strv_free_
char **os_release_pairs
= NULL
;
3887 /* This is the "outer" child process, i.e the one forked off by the container manager itself. Its
3888 * namespace situation is:
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
3898 * After it completed a number of initializations a second child (the "inner" one) is forked off it,
3903 assert(fd_outer_socket
>= 0);
3904 assert(fd_inner_socket
>= 0);
3906 log_debug("Outer child is initializing.");
3908 r
= load_os_release_pairs_with_prefix("/", "container_host_", &os_release_pairs
);
3910 log_debug_errno(r
, "Failed to read os-release from host for container, ignoring: %m");
3912 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
) < 0)
3913 return log_error_errno(errno
, "PR_SET_PDEATHSIG failed: %m");
3915 r
= reset_audit_loginuid();
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
);
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
);
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");
3935 mount_fd
= safe_close(mount_fd
);
3936 log_debug("Successfully attached root directory to '%s'.", directory
);
3938 } else if (dissected_image
) {
3939 assert(!arg_directory
);
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. */
3947 r
= dissected_image_mount_and_warn(
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));
3959 assert(arg_directory
);
3962 r
= mount_nofollow_verbose(LOG_ERR
, arg_directory
, directory
, /* fstype= */ NULL
, MS_BIND
|MS_REC
, /* options= */ NULL
);
3967 r
= determine_uid_shift(directory
);
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
3974 uid_t chown_uid
, chown_range
;
3975 if (in_child_chown()) {
3976 chown_uid
= arg_uid_shift
;
3977 chown_range
= arg_uid_range
;
3980 chown_range
= UINT32_C(0x10000);
3983 if (arg_userns_mode
!= USER_NAMESPACE_NO
) {
3984 _cleanup_close_
int mntns_fd
= -EBADF
;
3986 mntns_fd
= namespace_open_by_type(NAMESPACE_MOUNT
);
3988 return log_error_errno(mntns_fd
, "Failed to pin outer mount namespace: %m");
3990 l
= send_one_fd(fd_outer_socket
, mntns_fd
, 0);
3992 return log_error_errno(l
, "Failed to send outer mount namespace fd: %m");
3993 mntns_fd
= safe_close(mntns_fd
);
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
);
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.");
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. */
4008 l
= recv(fd_outer_socket
, &arg_uid_shift
, sizeof(arg_uid_shift
), 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.");
4015 if (in_child_chown())
4016 chown_uid
= arg_uid_shift
;
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
);
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
);
4031 r
= setup_pivot_root(
4034 arg_pivot_root_old
);
4038 r
= setup_volatile_mode(
4042 arg_selinux_apifs_context
);
4046 r
= bind_user_prepare(
4049 arg_bind_user_shell
,
4050 arg_bind_user_shell_copy
,
4053 &arg_custom_mounts
, &arg_n_custom_mounts
,
4054 &bind_user_context
);
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 */
4062 FOREACH_ARRAY(d
, bind_user_context
->data
, bind_user_context
->n_data
) {
4064 d
->payload_user
->uid
,
4066 (uid_t
) d
->payload_group
->gid
,
4067 (uid_t
) d
->host_group
->gid
,
4070 l
= send(fd_outer_socket
, map
, sizeof(map
), MSG_NOSIGNAL
);
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.");
4082 arg_n_custom_mounts
,
4085 arg_selinux_apifs_context
,
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
) &&
4093 _cleanup_strv_free_
char **dirs
= NULL
;
4094 RemountIdmapping mapping
;
4096 switch (arg_userns_ownership
) {
4097 case USER_NAMESPACE_OWNERSHIP_MAP
:
4098 mapping
= REMOUNT_IDMAPPING_HOST_ROOT
;
4101 case USER_NAMESPACE_OWNERSHIP_FOREIGN
:
4102 mapping
= REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT
;
4105 case USER_NAMESPACE_OWNERSHIP_AUTO
: {
4108 if (lstat(directory
, &st
) < 0)
4109 return log_error_errno(errno
, "Failed to stat() container root directory '%s': %m", directory
);
4111 r
= stat_verify_directory(&st
);
4113 return log_error_errno(r
, "Container root directory '%s' is not a directory: %m", directory
);
4115 mapping
= uid_is_foreign(st
.st_uid
) ?
4116 REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT
:
4117 REMOUNT_IDMAPPING_HOST_ROOT
;
4122 assert_not_reached();
4125 if (arg_volatile_mode
!= VOLATILE_YES
) {
4126 r
= strv_extend(&dirs
, directory
);
4131 if ((dissected_image
&& dissected_image
->partitions
[PARTITION_USR
].found
) ||
4132 arg_volatile_mode
== VOLATILE_YES
) {
4133 char *s
= path_join(directory
, "/usr");
4137 r
= strv_consume(&dirs
, s
);
4146 /* host_owner= */ UID_INVALID
,
4147 /* dest_owner= */ UID_INVALID
,
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.");
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
;
4160 return log_error_errno(r
, "Failed to set up ID mapped mounts: %m");
4162 log_debug("ID mapped mounts available, making use of them.");
4167 r
= setup_volatile_mode_after_remount_idmap(
4171 arg_selinux_apifs_context
);
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(
4182 /* userns_fd= */ -EBADF
,
4183 determine_dissect_image_flags()|
4184 DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
|
4185 (idmap
? DISSECT_IMAGE_MOUNT_IDMAPPED
: 0));
4190 r
= recursive_chown(directory
, chown_uid
, chown_range
);
4194 r
= base_filesystem_create(directory
, chown_uid
, (gid_t
) chown_uid
);
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
);
4202 return log_error_errno(r
, "Failed to make tree read-only: %m");
4205 r
= mount_all(directory
,
4208 arg_selinux_apifs_context
);
4212 r
= copy_devnodes(directory
);
4216 r
= make_extra_nodes(directory
);
4220 (void) dev_setup(directory
, chown_uid
, chown_uid
);
4222 _cleanup_free_
char *p
= path_join(directory
, "/run/host");
4226 (void) make_inaccessible_nodes(p
, chown_uid
, chown_uid
);
4228 r
= setup_unix_export_host_inside(directory
, unix_export_path
);
4232 r
= setup_pts(directory
, chown_uid
);
4236 r
= mount_tunnel_dig(directory
);
4240 r
= setup_keyring();
4244 r
= setup_credentials(directory
);
4248 r
= bind_user_setup(bind_user_context
, directory
);
4255 arg_n_custom_mounts
,
4258 arg_selinux_apifs_context
,
4259 MOUNT_NON_ROOT_ONLY
);
4263 r
= setup_timezone(directory
);
4267 r
= setup_resolv_conf(directory
);
4271 r
= setup_machine_id(directory
);
4275 r
= setup_journal(directory
);
4279 /* The same stuff as the $container env var, but nicely readable for the entire payload */
4281 p
= path_join(directory
, "/run/host/container-manager");
4285 (void) write_string_file(p
, arg_container_service_name
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_MODE_0444
);
4287 /* The same stuff as the $container_uuid env var */
4289 p
= path_join(directory
, "/run/host/container-uuid");
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
));
4295 if (!arg_use_cgns
) {
4296 r
= mount_cgroups(directory
, /* accept_existing = */ true);
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. */
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.
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
4320 r
= mount_switch_root(directory
, MS_SHARED
);
4322 return log_error_errno(r
, "Failed to move root directory: %m");
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
4327 r
= mount_tunnel_open();
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
4340 r
= pin_fully_visible_api_fs();
4345 notify_fd
= setup_notify_child(NULL
);
4347 notify_fd
= setup_notify_child(directory
);
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));
4356 return log_error_errno(errno
, "Failed to fork inner child: %m");
4358 fd_outer_socket
= safe_close(fd_outer_socket
);
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. */
4363 if (arg_network_namespace_path
) {
4364 r
= namespace_enter(/* pidns_fd = */ -EBADF
,
4365 /* mntns_fd = */ -EBADF
,
4367 /* userns_fd = */ -EBADF
,
4368 /* root_fd = */ -EBADF
);
4370 return log_error_errno(r
, "Failed to join network namespace: %m");
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
4377 _cleanup_free_
char *j
= path_join(directory
, "/proc");
4381 r
= mount_follow_verbose(LOG_ERR
, "proc", j
, "proc", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, NULL
);
4385 r
= mount_sysfs(directory
, arg_mount_settings
);
4389 r
= mount_switch_root(directory
, MS_SHARED
);
4391 return log_error_errno(r
, "Failed to move root directory: %m");
4394 r
= inner_child(barrier
, fd_inner_socket
, fds
, os_release_pairs
);
4396 _exit(EXIT_FAILURE
);
4398 _exit(EXIT_SUCCESS
);
4401 l
= send(fd_outer_socket
, &pid
, sizeof(pid
), MSG_NOSIGNAL
);
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.");
4408 l
= send(fd_outer_socket
, &arg_uuid
, sizeof(arg_uuid
), MSG_NOSIGNAL
);
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.");
4415 l
= send_one_fd(fd_outer_socket
, notify_fd
, 0);
4417 return log_error_errno(l
, "Failed to send notify fd: %m");
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
);
4426 static int uid_shift_pick(uid_t
*shift
, LockFile
*ret_lock_file
) {
4427 bool tried_hashed
= false;
4428 unsigned n_tries
= 100;
4433 assert(ret_lock_file
);
4434 assert(arg_userns_mode
== USER_NAMESPACE_PICK
);
4435 assert(arg_uid_range
== 0x10000U
);
4439 (void) mkdir("/run/systemd/nspawn-uid", 0755);
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
;
4448 if (candidate
< CONTAINER_UID_BASE_MIN
|| candidate
> CONTAINER_UID_BASE_MAX
)
4450 if ((candidate
& UINT32_C(0xFFFF)) != 0)
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 */
4460 /* Make some superficial checks whether the range is currently known in the user database */
4461 if (getpwuid_malloc(candidate
, /* ret= */ NULL
) >= 0)
4463 if (getpwuid_malloc(candidate
+ UINT32_C(0xFFFE), /* ret= */ NULL
) >= 0)
4465 if (getgrgid_malloc(candidate
, /* ret= */ NULL
) >= 0)
4467 if (getgrgid_malloc(candidate
+ UINT32_C(0xFFFE), /* ret= */ NULL
) >= 0)
4470 *ret_lock_file
= lf
;
4471 lf
= (struct LockFile
) LOCK_FILE_INIT
;
4476 if (arg_machine
&& !tried_hashed
) {
4477 /* Try to hash the base from the container name */
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
4484 candidate
= (uid_t
) siphash24(arg_machine
, strlen(arg_machine
), hash_key
);
4486 tried_hashed
= true;
4488 random_bytes(&candidate
, sizeof(candidate
));
4490 candidate
= (candidate
% (CONTAINER_UID_BASE_MAX
- CONTAINER_UID_BASE_MIN
)) + CONTAINER_UID_BASE_MIN
;
4491 candidate
&= (uid_t
) UINT32_C(0xFFFF0000);
4495 static int add_one_uid_map(
4497 uid_t container_uid
,
4501 return strextendf(p
,
4502 UID_FMT
" " UID_FMT
" " UID_FMT
"\n",
4503 container_uid
, host_uid
, range
);
4506 static int make_uid_map_string(
4507 const uid_t bind_user_uid
[],
4508 size_t n_bind_user_uid
,
4512 _cleanup_free_
char *s
= NULL
;
4513 uid_t previous_uid
= 0;
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 */
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. */
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];
4527 assert(previous_uid
<= payload_uid
);
4528 assert(payload_uid
< arg_uid_range
);
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
);
4537 /* Map this specific user */
4538 r
= add_one_uid_map(&s
, payload_uid
, host_uid
, 1);
4542 previous_uid
= payload_uid
+ 1;
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
);
4558 static int setup_uid_map(
4560 const uid_t bind_user_uid
[],
4561 size_t n_bind_user_uid
) {
4563 char uid_map
[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(uid_t
) + 1];
4564 _cleanup_free_
char *s
= NULL
;
4567 assert(pidref_is_set(pid
));
4568 assert(pid
->pid
> 1);
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 */
4574 xsprintf(uid_map
, "/proc/" PID_FMT
"/uid_map", pid
->pid
);
4575 r
= write_string_file(uid_map
, s
, WRITE_STRING_FILE_DISABLE_BUFFER
);
4577 return log_error_errno(r
, "Failed to write UID map: %m");
4579 /* And now build the GID map string */
4581 if (make_uid_map_string(bind_user_uid
, n_bind_user_uid
, 2, &s
) < 0) /* offset=2 contains the GID pair */
4584 xsprintf(uid_map
, "/proc/" PID_FMT
"/gid_map", pid
->pid
);
4585 r
= write_string_file(uid_map
, s
, WRITE_STRING_FILE_DISABLE_BUFFER
);
4587 return log_error_errno(r
, "Failed to write GID map: %m");
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
);
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
);
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.");
4611 if (DEBUG_LOGGING
) {
4612 _cleanup_free_
char *joined
= strv_join(tags
, " ");
4615 _cleanup_free_
char *j
= cescape(joined
);
4616 free_and_replace(joined
, j
);
4619 log_debug("Got sd_notify() message: %s", strnull(joined
));
4622 if (strv_contains(tags
, "READY=1")) {
4623 r
= sd_notify(false, "READY=1\n");
4625 log_warning_errno(r
, "Failed to send readiness notification, ignoring: %m");
4628 char *p
= strv_find_startswith(tags
, "STATUS=");
4630 (void) sd_notifyf(false, "STATUS=Container running: %s", p
);
4635 static int setup_notify_parent(sd_event
*event
, int fd
, PidRef
*inner_child_pid
, sd_event_source
**notify_event_source
) {
4641 r
= sd_event_add_io(event
, notify_event_source
, fd
, EPOLLIN
, nspawn_dispatch_notify_fd
, inner_child_pid
);
4643 return log_error_errno(r
, "Failed to allocate notify event source: %m");
4645 (void) sd_event_source_set_description(*notify_event_source
, "nspawn-notify");
4650 static int ptyfwd_hotkey(PTYForward
*f
, char c
, void *userdata
) {
4651 PidRef
*pid
= ASSERT_PTR(userdata
);
4669 log_info("Unknown hotkey sequence ^]^]%c, ignoring.", c
);
4673 r
= pidref_kill(pid
, sig
);
4675 log_error_errno(r
, "Failed to send %s (%s request) to PID 1 of container: %m", signal_to_string(sig
), word
);
4677 log_info("Sent %s (%s request) to PID 1 of container.", signal_to_string(sig
), word
);
4682 static int merge_settings(Settings
*settings
, const char *path
) {
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. */
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
);
4697 if ((arg_settings_mask
& SETTING_EPHEMERAL
) == 0 &&
4698 settings
->ephemeral
>= 0)
4699 arg_ephemeral
= settings
->ephemeral
;
4701 if ((arg_settings_mask
& SETTING_DIRECTORY
) == 0 &&
4704 if (!arg_settings_trusted
)
4705 log_warning("Ignoring root directory setting, file %s is not trusted.", path
);
4707 free_and_replace(arg_directory
, settings
->root
);
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
);
4716 if ((arg_settings_mask
& SETTING_WORKING_DIRECTORY
) == 0 &&
4717 settings
->working_directory
)
4718 free_and_replace(arg_chdir
, settings
->working_directory
);
4720 if ((arg_settings_mask
& SETTING_ENVIRONMENT
) == 0 &&
4721 settings
->environment
)
4722 strv_free_and_replace(arg_setenv
, settings
->environment
);
4724 if ((arg_settings_mask
& SETTING_USER
) == 0) {
4727 free_and_replace(arg_user
, settings
->user
);
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
;
4739 if ((arg_settings_mask
& SETTING_CAPABILITY
) == 0) {
4740 uint64_t plus
, minus
;
4741 uint64_t network_minus
= 0;
4744 /* Note that we copy both the simple plus/minus caps here, and the full quintet from the
4745 * Settings structure */
4747 plus
= settings
->capability
;
4748 minus
= settings
->drop_capability
;
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
;
4755 network_minus
|= UINT64_C(1) << CAP_NET_ADMIN
;
4758 if (!arg_settings_trusted
&& plus
!= 0) {
4759 if (settings
->capability
!= 0)
4760 log_warning("Ignoring Capability= setting, file %s is not trusted.", path
);
4762 arg_caps_retain
&= ~network_minus
;
4763 arg_caps_retain
|= plus
;
4766 arg_caps_retain
&= ~minus
;
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
);
4773 arg_full_capabilities
= settings
->full_capabilities
;
4776 ambient
= settings
->ambient_capability
;
4777 if (!arg_settings_trusted
&& ambient
!= 0)
4778 log_warning("Ignoring AmbientCapability= setting, file %s is not trusted.", path
);
4780 arg_caps_ambient
|= ambient
;
4783 if ((arg_settings_mask
& SETTING_KILL_SIGNAL
) == 0 &&
4784 settings
->kill_signal
> 0)
4785 arg_kill_signal
= settings
->kill_signal
;
4787 if ((arg_settings_mask
& SETTING_PERSONALITY
) == 0 &&
4788 settings
->personality
!= PERSONALITY_INVALID
)
4789 arg_personality
= settings
->personality
;
4791 if ((arg_settings_mask
& SETTING_MACHINE_ID
) == 0 &&
4792 !sd_id128_is_null(settings
->machine_id
)) {
4794 if (!arg_settings_trusted
)
4795 log_warning("Ignoring MachineID= setting, file %s is not trusted.", path
);
4797 arg_uuid
= settings
->machine_id
;
4800 if ((arg_settings_mask
& SETTING_READ_ONLY
) == 0 &&
4801 settings
->read_only
>= 0)
4802 arg_read_only
= settings
->read_only
;
4804 if ((arg_settings_mask
& SETTING_VOLATILE_MODE
) == 0 &&
4805 settings
->volatile_mode
!= _VOLATILE_MODE_INVALID
)
4806 arg_volatile_mode
= settings
->volatile_mode
;
4808 if ((arg_settings_mask
& SETTING_CUSTOM_MOUNTS
) == 0 &&
4809 settings
->n_custom_mounts
> 0) {
4811 if (!arg_settings_trusted
)
4812 log_warning("Ignoring TemporaryFileSystem=, Bind= and BindReadOnly= settings, file %s is not trusted.", path
);
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;
4821 if ((arg_settings_mask
& SETTING_NETWORK
) == 0 &&
4822 settings_network_configured(settings
)) {
4824 if (!arg_settings_trusted
)
4825 log_warning("Ignoring network settings, file %s is not trusted.", path
);
4827 arg_network_veth
= settings_network_veth(settings
);
4828 arg_private_network
= settings_private_network(settings
);
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
);
4835 free_and_replace(arg_network_bridge
, settings
->network_bridge
);
4836 free_and_replace(arg_network_zone
, settings
->network_zone
);
4838 free_and_replace(arg_network_namespace_path
, settings
->network_namespace_path
);
4842 if ((arg_settings_mask
& SETTING_EXPOSE_PORTS
) == 0 &&
4843 settings
->expose_ports
) {
4845 if (!arg_settings_trusted
)
4846 log_warning("Ignoring Port= setting, file %s is not trusted.", path
);
4848 expose_port_free_all(arg_expose_ports
);
4849 arg_expose_ports
= TAKE_PTR(settings
->expose_ports
);
4853 if ((arg_settings_mask
& SETTING_USERNS
) == 0 &&
4854 settings
->userns_mode
!= _USER_NAMESPACE_MODE_INVALID
) {
4856 if (!arg_settings_trusted
)
4857 log_warning("Ignoring PrivateUsers= and PrivateUsersChown= settings, file %s is not trusted.", path
);
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
;
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
);
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
;
4876 if ((arg_settings_mask
& SETTING_NOTIFY_READY
) == 0 &&
4877 settings
->notify_ready
>= 0)
4878 arg_notify_ready
= settings
->notify_ready
;
4880 if ((arg_settings_mask
& SETTING_SYSCALL_FILTER
) == 0) {
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
);
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
);
4892 if (settings
->seccomp
) {
4893 if (!arg_settings_trusted
)
4894 log_warning("Ignoring SECCOMP filter, file %s is not trusted.", path
);
4896 seccomp_release(arg_seccomp
);
4897 arg_seccomp
= TAKE_PTR(settings
->seccomp
);
4903 for (rl
= 0; rl
< _RLIMIT_MAX
; rl
++) {
4904 if ((arg_settings_mask
& (SETTING_RLIMIT_FIRST
<< rl
)))
4907 if (!settings
->rlimit
[rl
])
4910 if (!arg_settings_trusted
) {
4911 log_warning("Ignoring Limit%s= setting, file '%s' is not trusted.", rlimit_to_string(rl
), path
);
4915 free_and_replace(arg_rlimit
[rl
], settings
->rlimit
[rl
]);
4918 if ((arg_settings_mask
& SETTING_HOSTNAME
) == 0 &&
4920 free_and_replace(arg_hostname
, settings
->hostname
);
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
;
4926 if ((arg_settings_mask
& SETTING_OOM_SCORE_ADJUST
) == 0 &&
4927 settings
->oom_score_adjust_set
) {
4929 if (!arg_settings_trusted
)
4930 log_warning("Ignoring OOMScoreAdjust= setting, file '%s' is not trusted.", path
);
4932 arg_oom_score_adjust
= settings
->oom_score_adjust
;
4933 arg_oom_score_adjust_set
= true;
4937 if ((arg_settings_mask
& SETTING_CPU_AFFINITY
) == 0 &&
4938 settings
->cpu_set
.set
) {
4940 if (!arg_settings_trusted
)
4941 log_warning("Ignoring CPUAffinity= setting, file '%s' is not trusted.", path
);
4943 cpu_set_done_and_replace(arg_cpu_set
, settings
->cpu_set
);
4946 if ((arg_settings_mask
& SETTING_RESOLV_CONF
) == 0 &&
4947 settings
->resolv_conf
!= _RESOLV_CONF_MODE_INVALID
)
4948 arg_resolv_conf
= settings
->resolv_conf
;
4950 if ((arg_settings_mask
& SETTING_LINK_JOURNAL
) == 0 &&
4951 settings
->link_journal
!= _LINK_JOURNAL_INVALID
) {
4953 if (!arg_settings_trusted
)
4954 log_warning("Ignoring journal link setting, file '%s' is not trusted.", path
);
4956 arg_link_journal
= settings
->link_journal
;
4957 arg_link_journal_try
= settings
->link_journal_try
;
4961 if ((arg_settings_mask
& SETTING_TIMEZONE
) == 0 &&
4962 settings
->timezone
!= _TIMEZONE_MODE_INVALID
)
4963 arg_timezone
= settings
->timezone
;
4965 if ((arg_settings_mask
& SETTING_SLICE
) == 0 &&
4968 if (!arg_settings_trusted
)
4969 log_warning("Ignoring slice setting, file '%s' is not trusted.", path
);
4971 free_and_replace(arg_slice
, settings
->slice
);
4974 if ((arg_settings_mask
& SETTING_USE_CGNS
) == 0 &&
4975 settings
->use_cgns
>= 0) {
4977 if (!arg_settings_trusted
)
4978 log_warning("Ignoring cgroup namespace setting, file '%s' is not trusted.", path
);
4980 arg_use_cgns
= settings
->use_cgns
;
4983 if ((arg_settings_mask
& SETTING_CLONE_NS_FLAGS
) == 0 &&
4984 settings
->clone_ns_flags
!= ULONG_MAX
) {
4986 if (!arg_settings_trusted
)
4987 log_warning("Ignoring namespace setting, file '%s' is not trusted.", path
);
4989 arg_clone_ns_flags
= settings
->clone_ns_flags
;
4992 if ((arg_settings_mask
& SETTING_CONSOLE_MODE
) == 0 &&
4993 settings
->console_mode
>= 0) {
4995 if (!arg_settings_trusted
)
4996 log_warning("Ignoring console mode setting, file '%s' is not trusted.", path
);
4998 arg_console_mode
= settings
->console_mode
;
5001 if ((arg_settings_mask
& SETTING_SUPPRESS_SYNC
) == 0 &&
5002 settings
->suppress_sync
>= 0)
5003 arg_suppress_sync
= settings
->suppress_sync
;
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. */
5008 sd_bus_message_unref(arg_property_message
);
5009 arg_property_message
= TAKE_PTR(settings
->properties
);
5011 arg_console_width
= settings
->console_width
;
5012 arg_console_height
= settings
->console_height
;
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;
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
;
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
))
5036 /* We first look in the admin's directories in /etc and /run */
5038 FOREACH_STRING(i
, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
5039 _cleanup_free_
char *j
= NULL
;
5041 j
= path_join(i
, arg_settings_filename
);
5049 /* By default, we trust configuration from /etc and /run */
5050 if (arg_settings_trusted
< 0)
5051 arg_settings_trusted
= true;
5056 if (errno
!= ENOENT
)
5057 return log_error_errno(errno
, "Failed to open %s: %m", j
);
5061 /* After that, let's look for a file next to the
5062 * actual image we shall boot. */
5065 r
= file_in_same_dir(arg_image
, arg_settings_filename
, &p
);
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");
5076 if (!f
&& errno
!= ENOENT
)
5077 return log_error_errno(errno
, "Failed to open %s: %m", p
);
5079 /* By default, we do not trust configuration from /var/lib/machines */
5080 if (arg_settings_trusted
< 0)
5081 arg_settings_trusted
= false;
5088 log_debug("Settings are trusted: %s", yes_no(arg_settings_trusted
));
5090 r
= settings_load(f
, p
, &settings
);
5094 return merge_settings(settings
, p
);
5097 static int load_oci_bundle(void) {
5098 _cleanup_(settings_freep
) Settings
*settings
= NULL
;
5101 if (!arg_oci_bundle
)
5104 /* By default let's trust OCI bundles */
5105 if (arg_settings_trusted
< 0)
5106 arg_settings_trusted
= true;
5108 r
= oci_load(NULL
, arg_oci_bundle
, &settings
);
5112 return merge_settings(settings
, arg_oci_bundle
);
5115 static int run_container(
5116 const char *directory
,
5118 DissectedImage
*dissected_image
,
5121 char veth_name
[IFNAMSIZ
],
5123 struct ExposeArgs
*expose_args
,
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
;
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;
5148 _cleanup_close_
int child_netns_fd
= -EBADF
;
5150 assert_se(sigemptyset(&mask_chld
) == 0);
5151 assert_se(sigaddset(&mask_chld
, SIGCHLD
) == 0);
5153 /* Set up the unix export host directory on the host first */
5154 r
= setup_unix_export_dir_outside(&unix_export_host_dir
);
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
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");
5171 r
= barrier_create(&barrier
);
5173 return log_error_errno(r
, "Cannot initialize IPC barrier: %m");
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");
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");
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
);
5185 return log_error_errno(errno
, "Failed to change the signal mask: %m");
5187 r
= sigaction(SIGCHLD
, &sigaction_nop_nocldstop
, NULL
);
5189 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
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
);
5196 r
= fd_is_namespace(child_netns_fd
, NAMESPACE_NET
);
5198 return log_error_errno(r
, "Failed to check %s fs type: %m", arg_network_namespace_path
);
5200 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
5201 "Path %s doesn't refer to a network namespace, refusing.", arg_network_namespace_path
);
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. */
5209 pid_t _pid
= raw_clone(SIGCHLD
|CLONE_NEWNS
);
5211 return log_error_errno(errno
, "clone() failed%s: %m",
5213 ", do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in)" : "");
5215 r
= pidref_set_pid(pid
, _pid
);
5217 return log_error_errno(r
, "Failed to allocate pidfd: %m");
5220 in_child
= _pid
== 0;
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 */
5226 pid_t _pid
= raw_clone(SIGCHLD
);
5228 return log_error_errno(errno
, "clone() failed: %m");
5231 r
= pidref_set_pid(pid
, _pid
);
5233 return log_error_errno(r
, "Failed to allocate pidfd: %m");
5236 in_child
= _pid
== 0;
5238 if (setns(userns_fd
, CLONE_NEWUSER
) < 0) {
5239 log_error_errno(errno
, "Failed to join allocate user namespace: %m");
5240 _exit(EXIT_FAILURE
);
5243 r
= reset_uid_gid();
5245 log_error_errno(r
, "Failed to reset UID/GID to root: %m");
5246 _exit(EXIT_FAILURE
);
5249 if (unshare(CLONE_NEWNS
) < 0) {
5250 log_error_errno(errno
, "Failed to unshare file system namespace: %m");
5251 _exit(EXIT_FAILURE
);
5257 /* The outer child only has a file system namespace. */
5258 barrier_set_role(&barrier
, BARRIER_CHILD
);
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]);
5263 (void) reset_all_signal_handlers();
5264 (void) reset_signal_mask();
5266 r
= outer_child(&barrier
,
5270 fd_outer_socket_pair
[1],
5271 fd_inner_socket_pair
[1],
5274 unix_export_host_dir
);
5276 _exit(EXIT_FAILURE
);
5278 _exit(EXIT_SUCCESS
);
5281 barrier_set_role(&barrier
, BARRIER_PARENT
);
5283 fdset_close(fds
, /* async= */ false);
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]);
5288 if (arg_userns_mode
!= USER_NAMESPACE_NO
) {
5289 mntns_fd
= receive_one_fd(fd_outer_socket_pair
[0], 0);
5291 return log_error_errno(mntns_fd
, "Failed to receive mount namespace fd from outer child: %m");
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);
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.");
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. */
5305 r
= uid_shift_pick(&arg_uid_shift
, &uid_shift_lock
);
5307 return log_error_errno(r
, "Failed to pick suitable UID/GID range: %m");
5309 l
= send(fd_outer_socket_pair
[0], &arg_uid_shift
, sizeof arg_uid_shift
, MSG_NOSIGNAL
);
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.");
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. */
5321 bind_user_uid
= new(uid_t
, n_bind_user_uid
*4);
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);
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.");
5337 /* Wait for the outer child. */
5338 r
= pidref_wait_for_terminate_and_check("(sd-namespace)", pid
, WAIT_LOG_ABNORMAL
);
5342 if (r
!= EXIT_SUCCESS
)
5345 /* And now retrieve the PID of the inner child. */
5347 l
= recv(fd_outer_socket_pair
[0], &_pid
, sizeof _pid
, 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.");
5353 r
= pidref_set_pid(pid
, _pid
);
5355 return log_error_errno(r
, "Failed to allocate pidfd: %m");
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);
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.");
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");
5370 log_debug("Init process invoked as PID "PID_FMT
, pid
->pid
);
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.");
5376 if (arg_userns_mode
!= USER_NAMESPACE_MANAGED
) {
5377 r
= setup_uid_map(pid
, bind_user_uid
, n_bind_user_uid
);
5382 (void) barrier_place(&barrier
); /* #2 */
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");
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");
5399 r
= move_network_interfaces(child_netns_fd
, arg_network_interfaces
);
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
);
5412 _cleanup_free_
char *host_ifname
= NULL
;
5414 r
= nsresource_add_netif_veth(userns_fd
, child_netns_fd
, /* namespace_ifname= */ NULL
, &host_ifname
, /* ret_namespace_ifname= */ NULL
);
5416 return log_error_errno(r
, "Failed to add network interface to container: %m");
5418 ifi
= if_nametoindex(host_ifname
);
5420 return log_error_errno(errno
, "Failed to resolve interface '%s': %m", host_ifname
);
5422 if (strlen(host_ifname
) >= IFNAMSIZ
)
5423 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Host interface name too long?");
5425 strcpy(veth_name
, host_ifname
);
5428 if (arg_network_bridge
) {
5429 /* Add the interface to a bridge */
5430 r
= setup_bridge(veth_name
, arg_network_bridge
, false);
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);
5445 r
= setup_veth_extra(arg_machine
, pid
, arg_network_veth_extra
);
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;
5455 r
= setup_macvlan(arg_machine
, pid
, arg_network_macvlan
);
5459 r
= setup_ipvlan(arg_machine
, pid
, arg_network_ipvlan
);
5464 if (arg_register
|| !arg_keep_unit
) {
5465 if (arg_privileged
|| arg_register
)
5466 r
= sd_bus_default_system(&bus
);
5468 r
= sd_bus_default_user(&bus
);
5470 return log_error_errno(r
, "Failed to open bus: %m");
5472 r
= sd_bus_set_close_on_exit(bus
, false);
5474 return log_error_errno(r
, "Failed to disable close-on-exit behaviour: %m");
5476 (void) sd_bus_set_allow_interactive_authorization(bus
, arg_ask_password
);
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. */
5484 r
= sd_bus_match_signal_async(
5487 "org.freedesktop.systemd1",
5489 "org.freedesktop.systemd1.Scope",
5495 return log_error_errno(r
, "Failed to request RequestStop match: %m");
5499 RegisterMachineFlags flags
= 0;
5500 SET_FLAG(flags
, REGISTER_MACHINE_KEEP_UNIT
, arg_keep_unit
);
5501 r
= register_machine(
5509 arg_custom_mounts
, arg_n_custom_mounts
,
5512 arg_property_message
,
5513 arg_container_service_name
,
5519 } else if (!arg_keep_unit
) {
5520 AllocateScopeFlags flags
= ALLOCATE_SCOPE_ALLOW_PIDFD
;
5526 arg_custom_mounts
, arg_n_custom_mounts
,
5529 arg_property_message
,
5535 } else if (arg_slice
|| arg_property
)
5536 log_notice("Machine and scope registration turned off, --slice= and --property= settings will have no effect.");
5538 r
= create_subcgroup(
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 */
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);
5555 /* Reset signal to default */
5556 r
= default_signals(SIGCHLD
);
5558 return log_error_errno(r
, "Failed to reset SIGCHLD: %m");
5560 r
= sd_event_new(&event
);
5562 return log_error_errno(r
, "Failed to get default event source: %m");
5564 (void) sd_event_set_watchdog(event
, true);
5567 r
= sd_bus_attach_event(bus
, event
, 0);
5569 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
5572 r
= setup_notify_parent(event
, notify_socket
, pid
, ¬ify_event_source
);
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.");
5581 if (!IN_SET(arg_userns_mode
, USER_NAMESPACE_NO
, USER_NAMESPACE_MANAGED
)) {
5582 r
= wipe_fully_visible_api_fs(mntns_fd
);
5585 mntns_fd
= safe_close(mntns_fd
);
5588 /* And now let the child know that we completed removing the procfs instances, and it can start the
5590 if (!barrier_place(&barrier
)) /* #5.2 */
5591 return log_error_errno(SYNTHETIC_ERRNO(ESRCH
), "Child died too early.");
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
);
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");
5603 log_warning_errno(r
, "Failed to send readiness notification, ignoring: %m");
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();
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. */
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
);
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
);
5625 (void) sd_event_add_signal(event
, NULL
, SIGRTMIN
+18, sigrtmin18_handler
, NULL
);
5627 r
= sd_event_add_memory_pressure(event
, NULL
, NULL
, NULL
);
5629 log_debug_errno(r
, "Failed allocate memory pressure event source, ignoring: %m");
5631 /* Exit when the child exits */
5632 (void) sd_event_add_signal(event
, NULL
, SIGCHLD
, on_sigchld
, pid
);
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");
5639 if (arg_expose_ports
) {
5640 r
= expose_port_watch_rtnl(event
, fd_inner_socket_pair
[0], on_address_change
, expose_args
, &rtnl
);
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
);
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
);
5655 if (arg_console_mode
!= CONSOLE_PIPE
) {
5656 _cleanup_close_
int fd
= -EBADF
;
5657 PTYForwardFlags flags
= 0;
5659 /* Retrieve the master pty allocated by inner child */
5660 fd
= receive_one_fd(fd_inner_socket_pair
[0], 0);
5662 return log_error_errno(fd
, "Failed to receive master pty from the inner child: %m");
5664 switch (arg_console_mode
) {
5666 case CONSOLE_READ_ONLY
:
5667 flags
|= PTY_FORWARD_READ_ONLY
;
5671 case CONSOLE_INTERACTIVE
:
5672 flags
|= PTY_FORWARD_IGNORE_VHANGUP
;
5674 r
= pty_forward_new(event
, fd
, flags
, &forward
);
5676 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
5678 if (arg_console_width
!= UINT_MAX
|| arg_console_height
!= UINT_MAX
)
5679 (void) pty_forward_set_width_height(
5682 arg_console_height
);
5684 if (!arg_background
&& shall_tint_background()) {
5685 _cleanup_free_
char *bg
= NULL
;
5687 r
= terminal_tint_color(220 /* blue */, &bg
);
5689 log_debug_errno(r
, "Failed to determine terminal background color, not tinting.");
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
);
5695 (void) pty_forward_set_window_title(forward
, GLYPH_BLUE_CIRCLE
, /* hostname = */ NULL
,
5696 STRV_MAKE("Container", arg_machine
));
5698 pty_forward_set_hotkey_handler(forward
, ptyfwd_hotkey
, pid
);
5702 assert(arg_console_mode
== CONSOLE_PASSIVE
);
5705 *master
= TAKE_FD(fd
);
5708 fd_inner_socket_pair
[0] = safe_close(fd_inner_socket_pair
[0]);
5710 r
= sd_event_loop(event
);
5712 return log_error_errno(r
, "Failed to run event loop: %m");
5714 /* Kill if it is not dead yet anyway */
5715 if (!arg_register
&& !arg_keep_unit
&& bus
)
5716 terminate_scope(bus
, arg_machine
);
5718 /* Normally redundant, but better safe than sorry */
5719 (void) pidref_kill(pid
, SIGKILL
);
5721 fd_kmsg_fifo
= safe_close(fd_kmsg_fifo
);
5723 if (arg_private_network
&& arg_userns_mode
!= USER_NAMESPACE_MANAGED
) {
5724 r
= move_back_network_interfaces(child_netns_fd
, arg_network_interfaces
);
5728 r
= remove_macvlan(child_netns_fd
, arg_network_macvlan
);
5733 r
= wait_for_container(pid
, &container_status
);
5735 /* Tell machined that we are gone. */
5736 if (arg_register
&& bus
)
5737 (void) unregister_machine(bus
, arg_machine
);
5740 /* We failed to wait for the container, or the container exited abnormally. */
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.
5748 if (r
== EXIT_FORCE_RESTART
)
5749 r
= EXIT_FAILURE
; /* replace 133 with the general failure code */
5751 return 0; /* finito */
5754 /* CONTAINER_REBOOTED, loop again */
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 */
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
);
5770 (void) remove_veth_links(veth_name
, arg_network_veth_extra
);
5771 *veth_created
= false;
5772 return 1; /* loop again */
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. */
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
},
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. */
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
;
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. */
5815 r
= pid_getrlimit(1, rl
, &buffer
);
5817 return log_error_errno(r
, "Failed to read resource limit RLIMIT_%s of PID 1: %m", rlimit_to_string(rl
));
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
5826 buffer
= kernel_defaults
[rl
];
5827 buffer
.rlim_max
= MIN((rlim_t
) read_nr_open(), (rlim_t
) HIGH_RLIMIT_NOFILE
);
5830 v
= kernel_defaults
+ rl
;
5832 arg_rlimit
[rl
] = newdup(struct rlimit
, v
, 1);
5833 if (!arg_rlimit
[rl
])
5837 if (DEBUG_LOGGING
) {
5838 _cleanup_free_
char *k
= NULL
;
5840 (void) rlimit_format(arg_rlimit
[rl
], &k
);
5841 log_debug("Setting RLIMIT_%s to %s.", rlimit_to_string(rl
), k
);
5848 static int cant_be_in_netns(void) {
5849 _cleanup_close_
int fd
= -EBADF
;
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
5857 if (!arg_image
) /* only matters if --image= us used, i.e. we actually need to use loopback devices */
5860 fd
= socket(AF_UNIX
, SOCK_SEQPACKET
|SOCK_NONBLOCK
|SOCK_CLOEXEC
, 0);
5862 return log_error_errno(errno
, "Failed to allocate udev control socket: %m");
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.");
5873 return log_error_errno(r
, "Failed to connect socket to udev control socket: %m");
5875 r
= getpeercred(fd
, &ucred
);
5877 return log_error_errno(r
, "Failed to determine peer of udev control socket: %m");
5879 r
= in_same_namespace(ucred
.pid
, 0, NAMESPACE_NET
);
5881 return log_error_errno(r
, "Failed to determine network namespace of udev: %m");
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.");
5888 static void initialize_defaults(void) {
5889 arg_privileged
= getuid() == 0;
5891 /* If running unprivileged default to systemd-nsresourced operation */
5892 arg_userns_mode
= arg_privileged
? USER_NAMESPACE_NO
: USER_NAMESPACE_MANAGED
;
5894 /* Imply private networking for unprivileged operation, since kernel otherwise refuses mounting sysfs */
5895 arg_private_network
= !arg_privileged
;
5898 static void cleanup_propagation_and_export_directories(void) {
5901 if (!arg_machine
|| !arg_privileged
)
5904 p
= strjoina("/run/systemd/nspawn/propagate/", arg_machine
);
5905 (void) rm_rf(p
, REMOVE_ROOT
);
5907 p
= strjoina("/run/systemd/nspawn/unix-export/", arg_machine
);
5908 (void) umount2(p
, MNT_DETACH
|UMOUNT_NOFOLLOW
);
5912 static int do_cleanup(void) {
5916 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot specify --ephemeral with --cleanup.");
5918 r
= determine_names();
5922 cleanup_propagation_and_export_directories();
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
;
5942 initialize_defaults();
5944 r
= parse_argv(argc
, argv
);
5949 return do_cleanup();
5951 r
= cg_has_legacy();
5955 r
= log_error_errno(SYNTHETIC_ERRNO(EPROTO
),
5956 "Detected host uses legacy cgroup v1 hierarchy, refusing.");
5960 r
= cant_be_in_netns();
5964 r
= initialize_rlimits();
5968 r
= load_oci_bundle();
5976 r
= determine_names();
5980 r
= load_settings();
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
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
);
5990 r
= verify_arguments();
5994 r
= resolve_network_interface_names(arg_network_interfaces
);
5998 r
= verify_network_interfaces_initialized();
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
);
6007 r
= fdset_new_listen_fds(&fds
, /* unset = */ false);
6009 log_error_errno(r
, "Failed to collect file descriptors: %m");
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. */
6018 if (arg_console_mode
< 0)
6019 arg_console_mode
= isatty_safe(STDIN_FILENO
) && isatty_safe(STDOUT_FILENO
) ?
6020 CONSOLE_INTERACTIVE
: CONSOLE_READ_ONLY
;
6022 if (arg_console_mode
== CONSOLE_PIPE
) /* if we pass STDERR on to the container, don't add our own logs into it too */
6025 polkit_agent_open();
6027 if (arg_userns_mode
== USER_NAMESPACE_MANAGED
) {
6028 /* Let's allocate a 64K userns first, if managed mode is chosen */
6030 _cleanup_free_
char *userns_name
= NULL
;
6031 if (asprintf(&userns_name
, "nspawn-" PID_FMT
"-%s", getpid_cached(), arg_machine
) < 0) {
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");
6042 r
= userns_get_base_uid(userns_fd
, &arg_uid_shift
, /* ret_gid= */ NULL
);
6044 log_error_errno(r
, "Failed to determine UID shift from userns: %m");
6048 arg_uid_range
= UINT32_C(0x10000);
6051 if (arg_directory
) {
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.");
6064 if (arg_ephemeral
) {
6065 _cleanup_free_
char *np
= NULL
;
6067 r
= chase_and_update(&arg_directory
, 0);
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
);
6076 log_error_errno(r
, "Failed to determine whether directory %s is mount point: %m", arg_directory
);
6080 r
= tempfn_random_child(arg_directory
, "machine.", &np
);
6082 r
= tempfn_random(arg_directory
, "machine.", &np
);
6084 log_error_errno(r
, "Failed to generate name for directory snapshot: %m");
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(
6093 arg_privileged
? &tree_global_lock
: NULL
,
6096 log_error_errno(r
, "Failed to lock %s: %m", np
);
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
);
6111 log_error_errno(r
, "Interrupted while copying file system tree to %s, removed again.", np
);
6115 log_error_errno(r
, "Failed to create snapshot %s from %s: %m", np
, arg_directory
);
6119 free_and_replace(arg_directory
, np
);
6120 remove_directory
= true;
6122 r
= chase_and_update(&arg_directory
, arg_template
? CHASE_NONEXISTENT
: 0);
6126 r
= image_path_lock(
6128 (arg_read_only
? LOCK_SH
: LOCK_EX
) | LOCK_NB
,
6129 arg_privileged
? &tree_global_lock
: NULL
,
6132 log_error_errno(r
, "Directory tree %s is currently busy.", arg_directory
);
6136 log_error_errno(r
, "Failed to lock %s: %m", arg_directory
);
6141 r
= chase_and_update(&arg_template
, 0);
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
);
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
);
6163 log_error_errno(r
, "Couldn't create snapshot %s from %s: %m", arg_directory
, arg_template
);
6166 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
,
6167 "Populated %s from template %s.", arg_directory
, arg_template
);
6171 if (arg_start_mode
== START_BOOT
) {
6172 _cleanup_free_
char *b
= NULL
;
6174 int check_os_release
, is_os_tree
;
6176 if (arg_pivot_root_new
) {
6177 b
= path_join(arg_directory
, arg_pivot_root_new
);
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");
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
);
6202 _cleanup_free_
char *p
= NULL
;
6204 if (arg_pivot_root_new
)
6205 p
= path_join(arg_directory
, arg_pivot_root_new
, "/usr/");
6207 p
= path_join(arg_directory
, "/usr/");
6213 r
= access_nofollow(p
, F_OK
);
6215 log_error_errno(r
, "Directory %s doesn't look like it has an OS tree (/usr/ directory is missing). Refusing.", arg_directory
);
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
);
6223 if (arg_userns_mode
== USER_NAMESPACE_MANAGED
) {
6224 r
= mountfsd_mount_directory(
6227 determine_dissect_image_flags(),
6233 DissectImageFlags dissect_image_flags
=
6234 determine_dissect_image_flags();
6237 assert(!arg_template
);
6239 r
= chase_and_update(&arg_image
, 0);
6243 if (arg_ephemeral
) {
6244 _cleanup_free_
char *np
= NULL
;
6246 r
= tempfn_random(arg_image
, "machine.", &np
);
6248 log_error_errno(r
, "Failed to generate name for image snapshot: %m");
6252 /* Always take an exclusive lock on our own ephemeral copy. */
6253 r
= image_path_lock(
6256 arg_privileged
? &tree_global_lock
: NULL
,
6259 log_error_errno(r
, "Failed to create image lock: %m");
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
);
6269 log_error_errno(r
, "Interrupted while copying image file to %s, removed again.", np
);
6273 r
= log_error_errno(r
, "Failed to copy image file: %m");
6277 free_and_replace(arg_image
, np
);
6278 remove_image
= true;
6280 r
= image_path_lock(
6282 (arg_read_only
? LOCK_SH
: LOCK_EX
) | LOCK_NB
,
6283 arg_privileged
? &tree_global_lock
: NULL
,
6286 log_error_errno(r
, "Disk image %s is currently busy.", arg_image
);
6290 log_error_errno(r
, "Failed to create image lock: %m");
6294 r
= verity_settings_load(
6295 &arg_verity_settings
,
6296 arg_image
, NULL
, NULL
);
6298 log_error_errno(r
, "Failed to read verity artefacts for %s: %m", arg_image
);
6302 if (arg_verity_settings
.data_path
)
6303 dissect_image_flags
|= DISSECT_IMAGE_NO_PARTITION_TABLE
;
6306 if (arg_userns_mode
!= USER_NAMESPACE_MANAGED
) {
6307 r
= loop_device_make_by_path(
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
,
6315 log_error_errno(r
, "Failed to set up loopback block device: %m");
6319 r
= dissect_loop_device_and_warn(
6321 &arg_verity_settings
,
6322 /* mount_options= */ NULL
,
6323 arg_image_policy
?: &image_policy_container
,
6324 /* image_filter= */ NULL
,
6325 dissect_image_flags
,
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.");
6340 r
= dissected_image_load_verity_sig_partition(
6343 &arg_verity_settings
);
6345 log_error_errno(r
, "Failed to load Verity signature partition: %m");
6349 r
= dissected_image_guess_verity_roothash(
6351 &arg_verity_settings
);
6353 log_error_errno(r
, "Failed to guess Verity root hash: %m");
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
);
6361 r
= dissected_image_decrypt_interactively(
6364 &arg_verity_settings
,
6365 dissect_image_flags
);
6369 r
= mountfsd_mount_image(
6373 dissect_image_flags
,
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;
6383 if (arg_architecture
< 0)
6384 arg_architecture
= dissected_image_architecture(dissected_image
);
6387 /* Create a temporary place to mount stuff. */
6388 r
= mkdtemp_malloc("/tmp/nspawn-root-XXXXXX", &rootdir
);
6390 log_error_errno(r
, "Failed to create temporary directory: %m");
6394 r
= custom_mount_prepare_all(rootdir
, arg_custom_mounts
, arg_n_custom_mounts
);
6399 const char *t
= arg_image
?: arg_directory
;
6400 _cleanup_free_
char *u
= NULL
;
6401 (void) terminal_urlify_path(t
, t
, &u
);
6403 log_info("%s %sSpawning container %s on %s.%s",
6404 glyph(GLYPH_LIGHT_SHADE
), ansi_grey(), arg_machine
, u
?: t
, ansi_normal());
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());
6413 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGCHLD
, SIGWINCH
, SIGTERM
, SIGINT
, SIGRTMIN
+18) >= 0);
6415 r
= make_reaper_process(true);
6417 log_error_errno(r
, "Failed to become subreaper: %m");
6421 if (arg_expose_ports
) {
6422 r
= fw_ctx_new(&fw_ctx
);
6424 log_error_errno(r
, "Cannot expose configured ports, firewall initialization failed: %m");
6427 expose_args
.fw_ctx
= fw_ctx
;
6437 veth_name
, &veth_created
,
6438 &expose_args
, &master
,
6445 (void) sd_notify(false,
6446 r
== 0 && ret
== EXIT_FORCE_RESTART
? "STOPPING=1\nSTATUS=Restarting..." :
6447 "STOPPING=1\nSTATUS=Terminating...");
6449 if (pidref_is_set(&pid
))
6450 (void) pidref_kill(&pid
, SIGKILL
);
6452 /* Try to flush whatever is still queued in the pty */
6454 (void) copy_bytes(master
, STDOUT_FILENO
, UINT64_MAX
, 0);
6455 master
= safe_close(master
);
6458 if (pidref_is_set(&pid
)) {
6459 (void) pidref_wait_for_terminate(&pid
, NULL
);
6465 if (remove_directory
&& arg_directory
) {
6468 k
= rm_rf(arg_directory
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_SUBVOLUME
);
6470 log_warning_errno(k
, "Cannot remove '%s', ignoring: %m", arg_directory
);
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
);
6478 if (arg_machine
&& arg_userns_mode
!= USER_NAMESPACE_MANAGED
) {
6481 p
= strjoina("/run/systemd/nspawn/propagate/", arg_machine
);
6482 (void) rm_rf(p
, REMOVE_ROOT
);
6484 p
= strjoina("/run/systemd/nspawn/unix-export/", arg_machine
);
6485 (void) umount2(p
, MNT_DETACH
|UMOUNT_NOFOLLOW
);
6489 cleanup_propagation_and_export_directories();
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
);
6494 if (arg_userns_mode
!= USER_NAMESPACE_MANAGED
) {
6496 (void) remove_veth_links(veth_name
, arg_network_veth_extra
);
6497 (void) remove_bridge(arg_network_zone
);
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
);
6511 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);