PSA: `systemd` is becoming kernel bound

TL;DR : systemd now ships eBPF programs (nsresourced, mountfsd, networkd helpers). eBPF programs are compiled against the Linux kernel they will run on, specifically kernel’s BTF informations, its vmlinux.h, its exact structure layouts. This is because the Linux kernel has no stable ABI for its internal data structures. eBPF CO-RE is unfortunately insufficient as a generic solution to this problem. This result into forcing systemd into the per-kernel package set (config.boot.kernelPackages.systemd on NixOS), the same way nvidia or zfs live in linuxPackages. The moment systemd is per-kernel, every package that depends on the full systemd will either have to inherit that coupling or migrate to a lighter package such as systemdLibs.

nsresourced and friends

Recent systemd releases have started to ship eBPF based tools such as nsresourced, mountfsd and BPF-LSM more generally which paves the path for unprivileged systemd-nspawn, unprivileged UID delegations, unprivileged mounting of disk images based on policies (dm-verity, etc.), policies to restrict binary execution from non-dm-verity partitions and more.

eBPF will probably see even more adoption in the future of the Linux userspace.

For nixpkgs, this has two consequences:

  1. systemd requires a vmlinux.h (either provided or derived from the build host’s running kernel) to build these components.
  2. The resulting systemd built is valid for a kernel whose type information (think: data structures offsets, etc.) matches the one they were built against, otherwise, horrible things may happen.

Why does eBPF requires such strong coupling to the kernel?

eBPF programs run inside the kernel. The types using in an eBPF kernel observe kernel internal data structures which are not part of the stable ABI promise that the Linux kernel offer to the userspace, for reminders: Linux kernel guarantee that the syscall API and the exported UAPI headers are stable. Everything else, e.g. struct task_struct* is not. Some of these structures even change across KConfig changes. See https://www.kernel.org/doc/Documentation/process/stable-api-nonsense.rst for more.

How portable eBPF is even supposed to work? One may ask.

BTF and CO-RE were developed to this end. BTF allow you to reconstruct the vmlinux.h from a kernel image via bpftool btf dump file vmlinux format c and CO-RE records relocations so fields offsets can be fixed up at load time.

But… CO-RE is a mitigation and is not finished. It can relocate a field that moved, it cannot conjure a field that doesn’t exist and many other scenarios can show up that CO-RE cannot repair. In practice, BPF objects must be built against a BTF that matches (or safely subsumes) the target kernel.

This lead to a debate among nixpkgs maintainers whether we should maintain our own vmlinux.h file (home grown) across the list of nixpkgs supported kernels — or abstain from such a maintenance load. We discussed this solution with systemd upstream and they do not advise it and would not want to share any maintenance load on this for all the distros out there.

It is now possible in unstable to provide vmlinux-btf to systemd and linuxPackages.ebpf-headers is exactly the output of bpftool btf dump file vmlinux format c which is plugged into vmlinux-btf’s systemd argument.

(Please do not reopen the debate on whether we should maintain our own vmlinux.h or not. Please do not pester the systemd upstream on this if you are not involved with systemd maintenance already.)

Hence… linuxPackages.systemd

As a logical conclusion, systemd is now observing the Linux kernel implementation details, thus it goes into the linuxPackages set.

Note that NixOS did not switch yet to a kernel-bound systemd: nixos: switch to kernel-bound systemd by default by RaitoBezarius · Pull Request #569868 · NixOS/nixpkgs · GitHub .

This means that the eBPF programs are still unavailable by default on NixOS but you can decide (today!) to run with systemd.package = config.boot.kernelPackages.systemd; and report whether this works out for you or not.

Moving to a kernel-bound systemd can only happen after remaining cleanups are taken care of, more on this below.

The first half of remaining chores: systemdLibs

Here is the part that is the most important for packagers and maintainers.

If systemd is now a per-kernel artifact, then “my package depends on systemd” means “my package depends on a Linux kernel”, writing:

buildInputs = [ systemd ];

is not a good idea anymore if you only need sd_notify for example.

So we have started a treewide migration moving as many programs as possible to systemdLibs which is the library only part of systemd.

As much as possible, consider:

buildInputs = [ systemdLibs ];

In addition to making your package not depend on the kernel, this also result in your package depending on less (!) stuff, i.e. 1k build-time dependencies vs. 2k build-time dependencies and save up to ~100MB of closure size.

The other half of remaining chores: late binding

systemdLibs handle packages that links against systemd. Packages that execute systemd binaries also need a solution.

Today the answer is “whatever systemd derivation this package was built with”, e.g.

substituteInPlace ... \
   --replace-fail "systemd-escape" "${lib.getExe' systemd "systemd-escape}"

That is a hard build-time dependency on one systemd variant which might not even be related to the systemd running on your system because we upgrade systemd at runtime via switch-to-configuration.

Instead, the package should refer to the running system’s tools, resolved at runtime, from /run/current-system/sw/bin. This increases correctness and remove this dependency edge.

  1. On non-NixOS systems, the most accurate systemd tool is the one of the distro’s system and not ours, we should not push our own client which may be incompatible with the remote distro systemd server.
  2. On kernel-bound systemd NixOS systems, we can upgrade a systemd and have a desync with the client.

Here’s the replacements, ranked from the worst to the best:

substituteInPlace ... \
   --replace-fail "systemd-escape" "/run/current-system/sw/bin/systemd-escape"

This breaks the program for non-NixOS systems.

wrapGApp $out/bin/miracle-wm \
   --set PATH ${lib.makeBinPath [ coreutils dbus ]} # dropped systemd from here
   --suffix PATH : "/run/current-system/sw/bin" # new

This also breaks program for non-NixOS systems because PATH is clobbered, if possible, proceed this way:

wrapGApp $out/bin/miracle-wm \
   --prefix PATH : ${lib.makeBinPath [ coreutils dbus ]} # if coreutils and dbus must override the ambient PATH absolutely
   --suffix PATH : "/run/current-system/sw/bin" # as a fallback location for NixOS.

This migration has not started yet.

Status of the migration

How to help

  1. Review open PRs if they affect your subsystems
  2. Fix your own package set. If a package you maintain use systemd, consider migrating to systemdLibs or late binding.
  3. Help testing the packages like the case with podman or the logging subsystem which showed that systemdLibs needed withCompression = true; to avoid breaking loggers.

Next steps

  • Land on a solution for udevCheckHook — we may be looking at removing it or replacing it with a separate udev parser (lighter in dependencies)
  • Complete the migration and ensure that things are working as intended wrt to the above described workflow (no mass rebuild events, no broken programs, etc.)
  • Remove pkgs.systemd or keep it for very peculiar cases
  • Switch by default to kernel-bound system on NixOS.
  • Examine the case of systemdMinimal which NixOS systemd maintainers would also like to get rid of, it is meant as a tool to break off dependency cycles with LVM2 and cryptsetup.
49 Likes

This may be a silly question, but do the BPF programs get compiled into the systemd binaries, or do they exist as .bpf files separately? Is there a way we can have a single systemd build that dynamically loads the correct bpf files for the current kernel, e.g. systemd.bpf-package = config.boot.kernelPackages.systemd-bpf ?

Another question, now that systemd is loading BPF payloads, do we need to sign them as part of the autopen/e2e boot security work?

2 Likes

We use the same structure for bcachefs and zfs. Tools package is universal, kernel module is separately built from the same monorepo.

The BPF objects are in .rodata of every TU. This would require supporting relinkage for the C objects that are included, approx. 3 binaries and the PID1 itself.

If we convince systemd upstream to make the skeleton a runtime file which libbpf may support, we could build a systemd-ebpf-objects per kernel. This would mean that systemd would write bpf_object__open_file("${libdir}/systemd/bpf/userns-restrict.bpf.o", ...) in their C code. We could late bind this path and suppress systemd kernel dependency and have systemd-ebpf-objects per-kernel.

This makes sense and I will propose it next time I have a moment with systemd upstream but this probably mean doing the work for upstream :slight_smile:. If you are interested, that’d be most welcome.

Signing eBPF code is still fresh AFAIK: Code signing for BPF programs [LWN.net] . The day where it becomes a practice, we will probably need to tap into autopen, but I’m not yet sure if the signature scheme used by the kernel will 100% match autopen. Perhaps, @emily could chime in on this.

6 Likes

Yes, except, this is entirely for userspace programs here, there’s no kernel module involved :slight_smile:.

This seems like something other distros would prefer as well, not just us. I doubt they want to build and distribute entire systemd packages for each kernel in their package if they could isolate just the kernel-dependent part.

It’s not as important for them but they should still be positive about the change, I expect.

3 Likes

I’m adding this mess to my list of reasons to disable eBPF at kernel build time.

2 Likes

From what we saw, other distros have chosen only what I could describe as painful paths with respect to this problem… !

Updating myself on this: Making sure you're not a bot! — the Linux kernel got eBPF signing merged very recently.

Upstream is interested as they need a way to split objects… well… to sign them. :slight_smile:

1 Like

Can someone explain how the second suggestion (reproduced below) makes it work on non-NixOS systems? To me, it seems like this is still clobbering the PATH, so the program won’t look for /usr/bin/systemctl. Also, why not combine the --set PATH and --suffix PATH into just --set PATH ${lib.makeBinPath [ coreutils dbus "/run/current-system/sw" ]}?

wrapGApp $out/bin/miracle-wm \
   --set PATH ${lib.makeBinPath [ coreutils dbus ]} # dropped systemd from here
   --suffix PATH : "/run/current-system/sw/bin" # new
2 Likes

If those systemd binaries are now kernel dependent, should this not be /run/booted-system?

7 Likes

Yeah, I’m scratching my head over this one too. I understand It’s clobbering the path to avoid calling any systemd binaries that may currently be on the path. maybe the solution is to prefix the path with the special nixos location, and allow it to fall back to the system provided binaries for non-nixos systems.

wrapGApp $out/bin/miracle-wm \
   --prefix PATH : "/run/current-system/sw/bin" \
   --prefix PATH ${lib.makeBinPath [ coreutils dbus ]}

because lib.makeBinPath takes derivations, not path strings IIRC.

I’m interested, but I have not worked with bpf loading before, would you be available to ask questions?

1 Like

If we’re not clobbering the PATH, why even set the special NixOS location? That should already be in the environment since it needs to be for other distros. The only reason I can see for it is the idea from above to use /run/booted-system instead.

As for lib.makeBinPath, the type says it takes in derivations, but the example shows it also works with strings: lib.makeBinPath - Nix function reference | Noogle.

Well, this is a tradeoff, it’s more likely that a systemd upgrade will propagate into new code for client<->server than new code for eBPF probes, but you are right that systemd could ship a new eBPF change against the new kernel, the new kernel could have a new data structure, loading that eBPF program will fail after the switch to configuration, but the rest of the system should continue to work.

Client to server comms are more important than eBPF program loading staying functional. If we could detect incompatible eBPF changes, we could decide to reuse the previous eBPF objects following the split up that @twoolie suggested and move them into /run/booted-system/ebpf-objects/....

1 Like

Apologies, I got it wrong, I had meant that --suffix should be used to provide a NixOS final fallback location for OS binaries and avoid --prefix or --set PATH to that end. Obviously, I chose an example that use --set PATH and so will already lock out things to work out on non-NixOS systems.

I will edit my initial explanation to reflect these details better.

1 Like

Yes, feel free to DM me over Matrix or here. I’m travelling so my response times may be slow.