alloc-util: make malloc_sizeof_safe() compatible with clang's _FORTIFY_SOURCE=3
Turns out that clang's interprocedural analysis is quite smart and can
look through our expand_to_usable() trick, which then causes crashes
with _FORTIFY_SOURCE=3.
clang's interprocedural analysis can see that expand_to_usable() simply
returns its first argument, so it replaces all uses of the return value
with that argument (the original realloc() result). This effectively
bypasses expand_to_usable()'s alloc_size attribute, causing the fortify
check to use the (smaller) size from realloc() instead, which eventually
leads to a false-positive buffer overflow:
This is not an issue with gcc (at least not yet), since gcc sees
expand_to_usable() as an opaque user-defined allocation-like function
and simply trusts the alloc_size attribute that comes with it.
To fix this, let's add a simple no-op barrier to malloc_sizeof_safe()
that clobbers the input pointer, which causes
__builtin_dynamic_object_size() to return (size_t)-1 - this is
interpreted as an "unknown" size by the following fortify check which is
then skipped instead of triggering the assertion.
Similarly, test-alloc-util now doesn't call malloc_usable_size()
directly but instead goes through malloc_sizeof_safe(), so it's also
guarded by the barrier.
This follows the already established pile of similar workaround for the
same class of issues we encountered with gcc, namely [0], which prompted
[1], that was later reverted in [2], and then followed by another couple
of fixes in [3] and [4].
Eric Curtin [Tue, 28 Jul 2026 13:27:15 +0000 (14:27 +0100)]
shared/switch-root: sync only file systems becoming unreachable, not everything
switch_root() calls a blanket sync() before detaching the old root
file system, in order to make sure it is in a good state before it
becomes unreachable via MNT_DETACH/pivot_root().
A global sync() however flushes out *every* mounted file system on
the system, not just the ones we are actually about to detach. On
real-world systems that commonly have several additional mounted file
systems (separate /home, /var, additional data partitions, network
shares, removable media, ...) this needlessly delays switch_root() with
completely unrelated I/O. This matters in particular for
initrd-switch-root.service, which runs this code on the critical path
of pretty much every single boot with an initrd, and for soft-reboot.
Replace the global sync() with a new sync_departing_file_systems()
helper that walks /proc/self/mountinfo and calls syncfs() on every
file system except:
- 'new_root' and anything mounted below it: these remain mounted
and reachable after the transition and keep being synced normally
as part of their regular life cycle, so they don't need to be
force-flushed here.
- API/pseudo file systems (proc, sysfs, cgroupfs, autofs, ...),
network file systems, and overlayfs (which has no backing store
of its own), as determined by the new fstype_is_worth_syncing()
predicate. There is nothing meaningful to flush on any of these,
and more importantly, opening an untriggered autofs mount point
would needlessly trigger it, and opening a stale network mount
could block for a long time - exactly what we are trying to avoid
on this code path.
- Any flavour of FUSE (plain 'fuse', 'fuseblk', or a
'fuse.<subtype>', e.g. sshfs, rclone, gvfs, ntfs-3g, exfat-fuse,
...), classified via the new fstype_is_fuse() predicate in
src/basic/mountpoint-util.c, plus a few other, non-FUSE guest/host
file sharing file systems with the same "backed by a companion
daemon/hypervisor that could be wedged" risk profile (virtiofs,
vboxsf, vmhgfs). All I/O against any of these, including the
syncfs() we'd otherwise issue, is routed through an arbitrary
userspace daemon (or, for virtiofs/vboxsf/vmhgfs, the host/
hypervisor side), which could hang indefinitely if wedged, dead,
or otherwise unresponsive - there's no timeout on this code path.
'fuseblk' might sound exempt given the name, and does wrap an
actual block device, but that doesn't bound its syncfs() latency
by the kernel block layer alone the way a native block device
file system's is: the request is still serviced by the same FUSE
daemon as any other FUSE variant, and can hang exactly the same
way, so it is excluded here too, trading its comparatively minor
data-safety benefit for avoiding that unbounded hang risk.
'9p' (which can be used with a writeback cache and hence carry
real dirty data, e.g. common in QEMU/KVM guests) and the
shared-storage cluster file systems 'gfs', 'gfs2' and 'ocfs2'
(which fstype_is_network() also happens to classify as "network"
file systems, since they additionally rely on a networked
distributed lock manager for coordination) are deliberately *not*
excluded: unlike FUSE/virtiofs/etc., these are serviced by a
mature, in-kernel client (talking directly to the hypervisor over
a bounded virtio transport, or to real - if shared - block
storage), not an arbitrary, potentially wedged userspace daemon,
so they carry the same bounded, local sync latency any other
block device backed file system already does here. Skipping them
would needlessly sacrifice the data-safety guarantee the original
blanket sync() gave them, without meaningfully improving safety.
- Mount table entries that we can positively confirm are currently
shadowed by another mount stacked on top of them at the same
path: since we can only reach a file system by (re-)opening its
target path, and that always resolves to whatever is currently on
top, syncing by path alone could end up flushing the wrong
superblock. Detect this via the new shared
libmount_fs_id_matches_path() helper (factored out of, and now
also used by, the pre-existing get_sub_mounts(), which needed the
exact same check for the same reason). This same check is also
applied to a mountinfo entry whose target is 'new_root' itself
(not just anything strictly below it): comparing its mount ID
against new_root's own, freshly determined mount ID tells apart
the file system that is actually still reachable there (which we
continue to skip) from a stale entry that merely shares the exact
same path (e.g. if new_root wasn't already its own mount point
and got bind-mounted onto itself earlier in switch_root()), which
is departing just the same and must not be skipped just because
of that coincidence.
Every failure mode that means we can no longer be sure we've covered
every departing file system correctly - libmount being unavailable,
/proc/self/mountinfo (or a specific entry in it) failing to parse,
being unable to tell whether a specific entry is currently shadowed,
or syncfs_path() itself failing for an otherwise-eligible entry - is
handled the exact same way: propagate the error up and let the sole
caller, switch_root(), fall back to one plain, global sync() to cover
everything, rather than deciding on and performing that fallback (or,
worse, silently skipping the affected file system without any
fallback at all) at each of these different spots individually. This
should be rare in practice, so it doesn't meaningfully undercut the
benefit of the targeted sync in the common case.
Everything else that's actually about to become unreachable (the old
root itself, but also any other, unrelated real file system that
happens to be mounted underneath it and gets detached along with it)
is still synced, so this keeps the same safety guarantee the original
blanket sync() gave for file systems that actually do go away here.
Uses the existing syncfs_path() helper for the actual open+syncfs.
sync_departing_file_systems() itself returns -EOPNOTSUPP if libmount
support isn't compiled in, handled the same way by switch_root() as
any of its other error returns.
Note we intentionally don't use O_PATH file descriptors here: syncfs()
requires a 'real' file descriptor and fails with EBADF on O_PATH ones.
Also note there remains an inherent, narrow TOCTOU race between the
mount-ID check described above and the open() syncfs_path() performs
right after it: if something else mounts something new on top of a
given 'path' in between, that open() could still end up triggering an
automount, or hanging on a stale mount, since there is no open()/
openat() equivalent of statx()'s AT_NO_AUTOMOUNT to prevent this for a
"real" (non-O_PATH) file descriptor. Unlike the other failure modes
handled here, a hanging open() can't be recovered from by falling back
to sync() afterwards, since control never returns to do so. Closing
this fully would require disproportionate effort (e.g. performing the
open() in a separate, killable/timeout-bounded process) for a window
that is already narrow, since this code only runs with most other
activity on the system already quiesced during the switch_root()
transition itself, so it is accepted as-is (see the comment at the
call site for details).
This mirrors the same reasoning already applied to the shutdown path
in src/shutdown/shutdown.c, which deliberately avoids a 'dumb' sync()
there for identical reasons.
core: postpone dbus queue dispatch while API bus setup is pending (#43200)
Since 1166f4472d7669c8008c158a178dd6f76b601fe1 the API bus setup
and the subscriber coldplug happen only once the asynchronous GetId
reply is processed by the event loop. After a daemon-reexec,
manager_dispatch_dbus_queue() runs before subscribers were registered
and consumed send_reloading_done, so the one-shot Reloading(false)
signal was never sent.
Clients that wait for this signal to detect that a reexec finished time out.
Track the pending setup and hold the flag until the reply handler has
re-added the subscriptions.
Check that the manager broadcasts Reloading(true/false) on the API bus
for daemon-reload, and the one-shot Reloading(false) after a
daemon-reexec, which requires the subscribers of the previous instance
to be coldplugged before the D-Bus queue is dispatched.
core: postpone D-Bus queue dispatch until the API bus is set up
Since 1166f4472d ("core/dbus: do not block the manager on GetId during
bus (re-)connection") the API bus setup and the subscriber coldplug
happen only once the asynchronous GetId reply is processed by the
event loop. After a daemon-reexec, manager_dispatch_dbus_queue() runs
before subscribers were re-added, so bus_foreach_bus() skipped the
API bus and queued messages were lost for subscribers. In particular
the one-shot Reloading(false) signal was never sent, and clients that
wait for it to detect that a reexec finished timed out.
Track whether bus_setup_api() has run for the current API bus
connection, and postpone dispatching the queue until then.
Paul Meyer [Wed, 29 Jul 2026 05:21:08 +0000 (07:21 +0200)]
cryptsetup: measure volume key and keyslot via the pcrextend Varlink service (#43109)
Motivated by
https://github.com/systemd/systemd/pull/43041#discussion_r3595022610.
Switch systemd-cryptsetup's volume-key and keyslot measurements from
driving the TPM directly (tpm2-util) to the io.systemd.PCRExtend Varlink
service, aligning it with how the verity and imds measurements already
work.
Some notes on decisions taken:
- The volume key is sent over the wire. systemd-pcrextend will do the
hmac. The socket is root only. Otherwise we would need to do bank
negotiation via varlink and pollute the interface with it.
- `tpm2-measure-bank=` deprecated/dropped. Same reason as above.
- `tpm2-device=` now only affects unlocking. The device for measurements
is selected by pcrextend.
- Measuring requires the presence of `systemd-pcrextend.socket` in the
initrd, should be already given as systemd-veritysetup relies on it,
too.
- Logs are done on the pcrextend side.
Eric Curtin [Wed, 29 Jul 2026 02:46:05 +0000 (03:46 +0100)]
test-bpf-restrict-fs: skip if manager startup fails due to lack of privileges (#43202)
test-bpf-restrict-fs.c creates a Manager with RUNTIME_SCOPE_SYSTEM, which
tries to set up the real system runtime directory hierarchy (e.g. create
/run/systemd/), and that requires privileges the test process may not
have (e.g. unprivileged sandboxed builders such as OBS).
Previously this was masked because bpf_restrict_fs_supported() did a
trial open/load/attach of the BPF program itself, which also requires
elevated privileges and so failed first, causing the test to skip
before ever reaching manager_new()/manager_startup(). Since
bpf_restrict_fs_supported() no longer does that trial load, the test
now reaches manager_new()/manager_startup() in these unprivileged
environments and hard-fails instead of skipping, e.g.:
Assertion failed: Expected "manager_startup(m, NULL, NULL, NULL, NULL)"
to succeed, but got error: -13/EACCES
Use the same manager_errno_skip_test() pattern already used by other
tests (test-engine.c, test-execute.c, test-path.c, ...) to skip
gracefully when manager_new() or manager_startup() fail due to missing
privileges, instead of asserting.
Markus Boehme [Wed, 29 Jul 2026 02:41:17 +0000 (04:41 +0200)]
update-utmp: shorten comm on boot/shutdown
audit_log_user_comm_message from libaudit 4.2 rejects comm arguments
that exceed the kernel's comm limit of 15 characters with EINVAL. The
hard-coded "systemd-update-utmp" exceeds this by 4 characters. Shorten
it to "update-utmp" instead.
Paul Meyer [Wed, 22 Jul 2026 06:28:53 +0000 (08:28 +0200)]
cryptsetup: measure via the pcrextend varlink service
Measure the volume key and unlock keyslot through io.systemd.PCRExtend
instead of driving the TPM directly via tpm2-util, matching how the
verity and imds measurements already work.
Bank selection and the TPM context now live entirely in
systemd-pcrextend. As a result the tpm2-measure-bank= crypttab option
can no longer be honored per volume and is now a deprecated no-op.
network: document that Domains= may be specified more than once (#43194)
The `Domains=` option in the `[Network]` section did not document its
behaviour when specified repeatedly. In practice the option is additive
(each occurrence accumulates search/routing domains) and assigning an
empty string resets the list, matching the closely related `DNS=`
option. This is implemented by `config_parse_domains()` in
`src/network/networkd-dns.c`, which frees both the search and route
domain sets on an empty `rvalue` and otherwise inserts each
whitespace-separated entry into the corresponding set.
Document this explicitly, using the same wording already used for
`DNS=` in the same man page, so users know repeated assignments are
combined and that an empty value clears them.
Eric Curtin [Mon, 27 Jul 2026 10:42:37 +0000 (11:42 +0100)]
core/bpf-restrict-fs: avoid loading the LSM BPF program twice at boot
bpf_restrict_fs_setup() is always called right after a successful
bpf_restrict_fs_supported(true) probe (see manager_setup() in
manager.c). Previously the probe independently opened, sized and
kernel-verifier-loaded the BPF object via prepare_restrict_fs_bpf(),
then did a trial LSM attach/detach via bpf_can_link_lsm_program() to
confirm the program *could* attach, and threw the whole object away
-- only for bpf_restrict_fs_setup() to build and verifier-load an
identical one from scratch again for the real, permanent attach.
The trial attach in the probe is redundant: if BPF_LSM_MAC attach
isn't actually usable (e.g. no BPF trampoline support on the running
architecture/kernel), bpf_restrict_fs_setup()'s own
sym_bpf_program__attach_lsm() call will simply fail, and that failure
is already logged and handled gracefully by its caller in manager.c
(logged as a warning, systemd continues without RestrictFileSystems=
enforcement). So bpf_restrict_fs_supported() only needs to check
whether the BPF LSM hook is enabled in the kernel at all
(lsm_supported("bpf")); it doesn't need to open/load/attach the BPF
program itself. Drop that from the probe, so the program is opened,
sized and verified by the kernel exactly once per boot instead of
twice.
Since the probe no longer verifies that the LSM BPF program can
actually attach, test-bpf-restrict-fs.c can no longer rely on
bpf_restrict_fs_supported(true) alone to skip on kernels/architectures
where the hook is listed but the real attach fails (e.g. missing BPF
trampoline support). Have the test also check m->restrict_fs after
manager_startup() and skip if the program never got attached, instead
of proceeding to hard-fail the enforcement assertions.
sysupdate: Change feature/component enablement and disablement (#43191)
- sysupdate: In the auto-enable service, don't enable all features
The auto-enable service should activate suggested components and
features but enabled all features which includes the default components
unsuggested features and any unsuggested features of the suggested
components. This is unexpected behavior and we rather want this service
to be limited to suggested features.
Switch the service flag to suggested and make the wording more explicit
in the man page. Also fix the wrong statement that it operates on
enabled components, it operates on all components, also explicitly
disabled ones.
- sysupdate: Change disabling with
--component-suggested/--feature-suggested
The disabling of features or components with the flag
--component-suggested/--feature-suggested didn't disable the suggested
ones but instead disabled all other ones. This is rather unintuitive due
to how the flags are named and also not really needed because the
intended reconciliation outcome can instead be done by first disabling
everything and then enabling the suggested ones again which is easier to
reason about. For components the tricky part is that they default to
enabled and thus it's better to have the disable/enable commands with
--component-suggested operate only on suggested ones instead of touching
others like "legacy" components that don't explicity say whether they
are enabled and suggested or not.
Make running disablement of components/features with
--component-suggested/--feature-suggested undo a previous enablement
with the same flags. Document how one can align the system to only use
suggested components/features and not anything else by doing it in two
steps, first disabling everything and then enabling suggested ones. This
also makes it clearer now that all components that are not explicitly
enabled nor suggested will be disabled then.
Nick Rosbrook [Wed, 8 Jul 2026 13:15:37 +0000 (09:15 -0400)]
meson: add build option for /var/log mode
In Ubuntu, rsyslog is (a) part of the minimal image and (b) does not run
as root. To facilitate this, the rsyslog package configures /var/log
to be writeable by the syslog group.
There are currently conflicts in the Ubuntu packaging due to the way
tmpfiles are handled in package scripts: when systemd-tmpfiles is
invoked with both configurations (or for all configurations), things
work fine. But if invoked with only var.conf, which is the default case
for package upgrades, rsyslog is broken.
One suggestion to approach this was to make rsyslog's tmpfile
configuration use ACLs instead of trying to change the owning group and
directory mode. This can work, but since the ACL mask is stored in the
group permission bits, the effective mask for rsyslog becomes r-x again
when var.conf is invoked, because it sees that 0775 != 0755, and chmods
the directory.
Hence, for /var/log write permisssions to be extendable with ACLs,
the mode must be at least 0775. Rather than change the default,
add a build option to configure the /var/log mode.
Kai Lüke [Tue, 28 Jul 2026 07:01:38 +0000 (16:01 +0900)]
sysupdate: Change disabling with --component-suggested/--feature-suggested
The disabling of features or components with the flag
--component-suggested/--feature-suggested didn't disable the suggested
ones but instead disabled all other ones. This is rather unintuitive due
to how the flags are named and also not really needed because the
intended reconciliation outcome can instead be done by first disabling
everything and then enabling the suggested ones again which is easier to
reason about. For components the tricky part is that they default to
enabled and thus it's better to have the disable/enable commands with
--component-suggested operate only on suggested ones instead of touching
others like "legacy" components that don't explicity say whether they
are enabled and suggested or not.
Make running disablement of components/features with
--component-suggested/--feature-suggested undo a previous enablement
with the same flags. Document how one can align the system to only use
suggested components/features and not anything else by doing it in two
steps, first disabling everything and then enabling suggested ones. This
also makes it clearer now that all components that are not explicitly
enabled nor suggested will be disabled then.
Paul Meyer [Tue, 21 Jul 2026 14:32:20 +0000 (16:32 +0200)]
pcrextend: extract varlink call boilerplate into shared helpers
pcrextend_verity_now() and pcrextend_imds_userdata_now() carried
near-identical copies of the connect + io.systemd.PCRExtend.Extend call.
Factor that into pcrextend_pcr_now() and pcrextend_nvpcr_now() and
reimplement both on top of them. No functional change.
Paul Meyer [Tue, 21 Jul 2026 13:40:18 +0000 (15:40 +0200)]
pcrextend: add secret parameter to varlink interface
Add an optional 'secret' input to io.systemd.PCRExtend.Extend. When set,
the HMAC of the measured data keyed by the secret is extended instead of
a plain hash, matching the existing tpm2_{pcr,nvpcr}_extend_bytes()
secret parameter. This lets callers measure a secret (e.g. a volume key)
without leaking a hash of it.
Paul Meyer [Tue, 21 Jul 2026 13:06:37 +0000 (15:06 +0200)]
pcrextend: pass iovecs through the extend helpers
extend_pcr_now(), extend_nvpcr_now() and escape_and_truncate_data() took
a (void *data, size_t) pair, even though both the dispatch layer and
tpm2_{pcr,nvpcr}_extend_bytes() already speak struct iovec. Drop the
pointless deconstruct/reassemble and pass the iovec through directly.
Chris Coulson [Tue, 23 Jun 2026 19:58:17 +0000 (20:58 +0100)]
tpm2: Improve how NvPCR protection works.
NV indexes created in the storage hierarchy can be undefined and
redefined with TPM owner auth. Because of this, NvPCRs need some way
to prevent them from being redfined in a way that allows spoof
measurements to be replayed.
The current approach requires knowledge of a secret ("anchor secret")
in order to derive the initial NvPCR measurement and to derive a
measurement to an existing PCR (9). The credential is protected by the
TPM with a PCR policy. Without access to the credential, it's not
possible to replay measurements to a newly defined NvPCR without
breaking the binding with the measurement in PCR 9. However, this
approach has a couple of issues:
- The credential is currently only protected by PCR11. As it's not
protected by the rest of the boot chain, it's possible to boot other
operating systems in order to replay the PCR11 measurements and
recover the secret. Note that as the NvPCR anchoring happens in early
boot, the credential is stored in the ESP.
- Someone with privileged access to a system can just create a new
credential containing a known secret and store this in /var/lib and
the ESP. The NvPCRs are anchored with this known secret on subsequent
boots, and therefore the measurements can no longer be trusted.
Imagine the scenario where privileged access is theoretically possible
as a result of some vulnerability. After upgrading the system to fix
this vulnerability, the system should be able to attest that it is
now in a good state. However, if an adversary were able to use their
priviliges to replace the credential, they are able to obtain
persistence and the NvPCR measurements are no longer trustworthy.
This PR changes things to take a different approach. Instead of
requiring knowledge of a secret, the NvPCRs are now created in a way
that requires a policy to be satisfied for writing. The write policy has
2 branches:
- TPM2_PolicyNvWritten(true), which can be satisified without any
further authorization if the NvPCR has already been extended.
- TPM2_PolicyAuthorize(pcrPubKey, SHA256("nvpcr-init")) which can be
satisfied with a signed PCR policy, and must be used to perform the
initial extend to a NvPCR.
The intention here is that the signed PCR policy that can be used to
authorize the initial extend to the NvPCR can only be satisfied during
early boot. During later boot phases, this signed PCR policy must not be
valid. This means that if a NvPCR is undefined and redefined, it won't
be possible to satisfy its write policy in order to able to perform the
initial extend.
In order to anchor the NvPCRs and prevent them from being undefined and
then redefined with a different policy that does allow them to be
extended, the names of the NvPCRs are measured to PCR9. Verifiers must
check that the names of attested NvPCRs match the measurements in PCR9.
This uses the PCR signing key from the currently booted UKI to create
the NvPCRs. If this changes between boots, then tpm2-setup automatically
recreates new NvPCRs with an updated write policy to reflect this. I've
tried to be careful to not undefine arbitrary NV indexes in this case,
so it checks that the existing NV index looks like a NvPCR (ie, it has
the expected attributes) before undefining it.
I did originally try to preserve the old behaviour for existing systems,
but it makes things a lot more complicated. As the new implementation
already creates new NvPCRs when the PCR signing key changes, I ended up
just automatically upgrading the old NvPCRs as well. Again, I check here
that any existing NV index looks like an old style NvPCR (ie, it has the
expected attributes) before undefining it.
I did notice that the initial NvPCR measurement isn't going into the
log. I don't know if that was an intentional choice, but I've preserved
that behaviour in this PR.
This also adds a new option to ukify (--sign-initrd-pcrs) which creates
signed policies (one per PCR bank) that can only be satisfied from the
initrd. These policies are used for initializing the NvPCRs, but can also
be used for protecting TPM2 keyslots enrolled with systemd-cryptenroll
(by using the --tpm2-public-key-policyref=initrd option).
There is one outstanding issue. The NvPCR definitions support different
algorithms, but the use of PolicyAuthorize means that they can only support
SHA-256 for now. This is because the signed policy algorithm must match
the name algorithm, and some additional work is required to support
signed PCR policies for algorithms other than SHA256. I've left a note in
tpm2_nvpcr_initialize that details what's required, and I'll take a look
at that in a subsequent PR.
Kai Lüke [Tue, 28 Jul 2026 05:32:01 +0000 (14:32 +0900)]
sysupdate: In the auto-enable service, don't enable all features
The auto-enable service should activate suggested components and
features but enabled all features which includes the default components
unsuggested features and any unsuggested features of the suggested
components. This is unexpected behavior and we rather want this service
to be limited to suggested features.
Switch the service flag to suggested and make the wording more explicit
in the man page. Also fix the wrong statement that it operates on
enabled components, it operates on all components, also explicitly
disabled ones.
Liu Zheng [Tue, 28 Jul 2026 00:07:16 +0000 (08:07 +0800)]
localed: normalize empty X11 option values to NULL after parsing
x11_read_data() parses an 'Option "XkbVariant" ""' line in
00-keyboard.conf with strv_split_full(..., EXTRACT_UNQUOTE), which turns
the empty quoted value into a non-NULL empty string rather than NULL.
Since 812aa57d2c ("string-util: beef up string_is_safe()") an empty
string is rejected by string_is_safe() unless STRING_ALLOW_EMPTY is
passed, so x11_context_is_safe() now refuses such a context and
x11_context_verify() discards the whole thing. As a result "localectl
status" reports "X11 Layout: (unset)" even though the file names a valid
layout, and compositors reading org.freedesktop.locale1 (e.g. the SDDM
greeter) fall back to the us layout.
Introduce x11_context_normalize(), suggested by @lionheartyu, which
converts empty strings to NULL while freeing the heap allocation —
unlike x11_context_empty_to_null() which only NULLs the pointer without
freeing. Call it at the end of x11_read_data(), before
x11_context_verify(), so empty option values are treated as unset. This
also keeps x11_context_equal() comparisons consistent with the setter
path (method_set_x11_keyboard) and vconsole_read_data(), which both
store NULL for empty values.
Alexander Egorov [Mon, 27 Jul 2026 19:47:03 +0000 (22:47 +0300)]
hwdb: Add accelerometer matrix for OneXPlayer Super X
The BMI260 accelerometer in the OneXPlayer Super X is exposed through
the ACPI BMI0160 ID. Its X and Y axes do not match the built-in display
axes, and no firmware mount matrix is provided.
Add an exact vendor and product DMI match with the matrix verified on
the hardware. The matrix keeps the native landscape position normal and
maps both portrait rotations to the corresponding display orientation.
Tested with iio-sensor-proxy 3.8 and Mutter 49.7 in all display
orientations. The compiled hwdb entry also matches the complete modalias
reported by the device.
Development of this patch used assistance from ChatGPT 5.6 sol.
udev: probe_superblocks: return a real negative errno on failure
Previously, probe_superblocks() forwarded blkid_do_fullprobe()'s and
blkid_do_safeprobe()'s raw return code on error, which is just -1 with
no errno attached. The caller passes this value straight to
log_device_debug_errno() with %m, so a generic probing failure always
printed strerror(-1) regardless of what actually went wrong.
Convert the -1 error case to a proper negative errno via
errno_or_else(), matching the pattern used elsewhere in this file. The
'nothing found' (1) and success (0) return values are unchanged.
Eric Curtin [Sun, 26 Jul 2026 17:06:45 +0000 (18:06 +0100)]
mount-util: don't trigger automounts when cloning submounts
get_sub_mounts() clones each submount of the given prefix with
OPEN_TREE_CLONE. The kernel resolves the path of an OPEN_TREE_CLONE
with LOOKUP_AUTOMOUNT, i.e. if the submount is an autofs automount
point that has not been triggered yet, cloning it forces the automount
to trigger, and open_tree() blocks until the automount request has
been served.
This is particularly problematic during boot: setting up a private
/proc for the first sandboxed service (e.g. systemd-userdbd.service,
which uses ProtectProc=invisible) clones the submounts of /proc, which
include PID 1's own /proc/sys/fs/binfmt_misc automount point. The
executor then blocks until PID 1 gets around to dispatching the
resulting proc-sys-fs-binfmt_misc.mount job, which competes with the
ongoing boot transaction. On a Fedora 44 VM this delayed
systemd-userdbd.service by ~0.9s, and with it every early-boot NSS
user/group lookup that ends up in nss-systemd's varlink queries — most
importantly systemd-tmpfiles-setup-dev-early.service, which
systemd-udevd.service is ordered after, stalling the whole boot
critical path:
[2.131846] proc-sys-fs-binfmt_misc.automount: Got automount request
for /proc/sys/fs/binfmt_misc, triggered by 323 ((systemd-userd))
[2.943574] Mounting proc-sys-fs-binfmt_misc.mount...
[2.968507] Mounted proc-sys-fs-binfmt_misc.mount.
Triggering the automount here also defeats its purpose, since
binfmt_misc ends up mounted on every boot even if nothing ever
accesses it.
Pass AT_NO_AUTOMOUNT so that untriggered automount points are cloned
as they are instead.
Before (Fedora 44 VM, 4 vCPUs):
Startup finished in ... + 2.559s (userspace)
1.058s systemd-tmpfiles-setup-dev-early.service
938ms systemd-userdbd.service
Fixes the following failure on Fedora 44:
```
TEST-58-REPART.sh[932]: Executing mkfs command: /usr/bin/mkfs.erofs -U 45745a56-aa2f-4619-8ca7-9cb63667c2ae -zlz4hc,level=3 /dev/loop0 /var/tmp/.#reparteb739e8b8cae7b70
TEST-58-REPART.sh[932]: Successfully forked off '(mkfs)' as PID 933.
TEST-58-REPART.sh[933]: ==933==ASan runtime does not come first in initial library list; you should either link runtime to your application or manually preload it with LD_PRELOAD.
TEST-58-REPART.sh[932]: '(mkfs)' failed with exit status 1.
```
Move the bind mount retry path into a small helper so
apply_one_mount() no longer carries destination creation and
retry state inline.
Report destination creation and retry failures at debug level,
then return the error to apply_mounts(). The caller still reports
the final mount namespace failure with the cleaned-up mount path.
env-file-label.[ch] was removed by 3e5320e27d3e
("env-file: port write_env_file() to label_ops_pre()"), which
replaced write_env_file_label() with WRITE_ENV_FILE_LABEL.
0dc39dffbd45 ("Use paths specified from environment variables for
/etc configuration files") later reintroduced only
src/shared/env-file-label.c. The header and meson entry were not
restored, no callers use write_env_file_label() or
write_vconsole_conf_label(), and the current write_env_file()
signature no longer matches the stale wrapper.
sysupdate: include default component for feature-all
--component-all is documented to include the default component-less
installation. Do not drop it merely because the context operates on a
root/image, or because all its transfers are currently disabled by
features.
This lets --component-all --feature-all enable-feature write the
default component feature drop-ins instead of succeeding with no
components selected.
TEST-72-SYSUPDATE covers both all transfers disabled by features and
the same default component feature operation under --root=.
Repro: create a default feata.feature plus a transfer gated by feata,
then run:
build/systemd-sysupdate --root="$root" --component-all --feature-all enable-feature
When recording installdb entries under --root=, keep the leading slash
after stripping the root. Compare current transfer target paths in the
same root-relative form during cleanup.
This prevents cleanup from treating still-owned resources below --root=
as orphaned.
TEST-72-SYSUPDATE covers --root= cleanup keeping a still-owned file and
its matching installdb entry.
Repro: create a rooted transfer for /target/foo-@v.bin, add a
matching installdb entry for /target/./foo-@v.bin, then run:
build/systemd-sysupdate --root="$root" --verify=no cleanup
Before: foo-1.bin and the installdb entry were removed.
test: add coverage for systemctl preset in test-systemctl-enable.sh
Repeats the enable/disable specifier-expansion check with 'systemctl
preset' instead. preset-all is intentionally not exercised here, since
$root accumulates unit files from earlier sections that are
deliberately invalid, and preset-all would trip on those unrelated
units.
sysupdate: don't double-prefix definitions with --root=
Definitions enumerated under --root= are already rooted. Passing those
paths to the config parsers with the same root prefixes the root again,
so feature and transfer files are parsed from the wrong path.
Repro: create root/etc/sysupdate.d/rootfeat.feature and
01-root.transfer, then run:
build/systemd-sysupdate --root="$root" --verify=no --offline features rootfeat
Before: parsing failed at line 1 with a bogus Source Type= error.
veritysetup: keep parsing after ignored NvPCR options
tpm2-measure-nvpcr=no and invalid NvPCR names only affect the current
comma-separated option. They returned from parse_options(), so later
options were silently skipped.
systemd-escape currently only processes strings passed as
command line arguments. This is awkward for callers that already
have a generated list of strings, because they need to loop around
the tool or use xargs and carefully preserve whitespace and other
special characters.
Add --stdin to read one string per line from standard input and
write one escaped result per output line. Keep command line strings
mutually exclusive with --stdin so the input source remains
unambiguous.
Use an explicit option instead of treating '-' specially, since '-'
is itself a valid string to escape. The existing escape, unescape,
mangle, path, suffix, and template rules are reused unchanged.
Eric Curtin [Thu, 2 Jul 2026 12:37:06 +0000 (13:37 +0100)]
shared/dropin: don't re-derive drop-in name candidates per lookup dir
unit_file_find_dirs() is called once for every (unit name or alias,
lookup directory, drop-in suffix) combination while enumerating units
at boot, to check whether that unit has a ".d", ".wants", ".requires"
or ".upholds" drop-in directory in that particular lookup path. On a
typical system with ~270 loaded units and ~12 directories in the unit
search path, this adds up to tens of thousands of calls.
For every one of those calls, the function used to independently
re-derive the full chain of candidate unit names to check for that one
directory: the name itself, its template if it is a template instance,
and its "-" prefix chain (e.g. for "foo-bar-waldo.service" also
"foo-bar-.service" and "foo-.service"), recursively expanding further
where applicable. That derivation only depends on the unit name itself
and does not involve the lookup directory at all, so it produces the
exact same list of candidate names regardless of which of the 12
lookup directories is currently being checked. Despite this, it was
being fully recomputed for every single directory, doing several small
allocations and unit-name parsing calls (unit_name_template(),
unit_name_to_prefix(), unit_name_build_from_type(), ...) each time.
Split the name-derivation logic out into its own function,
unit_file_expand_dropin_names(), and compute it once per unit
name/alias, then reuse the resulting candidate list across all lookup
directories instead of re-deriving it for each of them. The order in
which candidate directories end up being added is unchanged, so this
is not expected to alter drop-in resolution behaviour: I confirmed this
by comparing the sorted unit load state, fragment path and drop-in path
output of "systemd --test --system" before and after this change on the
same unit tree, which is byte-for-byte identical.
I measured the effect by instrumenting manager_enumerate() with
CLOCK_MONOTONIC timestamps and running systemd, built from this exact
tree, as actual PID 1 in a container with ~270 real units loaded, 50
runs each before and after this change:
before: mean 45.35ms (stddev 0.60ms)
after: mean 38.81ms (stddev 0.81ms)
a ~14% reduction with about 8 standard deviations of separation between
the two distributions, i.e. well outside of run-to-run noise.
unit_file_expand_dropin_names()'s out parameter is renamed from
ret_names to names, since it is appended to (including recursively)
rather than only being populated on success, matching the ret_ naming
convention used elsewhere for output-only parameters. Also, a failure
partway through expanding a name's candidates (e.g. OOM) no longer
discards the candidates already derived before the failure, keeping
unit_file_find_dirs() closer to the original recursive
implementation's error handling.
unit_file_add_dir_if_exists(), which builds the path to check for each
(lookup directory, candidate name) pair, is now the hottest remaining
part of this code: with the per-directory re-derivation gone, it is
called once for every directory/candidate combination instead of once
per candidate. It used to build that path with strjoin(name, suffix)
followed by path_join(unit_path, name_and_suffix), i.e. two heap
allocations plus path_join()'s normalization pass. Lookup paths are
already normalized (path_simplify() + strv_uniq()), so a single
strjoin(unit_path, "/", name, suffix) produces the same string while
halving the allocations and skipping the redundant normalization.
ask-password: refuse agent requests with unsafe characters in prompt fields
The message, icon and id fields are written verbatim into single-line
assignments of the [Ask] section of the agent request file, so a newline in
them lets the caller append arbitrary further assignments. Agents let a later
assignment override an earlier one, so an injected Socket= line redirects the
password to a path of the injector's choosing. Validate the fields and refuse
the request instead.
homed/fscrypt: default new homes to v2 policies (#18280) (#42397)
## Summary
Closes #18280.
`systemd-homed` currently writes fscrypt v1 policies, which bind the
master key to the calling process's keyring. This means files in a
homed-managed directory aren't readable when accessed through a
container bind mount, a different mount namespace, or by any process
other than the one that first unlocked the home. Reading the file from a
context that has the key first warms the page cache, but the underlying
problem remains.
v2 policies (Linux 5.4+) route the master key through the filesystem
keyring, via `FS_IOC_ADD_ENCRYPTION_KEY` /
`FS_IOC_REMOVE_ENCRYPTION_KEY`, so the key is visible to every process
accessing the filesystem.
This PR switches `systemd-homed` to v2 by default and keeps existing v1
homes working.
## Changes
**`shared/crypto-util`**: Add `kdf_hkdf_derive` (HKDF, RFC 5869) wrapper
around OpenSSL's `EVP_KDF` "HKDF", alongside the existing SSKDF/KBKDF
helpers.
**`homed/fscrypt`**:
- Read the existing policy via `FS_IOC_GET_ENCRYPTION_POLICY_EX`,
falling back to the legacy ioctl on pre-5.4 kernels.
- `HomeSetup` now carries a full `struct fscrypt_key_specifier` instead
of a bare 8-byte descriptor. Slot decryption derives either the v1
descriptor (double SHA-512) or the v2 identifier (HKDF-SHA512 with the
kernel's info string) from the unwrapped volume key and compares against
the policy.
- Install the master key the right way per version: `add_key("logon",
...)` to thread+user keyrings for v1, `FS_IOC_ADD_ENCRYPTION_KEY` for
v2.
- `home_flush_keyring_fscrypt` opens the image directory, reads the
policy version, and either calls `FS_IOC_REMOVE_ENCRYPTION_KEY` (v2) or
walks the user keyring (v1).
- New homes default to v2; fall back to v1 only when the kernel rejects
v2.
The on-disk slot xattr format is unchanged - the volume key is the same,
only how it binds to the directory changes. There is no v1 -> v2
migration; existing v1 homes continue to unlock, rekey, and deactivate
as before.
Tim Culverhouse [Sat, 18 Jul 2026 00:42:37 +0000 (00:42 +0000)]
core: support CollectMode in Varlink StartTransient
The io.systemd.Unit context exposes CollectMode, but StartTransient
rejects it as unsupported. This prevents Varlink clients from selecting
whether failed transient units should be garbage-collected.
Accept CollectMode when creating transient units and persist the setting
in the runtime unit configuration. Extend the integration test to verify
the value in both the Varlink response and the resulting unit.
format-table: give mixed cell types a stable sort order (#43129)
Mixed-type cells were compared by their insertion indices, while cells
of the same type were compared by value. Combining those rules
could make `cell_data_compare()` non-transitive.
Give different non-empty `TableDataType` values a stable order. Define
empty cells as greater than non-empty cells, so they appear last in
ascending sorts and first when the order is reversed. This ensures that
the comparator defines a consistent ordering.
password-cache= tracks both the cache mode and whether the option was
configured explicitly. The parser set arg_password_cache_set before
validating the value, so an invalid value was logged as ignored but
still blocked the PKCS#11 default no-cache policy.
Only mark password-cache= as configured after accepting read-only or a
valid boolean.
size= is specified in bits, but arg_key_size stores bytes after
parsing. The parser used arg_key_size as temporary storage before
validation. When the value was not divisible by 8, the warning said
the option was ignored, but the invalid bit count remained.
Parse into a local variable and update arg_key_size only after
validation.
X entries inherit the cleanup age from the closest parent directory rule.
Inherit the age-by fields too, so parent rules such as m:1d keep their
full cleanup policy.
Reproducer:
mkdir -p /tmp/tmpfiles-ageby/parent/{child,other}
printf old >/tmp/tmpfiles-ageby/parent/child/file
printf old >/tmp/tmpfiles-ageby/parent/other/file
touch -d '3 days ago' /tmp/tmpfiles-ageby/parent/{child,other}/file
systemd-tmpfiles --clean - <<'EOT'
d /tmp/tmpfiles-ageby/parent - - - m:1d
X /tmp/tmpfiles-ageby/parent/child - - - -
EOT
Before:
child/file remained because X used the default age-by set.
other/file was removed by the parent m: rule.
seccomp-util: allow openat2() with --suppress-sync=yes
When --suppress-sync=yes was introduced in 4a4654e0241fbeabecb8587fd3520b6b39264b9c it filtered out openat2()
completely, as we can't check its "flags" argument because it's hidden
in an indirect struct. This was perfectly fine at that time, as
openat2() was quite new and software shipped with a fallback to
open()/openat() if the syscall wasn't present.
However, today the situation is different and an increasing number of
software is moving to openat2() without any fallback - tar [0] being the
most common one in the recent reports and workarounds, and attr recently
fixed a CVE by switching to openat2() [1] as well, to name a few.
Given that we already block all the sync-family syscalls and calling
openat2() with O_SYNC is relatively rare, let's just blanket-enable it
in the --suppress-sync=yes mode. This means that we might issue a
synchronous write when something calls openat2() with O_SYNC, but not
breaking the apps here feels like a reasonable trade-off, at least until
a better solution pops up.
Note that the same situation is in seccomp_restrict_sxid(), but allowing
the openat2() syscall there could actually have some security-related
implications under certain circumstances.
core: tolerate kernels without POSIX mqueue support
PrivateIPC= sets up a private mqueue mount for the service. When
CONFIG_POSIX_MQUEUE is disabled, mounting mqueue fails with ENODEV and
prevents the service from starting.
Treat ENODEV as an unavailable optional kernel feature while preserving
the private IPC namespace. Keep all other mount errors fatal.
Add coverage verifying that PrivateIPC= still creates a separate IPC
namespace when POSIX message queues are unavailable.
network: make VLAN= and friends take multiple names
Previously, specifying multiple stacked netdevs of the same type required
repeating the corresponding setting, e.g.:
```
[Network]
VLAN=vlan_10
VLAN=vlan_20
VLAN=vlan_30
```
With this change, the same configuration can be written as:
```
[Network]
VLAN=vlan_10 vlan_20 vlan_30
```
Specifying an empty string now also clears all previously assigned stacked
netdevs.
meson: stop registering .standalone in executables_by_name
af4c5730e524c972994232259e5051b951142485 tried to have meson stop
building all possible .standalone binaries in for tests. But it turns out
that those binaries are still built for meson-test-prereq, because they
are listed in executables_by_name, and we interate over
executables_by_name and add all exes found there as dependencies for two
tests: test-link-abi and libshared-unused-symbols. So we'd end up still
building all the .standalone binaries. To really fix this, define the
executables() for .standalone targets, but don't add them to this array.
A secondary change is to set build_by_default to true for .standalone
binaries if have_dlopen_tests is set. This means that we'll build more
binaries in the "build" phase, instead of only building them "on demand"
for tests. I think it is nicer to build everything that'll be used in one
step, and then only run the tests in the test target. For example, tests
may be run under root or in some special environment, and building thins
there is iffy.
The overall effect of this change should be that we stop building or
testing .standalone variants for binaries that we'll not later install,
unless -Ddlopen-tests=true is specified.
Also exclude .standalone binaries from check-help test. The test fails
for some binaries when the width is exceeded because of the ".standalone"
suffix in the name. The actual binary would be called without the
suffix, so the test is not testing a realistic scenario.
The option is generalized from a simple boolean switch that enables
a fixed list to a list-of-patterns.
The old value works, but is deprecated: -Dstandalone-binaries=true is translated
to -Dstandalone-binaries=repart,report,tmpfiles,sysusers,shutdown.
We could already build all normal executables as .standalone, but the
installation only supported a small fixes subset. This wasn't flexible
enough:
- packagers might want to provide additional standalone binaries then the
small subset that was already enabled
- but at the same time, whenever new binaries were added to this subset,
downstream packaging had to be adjusted in sync, at least in the case of
Fedora, because otherwise we'd get a complaint about unexpected .standalone
binaries in the temporary install root.
With the new option, downstreams can just specify the binaries that they
want to be installed in the .standalone variant.
As usual with this type of change, the build dir must be reprovisioned.
user-record: validate JSON shell fields with valid_shell()
The user record loader currently uses a generic filename-or-path check
for shell and fallbackShell. This allows values that homectl rejects,
including relative names, control characters, colons, and trailing
slashes.
Use valid_shell() for all three record locations and cover the top-level,
matching per-machine, and status fallback fields at the loader boundary.
timer: clamp future calendar base after clock jumps back
A calendar timer that is already waiting keeps the base timestamp it was
last armed from. When the wall clock is set backwards, that base can end
up in the future relative to the new realtime, and passing it to
calendar_spec_next_usec() schedules the next elapse relative to the old
future time instead of recalculating from now. systemctl list-timers
then keeps showing the stale pre-adjustment elapse (e.g. "3 years left"
after the clock moved back two years) and the timer never catches up.
Clamp the selected calendar base to the current realtime before asking
calendar_spec_next_usec() for the next occurrence. The clamp only kicks
in when the base is genuinely in the future, so Persistent=yes timers
whose last trigger is still in the past keep their catch-up behaviour and
we don't reintroduce the missed-run regression seen after suspend.
meson: disable dlopen tests by default, enable in gcc github workflow
1f76654f942893155bd42b0373b8130d2a9e1dcf added support to build .standalone
variants of most binaries. test-dlopen-note.py is hooked in the test suite for
everything that can do .standalone, but this means that the .standalone
variants become a prerequisite for tests. This means that meson will build the
.standalone variants for all binaries before running tests, which takes quite a
bit of time in some situations. (Arguably, the dlopen test suite was excluded
by default, so maybe meson could be smart and figure out that those tests are
not enabled by default. But it doesn't seem to make this distinction.)
network: invalidate cached driver when an interface is renamed
During early boot, interfaces may be renamed frequently, which can lead to
caching the driver name of a different interface. Invalidate the cached
driver whenever an interface rename is detected so it can be re-read using
the new name.
Plymouth encodes the password prompt length in a single byte.
Reject prompts whose length cannot be represented instead of
wrapping the encoded length while sending the complete message.
strv: refuse invalid UTF-8 in strv_rebreak_lines()
The scan pointer was advanced with utf8_next_char(), which blindly skips
utf8_skip_data[lead byte] bytes, so a line ending in a truncated multibyte
sequence like "foo\xF0" stepped over the NUL and the loop read past the end
of the string. Decode each character with utf8_encoded_to_unichar() and
propagate the error instead of measuring broken characters.
Sven Joachim [Thu, 23 Jul 2026 08:53:17 +0000 (10:53 +0200)]
emacs: Fix warning when opening shell scripts
Opening a shell script, Emacs notified me in the echo area:
sh-indentation is obsolete (since 26.1); use ‘sh-basic-offset’ instead
Commit 0c40aef7ef14 ("emacs: drop obsolete emacs property") got it backwards,
keeping sh-indentation rather than sh-basic-offset. The latter is an obsolete
alias for the former.
tmpfiles: propagate copy errors after opening target
Opening the destination only proves that it exists. If copy_tree_at()
failed for any reason other than an existing destination, report that
copy error.
I noticed that the use of sed in the `80-systemd-osc-context.sh` was
unnecessary, and upon writing a replacement in pure bash and testing it,
actually buggy. While in there, I also spotted some other minor things
that might be worth doing.
Getting rid of fork+exec for doing sed is probably the biggest win, but
there are still quite a few subshell invocations (that only do fork, not
exec). I haven't measured the overhead of those, but it seems that we
could get rid of those as well if we want.
Another thing I wonder about is whether we should emit an end= marker on
shell exit. There's no guaranteed way of doing it. Just as everything
else, we could get killed before getting a chance to do it. But also,
unlike PROMPT_COMMANDS, there's no "at_exit" array to hook into. Still,
we could ask if there is a 'trap exit' hook installed, and if not,
install one ourselves; if the user's bashrc subsequently overrides that,
so be it (though .bash_logout would be more appropriate).
machined: refresh resolve hook addresses per machine
Track which machine the cached address list belongs to and refresh it
when ResolveRecord() advances to another machine. This keeps A/AAAA
reuse for the same machine while avoiding mixed name/address records.
Reproducer: register two machines with private addresses 10.88.1.1
and 10.88.2.1, then call io.systemd.Resolve.Hook.ResolveRecord
with both A questions in one request.
Before: the answer for the second machine used its own name but
reused the first machine's address, e.g. resolve-bug-m2 returned
10.88.1.1 instead of 10.88.2.1.
KERNEL_INSTALL_CONF_ROOT overrides kernel-install config lookup. When it
was set and cmdline was absent, 60-ukify still fell back to
/proc/cmdline and embedded host boot options into the target UKI.
Return an empty base cmdline in that case, matching the adjacent
90-loaderentry behavior of not searching outside the override root.
status with --static, --pretty, or --transient prints only the
selected hostname in regular output. JSON status output is built from
hostnamed's Describe data and remains a full status object.
Document this distinction so callers do not expect the name type
switches to turn JSON status into a single scalar value.