repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
recovery.mdMarkdown669 lines27.8 KiBsource raw download

Recover a locked-out account from a NixOS live USB#

Locked out right now? Read section 1 first — it is 40 lines and it explains why rolling back does not fix this. Then pick your path.

Your account exists, your files are on the disk, and every entry in the boot menu rejects your password. This guide gets you back in.

Contents

  1. What actually happened
  2. Words that trip people up
  3. Will this work on my machine?
  4. Pick your path
  5. Path A — the recovery script
  6. Path B — by hand
  7. When something goes wrong
  8. This laptop's values
  9. Prevent a repeat

1. What actually happened#

NixOS keeps two kinds of state, and only one of them is in your flake:

Rebuilding to a host that does not declare your user removes the account. Your home directory is not declared, so it stays. Then the trap closes:

       DECLARED in the flake                 MUTABLE on the disk
       (rebuilt into every generation)       (written once, never rolled back)

gen 41   users.daemonsec = { … }     ──────▶  /etc/shadow: daemonsec hash  ✓
            │                                 /home/daemonsec              ✓
            │
            │   nh os switch -H nixdaemon   ← a host that declares only `operator`
            ▼
gen 42   users.operator  = { … }     ──────▶  /etc/shadow: daemonsec GONE   ✗
                                              /home/daemonsec   still there ✓

boot gen 41 again?
   the account comes back, from the generation  ──▶  but /etc/shadow is NOT
                                                      rolled back with it
                                                      = login fails on every entry

-H selects a whole nixosConfigurations host, not a username. In this repo nixdaemon is the generic host with user operator, and nixos is the owner's laptop with user daemonsec. Only switch a machine to its own host.

The one idea to take from this: a generation restores the configuration, not the password. So you cannot fix it from the boot menu. You need to be root without logging in, which is what the live USB gives you — then you activate an old generation (that recreates the account) and set the password yourself (that fills in the mutable state).

Both paths below do exactly those two things, using a saved generation that is already on your disk. Nothing is downloaded, built or reinstalled.


2. Words that trip people up#

Word What it means here
generation One complete saved system build, kept as /nix/var/nix/profiles/system-<N>-link. Every entry in your boot menu is a generation.
activation The step that makes a generation live: it creates users, links /etc, starts services. This is the part that brings your account back.
profile The symlink recording which generation is current. nix-env --switch-generation moves it.
store path /nix/store/<hash>-nixos-system-<host>-<version> — one generation's immutable build directory. The <host> in the middle tells you which machine it was built for, which is how you avoid restoring the wrong host's config.
mutable state What NixOS writes once and never rebuilds: /etc/shadow, /var/lib/nixos/uid-map. Not in any generation, so not covered by rollback.
mutableUsers true: passwd changes stick. false: every boot rewrites passwords from the flake, so a manual reset is silently undone.
hashedPassword / hashedPasswordFile A password declared in the flake. Same problem — it overwrites your reset at the next boot.
subvolume A named sub-filesystem inside a single Btrfs partition (@, nix, home). They are mounted separately, all from the same device.
nixos-enter Runs a command inside the installed system mounted at /mnt. It activates the generation first — that activation is the whole point, not a side effect.

3. Will this work on my machine?#

Check this before you start. Both paths make the same assumptions.

Works Does not work
Filesystems ext4, ext2, Btrfs, XFS, FAT (for /boot) ZFS
Account layout standard NixOS users-groups.json userborn, or custom user managers
Disk layout plain partitions, Btrfs subvolumes impermanence / bind-mounted /etc or /var
Encryption LUKS — if you unlock it first anything the live USB cannot open
Generations still on disk garbage-collected or deleted

Read-only inspection has to disable journal and log replay, so a dirty filesystem may be unreadable. If that happens, assess it — do not force a repair to get past this guide.

You also need a NixOS installer USB of the same CPU architecture as the installed system, a terminal on it, and (for Path A) a network connection.


4. Pick your path#

Can you still log in as root on a text console (Ctrl+Alt+F2)?
├── yes ────────────────────────────────────────────▶ you don't need this guide.
│                                                     Just run: passwd <user>
└── no
    ├── does your machine appear in the "Does not work"
    │   column in section 3?
    │   └── yes ─────────────────────────────────────▶ STOP. Repair it by hand.
    │                                                  These steps can make an
    │                                                  impermanence/ZFS box worse.
    └── no
        ├── happy to download and read a script ────▶ Path A — it finds the right
        │                                              generation for you and
        │                                              refuses the wrong ones
        └── want to type every command yourself ────▶ Path B — same result, more
                                                       steps, no download

Path A is the shorter route and it applies the safety checks for you. Path B is there when you cannot or will not download anything, and as the explanation of what Path A is doing.


5. Path A — the recovery script#

The script works on the installed disk while the live USB is running. It does not install NixOS, format partitions, delete home directories, recursively change ownership, or reboot. It mounts read-only until you type an explicit confirmation phrase.

5.1 Download it#

The script lives at scripts/recover-user.py in this repo. Use GitLab:

curl --fail --show-error --location --proto '=https' \
  https://gitlab.com/DAEMON-404/NixDaemon/-/raw/main/scripts/recover-user.py \
  --output /tmp/nixdaemon-recover.py

# no curl on the installer? use wget instead:
wget -O /tmp/nixdaemon-recover.py \
  https://gitlab.com/DAEMON-404/NixDaemon/-/raw/main/scripts/recover-user.py

Or the git.daemon-sec.xyz mirror, which serves every file in the repo raw and is useful when GitLab is unreachable. It follows GitLab on a 15-minute timer, so GitLab stays the source of truth:

curl --fail --show-error --location --proto '=https' \
  https://git.daemon-sec.xyz/NixDaemon/raw/scripts/recover-user.py \
  --output /tmp/nixdaemon-recover.py

You should see a saved file and no error. A 404 means the script is not published at that URL — stop, rather than executing an error page. To read it in a browser first, with a download button: https://git.daemon-sec.xyz/NixDaemon/file/scripts/recover-user.py.html.

Already have it on a second USB? Use that path everywhere below instead; recovery uses generations already on the disk and never fetches a replacement system.

5.2 Read it, then get a Python#

less /tmp/nixdaemon-recover.py

# the installer may already have python3 — check before downloading one:
command -v python3 || nix-shell -p python3

5.3 Inspect, read-only#

Nothing is written in this mode. Run it first, every time:

sudo "$(command -v python3)" /tmp/nixdaemon-recover.py

It asks for the installed root partition — not the installer USB:

  1. It prints every disk with its filesystem type, label and UUID. Enter the root device. It refuses a device already mounted outside the script, so unmount any earlier rescue mounts first. For LUKS, unlock the volume yourself first and give the resulting /dev/mapper/... device; the script never asks for or stores a key.
  2. Enter the root Btrfs subvolume (@, root, …), or press Enter for the default subvolume or a non-Btrfs filesystem. If the Nix store is on its own subvolume or device, it asks for that next.
  3. It then reads the installed /etc/fstab and asks before mounting each separate /home, /var, /nix and boot filesystem, read-only.

You should see the report described in 5.4, and then:

Inspection complete. No activation or password changes. Re-run with --recover to restore.
All script-owned mounts unmounted.

5.4 Read the report#

This is the part worth slowing down for. The report has four blocks:

Installed accounts (no password hashes printed):
  root: uid=0, home=/root, locked
  operator: uid=1000, home=/home/operator, hash present (expiry/PAM may still prevent login)

Remaining home directories (names are candidates, not proof of an account):
  operator: uid=1000, account present
  daemonsec: uid=1000, ACCOUNT MISSING

Previous passwd backup (may contain the former username/UID):
  daemonsec: uid=1000, home=/home/daemonsec

Saved generations: number | link date | build | declared regular users
  40 | 2026-10-08T21:15 | <hash>-nixos-system-nixos-25.11.20261008 | daemonsec
  41 | 2026-10-09T18:42 | <hash>-nixos-system-nixos-25.11.20261009 | daemonsec
  42 | 2026-10-10T11:07 | <hash>-nixos-system-nixdaemon-25.11.20261010 | operator

Needs recovery (declared by a saved build, cannot log in now). Installed host: nixos
  daemonsec: recommended generation 41 (2026-10-09T18:42, <hash>-nixos-system-nixos-25.11.20261009) -- the newest build that can restore it

This shows the shape of the output, assembled from the script's own messages. Your numbers, dates and hashes will differ — read yours, do not pattern-match against this.

How to read it:

The search deliberately skips generations that would fail or be undone — ones that never declared the user, ones built for a different host than the installed one, and ones with mutableUsers = false or a declared hashedPassword/hashedPasswordFile, where a passwd reset is overwritten at the next boot. If nothing can restore the account, it says so with the reason instead of naming a generation it would later refuse.

5.5 Recover#

Same questions as before, then the recovery prompts:

sudo "$(command -v python3)" /tmp/nixdaemon-recover.py --recover
  1. Enter your exact lost username.
  2. At the generation prompt, the recommendation from section 5.4 is the default — press Enter to accept it, or type another number to override. Link dates help you identify builds, but they are not a substitute for the hostname and user checks the script already applied.
  3. It prints the username, expected UID, home and generation, and warns that activation can change other services' persistent state.
  4. Type the exact phrase RECOVER <username> <number>. Nothing has been written before this point.
  5. It remounts writable, backs up the account files, and prints where: Account backup on installed disk: /var/lib/nixdaemon-recovery/<UTC timestamp>
  6. It asks whether to also set a root password for emergency console access. Say yes — it is how you get in next time without a USB.
  7. It activates the selected generation, runs passwd for your user (and for root if you said yes), switches the system profile and updates the boot loader.

That backup directory is root-only and contains password hashes — keep it private. It holds the /etc account files, the NixOS user/group mapping and the previous profile target. It is not a backup of your data; if you want one, copy your files to another disk before you get here.

You should see, at the end:

Recovery commands completed for <username>, generation <N>.
...
All script-owned mounts unmounted.

Wait for that unmount line before touching the disk. Then:

sudo reboot

5.6 Verify#

Remove the USB and choose the recovered generation. Test a text-console login first (Ctrl+Alt+F2) — before troubleshooting any desktop problem. Once in:

id
ls -ldn "$HOME"

The UID from id and the numeric owner of your home must agree. Do not recursively chown your home as a blanket fix — some files legitimately have other owners. Then go to section 9 and repair the flake before you rebuild again, or the same lockout recurs.


6. Path B — by hand#

Same outcome, no download. Run each command separately and check its output before the next one. If a command fails, stop at that step.

Two rules for this whole section:

One extra tool is needed in step 6.4:

command -v jq || nix-shell -p jq

6.1 Set your values once#

lsblk -f                 # find your devices
findmnt -R /mnt          # no output = nothing mounted there yet

If findmnt lists an earlier rescue mount, finish with it and unmount it first. Never mount a second root over an existing mount.

Encrypted? Unlock the correct LUKS partition now, and use the mapper device below:

sudo cryptsetup open /dev/nvme0n1p2 rescue-root    # your partition, not this one

Now fill these in for your machine — everything after this point uses them:

recovery_root=/dev/disk/by-uuid/XXXXXXXX          # or /dev/mapper/rescue-root
recovery_boot=/dev/disk/by-uuid/XXXX-XXXX
recovery_user=yourusername

6.2 Mount the installed system, read-only#

nologreplay stops Btrfs replaying its log — i.e. writing — while you look around. The mounts below match a Btrfs root with separate nix and home subvolumes and an EFI /boot:

sudo mkdir -p /mnt
sudo mount -o ro,nologreplay "$recovery_root" /mnt
sudo mount -o ro,nologreplay,subvol=nix "$recovery_root" /mnt/nix
sudo mount -o ro,nologreplay,subvol=home "$recovery_root" /mnt/home
sudo mount -o ro "$recovery_boot" /mnt/boot

Adjust for your own layout:

Your situation Change
Named root subvolume (@) add subvol=@ to the root mount
ext4 root ro,noload instead of ro,nologreplay
XFS root ro,norecovery
Separate real partitions mount them at their actual paths, no subvol=
Separate /var holding account state mount it too

You should see no errors, and /mnt/etc should exist. A missing mount directory means the root or subvolume choice is wrong — fix that before going on, rather than creating the directory.

6.3 Find the missing account and its home#

# ordinary user accounts and their UIDs
sudo awk -F: '$3 >= 1000 && $3 < 60000 {print $1, "uid=" $3, "home=" $6}' /mnt/etc/passwd

# the selected user's password status, without printing the hash
sudo awk -F: -v user="$recovery_user" '
  $1 == user {
    found = 1
    print $1, ($2 ~ /^[!*]/ ? "locked" : ($2 == "" ? "empty password" : "password hash present"))
  }
  END { if (!found) print user, "has no shadow entry" }
' /mnt/etc/shadow

# the home directory and its NUMERIC owner — write this number down
sudo ls -lan /mnt/home
sudo stat -c 'uid=%u gid=%g home=%n' "/mnt/home/$recovery_user"

You should see your username absent from passwd, has no shadow entry (or locked), and a home directory that still exists with a numeric UID. Note that UID — step 6.6 compares against it.

If the home directory is missing, check whether /home is a separate filesystem that still needs mounting. A hash being present does not rule out an expired account or another login problem.

6.4 Choose a generation and check what it declares#

sudo ls -l /mnt/nix/var/nix/profiles/system-*-link

Pick a known-good generation from before the bad switch, built for the correct machine — look at the -nixos-system-<host>- part of each target. On this laptop that means nixos, not the generic nixdaemon. Then:

recovery_generation=42                            # replace with your number
recovery_system=$(readlink "/mnt/nix/var/nix/profiles/system-$recovery_generation-link")
printf '%s\n' "$recovery_system"

# the build must still be on the disk — a profile link alone is not enough
sudo test -x "/mnt$recovery_system/activate" && echo 'Saved build is present'

You should see an absolute /nix/store/...-nixos-system-... path, then Saved build is present. If that check fails, verify the /nix mount and pick a generation whose store files still exist.

Compare the installed filesystem table with what you actually mounted:

sudo chroot /mnt "$recovery_system/sw/bin/cat" /etc/fstab

This plain chroot only runs cat — it does not activate anything. Going through the chroot makes absolute /nix/store symlinks resolve on the installed disk instead of accidentally reading the USB's own store. Mount any missing /home, /var, /nix or boot filesystem before continuing.

Now read what that build declares about your user:

recovery_users=$(sudo grep -oE '/nix/store/[a-z0-9]+-users-groups\.json' \
  "/mnt$recovery_system/activate" | sort -u)
printf '%s\n' "$recovery_users"

There must be exactly one path. None means this build uses a different account system and needs its own review before activation.

sudo chroot /mnt "$recovery_system/sw/bin/cat" "$recovery_users" |
  jq --arg user "$recovery_user" '{
    mutableUsers,
    users: [.users[] | select(.name == $user) | {
      name, uid, home, isSystemUser,
      persistentPassword: (.password != null or .hashedPassword != null or .hashedPasswordFile != null)
    }]
  }'

No passwords or hashes are printed. You should see all four of these, or this generation is the wrong one:

Field Required Why
users your user present, isSystemUser: false a generation that never declared it cannot restore it
uid matches the home owner from 6.3, or null null means NixOS assigns it — check again after activation
home the expected path wrong home means the wrong account
mutableUsers true false means your passwd reset is overwritten at boot
persistentPassword false true means the flake's declared password wins at boot

If the user is absent, try an earlier generation. If mutableUsers is false or persistentPassword is true, repair the declared password or secret first — resetting by hand will not survive.

6.5 Back up the account state, then remount writable#

Make a root-only backup while everything is still read-only. It covers /etc, NixOS account state and the profile links. It does not follow symlinks into the store and is not a backup of your home files:

recovery_backup=$(sudo mktemp -d /tmp/nixdaemon-recovery.XXXXXXXX)
sudo tar --acls --xattrs --numeric-owner -cpf "$recovery_backup/accounts.tar" \
  -C /mnt etc var/lib/nixos nix/var/nix/profiles
sudo tar -tf "$recovery_backup/accounts.tar" >/dev/null && echo 'Account backup is readable'

You should see Account backup is readable.

Unmount, then mount the same layout writable. This drops nologreplay/noload/norecovery rather than trying to carry inspection options into a writable mount:

sudo umount -R /mnt
sudo mount "$recovery_root" /mnt
sudo mount -o subvol=nix "$recovery_root" /mnt/nix
sudo mount -o subvol=home "$recovery_root" /mnt/home
sudo mount "$recovery_boot" /mnt/boot

Use the same subvol= options and extra filesystems you verified in 6.2. /tmp on the live USB is lost at reboot, so copy the backup onto the installed disk now:

sudo install -d -m 700 /mnt/var/lib/nixdaemon-recovery
sudo cp -a "$recovery_backup" /mnt/var/lib/nixdaemon-recovery/

That copy contains password hashes — keep it private. If you also want your work backed up, copy it to another disk before the next step.

6.6 Activate the generation and set the password#

Point the installed profile at the generation you checked, then enter the system:

sudo nix-env -p /mnt/nix/var/nix/profiles/system --switch-generation "$recovery_generation"
sudo nixos-enter --root /mnt

nixos-enter activates the selected generation — this is the step that recreates the account. It also runs that build's other activation steps. Read its output.

nixos-enter can still drop you into a shell after an activation error, so confirm activation explicitly, with a checked status:

IN_NIXOS_ENTER=1 /nix/var/nix/profiles/system/activate && echo 'Activation completed'

You should see Activation completed. If not, stop and resolve the reported error — the system may already have changed, and getting a shell is not proof of success.

From here you are inside the installed system, so paths no longer start with /mnt. Substitute your own username:

id yourusername
stat -c 'uid=%u gid=%g home=%n' /home/yourusername

You should see a UID matching the home owner you recorded in 6.3, before activation. If the account is still missing, exit and try another generation. If the UIDs differ, stop and investigate the original mapping — do not recursively chown the home to make the numbers agree.

passwd yourusername
passwd root           # optional, strongly recommended: emergency console login

6.7 Update the boot menu, unmount, reboot#

Still inside the installed system, make the selected generation the default:

/nix/var/nix/profiles/system/bin/switch-to-configuration boot

If this fails, keep the error and check that the real boot/EFI partition is mounted where this generation expects it. Fix it before rebooting if you can. An existing GRUB entry for the chosen generation may still let you boot it manually — but a failed update does not guarantee it is the default.

exit                          # back to the live USB
sudo umount -R /mnt

If unmounting fails, run findmnt -R /mnt to see what is still held, and close any shell using it. Wait for a successful unmount before removing the disk. If you opened a LUKS mapping in 6.1, close it:

sudo cryptsetup close rescue-root
sudo reboot

Then verify exactly as in section 5.6.


7. When something goes wrong#

What you see What it means What to do
404 on the download the script is not published at that URL stop; do not pipe an error page into Python. Use the mirror, or Path B
Device is already mounted outside this script an earlier rescue mount is still active findmnt -R /mnt, unmount it, re-run
Unsupported filesystem …; unlock LUKS first you gave the encrypted partition, not the mapper cryptsetup open, then give /dev/mapper/...
No /etc found wrong root partition or wrong subvolume re-check lsblk -f; try the named subvolume (@)
Manual recovery needed for filesystem: … a bind mount or impermanence layout Path A cannot help; see section 3
NO build can restore it + a reason every generation is disqualified fix the stated cause (immutable users, declared password), or the flake, first
Generation N cannot restore <user> that specific generation is disqualified accept the recommended default instead
Home owner and declared UID do not agree the generation's UID ≠ the home's owner investigate the original mapping. Do not chown -R
UID mismatch after activation; stopped. activation assigned a different UID same — stop, investigate, do not chown -R
Activation error, but you still get a shell nixos-enter tolerates activation failure resolve the error; a shell is not success
switch-to-configuration boot fails boot/EFI partition not mounted as expected fix the mount; pick the generation manually in GRUB if needed
UNMOUNT FAILED something still holds the mount findmnt -R, close it. Do not remove the disk yet

Two limits worth stating plainly: activation is not atomic and can alter other persistent state. And a failed boot-loader update can leave the profile already changed — use the firmware or GRUB menu to select your generation manually if its old entry still exists. On error the script exits unsuccessfully and unmounts its own mounts; it does not reboot, and it does not claim to roll back partial changes.


8. This laptop's values#

These are the values from the recovery on 2026-10-10, for reference only. Other machines must use their own devices and subvolumes — verify with lsblk -f.

Prompt Laptop value
Root device /dev/disk/by-uuid/e2664576-4e65-4c79-ac1c-9e2fa9e12a26
Root subvolume Enter (default)
Separate /nix device, if prompted same device as root
/nix subvolume nix
/home same device, home subvolume; confirm from the installed fstab
Boot /dev/disk/by-uuid/D3FC-22C2; confirm from the installed fstab
Host to look for in generations nixos (not nixdaemon)
Lost user daemonsec

9. Prevent a repeat#


Implementation reference: NixOS's nixos-enter source activates the selected installed system before running the requested command — which is why both paths check activation explicitly, since nixos-enter itself tolerates an activation failure. See also the NixOS account implementation.