#!/usr/bin/env python3
"""Inspect an offline NixOS disk; optionally recover a user from a saved generation.
Python standard library only. Run from a NixOS installer USB. See docs/recovery.md.
Never import this module with side effects: tests use the parsing helpers.
"""
import argparse
import datetime
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import tempfile
class RecoveryError(Exception):
pass
def run(*args, capture=False):
return subprocess.run(args, check=True, text=True,
stdout=subprocess.PIPE if capture else None).stdout
def ask(prompt):
return input(prompt + ": ").strip()
def inside(root, path):
"""Resolve absolute AND intermediate symlinks within the offline root.
Path.resolve() would follow /nix/store symlinks into the live USB's store.
"""
root = Path(root)
pending = str(path).split("/")
parts = []
links = 0
while pending:
part = pending.pop(0)
if part in ("", "."):
continue
if part == "..":
if parts:
parts.pop()
continue
candidate = root.joinpath(*parts, part)
if candidate.is_symlink():
links += 1
if links > 40:
raise RecoveryError("Too many symlinks: " + str(path))
target = os.readlink(candidate)
if target.startswith("/"):
parts = []
pending = target.split("/") + pending
else:
parts.append(part)
return root.joinpath(*parts)
def accounts(path):
result = {}
if path.is_file():
for line in path.read_text().splitlines():
fields = line.split(":")
if len(fields) == 7 and fields[2].isdigit():
result[fields[0]] = (int(fields[2]), fields[5])
return result
def password_states(path):
result = {}
if path.is_file():
for line in path.read_text().splitlines():
fields = line.split(":")
if len(fields) >= 2:
value = fields[1]
result[fields[0]] = ("locked" if value.startswith(("!", "*"))
else "EMPTY password" if not value
else "hash present (expiry/PAM may still prevent login)")
return result
def declarations(root, system):
activation = inside(root, system + "/activate")
if not activation.is_file():
return None
matches = set(re.findall(r"/nix/store/[a-z0-9]+-users-groups\.json",
activation.read_text()))
if len(matches) != 1:
return None # Refuse unsupported userborn/custom activation layouts.
path = inside(root, matches.pop())
return json.loads(path.read_text()) if path.is_file() else None
def generations(root):
result = {}
profiles = inside(root, "/nix/var/nix/profiles")
for link in sorted(profiles.glob("system-*-link")):
match = re.fullmatch(r"system-([0-9]+)-link", link.name)
if not match or not link.is_symlink():
continue
resolved = inside(root, "/nix/var/nix/profiles/" + link.name)
system = "/" + str(resolved.relative_to(root))
if not re.fullmatch(r"/nix/store/[a-z0-9]+-nixos-system-[^/]+", system):
continue
if not resolved.is_dir():
continue
date = datetime.datetime.fromtimestamp(link.lstat().st_mtime).isoformat(timespec="minutes")
result[int(match[1])] = (system, declarations(root, system), date)
return result
def hostname(root):
path = inside(root, "/etc/hostname")
return path.read_text().strip() if path.is_file() else ""
def build_host(system):
"""The host a build was made for: /nix/store/<hash>-nixos-system-<host>-<version>."""
return Path(system).name.split("-nixos-system-", 1)[-1]
def blocker(data, name):
"""Why this generation cannot restore `name`, or None when it can.
recover() refuses on exactly these grounds, so a recommendation built from
this function can never point at a generation recover() would then reject.
"""
if not data:
return "no readable user metadata"
user = next((u for u in data["users"] if u["name"] == name), None)
if not user or user.get("isSystemUser"):
return "does not verifiably declare this regular user"
if data.get("mutableUsers") is not True:
return "immutable users, so a passwd reset may be overwritten at boot"
if any(user.get(k) is not None for k in ("password", "hashedPassword", "hashedPasswordFile")):
return "declares a persistent password that would overwrite the reset"
return None
def recommend(root, builds, name):
"""The last build where `name` was active: newest generation that can restore it.
Builds for the installed hostname win over builds for another host, because
a switch to a different host is what usually drops the account in the first
place. Within that, the highest generation number is the most recent build.
"""
usable = [n for n, (_system, data, _date) in builds.items() if blocker(data, name) is None]
host = hostname(root)
matching = [n for n in usable
if host and (build_host(builds[n][0]) == host
or build_host(builds[n][0]).startswith(host + "-"))]
return max(matching or usable, default=None)
def fstab(root):
path = inside(root, "/etc/fstab")
if not path.is_file():
raise RecoveryError("Cannot read the installed /etc/fstab. Mount the correct /nix first.")
result = []
for line in path.read_text().splitlines():
fields = line.split()
if not fields or fields[0].startswith("#") or len(fields) < 4:
continue
fields = [re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), f) for f in fields]
result.append(fields[:4])
return result
class Rescue:
def __init__(self):
self.root = Path(tempfile.mkdtemp(prefix="nixdaemon-rescue-", dir="/mnt"))
self.mounts = []
# Capture before mounting; reject disks used by the running system or
# another rescue session, including aliases and other Btrfs subvolumes.
self.busy = set(run("findmnt", "-rn", "-o", "MAJ:MIN", capture=True).split())
def mount(self, device, destination="/", subvol="", writable=False):
if device.startswith(("UUID=", "LABEL=")):
device = run("findfs", device, capture=True).strip()
device = os.path.realpath(device)
info = os.stat(device)
if not stat.S_ISBLK(info.st_mode):
raise RecoveryError("Not a block device: " + device)
number = f"{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}"
if number in self.busy:
raise RecoveryError("Device is already mounted outside this script: " + device)
fs = run("blkid", "-s", "TYPE", "-o", "value", device, capture=True).strip()
if fs not in ("ext4", "btrfs", "xfs", "vfat", "ext2"):
raise RecoveryError(f"Unsupported filesystem {fs!r}; unlock LUKS first. No disk was formatted.")
if subvol and (fs != "btrfs" or "," in subvol):
raise RecoveryError("Subvolumes require Btrfs and cannot contain commas.")
target = inside(self.root, destination)
if destination == "/":
target.mkdir(exist_ok=True)
elif not target.is_dir():
raise RecoveryError("Missing mount directory on installed disk: " + destination)
options = ["rw" if writable else "ro"]
if not writable:
# ro alone may replay a filesystem journal and write to disk.
options += {"ext4": ["noload"], "btrfs": ["nologreplay"],
"xfs": ["norecovery"]}.get(fs, [])
if subvol:
options.append("subvol=" + subvol)
run("mount", "-t", fs, "-o", ",".join(options), device, str(target))
self.mounts.append((device, destination, subvol, target))
def unmount(self):
while self.mounts:
run("umount", str(self.mounts[-1][3]))
self.mounts.pop()
def writable(self):
layout = list(self.mounts)
self.unmount() # Drop noload/nologreplay correctly before writable mounts.
for device, destination, subvol, _ in layout:
self.mount(device, destination, subvol, writable=True)
def prepare(self):
run("lsblk", "-o", "NAME,PATH,SIZE,FSTYPE,LABEL,UUID,MOUNTPOINTS")
print("Choose the installed root partition, NOT the USB. Unlock encryption first.")
device = ask("Root device (e.g. /dev/nvme0n1p2 or /dev/mapper/cryptroot)")
subvol = ask("Root Btrfs subvolume (e.g. @ or root; Enter for default/non-Btrfs)")
self.mount(device, subvol=subvol)
if not inside(self.root, "/etc").is_dir():
raise RecoveryError("No /etc found. Check the root partition/subvolume.")
if not inside(self.root, "/nix/var/nix/profiles").is_dir():
print("The Nix store is separate. For Btrfs 'nix', reuse the root device and enter nix.")
nixdev = ask("Device containing /nix")
nixsub = ask("/nix Btrfs subvolume (Enter for non-Btrfs/default)")
self.mount(nixdev, "/nix", nixsub)
entries = fstab(self.root)
print("Installed filesystem table:")
for entry in entries:
print(" " + " ".join(entry))
required = {"/nix", "/home", "/var", "/boot", "/boot/efi", "/efi"}
for dev, dest, _fs, opts in sorted(entries, key=lambda e: (e[1].count("/"), e[1])):
# Include nested /home and /var mounts: profiles/account state can
# reside there. Nonstandard bind/impermanence layouts fail closed.
if dest not in required and not dest.startswith(("/home/", "/var/", "/nix/", "/boot/")):
continue
if any(m[1] == dest for m in self.mounts):
continue
if "bind" in opts.split(",") or _fs not in ("ext4", "btrfs", "xfs", "vfat", "ext2"):
raise RecoveryError("Manual recovery needed for filesystem: " + dest)
options = dict(o.split("=", 1) for o in opts.split(",") if "=" in o)
if "subvolid" in options and "subvol" not in options:
raise RecoveryError("Use a named Btrfs subvolume; subvolid-only fstab is unsupported.")
print(f"Mount read-only: {dev} on {dest}")
if ask("Type yes to mount this filesystem") != "yes":
raise RecoveryError("Stopped: required filesystem not mounted: " + dest)
self.mount(dev, dest, options.get("subvol", ""))
if not inside(self.root, "/etc/NIXOS").exists():
raise RecoveryError("The chosen disk is not a readable NixOS installation.")
def inspect(self):
current = accounts(inside(self.root, "/etc/passwd"))
states = password_states(inside(self.root, "/etc/shadow"))
print("\nInstalled accounts (no password hashes printed):")
for name, (uid, home) in current.items():
if uid == 0 or 1000 <= uid < 60000:
print(f" {name}: uid={uid}, home={home}, {states.get(name, 'no shadow entry')}")
print("\nRemaining home directories (names are candidates, not proof of an account):")
home = inside(self.root, "/home")
if home.is_dir():
for entry in sorted(home.iterdir()):
if entry.is_dir() and not entry.is_symlink():
uid = entry.stat().st_uid
status = "account present" if entry.name in current else "ACCOUNT MISSING"
print(f" {entry.name}: uid={uid}, {status}")
print("\nPrevious passwd backup (may contain the former username/UID):")
for name, (uid, home) in accounts(inside(self.root, "/etc/passwd-")).items():
if 1000 <= uid < 60000:
print(f" {name}: uid={uid}, home={home}")
builds = generations(self.root)
print("\nSaved generations: number | link date | build | declared regular users")
for n, (system, data, date) in sorted(builds.items()):
names = ", ".join(u["name"] for u in data["users"] if not u.get("isSystemUser")) if data else "UNKNOWN (unsupported/missing metadata)"
print(f" {n} | {date} | {Path(system).name} | {names}")
# Anyone a saved build declared who now has no account, or cannot log in,
# is a candidate. For each, name the last build where they were active.
candidates = sorted({
user["name"]
for _system, data, _date in builds.values() if data
for user in data["users"]
if not user.get("isSystemUser")
and not states.get(user["name"], "").startswith("hash present")
})
if candidates:
host = hostname(self.root) or "unknown"
print(f"\nNeeds recovery (declared by a saved build, cannot log in now)."
f" Installed host: {host}")
for name in candidates:
number = recommend(self.root, builds, name)
if number is None:
reasons = sorted({blocker(data, name) for _s, data, _d in builds.values()
if blocker(data, name)})
print(f" {name}: NO build can restore it -- {'; '.join(reasons)}")
continue
system, _data, date = builds[number]
print(f" {name}: recommended generation {number} "
f"({date}, {Path(system).name}) -- the newest build that can restore it")
return builds
def recover(self, builds):
name = ask("Exact lost username to restore")
if not re.fullmatch(r"[a-z_][a-z0-9_-]*\$?", name):
raise RecoveryError("Unsupported username; use manual recovery.")
suggested = recommend(self.root, builds, name)
prompt = "Known-good generation number from BEFORE the bad switch"
if suggested is not None:
prompt += f" (Enter for {suggested}, the last build where {name} was active)"
number = ask(prompt) or ("" if suggested is None else str(suggested))
if not number.isdigit() or int(number) not in builds:
raise RecoveryError("Generation not found.")
system, data, _ = builds[int(number)]
reason = blocker(data, name)
if reason:
raise RecoveryError(f"Generation {number} cannot restore {name}: {reason}. "
"Pick another generation, or repair that setting/secret first.")
user = next(u for u in data["users"] if u["name"] == name)
home = user.get("home", "")
if not home.startswith("/home/") or not inside(self.root, home).is_dir():
raise RecoveryError("Expected home directory is not mounted/found; manual recovery required.")
uid = inside(self.root, home).stat().st_uid
if uid < 1000 or uid >= 60000 or user.get("uid") not in (None, uid):
raise RecoveryError("Home owner and declared UID do not agree; refusing an ownership change.")
print(f"\nRestore {name}, expected UID {uid}, home {home}, generation {number}: {system}")
print("This activates the OLD configuration, resets the password, changes the system profile")
print("and updates the boot loader. Activation can change services' persistent state.")
print("Account backups are saved first. This is not a full disk backup or an atomic operation.")
if ask(f"Type RECOVER {name} {number} to permit these writes") != f"RECOVER {name} {number}":
raise RecoveryError("Cancelled before writes.")
self.writable()
stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
backup = inside(self.root, "/var/lib/nixdaemon-recovery") / stamp
backup.mkdir(parents=True, mode=0o700)
for relative in ("etc/passwd", "etc/shadow", "etc/group", "etc/gshadow",
"etc/passwd-", "etc/shadow-", "etc/group-", "etc/gshadow-",
"var/lib/nixos/declarative-users", "var/lib/nixos/declarative-groups",
"var/lib/nixos/uid-map", "var/lib/nixos/gid-map"):
source = inside(self.root, relative)
if source.is_file():
shutil.copy2(source, backup / relative.replace("/", "_"))
profile = inside(self.root, "/nix/var/nix/profiles/system")
(backup / "recovery.json").write_text(json.dumps({
"previous_system": "/" + str(profile.relative_to(self.root)),
"selected_system": system, "generation": number, "username": name,
"home_uid": uid,
}, indent=2) + "\n")
print("Account backup on installed disk: /var/lib/nixdaemon-recovery/" + stamp, flush=True)
reset_root = ask("Also set a root password for emergency console access? Type yes") == "yes"
# nixos-enter ignores activation failure internally. Re-run explicitly
# with a checked status so an activation error cannot report success.
command = r'''
set -euo pipefail
system=$1; username=$2; generation=$3; expected_uid=$4; reset_root=$5
export PATH="$system/sw/bin:/run/wrappers/bin"
IN_NIXOS_ENTER=1 "$system/activate"
actual_uid=$(id -u "$username")
if [ "$actual_uid" != "$expected_uid" ]; then
echo "UID mismatch after activation; stopped. Do not recursively chown the home." >&2
exit 1
fi
passwd "$username"
if [ "$reset_root" = yes ]; then passwd root; fi
nix-env -p /nix/var/nix/profiles/system --switch-generation "$generation"
"$system/bin/switch-to-configuration" boot
'''
run("nixos-enter", "--root", str(self.root), "--system", system, "--",
system + "/sw/bin/bash", "-c", command, "nixdaemon-recovery",
system, name, number, str(uid), "yes" if reset_root else "no")
state = password_states(inside(self.root, "/etc/shadow")).get(name, "missing")
if not state.startswith("hash present"):
raise RecoveryError("Password verification failed: " + state)
print(f"\nRecovery commands completed for {name}, generation {number}.")
print("After unmount succeeds, reboot and choose that generation. Test a console login first.")
print("Fix your flake's user/host settings before any future rebuild. No reboot is automatic.")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--recover", action="store_true", help="offer explicit recovery after read-only inspection")
args = parser.parse_args()
if os.geteuid() != 0:
parser.error("Run as root from a NixOS installer USB.")
if not sys.stdin.isatty():
parser.error("An interactive terminal is required; download the script before running it.")
required = ["lsblk", "findmnt", "findfs", "blkid", "mount", "umount"]
if args.recover:
required += ["nixos-enter"]
for command in required:
if not shutil.which(command):
parser.error("Missing tool: " + command + ". Use a NixOS installer USB.")
os.umask(0o077)
rescue = Rescue()
try:
rescue.prepare()
builds = rescue.inspect()
if args.recover:
rescue.recover(builds)
else:
print("\nInspection complete. No activation or password changes. Re-run with --recover to restore.")
finally:
try:
rescue.unmount()
rescue.root.rmdir()
print("All script-owned mounts unmounted.")
except (OSError, subprocess.CalledProcessError):
print(f"UNMOUNT FAILED: inspect findmnt -R {rescue.root}; do not remove the disk yet.", file=sys.stderr)
raise
if __name__ == "__main__":
try:
main()
except (RecoveryError, OSError, ValueError, subprocess.CalledProcessError, EOFError, KeyboardInterrupt) as error:
print(f"Stopped: {error or 'interrupted'}. No automatic reboot. If recovery began, inspect backups before retrying.", file=sys.stderr)
sys.exit(1)