clara's web page

patching nixos without causing a mass rebuild

The year is 2026. Computers suck more than ever these days, with critical vulnerabilities rolling onto your news feed on an almost daily basis. Mitigating this is not an easy task, especially for the maintainers of Linux distributions that are not included on various secret embargo disclosure mailing lists.

On NixOS, there are multiple ways to fix such vulnerabilities before a fix has arrived in a binary cache. The most simplest solution is probably to just use the small channel/branch of nixpkgs, hoping the fix has already been applied there. However, this might not often be a viable choice, either because the package that needs the fix is not a part of the small set or because the package is still stuck within the Hydra build queue. In those cases, calling overrideAttrs on the respective package and building it yourself is usually the most viable choice.

However, the real problem arises when the package you are trying to fix is deeply nested within the system, such as openssl, glibc, zstd, and a few others. Due to the functional nature of NixOS, an override of one of those packages would cause a mass rebuild due to so many other packages depending on it and therefore requiring a recompilation due to changes in their input set. Even though compiling openssl and zstd yourself is a quick task, rebuilding all the thousand packages that depend on it is rather not.

This is not just a problem that arises when doing it locally. In fact, when contributing to nixpkgs, pull requests that trigger such mass rebuilds are usually required to be merged into the so-called staging-next branch, which accumulates all changes that trigger mass rebuilds before eventually getting merged back into the main branch, finally performing the actual mass rebuild. This means, that for security fixes in such low-level packages, it may take even longer before the fix arrives in a binary cache, depending on when the next staging-next merge happens plus the rebuild finishes. Sometimes, but not for every package, these merges are done as soon as a certain fix landed inside staging-next. The Linux kernel is notable example for that, but for the recent zstd vulnerability it unfortunately did not happened.

So, in the case that a fix for such a deeply nested dependency does not arrive in time and you do not have the computing powers to perform such a mass rebuild in a sensible time, you effectively have only one option left: system.replaceDependencies.replacements, a rather niche feature allowing to replace a dependency on the system without causing a mass rebuild.

What system.replaceDependencies.replacements does is basically wrapping around pkgs.replaceDependencies for the entire system, which in turn is a function that replaces a dependency in a derivation in a cursed fashion using sed magic. It should be seen as a temporary solution however, as it may lead to the thing functional package managements wants to protect us from: ABI incompatibility and dependency hell. Please only use it if the cost outweighs the benefits!

Okay, so now, how do we use it? Although one quickly finds that this functionality exists, documentation around it is rather sparse, so I hope to provide a bit of guidance with this blog post. First and foremost, you must somehow create a package that contains the patched version, either through an override or by creating your own package definition. The important part here is, that both packages must have the same output path length. The second important thing to keep in mind is, that this mechanism works solely on outputs. For example, if you want to use this to fix zstd, you must apply it to each zstd output manually, that is, bin, dev, man, and out. Failure to do so, may lead to weird and inconsistent behavior.

Because all of this is quite error prone, I want to use as much meta-programming as possible to avoid any possible mistakes. Such copy&paste mistakes are easy to make, even easier to oversee, and most of the time incredibly hard to find when they cause a problem down the line. Fortunately, meta-programming solves this problem for the large part, hence why I recommend to embrace it whenever possible and feasible!

Okay, so how does a decent, or rather less fragile, usage of this look like? In my case, I start out with an override to nixpkgs that creates a new attribute set as pkgs.grafts, where each key corresponds to a name inside pkgs.* and each value to a respectively patched package derivation. For example, pkgs.grafts.zstd contains a pkgs.zstd.overrideAttrs with the respective fix applied.

What is now missing is code that basically glues every name inside pkgs.grafts to pkgs.* while doing this on an output per output basis. For this, I am going with the following:

{ lib, pkgs, ... }:
{
  system.replaceDependencies.replacements = lib.flatten (
    lib.mapAttrsToList (
      name: value:
      map (out: {
        oldDependency = pkgs."${name}"."${out}";
        newDependency = value."${out}";
      }) pkgs."${name}".outputs
    ) pkgs.grafts
  );
}

Although this code may look complicated at first, what it does is quite simple. It starts by converting the pkgs.grafts attribute set to a list while applying a mapping to each name/value pair. Remember that each name here corresponds to a name in pkgs.* whereas each value corresponds to a package derivation. The actual mapping then converts each name/value pair into a list by performing yet another mapping on the outputs value of the original package definition in pkgs."${name}".outputs. This inner mapping is now doing the interesting part: It creates the actual attribute set that is required by system.replaceDependencies.replacements, which is an attribute set consists of an oldDependency and a newDependency name with the respective values mapping to the respective derivations. Last but not least, we have to call lib.flatten, in order to flatten the two-dimensional list, which we have obtained as a side-effect of converting each value into an inner list, due to applying it to every output.

If this sounded too theoretical, you may find the applied description here more helpful:

# Original definition of pkgs.grafts.
{
  zstd = <patched-zstd>;
};

# However, system.replaceDependencies.replacements wants a list, so let's call
# lib.mapAttrsToList.
[
  (map @ zstd)
];

# We map each element to a list which in turn maps on every output.
[
  # zstd
  [
    (map @ pkgs.zstd.outputs)
  ]
]

# Evaluating the inner map call.
[
  # zstd
  [
    {
      oldDependency = zstd.bin;
      newDependency = <patched-zstd>.bin;
    }
    {
      oldDependency = zstd.dev;
      newDependency = <patched-zstd>.dev;
    }
    {
      oldDependency = zstd.man;
      newDependency = <patched-zstd>.man;
    }
    {
      oldDependency = zstd.out;
      newDependency = <patched-zstd>.out;
    }
  ]
]

# Finally, we need to flatten it, because that is the format that is expected.
[
  {
    oldDependency = zstd.bin;
    newDependency = <patched-zstd>.bin;
  }
  {
    oldDependency = zstd.dev;
    newDependency = <patched-zstd>.dev;
  }
  {
    oldDependency = zstd.man;
    newDependency = <patched-zstd>.man;
  }
  {
    oldDependency = zstd.out;
    newDependency = <patched-zstd>.out;
  }
]

Last but not least, I recommend to add some assertions as follows:

{
  assertions = lib.flatten (
    lib.mapAttrsToList (name: value: [
      # Derivation names must have the same length.
      {
        assertion = (lib.stringLength pkgs."${name}".name) == (lib.stringLength value.name);
        message = "${pkgs."${name}"} has different name than ${value.name} in graft";
      }

      # Both derivation must have the same outputs.
      {
        assertion = pkgs."${name}".outputs == value.outputs;
        message = "${pkgs."${name}"} has different outputs than ${value} in graft";
      }
    ]) pkgs.grafts
}
What these assertions are doing is to verify whether the names have equal length, which is a requirement, as well as checking whether both derivation have the exact same output names defined, which is a sensible thing to check.

As a summary: Using this technique is a powerful option to quickly patch a critical dependency when all other options are not sustainable. In fact, it is what I have done earlier this week as a consequence of a recent zstd vulnerability, with the patch still not being in nixos-unstable as of the time I am writing this unfortunately. Again, this breaks one of the fundamental ideas of functional package management, so please use it with care. However, sometimes risky dependency hell might be better than risking off a vulnerability ...