Files
ssw-mvp/scard/code/server/attest/attest.go
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

570 lines
18 KiB
Go

// Package attest implements remote attestation (TPM Quote) verification for
// device enrollment.
//
// Before this package existed the server accepted whatever RegisterRequest a
// client sent: TPMQuote / QuoteSignature / Nonce / FirmwareHash were parsed off
// the wire and then dropped on the floor. Anybody who could reach the
// enrollment endpoint could mint a fresh P-256 key, POST it, and receive a KEK
// plus an "active" device record. "Secure boot" and "remote attestation" were
// decorative.
//
// The verification performed here is the real thing, minus the hardware root of
// trust (the software TPM signs with a key that lives in process memory, so the
// AIK is trusted on first use rather than chained to a manufacturer EK cert):
//
// 1. The nonce must have been issued by this server, be unexpired, and be
// unused - this binds the quote to a live challenge and kills replay.
// 2. The quote blob must be structurally well-formed: magic header, the exact
// nonce we issued, and one 32-byte PCR digest per bit set in the mask.
// 3. The ECDSA signature over SHA-256(quote blob) must verify under the AIK
// the device is enrolling.
// 4. The quoted PCR set must cover the policy's required measurements.
// 5. The aggregate measurement must match the golden value recorded for this
// device (or be recorded on first use when TOFU is enabled).
//
// Steps 1-4 are enforced in every mode except ModeOff. Step 5 is advisory in
// ModePermissive and blocking in ModeStrict.
package attest
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"math/bits"
"sort"
"strings"
"sync"
"time"
)
// Quote blob framing produced by the software / FPGA TPM implementations.
const (
// QuoteMagicV1 is the header prepended to quote data by the connector TPM.
QuoteMagicV1 = "SW_TPM_QUOTE_V1"
// PCRSize is the size of a single SHA-256 PCR bank entry.
PCRSize = 32
// PCRCount is the number of PCRs exposed by the TPM implementations.
PCRCount = 24
)
// Nonce handling parameters.
const (
// NonceSize is the size of a server-issued enrollment nonce.
NonceSize = 32
// NonceMinSize rejects short (and therefore guessable) nonces outright.
NonceMinSize = 16
// DefaultNonceTTL bounds how long an enrollment nonce stays usable.
DefaultNonceTTL = 2 * time.Minute
// DefaultReplayWindow is how long consumed nonces are remembered so that a
// captured quote cannot be replayed after its nonce record is retired.
DefaultReplayWindow = 30 * time.Minute
)
// Mode selects how strictly attestation results are enforced.
type Mode string
const (
// ModeOff disables attestation entirely. Development only - it restores the
// original "anyone can enroll" behaviour and is reported as such.
ModeOff Mode = "off"
// ModePermissive verifies the nonce, quote structure and signature, but
// treats an unknown or changed measurement as a warning rather than a
// rejection. Intended for bring-up, where golden values are still churning.
ModePermissive Mode = "permissive"
// ModeStrict additionally requires the measurement to match the recorded
// golden value and the firmware hash to be on the allow list (when one is
// configured).
ModeStrict Mode = "strict"
)
// ParseMode converts a CLI/config string into a Mode.
func ParseMode(s string) (Mode, error) {
switch Mode(strings.ToLower(strings.TrimSpace(s))) {
case ModeOff:
return ModeOff, nil
case ModePermissive:
return ModePermissive, nil
case ModeStrict, "":
return ModeStrict, nil
default:
return "", fmt.Errorf("unknown attestation mode %q (want off|permissive|strict)", s)
}
}
// Verification failures. They are returned wrapped, so callers should use
// errors.Is rather than string matching.
var (
ErrDisabled = errors.New("attestation disabled")
ErrNonceMissing = errors.New("attestation nonce missing")
ErrNonceUnknown = errors.New("attestation nonce was not issued by this server")
ErrNonceExpired = errors.New("attestation nonce expired")
ErrNonceReplay = errors.New("attestation nonce already used")
ErrNonceDeviceMismatch = errors.New("attestation nonce was issued to a different device")
ErrNonceTooShort = errors.New("attestation nonce too short")
ErrQuoteMalformed = errors.New("tpm quote malformed")
ErrQuoteSignature = errors.New("tpm quote signature verification failed")
ErrPCRMaskInsufficient = errors.New("tpm quote does not cover the required PCRs")
ErrMeasurementMismatch = errors.New("boot measurement does not match the recorded golden value")
ErrFirmwareNotAllowed = errors.New("firmware hash is not on the allow list")
ErrUnknownDevice = errors.New("no golden measurement recorded for device")
)
// Challenge is the enrollment nonce handed to a device before it quotes.
type Challenge struct {
DeviceID string
Nonce []byte
PCRMask uint32
IssuedAt time.Time
ExpireAt time.Time
}
// NonceB64 returns the standard-base64 encoding used on the wire.
func (c *Challenge) NonceB64() string {
return base64.StdEncoding.EncodeToString(c.Nonce)
}
// Input is everything the verifier needs from a registration request.
type Input struct {
DeviceID string
AIK *ecdsa.PublicKey // key that signed the quote (== enrolling device key)
QuoteB64 string
SignatureB64 string
NonceB64 string
PCRMask uint32
FirmwareHash string
}
// Result describes the outcome of a verification.
type Result struct {
Mode Mode `json:"mode"`
Verified bool `json:"verified"`
Status string `json:"status"` // verified | tofu-recorded | unverified | disabled
PCRMask uint32 `json:"pcr_mask"`
PCRDigest string `json:"pcr_digest"` // sha256 over the quoted PCR blob, hex
PCRs []PCR `json:"pcrs"`
FirmwareHash string `json:"firmware_hash,omitempty"`
FirstSeen bool `json:"first_seen"`
Warnings []string `json:"warnings,omitempty"`
VerifiedAt time.Time `json:"verified_at"`
}
// PCR is a single quoted platform configuration register.
type PCR struct {
Index int `json:"index"`
Digest string `json:"digest"` // hex
}
type issuedNonce struct {
deviceID string
pcrMask uint32
expireAt time.Time
}
// Verifier validates TPM quotes against an enrollment policy.
//
// It is safe for concurrent use.
type Verifier struct {
mu sync.Mutex
mode Mode
policy *Policy
store Store
issued map[string]*issuedNonce // key: base64 nonce
consumed map[string]time.Time // key: base64 nonce
nonceTTL time.Duration
replayWindow time.Duration
// now and randRead are injection points for deterministic tests.
now func() time.Time
randRead func([]byte) (int, error)
}
// Option customises a Verifier.
type Option func(*Verifier)
// WithStore attaches a persistence backend for golden measurements.
func WithStore(s Store) Option { return func(v *Verifier) { v.store = s } }
// WithNonceTTL overrides the enrollment nonce lifetime.
func WithNonceTTL(d time.Duration) Option { return func(v *Verifier) { v.nonceTTL = d } }
// WithReplayWindow overrides how long consumed nonces are remembered.
func WithReplayWindow(d time.Duration) Option { return func(v *Verifier) { v.replayWindow = d } }
// WithClock overrides the time source (tests).
func WithClock(f func() time.Time) Option { return func(v *Verifier) { v.now = f } }
// NewVerifier creates a verifier. A nil policy falls back to DefaultPolicy.
func NewVerifier(mode Mode, policy *Policy, opts ...Option) *Verifier {
if policy == nil {
policy = DefaultPolicy()
}
v := &Verifier{
mode: mode,
policy: policy,
issued: make(map[string]*issuedNonce),
consumed: make(map[string]time.Time),
nonceTTL: DefaultNonceTTL,
replayWindow: DefaultReplayWindow,
now: time.Now,
randRead: rand.Read,
}
for _, o := range opts {
o(v)
}
return v
}
// Mode reports the configured enforcement mode.
func (v *Verifier) Mode() Mode { return v.mode }
// Policy returns the active policy. The returned pointer is shared; callers
// must not mutate it outside the verifier.
func (v *Verifier) Policy() *Policy { return v.policy }
// RequiredPCRMask is the set of PCRs a quote must cover.
func (v *Verifier) RequiredPCRMask() uint32 { return v.policy.RequiredPCRMask }
// QuotePCRMask is the PCR set devices are asked to quote.
func (v *Verifier) QuotePCRMask() uint32 { return v.policy.QuotePCRMask }
// PolicySnapshot is a JSON-safe copy of the active policy used by the
// management plane (SSWFlow TDS) to render the same view the server enforces.
// It is recomputed on demand so policy updates show up immediately.
func (v *Verifier) PolicySnapshot() map[string]interface{} {
v.mu.Lock()
defer v.mu.Unlock()
p := v.policy.clone()
// Build a stable per-device summary without the raw PCR map (which is
// large and not what a dashboard wants).
type goldenSummary struct {
PCRDigest string `json:"pcr_digest"`
FirmwareHash string `json:"firmware_hash,omitempty"`
RecordedAt time.Time `json:"recorded_at"`
TOFU bool `json:"tofu"`
Note string `json:"note,omitempty"`
}
golden := make(map[string]goldenSummary, len(p.Golden))
for dev, g := range p.Golden {
golden[dev] = goldenSummary{
PCRDigest: g.PCRDigest,
FirmwareHash: g.FirmwareHash,
RecordedAt: g.RecordedAt,
TOFU: g.TOFU,
Note: g.Note,
}
}
return map[string]interface{}{
"mode": string(v.mode),
"allow_tofu": p.AllowTOFU,
"quote_pcr_mask": fmt.Sprintf("0x%08X", p.QuotePCRMask),
"required_pcr_mask": fmt.Sprintf("0x%08X", p.RequiredPCRMask),
"allowed_firmware_hashes": p.AllowedFirmwareHashes,
"golden": golden,
"snapshot_at": time.Now().UTC().Format(time.RFC3339Nano),
}
}
// IssueNonce mints a fresh enrollment nonce bound to deviceID.
func (v *Verifier) IssueNonce(deviceID string) (*Challenge, error) {
if deviceID == "" {
return nil, errors.New("device id required")
}
nonce := make([]byte, NonceSize)
if _, err := io.ReadFull(readerFunc(v.randRead), nonce); err != nil {
return nil, fmt.Errorf("csprng unavailable: %w", err)
}
now := v.now()
ch := &Challenge{
DeviceID: deviceID,
Nonce: nonce,
PCRMask: v.policy.QuotePCRMask,
IssuedAt: now,
ExpireAt: now.Add(v.nonceTTL),
}
v.mu.Lock()
defer v.mu.Unlock()
v.gcLocked(now)
v.issued[ch.NonceB64()] = &issuedNonce{
deviceID: deviceID,
pcrMask: v.policy.QuotePCRMask,
expireAt: ch.ExpireAt,
}
return ch, nil
}
// Verify checks a device's quote. It returns a Result on success. On failure it
// returns a non-nil error and, when the failure happened after the quote was
// decoded, a partially populated Result for audit purposes.
func (v *Verifier) Verify(in Input) (*Result, error) {
now := v.now()
if v.mode == ModeOff {
return &Result{
Mode: ModeOff,
Verified: false,
Status: "disabled",
VerifiedAt: now,
Warnings: []string{"attestation is disabled; device identity is unauthenticated"},
}, nil
}
if in.AIK == nil {
return nil, fmt.Errorf("%w: no attestation key", ErrQuoteMalformed)
}
// --- 1. nonce ---------------------------------------------------------
if in.NonceB64 == "" {
return nil, ErrNonceMissing
}
nonce, err := base64.StdEncoding.DecodeString(in.NonceB64)
if err != nil {
return nil, fmt.Errorf("%w: nonce is not valid base64: %v", ErrQuoteMalformed, err)
}
if len(nonce) < NonceMinSize {
return nil, fmt.Errorf("%w: %d bytes, want >= %d", ErrNonceTooShort, len(nonce), NonceMinSize)
}
if err := v.consumeNonce(in.NonceB64, in.DeviceID, now); err != nil {
return nil, err
}
// --- 2. quote structure ----------------------------------------------
quote, err := base64.StdEncoding.DecodeString(in.QuoteB64)
if err != nil {
return nil, fmt.Errorf("%w: quote is not valid base64: %v", ErrQuoteMalformed, err)
}
sig, err := base64.StdEncoding.DecodeString(in.SignatureB64)
if err != nil {
return nil, fmt.Errorf("%w: signature is not valid base64: %v", ErrQuoteMalformed, err)
}
pcrBlob, err := parseQuote(quote, nonce, in.PCRMask)
if err != nil {
return nil, err
}
// --- 3. signature over the quote --------------------------------------
digest := sha256.Sum256(quote)
if !ecdsa.VerifyASN1(in.AIK, digest[:], sig) {
return nil, ErrQuoteSignature
}
// The quote is now authentic and fresh. Everything below is policy.
res := &Result{
Mode: v.mode,
PCRMask: in.PCRMask,
PCRDigest: hex.EncodeToString(hashBlob(pcrBlob)),
PCRs: splitPCRs(pcrBlob, in.PCRMask),
FirmwareHash: in.FirmwareHash,
VerifiedAt: now,
}
// --- 4. required PCR coverage -----------------------------------------
if missing := v.policy.RequiredPCRMask &^ in.PCRMask; missing != 0 {
return res, fmt.Errorf("%w: missing PCRs %v", ErrPCRMaskInsufficient, maskIndexes(missing))
}
// --- 5. measurement policy --------------------------------------------
if err := v.applyMeasurementPolicy(res, in, now); err != nil {
return res, err
}
return res, nil
}
// consumeNonce validates and burns an enrollment nonce.
func (v *Verifier) consumeNonce(nonceB64, deviceID string, now time.Time) error {
v.mu.Lock()
defer v.mu.Unlock()
// Look the nonce up before garbage collecting, otherwise an expired record
// gets swept away and the caller is told "never issued" - which sends
// whoever is reading the audit log hunting for the wrong bug.
if _, replayed := v.consumed[nonceB64]; replayed {
v.gcLocked(now)
return ErrNonceReplay
}
rec, ok := v.issued[nonceB64]
if !ok {
v.gcLocked(now)
return ErrNonceUnknown
}
if now.After(rec.expireAt) {
delete(v.issued, nonceB64)
v.gcLocked(now)
return ErrNonceExpired
}
v.gcLocked(now)
if subtle.ConstantTimeCompare([]byte(rec.deviceID), []byte(deviceID)) != 1 {
return fmt.Errorf("%w: issued to %q, presented by %q", ErrNonceDeviceMismatch, rec.deviceID, deviceID)
}
delete(v.issued, nonceB64)
v.consumed[nonceB64] = now.Add(v.replayWindow)
return nil
}
// applyMeasurementPolicy compares the quoted measurement against the golden
// record, recording it on first use when TOFU is enabled.
func (v *Verifier) applyMeasurementPolicy(res *Result, in Input, now time.Time) error {
strict := v.mode == ModeStrict
if len(v.policy.AllowedFirmwareHashes) > 0 && !v.policy.firmwareAllowed(in.FirmwareHash) {
if strict {
return fmt.Errorf("%w: %s", ErrFirmwareNotAllowed, in.FirmwareHash)
}
res.Warnings = append(res.Warnings, "firmware hash is not on the allow list")
}
v.mu.Lock()
golden, known := v.policy.Golden[in.DeviceID]
v.mu.Unlock()
switch {
case known:
if golden.PCRDigest != res.PCRDigest {
if strict {
return fmt.Errorf("%w: expected %s, measured %s",
ErrMeasurementMismatch, golden.PCRDigest, res.PCRDigest)
}
res.Warnings = append(res.Warnings,
fmt.Sprintf("measurement changed: expected %s, measured %s", golden.PCRDigest, res.PCRDigest))
res.Status = "unverified"
return nil
}
res.Verified = true
res.Status = "verified"
return nil
case v.policy.AllowTOFU:
entry := &GoldenEntry{
PCRDigest: res.PCRDigest,
PCRMask: res.PCRMask,
FirmwareHash: in.FirmwareHash,
PCRs: res.PCRs,
RecordedAt: now,
TOFU: true,
}
v.mu.Lock()
v.policy.Golden[in.DeviceID] = entry
snapshot := v.policy.clone()
v.mu.Unlock()
if v.store != nil {
if err := v.store.Save(snapshot); err != nil {
res.Warnings = append(res.Warnings, "failed to persist golden measurement: "+err.Error())
}
}
res.Verified = true
res.FirstSeen = true
res.Status = "tofu-recorded"
return nil
default:
if strict {
return fmt.Errorf("%w: %s (TOFU disabled)", ErrUnknownDevice, in.DeviceID)
}
res.Status = "unverified"
res.Warnings = append(res.Warnings, "no golden measurement recorded and TOFU is disabled")
return nil
}
}
// gcLocked drops expired issued and consumed nonces. Caller holds v.mu.
func (v *Verifier) gcLocked(now time.Time) {
for k, rec := range v.issued {
if now.After(rec.expireAt) {
delete(v.issued, k)
}
}
for k, until := range v.consumed {
if now.After(until) {
delete(v.consumed, k)
}
}
}
// parseQuote validates the framing of a software TPM quote and returns the
// concatenated PCR digests it commits to.
//
// Layout: MAGIC || nonce || pcr[i] for each i with bit i set in mask.
func parseQuote(quote, nonce []byte, mask uint32) ([]byte, error) {
magic := []byte(QuoteMagicV1)
if len(quote) < len(magic)+len(nonce) {
return nil, fmt.Errorf("%w: %d bytes is shorter than header+nonce", ErrQuoteMalformed, len(quote))
}
if subtle.ConstantTimeCompare(quote[:len(magic)], magic) != 1 {
return nil, fmt.Errorf("%w: bad magic header", ErrQuoteMalformed)
}
embedded := quote[len(magic) : len(magic)+len(nonce)]
if subtle.ConstantTimeCompare(embedded, nonce) != 1 {
return nil, fmt.Errorf("%w: quote is not bound to the presented nonce", ErrQuoteMalformed)
}
pcrBlob := quote[len(magic)+len(nonce):]
want := bits.OnesCount32(mask) * PCRSize
if len(pcrBlob) != want {
return nil, fmt.Errorf("%w: PCR blob is %d bytes, mask 0x%08X requires %d",
ErrQuoteMalformed, len(pcrBlob), mask, want)
}
return pcrBlob, nil
}
// splitPCRs expands a concatenated PCR blob into indexed digests.
func splitPCRs(blob []byte, mask uint32) []PCR {
out := make([]PCR, 0, bits.OnesCount32(mask))
off := 0
for i := 0; i < PCRCount; i++ {
if mask&(1<<uint(i)) == 0 {
continue
}
if off+PCRSize > len(blob) {
break
}
out = append(out, PCR{Index: i, Digest: hex.EncodeToString(blob[off : off+PCRSize])})
off += PCRSize
}
return out
}
// maskIndexes lists the PCR indexes set in mask.
func maskIndexes(mask uint32) []int {
var out []int
for i := 0; i < PCRCount; i++ {
if mask&(1<<uint(i)) != 0 {
out = append(out, i)
}
}
sort.Ints(out)
return out
}
func hashBlob(b []byte) []byte {
h := sha256.Sum256(b)
return h[:]
}
// readerFunc adapts a rand.Read-style function to io.Reader.
type readerFunc func([]byte) (int, error)
func (f readerFunc) Read(p []byte) (int, error) { return f(p) }