NixOS / nix

Nix, the purely functional package manager
https://nixos.org/
GNU Lesser General Public License v2.1
12.15k stars 1.47k forks source link

nix lock can modify lock files in the nix store and corrupt it #10139

Open mickael9 opened 6 months ago

mickael9 commented 6 months ago

Describe the bug

Using --update-input can allow nix to modify the lockfile in the nix store, rendering it corrupted

Steps To Reproduce


$ export NIX_CONFIG="experimental-features = nix-command flakes"

$ nix flake info "git+https://gist.github.com/8f6fae8f7406d2bb5edd636cdcd47d37.git"
[...]
Path:          /nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source
[...]

$ md5sum /nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source/flake.lock 
01f01a46a97b7e78de94cce4ebfeb989  /nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source/flake.lock

$ nix flake lock --update-input nixpkgs /nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source
warning: '--update-input' is a deprecated alias for 'flake update' and will be removed in a future version.
warning: updating lock file '/nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source/flake.lock':
• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/1d1817869c47682a6bee85b5b0a6537b6c0fba26' (2024-02-16)
  → 'github:NixOS/nixpkgs/79baff8812a0d68e24a836df0a364c678089e2c7' (2024-03-01)

$ md5sum /nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source/flake.lock 
095a3e64f215ba303a071ac0284816f9  /nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source/flake.lock

$ nix store verify /nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source 
path '/nix/store/ym20x8nwxyg574s4159947sbrn5a2ilr-source' was modified! expected hash 'sha256:0f8v47bpn5cdfvsah14ar2wljz72bprcm224g7jydqm1l8sfa5ca', got 'sha256:0lxi4zmykn5nnsdp8aa9p7q1jav8vvn34axbjgw089xp0jilflld'

Expected behavior

The store should not be modified (there should be an error, or --no-write-lock-file should be implied)

nix-env --version output nix-env (Nix) 2.20.4

Additional context

This was discovered by following the wiki guide here: https://nixos.wiki/wiki/Automatic_system_upgrades

With this configuration, the auto update script will run commands such as:

/nix/store/xnw2dyxxbasc6rxm7n4fq0fga2iiy1dn-nixos-rebuild/bin/nixos-rebuild switch --update-input nixpkgs -L --flake /nix/store/mis15fq6fbvv3r3pqrydk9qpxqvrn186-source --upgrade
thufschmitt commented 6 months ago

I can reproduce this when running the nix flake update command as root.

My (strong) intuition is that the command will run in a mount namespace with write access to the store (because some operations require it), and Nix doesn't check that the lockfile is in the store, so overwrites it.

Quick workaround: set the NIX_REMOTE environment variable to daemon (or set the store option to daemon in /etc/nix/nix.conf) to force using the daemon, even when running as root.