Files
diskless-workstation/files/enrol/main.go
T
Audiobuzz 6278f2847d tpm-enrol: pivot host enrolment to a Go binary, built out-of-VM
Replaces the shell/openssl-provider host enrolment (a35f2d6) with a static
Go + go-tpm binary, and moves BOTH host Go binaries out of the Packer VM.

fleet-enrol (files/enrol/, Go + go-tpm, no CGO):
  - talks to /dev/tpmrm0 DIRECTLY via transport.FromReadWriter(os.File) — no
    linuxtpm, so go-tpm is the only dep and there is NO tpm2-tools key-gen /
    openssl tpm2 provider / curl in the image (removes the biggest bench risk,
    the provider handle: key-ref).
  - ensures the ECDSA key @0x81010001, builds the CSR (crypto.Signer over the
    TPM key), POSTs CSR+context to the broker, shows the Plymouth fingerprint,
    polls /status, writes the leaf cert to NV 0x01800001.
  - tpmkey/ is an exported package so the TPM ceremony is tested against the
    go-tpm software simulator from a SEPARATE simtest/ module (CGO stays out of
    the shipped build). Transaction logic (mock broker) tested in-package.
  - deps pinned by go.sum (not vendored): the binary now builds on the CI
    runner, which has network — reproducible via pinned Go 1.26.4 + go.sum.

Out-of-VM build (decision): both fleet-enrol AND fleet-hostapi compile in the
CI "Build host Go binaries" step (Go 1.26.4, CGO off, -trimpath) and Packer
FILE-PROVISIONS the static binaries in. Dropped the in-VM `dnf install golang`
+ the 2d removal — the Rocky build image carries no Go toolchain / go-tpm tree.

Wiring:
  - tpm-enrol.sh: now a thin GATE (empty-NV check, pre-auth DHCP on en*,
    exec /usr/sbin/fleet-enrol, reboot-to-converge). module-setup.sh bundles the
    binary (asserted) + reverts the tpm2-openssl/curl installs.
  - diskless.pkr.hcl: file provisioners for both binaries; enrol installed to
    /usr/sbin before the initramfs build + fapolicyd-trusted; lsinitrd asserts
    fleet-enrol; dnf reverted to baseline (no tpm2-openssl/curl).
  - gitea-main-ci.yaml: Set up Go + build both binaries + run the simulator
    ceremony test, before packer validate.

TESTED here: transaction unit tests + the full TPM ceremony (key-gen -> persist
-> ECDSA sign -> CSR verify -> chunked NV write -> re-enrol) against the go-tpm
simulator. BENCH-VERIFY (real/swtpm, empty owner auth, pre-auth DHCP, Plymouth,
reboot-converge, prod HTTPS) tracked in docs/TODO.md #11.
2026-07-02 09:55:54 +00:00

188 lines
6.1 KiB
Go

// fleet-enrol — inline empty-NV first-boot TPM enrolment client.
//
// Invoked from the dracut hook (95dot1x-macsec/tpm-enrol.sh) ONLY when the
// secure build boots a host whose TPM NV 0x01800001 is empty. It:
// 1. ensures an ECDSA signing key exists at TPM handle 0x81010001,
// 2. builds a CSR with it (key never leaves the TPM),
// 3. submits CSR + device context to the enrolment broker, shows the returned
// fingerprint on the Plymouth splash, and polls until an admin approves,
// 4. writes the issued cert (DER) to NV 0x01800001.
//
// The hook then reboots into the normal secure path. Everything host-specific
// (key, cert, hostnqn) is created here at runtime — nothing is baked (invariant #1).
//
// Exit codes: 0 = enrolled (cert written to NV; caller should reboot);
//
// 10 = cert already present (normal boot — caller proceeds);
// 1 = failure (caller leaves NV empty -> boot fails -> emergency).
package main
import (
"context"
"crypto/x509"
"flag"
"fmt"
"log"
"os"
"os/exec"
"strconv"
"strings"
"time"
"fleet-enrol/tpmkey"
"github.com/google/go-tpm/tpm2"
"github.com/google/go-tpm/tpm2/transport"
)
const exitAlreadyEnrolled = 10
func main() {
var (
url = flag.String("url", "http://boot.fleet.lab/enrol", "enrolment broker base URL")
tpmPath = flag.String("tpm", "/dev/tpmrm0", "TPM device path")
nvHex = flag.String("nvindex", "0x01800001", "TPM NV index for the client cert")
handleHex = flag.String("handle", "0x81010001", "TPM persistent handle for the signing key")
cn = flag.String("cn", "fleet-host", "CSR CommonName (generic; identity is the cert serial)")
iface = flag.String("iface", "", "network interface for the device-context MAC")
caFile = flag.String("cacert", "/etc/dot1x/radius-ca.pem", "CA bundle for an https broker URL")
waitFor = flag.Duration("timeout", 30*time.Minute, "max wait for admin approval")
pollEvery = flag.Duration("poll", 5*time.Second, "status poll interval")
)
flag.Parse()
log.SetFlags(0)
log.SetPrefix("fleet-enrol: ")
nvIndex, err := parseHandle(*nvHex)
if err != nil {
log.Fatalf("bad -nvindex %q: %v", *nvHex, err)
}
keyHandle, err := parseHandle(*handleHex)
if err != nil {
log.Fatalf("bad -handle %q: %v", *handleHex, err)
}
// /dev/tpmrm0 (the kernel TPM resource manager) is a simple command/response
// char device: write one command, read one complete response. Wrapping the
// *os.File with transport.FromReadWriter (as the simulator tests do) avoids
// the linuxtpm transport and its golang.org/x/sys dependency, keeping the
// vendored, reproducible initramfs binary tiny (go-tpm only).
f, err := os.OpenFile(*tpmPath, os.O_RDWR, 0)
if err != nil {
log.Fatalf("open TPM %s: %v", *tpmPath, err)
}
defer f.Close()
tpm := transport.FromReadWriter(f)
// Already enrolled? Then this is a normal boot; let the secure path run.
if tpmkey.NVPresent(tpm, nvIndex) {
log.Printf("cert already present at NV %s — normal boot", *nvHex)
os.Exit(exitAlreadyEnrolled)
}
ply("enrol-active")
plyMsg("TPM enrolment: contacting fleet…")
signer, created, err := tpmkey.EnsureKey(tpm, keyHandle)
if err != nil {
plyMsg("TPM enrolment FAILED (key)")
log.Fatalf("ensure key at %s: %v", *handleHex, err)
}
if created {
log.Printf("created persistent signing key at %s", *handleHex)
} else {
log.Printf("reusing persistent signing key at %s", *handleHex)
}
csrPEM, err := buildCSR(signer, *cn)
if err != nil {
plyMsg("TPM enrolment FAILED (CSR)")
log.Fatalf("build CSR: %v", err)
}
client, err := newBrokerClient(*url, *caFile)
if err != nil {
log.Fatalf("broker client: %v", err)
}
dctx := gatherContext(*iface)
ctx, cancel := context.WithTimeout(context.Background(), *waitFor)
defer cancel()
log.Printf("submitting CSR to %s (waiting up to %s for approval)", *url, *waitFor)
st, err := enrol(ctx, client, csrPEM, dctx, *pollEvery, func(fp string) {
ply("enrol-wait")
plyMsg("APPROVE THIS DEVICE — code: " + fp)
log.Printf("fingerprint: %s", fp)
})
if err != nil {
plyMsg("TPM enrolment FAILED — reboot to retry")
log.Fatalf("enrolment: %v", err)
}
der, err := leafDER(st.Cert)
if err != nil {
plyMsg("TPM enrolment FAILED (bad cert)")
log.Fatalf("issued cert: %v", err)
}
if err := tpmkey.WriteNVCert(tpm, nvIndex, der); err != nil {
plyMsg("TPM enrolment FAILED (NV write)")
log.Fatalf("write cert to NV %s: %v (TPM owner auth?)", *nvHex, err)
}
ply("enrol-done")
plyMsg("Enrolment complete — rebooting")
log.Printf("ENROLLED: hostnqn %s (serial %s); cert written to NV %s",
st.Hostnqn, st.CertSerial, *nvHex)
// The caller (dracut hook) reboots into the secure path.
os.Exit(0)
}
func parseHandle(s string) (tpm2.TPMHandle, error) {
v, err := strconv.ParseUint(strings.TrimPrefix(strings.ToLower(s), "0x"), 16, 32)
if err != nil {
return 0, err
}
return tpm2.TPMHandle(v), nil
}
func newBrokerClient(url, caFile string) (*brokerClient, error) {
c := &brokerClient{baseURL: strings.TrimRight(url, "/"), http: httpClient(nil)}
if strings.HasPrefix(url, "https:") {
pem, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("read CA %s: %w", caFile, err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pem) {
return nil, fmt.Errorf("no certs in %s", caFile)
}
c.http = httpClient(pool)
}
return c, nil
}
// gatherContext collects advisory device context for the admin to recognise the
// device. Best-effort — every field is optional.
func gatherContext(iface string) deviceContext {
d := deviceContext{
DMIUUID: strings.TrimSpace(readFile("/sys/class/dmi/id/product_uuid")),
DMISerial: strings.TrimSpace(readFile("/sys/class/dmi/id/product_serial")),
}
if iface != "" {
d.MAC = strings.TrimSpace(readFile("/sys/class/net/" + iface + "/address"))
}
return d
}
func readFile(p string) string {
b, err := os.ReadFile(p)
if err != nil {
return ""
}
return string(b)
}
// Plymouth best-effort splash updates (states only; the fingerprint is public).
func ply(status string) { _ = exec.Command("plymouth", "update", "--status="+status).Run() }
func plyMsg(text string) { _ = exec.Command("plymouth", "message", "--text="+text).Run() }