Metadata-Version: 2.4
Name: dark-instux
Version: 0.1.0
Summary: Build bootable USB keys that install Debian, Ubuntu, AlmaLinux or Fedora offline and unattended.
Keywords: linux,installer,usb,unattended,offline,provisioning,debian,ubuntu,almalinux,fedora,uefi,bios
Author: Frédéric Laurencin
Author-email: Frédéric Laurencin <flaurencin2@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Natural Language :: English
Classifier: Topic :: System :: Installation/Setup
Classifier: Topic :: System :: Systems Administration
Classifier: Topic :: System :: Operating System
Requires-Dist: pyyaml>=6.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# dark-instux

> **⚠️ WARNING: pre-release experiment. Run with extreme caution.**
>
> - dark-instux **erases disks**: the USB key at build time, and every disk it matches on the
>   target machine at install time. A wrong device or a wrong disk matcher means lost data.
> - It is **far from bullet-proof**. It is an experiment, not a finished product, and it may stay
>   that way. Expect bugs, rough edges and breaking changes without notice.
> - It is **Linux only**: the build must run on a Linux workstation (root, podman), and the
>   targets are Linux hosts.
> - Test in a VM (QEMU) or on disposable hardware first, and keep backups. Use it at your own
>   risk: there is no warranty (see the license).

dark-instux builds a USB key that installs **one Linux host** completely **offline** and
**unattended**. You build the key on your workstation, edit one file on it, plug it into the
target machine and power on. The machine partitions its disks, installs the system and configures
it, without anyone in front of it. At the end a UEFI machine reboots into the new system by
itself; a legacy BIOS machine asks you to pull the key out, then restarts.

Supported targets: **Debian, Ubuntu, AlmaLinux, Fedora** on **amd64**, booting **UEFI** (Secure
Boot on or off) or **legacy BIOS**: the same key boots both ways. Disks are laid out with
[py-part-recipe](https://pypi.org/project/py-part-recipe/), so RAID and LVM work.

> - What is on the key, partition by partition, and how it is built and booted:
>   [docs/key-anatomy.md](docs/key-anatomy.md)
> - Developers: [DEVELOPMENT.md](DEVELOPMENT.md) for the architecture, the code layout and how to
>   test and extend dark-instux.
> - Tutorials, each with ready-to-use files and QEMU test commands:
>   - [A hardened Debian 13 Podman server](docs/tutorials/podman-server-anssi.md): UEFI, four
>     disks in RAID 1, LVM, XFS, ANSSI BP-028 partitioning, rootless containers under systemd.
>   - [A French Xfce desktop on an old legacy-BIOS laptop](docs/tutorials/xfce-laptop-bios.md):
>     Debian 13, one disk with LVM, full Xfce and LibreOffice, firmware from `non-free-firmware`.

---

## Quick start

```sh
# 1. On your workstation (Linux, root, podman): build the key. Everything on /dev/sdb is erased.
sudo dark-instux build --distro debian --storage single-lvm --device /dev/sdb

# 2. Edit host.yml on the key's CONFIG partition, then check it
dark-instux validate /media/$USER/CONFIG/host.yml

# 3. Boot the target machine from the key. A new key starts in check mode: it only reports the
#    disks it found in CONFIG/dark-instux/preflight.json, then powers off.
# 4. Once the disks are right, set `install.mode: install` in host.yml and boot the key again.
```

Details for each step follow, starting with [Requirements](#requirements).

---

## Contents

1. [How it works](#how-it-works)
2. [Boot modes: UEFI, legacy BIOS, or both](#boot-modes-uefi-legacy-bios-or-both)
3. [Requirements](#requirements)
4. [Installing dark-instux](#installing-dark-instux)
5. [Step 1: build a key](#step-1-build-a-key)
6. [Step 2: describe the host (host.yml)](#step-2-describe-the-host-hostyml)
7. [Step 3: identify the disks](#step-3-identify-the-disks)
8. [Step 4: choose the disk layout (storage.yml)](#step-4-choose-the-disk-layout-storageyml)
9. [Step 5: validate, check, install](#step-5-validate-check-install)
10. [After the installation](#after-the-installation)
11. [Troubleshooting](#troubleshooting)
12. [What is on the key](#what-is-on-the-key)
13. [Security notes](#security-notes)
14. [Command reference](#command-reference)
15. [host.yml reference](#hostyml-reference)

---

## How it works

```mermaid
flowchart LR
    subgraph WS["Admin workstation (online, root)"]
        B["dark-instux build"] --> K[("USB key")]
        K --> E["Edit CONFIG/host.yml"]
        E --> V["dark-instux validate"]
    end
    subgraph T["Target machine (offline)"]
        BOOT["Boot from the key"] --> PF{"Preflight OK?"}
        PF -- "no" --> STOP["Stop: report on the key"]
        PF -- "mode: check" --> OFF["Report disks, power off"]
        PF -- "mode: install" --> INST["Install"]
        INST -- "UEFI" --> RB["Reboot into the new system"]
        INST -- "legacy BIOS" --> RK["Remove the key: restarts into the new system"]
    end
    V -- "carry the key" --> BOOT
```

The build runs in six steps (`[1/6]` ... `[6/6]` in its output):

```mermaid
flowchart LR
    IMG["1. Pull the official container image (pinned by digest)"]
    IMG --> ROOT["2. Export its root filesystem: rootfs.tar.gz"]
    IMG --> REPO["3. Resolve updates, baseline and your packages: local repository"]
    LIVE["4. Build the live system (Debian)"]
    ROOT --> STAGE["5. Stage the partitions, write and sign the manifest"]
    REPO --> STAGE
    LIVE --> STAGE
    STAGE --> WRITE["6. Write the key (or an image file)"]
```

What happens during the build:

1. The **official container image** of the distribution is downloaded and pinned by digest.
2. Its root filesystem becomes `rootfs.tar.gz` on the key.
3. In that same image, the latest **updates**, a **baseline** (kernel, bootloader, SSH, NTP,
   network...) and **your packages** are downloaded with all their dependencies and turned into a
   local package repository on the key.
4. A small **live system** (Debian) is added: it boots the target and runs the installer.
5. Everything is listed with its checksum in a **signed manifest**.

What happens on the target:

1. The key boots (UEFI with or without Secure Boot, or legacy BIOS) and the installer starts by
   itself. The installed system boots the same way the key was booted.
2. **Preflight**: it verifies the key, validates your files and finds the disks. Nothing has been
   written yet.
3. It partitions the disks, unpacks the root filesystem, installs the updates and packages from
   the key, configures the system and installs the bootloader.
4. It marks the key as used. **UEFI**: it reboots straight into the new system. **Legacy BIOS**: it
   asks you to remove the key and restarts as soon as you do.

---

## Boot modes: UEFI, legacy BIOS, or both

Three rules decide everything:

1. **The key boots both ways** (UEFI, with or without Secure Boot, and legacy BIOS), unless it was
   built with `--uefi-only`.
2. **The installed system boots the same way the key was booted.** There is no setting for it:
   the installer looks at how the machine started the key. A machine that can do both (a UEFI
   machine with a compatibility/CSM mode) usually lists the key twice in its boot menu, for
   example `UEFI: SanDisk` and `SanDisk`; the entry you choose decides.
3. **The disk layout must contain the boot partition of that mode**: an ESP (FAT32 on
   `/boot/efi`) for UEFI, a 1 MiB `bios_grub` partition for legacy BIOS. The stock profiles have
   both, so they work either way.

| | UEFI | Legacy BIOS |
| --- | --- | --- |
| How the key starts | firmware runs `EFI/BOOT/BOOTX64.EFI` (shim, then signed GRUB) | BIOS runs the MBR code, then GRUB from the key's 1 MiB BIOS partition |
| Secure Boot | supported, on or off | does not exist |
| Layout needs | ESP on `/boot/efi` | partition with `flags: [bios_grub]` (on every disk of a RAID 1) |
| Boot loader installed on the host | the distribution's signed shim + GRUB on the ESP | GRUB for BIOS on every disk with a `bios_grub` partition |
| Boot order | the installer puts the new system first and sets it as the firmware's "next boot" | left to the BIOS settings |
| End of the installation | reboots into the new system by itself | shows "Remove the USB key now", restarts as soon as it is removed |
| Key booted again after install | hands control back to the firmware, which starts the host | shows "Remove the USB key", Enter restarts |

Which key to build:

| You install | Build with | Workstation needs |
| --- | --- | --- |
| UEFI and legacy BIOS machines (default) | nothing special | GRUB for BIOS (`grub-pc-bin` or `grub2-pc-modules`) |
| UEFI machines only | `--uefi-only` | nothing more |
| Very old BIOS machines that do not list the key | add `--pmbr-boot-flag` | same as the default |

`--pmbr-boot-flag` marks the key's protective MBR entry active. A machine that needs it for the
key needs it for its own disk too, so a BIOS installation from such a key marks the installed
disks the same way.

To check before installing which way a machine booted the key, use check mode: `preflight.json`
records `"boot_mode": "uefi"` or `"bios"`, and the installer prints it on the screen.

---

## Requirements

**Workstation** (where the key is built):

| Need | Why |
| --- | --- |
| Linux, root (sudo) | Partitioning and formatting the key |
| Internet access | Container images and packages are downloaded |
| `podman` or `docker` | Package resolution runs inside the distribution's own image |
| `sfdisk`, `wipefs`, `losetup`, `partx`, `lsblk` (util-linux) | Partitioning |
| `mkfs.vfat` (dosfstools), `mkfs.ext4` (e2fsprogs) | Formatting |
| `udevadm` (udev), `mksquashfs` (squashfs-tools) | Live system |
| `ssh-keygen` (openssh-client), `tar`, `gzip` | Signing and archives |
| `grub-install` or `grub2-install` with the BIOS modules (`grub-pc-bin`, `grub2-pc-modules`) | Making the key boot on legacy BIOS (not needed with `--uefi-only`) |
| Python 3.10+ | dark-instux itself |
| Disk space | About 5 to 10 GB in `/var/tmp/dark-instux` (cache) |

On Debian or Ubuntu:

```sh
sudo apt install podman fdisk dosfstools e2fsprogs udev squashfs-tools openssh-client grub-pc-bin
```

On Fedora or AlmaLinux:

```sh
sudo dnf install podman util-linux dosfstools e2fsprogs systemd-udev squashfs-tools openssh-clients \
     grub2-tools grub2-pc-modules
```

**USB key**: 8 GB or more. The exact size needed depends on the packages; the build tells you if
the key is too small. **Everything on it is erased.**

**Target machine**: amd64 (64-bit), UEFI or legacy BIOS firmware, able to boot from USB.
CPU generation matters for some distributions:

| Distribution | Minimum CPU | Example: a 2008 laptop (Core 2, no SSE4.2) |
| --- | --- | --- |
| Debian, Ubuntu, Fedora | any 64-bit x86 CPU | works |
| AlmaLinux 9 | x86-64-v2 (SSE4.2, POPCNT: Intel Nehalem 2008+, AMD Bulldozer 2011+) | does not work |
| AlmaLinux 10 | x86-64-v3 (AVX2: Intel Haswell 2013+, AMD Excavator 2015+) | does not work |

The workstation that builds an AlmaLinux key needs the same CPU level, since packages are resolved
in an AlmaLinux container.

---

## Installing dark-instux

From a checkout of this repository:

```sh
uv tool install .          # or: pipx install .   or: pip install .
dark-instux --version
```

The build must run as root, so either install it where root finds it or call it through `uv`:

```sh
sudo "$(command -v dark-instux)" build ...
```

---

## Step 1: build a key

### Find the USB key

Plug the key in and find its device name. **Writing to the wrong device destroys its data.**

```sh
lsblk -o NAME,SIZE,MODEL,TRAN,RM
# NAME   SIZE MODEL            TRAN RM
# nvme0n1 477G Samsung SSD 980  nvme  0   <- your system disk: NOT this one
# sdb    28.9G SanDisk Ultra    usb   1   <- the key
```

### Build

```sh
sudo dark-instux build --distro debian --storage single-lvm --device /dev/sdb
```

The build shows its progress in six steps and asks you to type `YES` before writing the key. The
first build takes a while (downloads); later builds for the same distribution reuse the cache.

Common variations:

```sh
# Another distribution or release (default: the current one)
sudo dark-instux build --distro ubuntu --release 24.04 --storage single-ext4 --device /dev/sdb
sudo dark-instux build --distro almalinux --storage raid1-lvm --device /dev/sdb
sudo dark-instux build --distro fedora --storage single-lvm --device /dev/sdb

# Add packages: on the command line or from a file (one per line, # comments allowed)
sudo dark-instux build --distro debian --storage single-lvm --device /dev/sdb \
     -p htop -p vim --packages-file packages/web-server.txt

# Start from a host.yml you already prepared (its certs/ and keys/ folders are copied too)
sudo dark-instux build --distro debian --storage single-lvm --device /dev/sdb --host hosts/web01/host.yml

# Your own disk layout instead of a stock profile
sudo dark-instux build --distro debian --storage layouts/db-server.yml --device /dev/sdb

# Build an image file instead of writing a device (to test in a VM or copy later with dd)
sudo dark-instux build --distro debian --storage single-lvm --image web01.img

# A key for UEFI machines only (no GRUB for BIOS needed on the workstation)
sudo dark-instux build --distro debian --storage single-lvm --device /dev/sdb --uefi-only
```

At the end the build prints a summary:

```
Key written: /dev/sdb
  build              20261103T101500Z-3fa2c1
  debian trixie (docker.io/library/debian@sha256:...)
  signing key        SHA256:Xk3...
```

Keep the **signing key fingerprint**: the installer logs it too, so you can check that the key
you boot is the key you built. To use the same signing key for every build, pass
`--signing-key ~/.config/dark-instux/signing-key` (an ed25519 key made with
`ssh-keygen -t ed25519 -N '' -f ~/.config/dark-instux/signing-key`).

### Default releases

| `--distro` | Default `--release` | Other examples | Network on the installed host |
| --- | --- | --- | --- |
| `debian` | `trixie` (13) | `bookworm` or `12` | systemd-networkd |
| `ubuntu` | `26.04` | `24.04` | netplan |
| `almalinux` | `10` | `9` | NetworkManager |
| `fedora` | `45` | `44` | NetworkManager |

### Packages

The key holds **only** the packages it was built with, because the target installs offline. Every
key gets a baseline: kernel, signed bootloader, SSH server, chrony, sudo, locales, RAID and LVM
tools, file system tools. Add what your host needs at build time. A package added later to
`host.yml` (`packages.extra`) must already be on the key: `dark-instux validate` checks it against
`dark-instux/available-packages.txt`.

Two build options change what is resolved:

- `--install-recommends` also takes the packages that the requested ones *recommend* (apt) or
  *weakly depend on* (dnf), and installs them on the host. Servers are usually built without it
  (small system); desktops need it (fonts, themes, applets).
- `--apt-components main,contrib,non-free-firmware` (Debian and Ubuntu) chooses the archive
  components, for example to get firmware from Debian's `non-free-firmware`. The installed host
  keeps the same components in its repository configuration.

```sh
sudo dark-instux build --distro debian --storage single-lvm --device /dev/sdb \
     --install-recommends --apt-components main,contrib,non-free-firmware \
     -p task-xfce-desktop -p firmware-iwlwifi
```

---

## Step 2: describe the host (host.yml)

After the build, the key shows a small FAT32 partition named **CONFIG**. Any computer (Linux,
Windows, macOS) can open it.

```
CONFIG/
├── host.yml            <- edit this
├── storage.yml         <- the disk layout (from --storage)
├── certs/              <- your internal CA certificates (.pem)
├── keys/               <- signing keys of your package repositories
├── README.txt
└── dark-instux/        <- written by dark-instux: key info, status, logs
```

A complete example for a web server with a static address:

```yaml
schema: 1
install:
  mode: check                    # check first; switch to install when the disks are right

identity:
  hostname: web01
  domain: corp.example

locale:
  lang: en_US.UTF-8
  timezone: Europe/Paris
  keyboard: fr                   # xkb layout, or layout:variant such as fr:oss

time:
  ntp: [ntp1.corp.example, ntp2.corp.example]

dns:
  servers: [10.0.0.2, 10.0.0.3]
  search: [corp.example]

pki:
  ca_certs: [certs/corp-root.pem]

network:
  interfaces:
    - match: {mac: "aa:bb:cc:dd:ee:ff"}
      addresses: [10.0.1.5/24]
      gateway: 10.0.1.1

admin:
  name: ops
  password_hash: "$6$rounds=...$..."   # openssl passwd -6
  ssh_authorized_keys:
    - ssh-ed25519 AAAAC3Nza... ops@laptop
  sudo: true

packages:
  extra: []

repositories:
  keep_defaults: true            # keep the distribution's own repositories
  post_install:
    - name: internal
      url: https://repo.corp.example/debian
      suites: [trixie]
      components: [main]
      key: keys/internal.asc

storage:
  recipe: storage.yml
  wipe_non_empty: false
  disks:
    os-disk: {serial: '^S4EVNX0R123456$'}
```

Practical notes:

- **Password**: put a crypt hash, never the password. Make one with `openssl passwd -6` or
  `mkpasswd -m sha-512`. To allow SSH keys only, use `password_hash: "!"` together with
  `sudo_nopasswd: true`.
- **Network**: with no interface listed, every wired interface uses DHCP. Match an interface by
  `mac` (stable) or `name` (such as `eno1`). Leave `addresses` out of an interface for DHCP on it.
- **DNS** settings apply to the whole host, not to one interface.
- **CA certificates** go in `CONFIG/certs/`; they are added to the system trust store.
- **Repositories**: for Debian and Ubuntu the repository `key` must be a file in `CONFIG/keys/`; for
  AlmaLinux and Fedora it can also be an `https://` URL.

All fields are listed in the [host.yml reference](#hostyml-reference).

---

## Step 3: identify the disks

The installer erases disks, so **you name each disk it may touch**, and it touches no other. In
`host.yml`, give each disk an **alias** (a name you choose, like its physical slot) and a
**matcher** that identifies the drive:

```yaml
storage:
  disks:
    slot-1-disk-1: {serial: '^S4EVNX0R123456$'}
    slot-1-disk-2: {serial: '^S4EVNX0R654321$'}
```

`storage.yml` then uses the aliases, never `/dev/sdX` names, which change from boot to boot.

### Use the serial number or the WWN, never a UUID

The serial and the WWN are printed on the drive label and never change. File system UUIDs and
partition UUIDs are created by the installation itself, and a disk's GPT identifier changes each
time it is wiped: they cannot identify a disk before installation.

### Scan the barcodes

A barcode scanner types like a keyboard, so you can scan the serial straight into `host.yml`:

```sh
dark-instux set-disk --write /media/$USER/CONFIG/host.yml slot-1-disk-1
# scan the barcode of slot-1-disk-1 (or type the serial), then Enter:
# /media/.../host.yml: storage.disks.slot-1-disk-1 = {serial: '^S4EVNX0R123456$'}
```

The serial is escaped and anchored (`^...$`), so it matches that exact drive and nothing else.
Without `--write`, the line is printed for you to paste. `--field wwn` scans a WWN instead.

### Matcher fields

All fields of one matcher must match. Text fields are regular expressions compared with the whole
value, ignoring case and extra spaces.

| Field | Matches | Example |
| --- | --- | --- |
| `serial` | Drive serial number | `'^S4EVNX0R123456$'` |
| `wwn` | World Wide Name | `'^(0x)?5002538e40a1b2c3$'` |
| `model` | Model name | `'Samsung SSD 980.*'` |
| `vendor` | Vendor | `'ATA'` |
| `transport` | `nvme`, `sata`, `sas`, `usb` | `nvme` |
| `by_id` | A name under `/dev/disk/by-id` | `'nvme-Samsung_SSD_980_.*_S4EV.*'` |
| `size` | Capacity range | `{min: 400GB, max: 520GB}` |

To see what Linux reports for the disks of a machine, run on it (any Linux live system):

```sh
sudo dark-instux disks
```

### Rules the installer enforces

- Each alias must match **exactly one** disk; zero or several matches stop the installation.
- Two aliases may not match the same disk.
- The USB key itself, loop, optical and RAM devices are never candidates.
- A disk that already holds partitions or data is refused unless `wipe_non_empty: true`. Set it
  when you reinstall a machine.

### Check mode: confirm before you erase

The sticker is not always what Linux sees: a RAID controller presents virtual disks, VMs invent
serials, some vendors relabel drives. **Boot the key once in check mode** before installing:

```mermaid
sequenceDiagram
    actor Admin
    participant Key as USB key (CONFIG)
    participant Host as Target machine
    Admin->>Key: host.yml with install.mode: check
    Admin->>Host: boot from the key
    Host->>Host: resolve the aliases (no writes)
    Host->>Key: dark-instux/preflight.json (aliases + full disk inventory)
    Host->>Host: power off
    Admin->>Key: read preflight.json, fix matchers if needed
    Admin->>Key: install.mode: install
    Admin->>Host: boot again: real installation
```

Every new key starts in check mode, so even an **unedited** key is useful: boot it once to
collect the machine's disk inventory in `dark-instux/preflight.json`, then write the matchers from it.

---

## Step 4: choose the disk layout (storage.yml)

`storage.yml` is a normal py_part_recipe recipe, except that `devices:` lists **aliases**.
Three layouts ship with dark-instux (`dark-instux profiles`, `dark-instux template --profile NAME`):

| Profile | Disks (aliases) | Layout |
| --- | --- | --- |
| `single-ext4` | `os-disk` | BIOS boot 1 MiB, ESP 1 GiB, swap 4 GiB, ext4 `/` on the rest |
| `single-lvm` | `os-disk` | BIOS boot, ESP, ext4 `/boot`, LVM: xfs `/` 50 %, xfs `/var` 30 %, swap 5 % |
| `raid1-lvm` | `disk-a`, `disk-b` | Same as single-lvm, everything mirrored (RAID 1), BIOS boot on both disks |

A custom layout, for example `/` on one SSD and `/srv` on a RAID 1 pair:

```yaml
partitioning:
  - devices: [system-ssd]
    recipe:
      wipe: true
      partitions:
        - {min_size: 1 GiB, max_size: 1 GiB, weight: 100, p_type: normal, flags: [esp], handle: p_esp}
        - {min_size: 30 GiB, max_size: 64 TiB, weight: 1000, p_type: normal, flags: [], handle: p_root}
  - devices: [data-a, data-b]
    recipe:
      wipe: true
      partitions:
        - {min_size: 100 GiB, max_size: 64 TiB, weight: 1000, p_type: normal, flags: [raid], handle: p_data}
volumes:
  - {handle: v_esp, type: raw, params: {partitions_handle: p_esp}}
  - {handle: v_root, type: raw, params: {partitions_handle: p_root}}
  - {handle: v_data, type: raid, params: {partitions_handle: p_data, level: 1, dev_indices: [0, 1], raid_dev_name: /dev/md20}}
file_systems:
  - {type: fat32, volume_handle: v_esp, mount: /boot/efi, mount_options: umask=0077}
  - {type: ext4, volume_handle: v_root, mount: /}
  - {type: xfs, volume_handle: v_data, mount: /srv}
```

Rules checked by `dark-instux validate`:

- every alias used in `storage.yml` is defined in `host.yml`, and every defined alias is used;
- there is a file system mounted on `/`;
- there is a boot partition for at least one boot mode: a **fat32** ESP on `/boot/efi` for UEFI,
  a 1 MiB partition with `flags: [bios_grub]` for legacy BIOS. `validate` prints which modes the
  layout supports; at install time the installer requires the one the machine actually booted in;
- the recipe passes py_part_recipe's own validation (when py_part_recipe is installed).

Sizes are in `MiB`, `GiB`, `TiB` (or `MB`, `GB`, ...) and must be whole numbers. A partition
gets its `max_size` when everything fits; otherwise space is shared by `weight`. Use a large
`max_size` (`64 TiB`) for "the rest of the disk". An ESP on RAID 1 needs `meta_data: "1.0"` so the
firmware can read it (see `raid1-lvm`).

**Booting both ways.** The stock profiles have both boot partitions, so the same layout installs a
UEFI machine or a legacy BIOS one. Keep both in your own layouts:

```yaml
      partitions:
        - {min_size: 1 MiB, max_size: 1 MiB, weight: 100, p_type: normal, flags: [bios_grub], handle: p_bios}
        - {min_size: 1 GiB, max_size: 1 GiB, weight: 100, p_type: normal, flags: [esp], handle: p_esp}
        - ...
```

The `bios_grub` partition carries no file system and needs no volume: GRUB for BIOS writes itself
into it. On RAID 1, put it in the group of disks so every member gets one: the installer puts
GRUB on each, and the machine still boots if one disk dies.

**Hardened mount options.** `mount_options` such as `nosuid,nodev,noexec` are applied as written,
including `noexec` on `/var`, `/tmp` or `/var/tmp` (ANSSI-style). During the installation those
file systems are remounted `exec`; on Debian and Ubuntu hosts dark-instux also writes
`/etc/apt/apt.conf.d/50dark-instux-noexec`, an apt hook that lifts `noexec` while dpkg runs, because
package scripts are executed from `/var` and `/tmp`. See the
[Podman server tutorial](docs/tutorials/podman-server-anssi.md) for a complete layout.

Several identical servers can share one `storage.yml`: name the aliases after the slots
(`slot-1-disk-1`) and only `host.yml` changes from host to host.

---

## Step 5: validate, check, install

```mermaid
flowchart TD
    A["Edit host.yml / storage.yml"] --> B["dark-instux validate CONFIG/host.yml"]
    B -- "problems" --> A
    B -- "OK, mode: check" --> C["Boot the target"]
    C --> D["Read CONFIG/dark-instux/preflight.json"]
    D -- "wrong disks" --> A
    D -- "right disks" --> E["Set install.mode: install"]
    E --> F["Boot the target"]
    F --> G["Installed: UEFI reboots by itself, legacy BIOS waits for the key to be removed"]
```

### Validate on your workstation

```sh
dark-instux validate /media/$USER/CONFIG/host.yml
# OK: web01.corp.example, 1 disk alias(es), mode check, boots: UEFI and legacy BIOS
```

It reports every problem at once, with its location:

```
3 problem(s) found:
  - identity.hostname: is not a valid hostname: 'web_01'
  - admin.password_hash: is not a valid crypt hash or '!' (clear-text passwords are rejected): 'secret'
  - partitioning[0].devices: alias 'os-disk' is not defined in host.yml storage.disks
```

### Boot the target

1. Plug the key in and boot it from the firmware's boot menu (often F11, F12 or Esc). Secure Boot
   can stay on.
   - **The way you boot the key decides how the system is installed.** A machine with a
     compatibility mode (CSM) often lists the key twice, for example `UEFI: SanDisk` and
     `SanDisk`: the first installs a UEFI system, the second a legacy BIOS one. The installer
     prints the mode it detected, and records it in `preflight.json` (`"boot_mode"`).
   - Old BIOSes that do not list the key at all: rebuild it with `--pmbr-boot-flag` (some BIOSes
     ignore a disk whose MBR has no active entry).
2. Choose nothing: after 5 seconds "unattended install" starts. The second menu entry, "live shell
   only", starts the live system without the installer.
3. The screen shows the installer's progress. It takes from 5 to 30 minutes depending on the disks
   and the number of packages, most of it verifying the key and installing packages.
4. In **check** mode it powers off when preflight is done. In **install** mode, at the end:
   - **UEFI**: it reboots straight into the new system. The new system's boot entry is put first
     *and* set as the firmware's one-time "next boot", so it starts even if the firmware prefers USB.
   - **Legacy BIOS**: a BIOS's boot order cannot be changed from the system, so the screen shows
     **"Remove the USB key now"**. The machine restarts by itself as soon as the key is pulled out.

---

## After the installation

- The host boots the way it was installed: from its UEFI entry (UEFI) or from the disk's MBR
  (legacy BIOS). On a BIOS machine keep the internal disk first in the BIOS boot order.
- Log in with the admin account over SSH (or on the console with its password).
- The installer's files are kept in `/var/log/dark-instux/` on the host: `install.log`,
  `preflight.json` and the partitioning report `report.yml`.
- AlmaLinux and Fedora relabel SELinux on the first boot and reboot once by themselves: this is
  expected.
- The package sources are the distribution's own (unless `keep_defaults: false`) plus your
  `post_install` repositories. The host updates normally when it has network access.

### The key will not install twice

On success the installer writes `dark-instux/DONE` on the CONFIG partition. If the machine boots the
key again (it is still plugged in, or the firmware prefers USB), the key's boot menu sees that
file first:

```mermaid
flowchart TD
    P["Firmware boots the key"] --> Q{"CONFIG/dark-instux/DONE exists?"}
    Q -- "no" --> S["Start the live system and the installer"]
    Q -- "yes, UEFI" --> R["Return to the firmware: the next boot entry starts (the installed host)"]
    Q -- "yes, legacy BIOS" --> B["Message: remove the USB key, press Enter to restart"]
```

**To reinstall the same host**, delete `dark-instux/DONE` from the CONFIG partition, set
`storage.wipe_non_empty: true` (the disks now hold data) and boot the key again.

---

## Troubleshooting

Everything the installer does is recorded on the CONFIG partition of the key:

| File | Contents |
| --- | --- |
| `dark-instux/status.json` | `state` (`running`, `checked`, `failed`, `done`), the current `stage`, the `error` |
| `dark-instux/preflight.json` | Resolved aliases, full disk inventory, preflight problems |
| `dark-instux/logs/install-*.log` | Detailed log of every run, including every command and its output |
| `dark-instux/report.yml` | What py_part_recipe created (partitions, RAID, LVM, UUIDs) |

When something fails the installer **stops and stays on**: it never reboots after a failure, and
it never erases anything after the failing step. Press **Alt+F2** on the machine for a root shell,
or take the key to your workstation and read the files above.

| Message | Meaning and fix |
| --- | --- |
| `storage.disks.X: matches no disk` | The matcher fits no disk. Compare with the inventory in `preflight.json` (serial padding, WWN with or without `0x`, RAID controller) |
| `storage.disks.X: matches 2 disks` | Make the matcher more precise (use the serial) |
| `... already holds data; set storage.wipe_non_empty: true` | The disk is not empty; confirm it may be erased |
| `the file still contains CHANGEME placeholders` | Edit every `CHANGEME` before `mode: install` |
| `'pkg' is not in this key's repository` | Rebuild the key with `-p pkg` |
| `the manifest signature does not verify` / `checksum mismatch` | The key is damaged or was modified: rebuild it |
| `unknown timezone` | Use a name from `/usr/share/zoneinfo`, such as `Europe/Paris` |
| Build: `is not a removable/USB disk` | Check the device name; `--allow-fixed-disk` only if you are sure |
| Build: `missing tools on this machine` | Install the listed tools (see [Requirements](#requirements)) |
| Build: `the repository lacks: ...` | A package name does not exist in that release |
| The key does not boot (UEFI) | Enable booting from USB in the firmware settings |
| The key does not boot (old BIOS) | Enable USB boot; if the key is not even listed, rebuild with `--pmbr-boot-flag` |
| `this machine boots in legacy BIOS mode: a 1 MiB partition with flags [bios_grub] is needed` | Add the `bios_grub` partition to `storage.yml` (the stock profiles have it) |
| `this machine boots in UEFI mode: an ESP on /boot/efi is needed` | Add an ESP, or boot the key in BIOS/CSM mode on purpose |
| `this key was built without bios support` | The key was built with `--uefi-only`: rebuild without it, or boot in UEFI mode |
| Installed in the wrong mode | The machine booted the key the other way (CSM): pick the right entry in the boot menu and reinstall |

To read the logs on the machine itself (Alt+F2):

```sh
journalctl -u dark-instux-install       # the installer's output
cat /run/dark-instux/config/dark-instux/status.json
lsblk -o NAME,SIZE,SERIAL,WWN,MODEL  # what the matchers see
```

---

## What is on the key

| # | Partition | File system | Size | Contents |
| --- | --- | --- | --- | --- |
| 1 | `DINSTUX_ESP` | FAT32 | 512 MiB | Signed shim and GRUB, boot menu, live kernel and initrd |
| 2 | `CONFIG` | FAT32 | 128 MiB | Your files, key info, status and logs |
| 3 | `DINSTUX_PAY` | ext4 | rest | `rootfs.tar.gz`, `repo/`, `live/filesystem.squashfs`, signed `dark-instux/manifest.json` |
| 4 | `DINSTUX_BIOS` | none | 1 MiB | GRUB for legacy BIOS (absent with `--uefi-only`); its first part is in the MBR |

```mermaid
flowchart LR
    FW["UEFI firmware"] --> SHIM["shim (Microsoft-signed)"] --> GRUB["GRUB (Debian-signed)"]
    BIOS["Legacy BIOS"] --> MBR["MBR boot code"] --> BGRUB["GRUB for BIOS (partition 4)"]
    GRUB --> KERN["Live kernel + initrd (ESP)"]
    BGRUB --> KERN
    KERN --> SQ["Live root: PAYLOAD/live/filesystem.squashfs"]
    SQ --> INST["dark-instux installer"]
    INST --> CFG["Reads/writes CONFIG"]
    INST --> PAY["Reads PAYLOAD: manifest, rootfs, repo"]
```

The partitions are found by identifiers generated for each build, not by their labels, so a target
disk that happens to have a partition called `CONFIG` can never be mistaken for the key.

Every file and identifier on the key is described in [docs/key-anatomy.md](docs/key-anatomy.md).

---

## Security notes

- `host.yml` contains a password **hash** and **public** SSH keys only. Treat the key as sensitive
  anyway: anyone holding it can install a machine that trusts your admin key.
- The manifest is signed and every payload file is checked before anything is erased. The public
  key travels on the key, so this detects corruption and mix-ups, not a deliberate rebuild by
  someone else; compare the fingerprint in the install log with the one printed by your build.
- During installation the packages come only from the key. AlmaLinux and Fedora packages are still
  checked against the distribution's signing keys.
- The root account of the installed host is locked; administration goes through the admin user and
  sudo.

---

## Command reference

| Command | What it does |
| --- | --- |
| `dark-instux build` | Build a key (`--device`) or an image (`--image`). Root. |
| `dark-instux validate HOST_YML` | Check host.yml and its storage.yml; on a key, also the package list |
| `dark-instux set-disk ALIAS [--write HOST_YML] [--field serial\|wwn\|model\|vendor\|transport] [--scan TEXT]` | Turn a scanned barcode into a matcher |
| `dark-instux disks [--host HOST_YML] [--exclude DEV] [--json]` | List the disks of this machine and resolve the aliases of a host.yml; `--exclude` ignores a device |
| `dark-instux profiles` | List the stock storage profiles |
| `dark-instux template [--profile NAME]` | Print the host.yml template or a storage profile |
| `dark-instux verify PAYLOAD_MOUNT` | Check a mounted PAYLOAD partition against its signed manifest |
| `dark-instux install` | The installer, started by the live system (debugging options: `--config`, `--payload`, `--target`, `--after`, `--skip-verify`) |

`dark-instux build` options:

| Option | Default | Meaning |
| --- | --- | --- |
| `--distro` | (required) | `debian`, `ubuntu`, `almalinux`, `fedora` |
| `--release` | current | Release or codename |
| `--storage` | (required) | Stock profile name or a storage.yml file |
| `--device` / `--image` | (one required) | USB device to write, or image file to create |
| `-p`, `--package` | | Extra package, repeatable |
| `--packages-file` | | File with packages, repeatable |
| `--host` | template | host.yml to put on the key (its `certs/` and `keys/` are copied) |
| `--workdir` | `/var/tmp/dark-instux` | Cache directory |
| `--engine` | podman, else docker | Container engine |
| `--container-image` | official image | Use another image (a mirror, a hardened base) |
| `--signing-key` | one per workdir | ed25519 private key that signs the manifest |
| `--py-part-recipe` | `py-part-recipe==0.2.1` (PyPI) | pip specification of py_part_recipe for the live system |
| `--allow-fixed-disk` | off | Allow a non-removable target device |
| `--uefi-only` | off | No legacy BIOS support: no BIOS GRUB on the key, no BIOS boot packages |
| `--pmbr-boot-flag` | off | Mark the MBR entry active, for old BIOSes that do not list the key otherwise; BIOS installs mark the installed disks too |
| `--install-recommends` | off | Also resolve and install Recommends (apt) or weak dependencies (dnf): desktops need it |
| `--apt-components` | image default (`main`) | Debian family: archive components, e.g. `main,contrib,non-free-firmware`; the installed host keeps them |
| `--rebuild` | off | Ignore the cache for this distribution and release |
| `-y`, `--yes` | off | Do not ask before writing the device |
| `-v`, `--verbose` | off | Show every command |

Exit codes: `0` success, `1` invalid configuration or verification failure, `2` build or
installation failed, `3` cancelled, `64` usage error.

---

## host.yml reference

| Key | Type | Default | Notes |
| --- | --- | --- | --- |
| `schema` | int | (required) | Always `1` |
| `install.mode` | `check` \| `install` | `install` | The template on a new key uses `check` |
| `identity.hostname` | string | (required) | Short name, letters, digits and `-` |
| `identity.domain` | string | | Makes the FQDN `hostname.domain` |
| `locale.lang` | string | (required) | `en_US.UTF-8`, `fr_FR.UTF-8`... |
| `locale.timezone` | string | (required) | `Europe/Paris`, `Etc/UTC`... |
| `locale.keyboard` | string | (required) | xkb layout, `layout:variant` |
| `time.ntp` | list | distro pool | NTP servers (names or addresses) |
| `dns.servers` | list | from DHCP | IP addresses |
| `dns.search` | list | | Search domains |
| `pki.ca_certs` | list | | PEM files relative to CONFIG |
| `network.backend` | `auto` \| `networkd` \| `networkmanager` | `auto` | `auto`: the distribution's default (networkd on Debian, netplan on Ubuntu, NetworkManager on AlmaLinux and Fedora). `networkmanager` on Debian needs `network-manager` on the key |
| `network.interfaces[].match` | `{mac}` or `{name}` | | Which interface |
| `network.interfaces[].addresses` | list | DHCP | `10.0.1.5/24`, `2001:db8::5/64` |
| `network.interfaces[].gateway` | address | | IPv4 or IPv6 |
| `admin.name` | string | (required) | Created if missing |
| `admin.password_hash` | crypt hash or `!` | (required) | `!` disables password login |
| `admin.ssh_authorized_keys` | list | | Public keys |
| `admin.sudo` | bool | `true` | Member of `sudo` (Debian, Ubuntu) or `wheel` |
| `admin.sudo_nopasswd` | bool | `false` | Required when the password is disabled |
| `packages.extra` | list | | Must be on the key |
| `repositories.keep_defaults` | bool | `true` | Keep the distribution's repositories |
| `repositories.post_install[]` | `name`, `url`, `suites`, `components`, `key` | | Extra repositories written on the host |
| `storage.recipe` | file | (required) | Usually `storage.yml` |
| `storage.wipe_non_empty` | bool | `false` | Allow erasing disks that hold data |
| `storage.disks` | alias: matcher | (required) | See [Step 3](#step-3-identify-the-disks) |
