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.
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
// enrol.go — the enrolment transaction: build a CSR, submit it to the broker,
|
||||
// show the returned fingerprint, poll until an admin approves, return the cert.
|
||||
// TPM-agnostic (takes a crypto.Signer) so it is fully unit-testable with a
|
||||
// software key against a mock broker; the real signer is TPM-backed (tpm.go).
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- broker wire types (mirror serving/enrol-broker) ------------------------
|
||||
|
||||
type deviceContext struct {
|
||||
MAC string `json:"mac,omitempty"`
|
||||
DMIUUID string `json:"dmi_uuid,omitempty"`
|
||||
DMISerial string `json:"dmi_serial,omitempty"`
|
||||
EKHash string `json:"ek_hash,omitempty"`
|
||||
}
|
||||
|
||||
type enrolRequest struct {
|
||||
CSR string `json:"csr"`
|
||||
Context deviceContext `json:"context"`
|
||||
}
|
||||
|
||||
type requestResp struct {
|
||||
EnrolID string `json:"enrol_id"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
type statusResp struct {
|
||||
State string `json:"state"`
|
||||
Cert string `json:"cert,omitempty"`
|
||||
Hostnqn string `json:"hostnqn,omitempty"`
|
||||
CertSerial string `json:"cert_serial,omitempty"`
|
||||
}
|
||||
|
||||
// buildCSR produces a PEM CSR signed by signer (the TPM key). The CN is generic
|
||||
// ("fleet-host") by convention — RADIUS derives real identity from the cert, and
|
||||
// the per-host NVMe hostnqn is the cert serial; nothing per-host is embedded here.
|
||||
func buildCSR(signer crypto.Signer, cn string) ([]byte, error) {
|
||||
tmpl := &x509.CertificateRequest{
|
||||
Subject: pkix.Name{CommonName: cn, Organization: []string{"fleet"}},
|
||||
}
|
||||
der, err := x509.CreateCertificateRequest(nil, tmpl, signer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create CSR: %w", err)
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: der}), nil
|
||||
}
|
||||
|
||||
type brokerClient struct {
|
||||
http *http.Client
|
||||
baseURL string // e.g. http://boot.fleet.lab/enrol
|
||||
}
|
||||
|
||||
func (c *brokerClient) submit(csrPEM []byte, dctx deviceContext) (*requestResp, error) {
|
||||
body, _ := json.Marshal(enrolRequest{CSR: string(csrPEM), Context: dctx})
|
||||
resp, err := c.http.Post(c.baseURL+"/request", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
|
||||
return nil, fmt.Errorf("broker /request: %s: %s", resp.Status, bytes.TrimSpace(b))
|
||||
}
|
||||
var r requestResp
|
||||
if err := json.Unmarshal(b, &r); err != nil {
|
||||
return nil, fmt.Errorf("broker /request: bad JSON: %w", err)
|
||||
}
|
||||
if r.EnrolID == "" {
|
||||
return nil, fmt.Errorf("broker /request: no enrol_id in response")
|
||||
}
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
func (c *brokerClient) status(id string) (*statusResp, error) {
|
||||
resp, err := c.http.Get(c.baseURL + "/status/" + id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("broker /status: %s: %s", resp.Status, bytes.TrimSpace(b))
|
||||
}
|
||||
var s statusResp
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return nil, fmt.Errorf("broker /status: bad JSON: %w", err)
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// enrol runs the full transaction: submit -> show fingerprint -> poll to a
|
||||
// terminal state. onFingerprint is called once with the code to display; the
|
||||
// returned statusResp is APPROVED (with cert) or an error for denied/expired/timeout.
|
||||
func enrol(ctx context.Context, c *brokerClient, csrPEM []byte, dctx deviceContext,
|
||||
pollEvery time.Duration, onFingerprint func(string)) (*statusResp, error) {
|
||||
|
||||
req, err := c.submit(csrPEM, dctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if onFingerprint != nil {
|
||||
onFingerprint(req.Fingerprint)
|
||||
}
|
||||
|
||||
tick := time.NewTicker(pollEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
s, err := c.status(req.EnrolID)
|
||||
if err == nil {
|
||||
switch s.State {
|
||||
case "approved":
|
||||
if s.Cert == "" {
|
||||
return nil, fmt.Errorf("broker approved but returned no cert")
|
||||
}
|
||||
return s, nil
|
||||
case "denied":
|
||||
return nil, fmt.Errorf("enrolment denied by admin")
|
||||
case "expired":
|
||||
return nil, fmt.Errorf("enrolment request expired")
|
||||
}
|
||||
}
|
||||
// pending (or a transient status error) — keep waiting until the deadline.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("enrolment not approved before timeout")
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// leafDER returns the DER of the FIRST certificate in a (possibly chained) PEM
|
||||
// bundle — the leaf, which is what wpa_supplicant presents and the hostnqn
|
||||
// derives from. Also validates it parses.
|
||||
func leafDER(bundlePEM string) ([]byte, error) {
|
||||
rest := []byte(bundlePEM)
|
||||
for {
|
||||
var blk *pem.Block
|
||||
blk, rest = pem.Decode(rest)
|
||||
if blk == nil {
|
||||
return nil, fmt.Errorf("no CERTIFICATE block in broker response")
|
||||
}
|
||||
if blk.Type == "CERTIFICATE" {
|
||||
if _, err := x509.ParseCertificate(blk.Bytes); err != nil {
|
||||
return nil, fmt.Errorf("issued cert does not parse: %w", err)
|
||||
}
|
||||
return blk.Bytes, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func bigOne() *big.Int { return big.NewInt(1) }
|
||||
func bigN(n int64) *big.Int { return big.NewInt(n) }
|
||||
func pkixCN(cn string) pkix.Name { return pkix.Name{CommonName: cn} }
|
||||
|
||||
// mockBroker mimics serving/enrol-broker: /request returns a fingerprint +
|
||||
// enrol-id; /status returns pending until approveAfter polls, then approved with
|
||||
// a cert signed by an in-process CA over the submitted CSR's public key.
|
||||
func mockBroker(t *testing.T, approveAfterPolls int) *httptest.Server {
|
||||
t.Helper()
|
||||
caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
caTmpl := &x509.Certificate{SerialNumber: bigOne(), Subject: pkixCN("mock CA"), IsCA: true, BasicConstraintsValid: true}
|
||||
caDER, _ := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey)
|
||||
caCert, _ := x509.ParseCertificate(caDER)
|
||||
|
||||
var polls int
|
||||
var certPEM string
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/request", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req enrolRequest
|
||||
json.NewDecoder(r.Body).Decode(&req)
|
||||
blk, _ := pem.Decode([]byte(req.CSR))
|
||||
if blk == nil {
|
||||
t.Errorf("submitted CSR is not PEM")
|
||||
http.Error(w, "bad csr", 400)
|
||||
return
|
||||
}
|
||||
csr, err := x509.ParseCertificateRequest(blk.Bytes)
|
||||
if err != nil || csr.CheckSignature() != nil {
|
||||
t.Errorf("CSR signature invalid: %v", err)
|
||||
http.Error(w, "bad csr sig", 400)
|
||||
return
|
||||
}
|
||||
// sign a leaf over the CSR's public key
|
||||
leaf := &x509.Certificate{SerialNumber: bigN(0xabc123), Subject: csr.Subject}
|
||||
der, _ := x509.CreateCertificate(rand.Reader, leaf, caCert, csr.PublicKey, caKey)
|
||||
certPEM = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})) +
|
||||
string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}))
|
||||
json.NewEncoder(w).Encode(requestResp{EnrolID: "e1", Fingerprint: "cedar-onyx-meadow", State: "pending"})
|
||||
})
|
||||
mux.HandleFunc("/status/", func(w http.ResponseWriter, r *http.Request) {
|
||||
polls++
|
||||
if polls <= approveAfterPolls {
|
||||
json.NewEncoder(w).Encode(statusResp{State: "pending"})
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(statusResp{
|
||||
State: "approved", Cert: certPEM,
|
||||
Hostnqn: "nqn.2026-06.org.example.fleet:host-abc123", CertSerial: "abc123",
|
||||
})
|
||||
})
|
||||
return httptest.NewServer(mux)
|
||||
}
|
||||
|
||||
func TestEnrolHappyPath(t *testing.T) {
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) // stands in for the TPM signer
|
||||
csrPEM, err := buildCSR(key, "fleet-host")
|
||||
if err != nil {
|
||||
t.Fatalf("buildCSR: %v", err)
|
||||
}
|
||||
srv := mockBroker(t, 2) // pending twice, then approved
|
||||
defer srv.Close()
|
||||
|
||||
c := &brokerClient{http: srv.Client(), baseURL: srv.URL}
|
||||
var gotFP string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
st, err := enrol(ctx, c, csrPEM, deviceContext{MAC: "de:ad:be:ef:00:01"}, 10*time.Millisecond,
|
||||
func(fp string) { gotFP = fp })
|
||||
if err != nil {
|
||||
t.Fatalf("enrol: %v", err)
|
||||
}
|
||||
if gotFP != "cedar-onyx-meadow" {
|
||||
t.Errorf("fingerprint not surfaced: %q", gotFP)
|
||||
}
|
||||
der, err := leafDER(st.Cert)
|
||||
if err != nil {
|
||||
t.Fatalf("leafDER: %v", err)
|
||||
}
|
||||
crt, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatalf("parse leaf: %v", err)
|
||||
}
|
||||
if crt.Subject.CommonName != "fleet-host" {
|
||||
t.Errorf("leaf CN = %q, want fleet-host", crt.Subject.CommonName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrolDenied(t *testing.T) {
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
csrPEM, _ := buildCSR(key, "fleet-host")
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/request", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(requestResp{EnrolID: "e1", Fingerprint: "x", State: "pending"})
|
||||
})
|
||||
mux.HandleFunc("/status/", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(statusResp{State: "denied"})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
c := &brokerClient{http: srv.Client(), baseURL: srv.URL}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
_, err := enrol(ctx, c, csrPEM, deviceContext{}, time.Millisecond, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "denied") {
|
||||
t.Fatalf("expected denied error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeafDERChain(t *testing.T) {
|
||||
// two-cert bundle -> leaf is the first
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
mk := func(cn string) string {
|
||||
tmpl := &x509.Certificate{SerialNumber: bigOne(), Subject: pkixCN(cn)}
|
||||
der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
|
||||
}
|
||||
der, err := leafDER(mk("leaf") + mk("inter"))
|
||||
if err != nil {
|
||||
t.Fatalf("leafDER: %v", err)
|
||||
}
|
||||
crt, _ := x509.ParseCertificate(der)
|
||||
if crt.Subject.CommonName != "leaf" {
|
||||
t.Errorf("got %q, want leaf", crt.Subject.CommonName)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// fleet-enrol — inline empty-NV first-boot TPM enrolment client (initramfs).
|
||||
// See docs/tpm-enrolment-design.md. Talks to the TPM directly via go-tpm (pure
|
||||
// Go, no CGO) — one static, reproducible binary (like fleet-hostapi), deps
|
||||
// VENDORED so the image build runs with GOPROXY=off. The go-tpm software
|
||||
// simulator (CGO) is confined to the separate simtest/ module.
|
||||
module fleet-enrol
|
||||
|
||||
go 1.26
|
||||
|
||||
require github.com/google/go-tpm v0.9.8
|
||||
|
||||
require golang.org/x/sys v0.8.0 // indirect
|
||||
@@ -0,0 +1,6 @@
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc=
|
||||
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
|
||||
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// httpClient builds the broker HTTP client. With a non-nil pool it pins the
|
||||
// fleet CA for an https broker (prod); plain http (lab) ignores it. Short
|
||||
// timeouts on the individual calls — the long human-approval wait is the poll
|
||||
// LOOP in enrol(), not a single request.
|
||||
func httpClient(pool *x509.CertPool) *http.Client {
|
||||
tr := &http.Transport{}
|
||||
if pool != nil {
|
||||
tr.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
return &http.Client{Timeout: 30 * time.Second, Transport: tr}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// 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() }
|
||||
@@ -0,0 +1,19 @@
|
||||
// fleet-enrol-simtest — a SEPARATE module so the go-tpm software simulator
|
||||
// (CGO + the MS TPM reference C, ~8MB) and go-tpm-tools stay OUT of the shipped
|
||||
// fleet-enrol module's vendored deps. Run from this dir:
|
||||
// go test ./... (needs CGO + a C toolchain for the simulator)
|
||||
// It exercises tpmkey's real TPM ceremony (key-gen, sign, NV) against a software
|
||||
// TPM, so the go-tpm code is proven off-hardware without bloating the image build.
|
||||
module fleet-enrol-simtest
|
||||
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
fleet-enrol v0.0.0
|
||||
github.com/google/go-tpm v0.9.8
|
||||
github.com/google/go-tpm-tools v0.4.9
|
||||
)
|
||||
|
||||
require golang.org/x/sys v0.38.0 // indirect
|
||||
|
||||
replace fleet-enrol => ../
|
||||
@@ -0,0 +1,26 @@
|
||||
github.com/GoogleCloudPlatform/confidential-space/server v0.0.0-20260522213940-e5c6d01a3007 h1:DoeEFwEGBdqcawmpiWtSsSVVZ+wk3zpqvcvssO2JLmY=
|
||||
github.com/GoogleCloudPlatform/confidential-space/server v0.0.0-20260522213940-e5c6d01a3007/go.mod h1:s8F0JYEods/WL03WxZaGsWCnumZeeLD+WKHzspOV9u0=
|
||||
github.com/google/go-configfs-tsm v0.3.3-0.20240919001351-b4b5b84fdcbc h1:SG12DWUUM5igxm+//YX5Yq4vhdoRnOG9HkCodkOn+YU=
|
||||
github.com/google/go-configfs-tsm v0.3.3-0.20240919001351-b4b5b84fdcbc/go.mod h1:EL1GTDFMb5PZQWDviGfZV9n87WeGTR/JUg13RfwkgRo=
|
||||
github.com/google/go-eventlog v0.0.3-0.20260416001248-6807b85eecf0 h1:STyioPkz8nqMMIk3+YlyJ/WyEJZxho1YUZXu99uAbQ0=
|
||||
github.com/google/go-eventlog v0.0.3-0.20260416001248-6807b85eecf0/go.mod h1:7huE5P8w2NTObSwSJjboHmB7ioBNblkijdzoVa2skfQ=
|
||||
github.com/google/go-sev-guest v0.14.0 h1:dCb4F3YrHTtrDX3cYIPTifEDz7XagZmXQioxRBW4wOo=
|
||||
github.com/google/go-sev-guest v0.14.0/go.mod h1:SK9vW+uyfuzYdVN0m8BShL3OQCtXZe/JPF7ZkpD3760=
|
||||
github.com/google/go-tdx-guest v0.3.2-0.20250814004405-ffb0869e6f4d h1:Ff8goEP/ue2/rZT5qyoRicuySCYDbAXEZS8Cf1fgsUo=
|
||||
github.com/google/go-tdx-guest v0.3.2-0.20250814004405-ffb0869e6f4d/go.mod h1:uHy3VaNXNXhl0fiPxKqTxieeouqQmW6A0EfLcaeCYBk=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/go-tpm-tools v0.4.9 h1:jZEhnE4WRFbomSssBH2gWaIViIHU1gjH1jz76+xC9bI=
|
||||
github.com/google/go-tpm-tools v0.4.9/go.mod h1:Omb8zosA8qY9URn1gsrO2i4b6DFqGp29BqNx18V66c4=
|
||||
github.com/google/logger v1.1.1 h1:+6Z2geNxc9G+4D4oDO9njjjn2d0wN5d7uOo0vOIW1NQ=
|
||||
github.com/google/logger v1.1.1/go.mod h1:BkeJZ+1FhQ+/d087r4dzojEg1u2ZX+ZqG1jTUrLM+zQ=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
@@ -0,0 +1,101 @@
|
||||
// Package simtest validates tpmkey's TPM ceremony against the go-tpm software
|
||||
// simulator (the MS TPM 2.0 reference). It lives in its own module so the CGO
|
||||
// simulator never enters the shipped fleet-enrol build; see go.mod.
|
||||
package simtest
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"testing"
|
||||
|
||||
"fleet-enrol/tpmkey"
|
||||
|
||||
"github.com/google/go-tpm-tools/simulator"
|
||||
"github.com/google/go-tpm/tpm2"
|
||||
"github.com/google/go-tpm/tpm2/transport"
|
||||
)
|
||||
|
||||
func openSim(t *testing.T) transport.TPM {
|
||||
t.Helper()
|
||||
sim, err := simulator.Get()
|
||||
if err != nil {
|
||||
t.Fatalf("simulator: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { sim.Close() })
|
||||
return transport.FromReadWriter(sim)
|
||||
}
|
||||
|
||||
func TestEnsureKeyAndSignCSR(t *testing.T) {
|
||||
tpm := openSim(t)
|
||||
const h = tpm2.TPMHandle(0x81010001)
|
||||
|
||||
signer, created, err := tpmkey.EnsureKey(tpm, h)
|
||||
if err != nil {
|
||||
t.Fatalf("EnsureKey: %v", err)
|
||||
}
|
||||
if !created {
|
||||
t.Errorf("first EnsureKey should report created=true")
|
||||
}
|
||||
if _, ok := signer.Public().(*ecdsa.PublicKey); !ok {
|
||||
t.Fatalf("signer public key is not ECDSA")
|
||||
}
|
||||
|
||||
// idempotent: second call reuses the persistent key (same pubkey).
|
||||
signer2, created2, err := tpmkey.EnsureKey(tpm, h)
|
||||
if err != nil || created2 {
|
||||
t.Fatalf("second EnsureKey: created=%v err=%v", created2, err)
|
||||
}
|
||||
if !signer.Public().(*ecdsa.PublicKey).Equal(signer2.Public()) {
|
||||
t.Errorf("persistent key changed between calls")
|
||||
}
|
||||
|
||||
// the TPM signer must produce a CSR that verifies — this is the exact
|
||||
// openssl-tpm2-provider path the Go binary replaces.
|
||||
tmpl := &x509.CertificateRequest{Subject: pkix.Name{CommonName: "fleet-host"}}
|
||||
der, err := x509.CreateCertificateRequest(rand.Reader, tmpl, signer)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCertificateRequest with TPM signer: %v", err)
|
||||
}
|
||||
csr, err := x509.ParseCertificateRequest(der)
|
||||
if err != nil {
|
||||
t.Fatalf("parse CSR: %v", err)
|
||||
}
|
||||
if err := csr.CheckSignature(); err != nil {
|
||||
t.Fatalf("CSR signature (TPM-signed) invalid: %v", err)
|
||||
}
|
||||
|
||||
// raw signer sanity: sign a digest, verify with the public key.
|
||||
dig := sha256.Sum256([]byte("hello"))
|
||||
sig, err := signer.Sign(rand.Reader, dig[:], nil)
|
||||
if err != nil {
|
||||
t.Fatalf("sign: %v", err)
|
||||
}
|
||||
if !ecdsa.VerifyASN1(signer.Public().(*ecdsa.PublicKey), dig[:], sig) {
|
||||
t.Fatalf("TPM ECDSA signature did not verify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNVWriteAndPresence(t *testing.T) {
|
||||
tpm := openSim(t)
|
||||
const nv = tpm2.TPMHandle(0x01800001)
|
||||
|
||||
if tpmkey.NVPresent(tpm, nv) {
|
||||
t.Fatalf("NV should be empty on a fresh TPM")
|
||||
}
|
||||
// realistic cert-sized payload that also crosses the 512B write chunk.
|
||||
want := make([]byte, 700)
|
||||
rand.Read(want)
|
||||
if err := tpmkey.WriteNVCert(tpm, nv, want); err != nil {
|
||||
t.Fatalf("WriteNVCert: %v", err)
|
||||
}
|
||||
if !tpmkey.NVPresent(tpm, nv) {
|
||||
t.Fatalf("NV should be present after write")
|
||||
}
|
||||
// re-write (re-enrolment) must succeed (undefine + redefine).
|
||||
if err := tpmkey.WriteNVCert(tpm, nv, want[:400]); err != nil {
|
||||
t.Fatalf("WriteNVCert rewrite: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
// Package tpmkey — TPM 2.0 operations via go-tpm (pure Go, no CGO, no tpm2-tools
|
||||
// / no openssl tpm2 provider). Provides: ensure a persistent ECDSA signing key
|
||||
// at 0x81010001, a crypto.Signer backed by it (for CSR signing), and NV cert
|
||||
// read-presence + write at 0x01800001. Talks to any transport.TPM, so the same
|
||||
// code runs against /dev/tpmrm0 (production) and the software simulator (tests).
|
||||
//
|
||||
// Exported so the ceremony can be tested against the go-tpm simulator from a
|
||||
// SEPARATE module (simtest/), keeping this module's vendored deps lean (go-tpm
|
||||
// only) — the simulator (CGO + the MS TPM reference C) never enters the image build.
|
||||
package tpmkey
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"encoding/asn1"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
|
||||
"github.com/google/go-tpm/tpm2"
|
||||
"github.com/google/go-tpm/tpm2/transport"
|
||||
)
|
||||
|
||||
// eccSigningTemplate: a NON-restricted ECC P-256 ECDSA-SHA256 signing key.
|
||||
// Non-restricted so it can sign an externally-computed digest (the CSR TBS) with
|
||||
// a NULL validation ticket; Symmetric/KDF are explicitly NULL (sign-only key).
|
||||
func eccSigningTemplate() tpm2.TPMTPublic {
|
||||
return tpm2.TPMTPublic{
|
||||
Type: tpm2.TPMAlgECC,
|
||||
NameAlg: tpm2.TPMAlgSHA256,
|
||||
ObjectAttributes: tpm2.TPMAObject{
|
||||
FixedTPM: true,
|
||||
FixedParent: true,
|
||||
SensitiveDataOrigin: true,
|
||||
UserWithAuth: true,
|
||||
SignEncrypt: true,
|
||||
NoDA: true,
|
||||
},
|
||||
Parameters: tpm2.NewTPMUPublicParms(tpm2.TPMAlgECC, &tpm2.TPMSECCParms{
|
||||
Symmetric: tpm2.TPMTSymDefObject{Algorithm: tpm2.TPMAlgNull},
|
||||
Scheme: tpm2.TPMTECCScheme{
|
||||
Scheme: tpm2.TPMAlgECDSA,
|
||||
Details: tpm2.NewTPMUAsymScheme(tpm2.TPMAlgECDSA, &tpm2.TPMSSigSchemeECDSA{
|
||||
HashAlg: tpm2.TPMAlgSHA256,
|
||||
}),
|
||||
},
|
||||
CurveID: tpm2.TPMECCNistP256,
|
||||
KDF: tpm2.TPMTKDFScheme{Scheme: tpm2.TPMAlgNull},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// Signer implements crypto.Signer using a persistent TPM key.
|
||||
type Signer struct {
|
||||
tpm transport.TPM
|
||||
handle tpm2.TPMHandle
|
||||
name tpm2.TPM2BName
|
||||
pub *ecdsa.PublicKey
|
||||
}
|
||||
|
||||
func (s *Signer) Public() crypto.PublicKey { return s.pub }
|
||||
|
||||
func (s *Signer) Sign(_ io.Reader, digest []byte, _ crypto.SignerOpts) ([]byte, error) {
|
||||
rsp, err := tpm2.Sign{
|
||||
KeyHandle: tpm2.NamedHandle{Handle: s.handle, Name: s.name},
|
||||
Digest: tpm2.TPM2BDigest{Buffer: digest},
|
||||
InScheme: tpm2.TPMTSigScheme{
|
||||
Scheme: tpm2.TPMAlgECDSA,
|
||||
Details: tpm2.NewTPMUSigScheme(tpm2.TPMAlgECDSA, &tpm2.TPMSSchemeHash{
|
||||
HashAlg: tpm2.TPMAlgSHA256,
|
||||
}),
|
||||
},
|
||||
Validation: tpm2.TPMTTKHashCheck{Tag: tpm2.TPMSTHashCheck},
|
||||
}.Execute(s.tpm)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tpm sign: %w", err)
|
||||
}
|
||||
ecc, err := rsp.Signature.Signature.ECDSA()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tpm sign: not ECDSA: %w", err)
|
||||
}
|
||||
r := new(big.Int).SetBytes(ecc.SignatureR.Buffer)
|
||||
sInt := new(big.Int).SetBytes(ecc.SignatureS.Buffer)
|
||||
// x509 expects an ASN.1 DER ECDSA-Sig-Value{ r, s }.
|
||||
return asn1.Marshal(struct{ R, S *big.Int }{r, sInt})
|
||||
}
|
||||
|
||||
func signerFromPub(tpm transport.TPM, handle tpm2.TPMHandle, name tpm2.TPM2BName, pub2b tpm2.TPM2BPublic) (*Signer, error) {
|
||||
pub, err := pub2b.Contents()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
det, err := pub.Parameters.ECCDetail()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("key at handle is not ECC: %w", err)
|
||||
}
|
||||
uniq, err := pub.Unique.ECC()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pk, err := tpm2.ECDSAPub(det, uniq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Signer{tpm: tpm, handle: handle, name: name, pub: pk}, nil
|
||||
}
|
||||
|
||||
// ensureKey returns a signer for the persistent key at handle, creating +
|
||||
// persisting a fresh ECDSA key there if none exists. Returns created=true when
|
||||
// a new key was generated.
|
||||
func EnsureKey(tpm transport.TPM, handle tpm2.TPMHandle) (signer *Signer, created bool, err error) {
|
||||
if rp, e := (tpm2.ReadPublic{ObjectHandle: handle}).Execute(tpm); e == nil {
|
||||
s, e2 := signerFromPub(tpm, handle, rp.Name, rp.OutPublic)
|
||||
return s, false, e2
|
||||
}
|
||||
|
||||
cp, err := tpm2.CreatePrimary{
|
||||
PrimaryHandle: tpm2.TPMRHOwner,
|
||||
InPublic: tpm2.New2B(eccSigningTemplate()),
|
||||
}.Execute(tpm)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("createprimary: %w", err)
|
||||
}
|
||||
// Persist at the well-known handle, then flush the transient object.
|
||||
_, err = tpm2.EvictControl{
|
||||
Auth: tpm2.TPMRHOwner,
|
||||
ObjectHandle: &tpm2.NamedHandle{Handle: cp.ObjectHandle, Name: cp.Name},
|
||||
PersistentHandle: handle,
|
||||
}.Execute(tpm)
|
||||
_, _ = (tpm2.FlushContext{FlushHandle: cp.ObjectHandle}).Execute(tpm)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("evictcontrol: %w", err)
|
||||
}
|
||||
rp, err := (tpm2.ReadPublic{ObjectHandle: handle}).Execute(tpm)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("readpublic after persist: %w", err)
|
||||
}
|
||||
s, err := signerFromPub(tpm, handle, rp.Name, rp.OutPublic)
|
||||
return s, true, err
|
||||
}
|
||||
|
||||
// nvPresent reports whether a defined NV index exists (our enrol NV is defined
|
||||
// and written atomically, so "defined" means "has a cert").
|
||||
func NVPresent(tpm transport.TPM, index tpm2.TPMHandle) bool {
|
||||
_, err := (tpm2.NVReadPublic{NVIndex: index}).Execute(tpm)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// nvWriteCert (re)defines the NV index sized to der and writes it under owner
|
||||
// auth. Chunks the write to stay within the TPM's NV buffer limit.
|
||||
func WriteNVCert(tpm transport.TPM, index tpm2.TPMHandle, der []byte) error {
|
||||
// Undefine a stale index first (re-enrolment / resized cert).
|
||||
if rp, err := (tpm2.NVReadPublic{NVIndex: index}).Execute(tpm); err == nil {
|
||||
if _, err := (tpm2.NVUndefineSpace{
|
||||
AuthHandle: tpm2.TPMRHOwner,
|
||||
NVIndex: tpm2.NamedHandle{Handle: index, Name: rp.NVName},
|
||||
}).Execute(tpm); err != nil {
|
||||
return fmt.Errorf("nv undefine: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
def := tpm2.NVDefineSpace{
|
||||
AuthHandle: tpm2.TPMRHOwner,
|
||||
PublicInfo: tpm2.New2B(tpm2.TPMSNVPublic{
|
||||
NVIndex: index,
|
||||
NameAlg: tpm2.TPMAlgSHA256,
|
||||
Attributes: tpm2.TPMANV{
|
||||
OwnerWrite: true,
|
||||
OwnerRead: true,
|
||||
AuthWrite: true,
|
||||
AuthRead: true,
|
||||
NT: tpm2.TPMNTOrdinary,
|
||||
NoDA: true,
|
||||
},
|
||||
DataSize: uint16(len(der)),
|
||||
}),
|
||||
}
|
||||
if _, err := def.Execute(tpm); err != nil {
|
||||
return fmt.Errorf("nv define: %w", err)
|
||||
}
|
||||
rp, err := (tpm2.NVReadPublic{NVIndex: index}).Execute(tpm)
|
||||
if err != nil {
|
||||
return fmt.Errorf("nv readpublic: %w", err)
|
||||
}
|
||||
|
||||
const chunk = 512 // conservatively under TPM_MAX_NV_BUFFER_SIZE
|
||||
for off := 0; off < len(der); off += chunk {
|
||||
end := min(off+chunk, len(der))
|
||||
if _, err := (tpm2.NVWrite{
|
||||
AuthHandle: tpm2.AuthHandle{Handle: index, Name: rp.NVName, Auth: tpm2.PasswordAuth(nil)},
|
||||
NVIndex: tpm2.NamedHandle{Handle: index, Name: rp.NVName},
|
||||
Data: tpm2.TPM2BMaxNVBuffer{Buffer: der[off:end]},
|
||||
Offset: uint16(off),
|
||||
}).Execute(tpm); err != nil {
|
||||
return fmt.Errorf("nv write @%d: %w", off, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user