Ver código fonte

Add the attestation package and a CMW record parser

The attestation package holds the results of verified remote attestation
evidence: Intel TDX quotes, AMD SEV-SNP reports and Google Confidential
Space tokens. Its types are JSON-tagged so the same value can be stored,
sent to webhooks and given to templates. Its only dependency is the
standard library. ErrInvalidEvidence separates bad evidence from a
verifier's own failures.

attestation/cmw parses RFC 9999 Conceptual Message Wrapper records, in
JSON and in CBOR. ACME's remote-attest-01 challenge
(draft-ietf-acme-rats) carries its evidence in one. Collections, CBOR
records typed by a CoAP content-format, and the CBOR tag form are refused
for now.

Claude-Session: https://claude.ai/code/session_01CjfEMLGpnHQaWsmxe1zmLF
Josh Drake 1 mês atrás
pai
commit
2f3648bdda

+ 133 - 0
attestation/attestation.go

@@ -0,0 +1,133 @@
+// Package attestation holds the results of verified remote attestation
+// evidence, shared by the verifiers in its subpackages and by the code that
+// stores them, sends them to webhooks and gives them to certificate templates.
+//
+// The verifiers return what the evidence binds, for example the report data of
+// a TDX quote or the nonces of an attestation token, and leave the binding rule
+// to their callers, since each protocol binds evidence differently.
+//
+// This package has no dependencies outside the standard library, so packages
+// that only describe results, such as webhook, can import it without pulling in
+// the verifiers' dependencies.
+package attestation
+
+import (
+	"errors"
+	"fmt"
+)
+
+// Format is the format of attestation evidence.
+type Format string
+
+const (
+	// FormatTDX is an Intel TDX quote.
+	FormatTDX Format = "tdx"
+	// FormatSEVSNP is an AMD SEV-SNP attestation report.
+	FormatSEVSNP Format = "sev-snp"
+	// FormatConfidentialSpace is a Google Cloud Attestation token for a
+	// Confidential Space workload.
+	FormatConfidentialSpace Format = "confidential-space"
+)
+
+// Validate returns an error if the format is not supported.
+func (f Format) Validate() error {
+	switch f {
+	case FormatTDX, FormatSEVSNP, FormatConfidentialSpace:
+		return nil
+	default:
+		return fmt.Errorf("attestation format %q is not supported", f)
+	}
+}
+
+// Result is verified attestation evidence. Binary values are hex encoded.
+// Exactly one of TDX, SEVSNP and ConfidentialSpace is set, as Format says.
+type Result struct {
+	// Format is the format of the evidence.
+	Format Format `json:"format"`
+	// MediaType is the media type the evidence was sent with, if any.
+	MediaType string `json:"mediaType,omitempty"`
+	// Evidence is the evidence as it was sent, so that a relying party can
+	// verify it again.
+	Evidence          []byte             `json:"evidence,omitempty"`
+	TDX               *TDX               `json:"tdx,omitempty"`
+	SEVSNP            *SEVSNP            `json:"sevSnp,omitempty"`
+	ConfidentialSpace *ConfidentialSpace `json:"confidentialSpace,omitempty"`
+}
+
+// TDX holds the measurements and attributes of a verified Intel TDX quote.
+type TDX struct {
+	MRTD          string   `json:"mrtd"`
+	RTMRs         []string `json:"rtmrs"`
+	MRSeam        string   `json:"mrSeam"`
+	MRConfigID    string   `json:"mrConfigId"`
+	MROwner       string   `json:"mrOwner"`
+	MROwnerConfig string   `json:"mrOwnerConfig"`
+	TDAttributes  string   `json:"tdAttributes"`
+	XFAM          string   `json:"xfam"`
+	TEETCBSVN     string   `json:"teeTcbSvn"`
+	// FMSPC identifies the platform's family, model and configuration in
+	// the PCK certificate.
+	FMSPC string `json:"fmspc"`
+	// TCBStatus is the TDX TCB status from Intel's collateral, for example
+	// UpToDate.
+	TCBStatus string `json:"tcbStatus,omitempty"`
+}
+
+// SEVSNP holds the measurements and attributes of a verified AMD SEV-SNP
+// attestation report.
+type SEVSNP struct {
+	Measurement     string `json:"measurement"`
+	HostData        string `json:"hostData"`
+	IDKeyDigest     string `json:"idKeyDigest"`
+	AuthorKeyDigest string `json:"authorKeyDigest"`
+	FamilyID        string `json:"familyId"`
+	ImageID         string `json:"imageId"`
+	GuestSVN        uint32 `json:"guestSvn"`
+	Policy          uint64 `json:"policy"`
+	VMPL            uint32 `json:"vmpl"`
+	CurrentTCB      uint64 `json:"currentTcb"`
+	ReportedTCB     uint64 `json:"reportedTcb"`
+	LaunchTCB       uint64 `json:"launchTcb"`
+	ChipID          string `json:"chipId"`
+	// SigningKey is the key that signed the report, "vcek" or "vlek".
+	SigningKey string `json:"signingKey"`
+	// Product is the AMD product line, for example Milan.
+	Product string `json:"product"`
+}
+
+// ConfidentialSpace holds the claims of a verified Google Cloud Attestation
+// token for a Confidential Space workload.
+type ConfidentialSpace struct {
+	// Claims are all the claims of the token.
+	Claims map[string]any `json:"claims"`
+	// SignerSerialNumber is the serial number of the certificate that signed
+	// the token.
+	SignerSerialNumber string `json:"signerSerialNumber,omitempty"`
+}
+
+// ErrInvalidEvidence is matched, with errors.Is, by the errors of evidence that
+// is malformed, fails verification or does not meet a verifier's requirements.
+// Other errors, such as a failure to fetch collateral, are the verifier's.
+var ErrInvalidEvidence = errors.New("invalid attestation evidence")
+
+type invalidError struct {
+	err error
+}
+
+func (e *invalidError) Error() string { return e.err.Error() }
+
+func (e *invalidError) Unwrap() []error { return []error{ErrInvalidEvidence, e.err} }
+
+// Invalid marks err as an error of the evidence, so that it matches
+// ErrInvalidEvidence. It returns nil if err is nil.
+func Invalid(err error) error {
+	if err == nil {
+		return nil
+	}
+	return &invalidError{err: err}
+}
+
+// Invalidf formats an error of the evidence, which matches ErrInvalidEvidence.
+func Invalidf(format string, args ...any) error {
+	return &invalidError{err: fmt.Errorf(format, args...)}
+}

+ 30 - 0
attestation/attestation_test.go

@@ -0,0 +1,30 @@
+package attestation
+
+import (
+	"errors"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestFormat_Validate(t *testing.T) {
+	for _, f := range []Format{FormatTDX, FormatSEVSNP, FormatConfidentialSpace} {
+		assert.NoError(t, f.Validate(), f)
+	}
+	assert.EqualError(t, Format("tpm").Validate(), `attestation format "tpm" is not supported`)
+}
+
+func TestInvalid(t *testing.T) {
+	cause := errors.New("bad signature")
+	err := Invalid(cause)
+	assert.ErrorIs(t, err, ErrInvalidEvidence)
+	assert.ErrorIs(t, err, cause)
+	assert.EqualError(t, err, "bad signature")
+	assert.NoError(t, Invalid(nil))
+
+	err = Invalidf("report data has %d bytes", 12)
+	assert.ErrorIs(t, err, ErrInvalidEvidence)
+	assert.EqualError(t, err, "report data has 12 bytes")
+
+	assert.NotErrorIs(t, errors.New("fetch failed"), ErrInvalidEvidence)
+}

+ 141 - 0
attestation/cmw/cmw.go

@@ -0,0 +1,141 @@
+// Package cmw parses RATS Conceptual Message Wrappers (CMW), defined in RFC
+// 9999, in their record form, in JSON or in CBOR.
+//
+// Not supported: collections, CBOR records whose type is a CoAP content-format
+// number, and the CBOR tag form, all of which return an error.
+package cmw
+
+import (
+	"bytes"
+	"encoding/base64"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"strings"
+
+	"github.com/fxamacker/cbor/v2"
+)
+
+// Indicator is the optional bit set of a record that says which kinds of
+// conceptual message its value carries.
+type Indicator uint
+
+// The indicator bits, from the RATS Conceptual Message Wrapper (CMW)
+// Indicators registry.
+const (
+	ReferenceValues Indicator = 1 << iota
+	Endorsements
+	Evidence
+	AttestationResults
+	AppraisalPolicy
+)
+
+// Has reports whether all the bits of b are set in i.
+func (i Indicator) Has(b Indicator) bool {
+	return i&b == b
+}
+
+// Record is a CMW record: a conceptual message and its media type.
+type Record struct {
+	// MediaType is the media type of the value, with its parameters.
+	MediaType string
+	// Value is the conceptual message.
+	Value []byte
+	// Indicator is the record's indicator, or 0 if it has none.
+	Indicator Indicator
+}
+
+// Parse parses a CMW record in JSON, an array whose first byte is '[', or in
+// CBOR.
+func Parse(data []byte) (*Record, error) {
+	trimmed := bytes.TrimSpace(data)
+	if len(trimmed) == 0 {
+		return nil, errors.New("cmw is empty")
+	}
+	switch trimmed[0] {
+	case '[':
+		return parseJSON(trimmed)
+	case '{':
+		return nil, errors.New("cmw collections are not supported")
+	}
+
+	// The CBOR major type is in the top three bits of the first byte.
+	switch data[0] >> 5 {
+	case 4: // array
+		return parseCBOR(data)
+	case 5: // map
+		return nil, errors.New("cmw collections are not supported")
+	case 6: // tag
+		return nil, errors.New("the cmw cbor tag form is not supported")
+	default:
+		return nil, errors.New("cmw is neither a json nor a cbor record")
+	}
+}
+
+func parseJSON(data []byte) (*Record, error) {
+	var fields []json.RawMessage
+	if err := json.Unmarshal(data, &fields); err != nil {
+		return nil, fmt.Errorf("error parsing cmw json record: %w", err)
+	}
+	if n := len(fields); n != 2 && n != 3 {
+		return nil, fmt.Errorf("cmw json record must have 2 or 3 elements, it has %d", n)
+	}
+
+	var r Record
+	if err := json.Unmarshal(fields[0], &r.MediaType); err != nil {
+		return nil, fmt.Errorf("cmw json record type must be a media type string: %w", err)
+	}
+	var value string
+	if err := json.Unmarshal(fields[1], &value); err != nil {
+		return nil, fmt.Errorf("cmw json record value must be a base64url string: %w", err)
+	}
+	b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(value, "="))
+	if err != nil {
+		return nil, fmt.Errorf("cmw json record value must be a base64url string: %w", err)
+	}
+	r.Value = b
+	if len(fields) == 3 {
+		if err := json.Unmarshal(fields[2], &r.Indicator); err != nil {
+			return nil, fmt.Errorf("cmw json record indicator must be an unsigned integer: %w", err)
+		}
+	}
+	return r.validate()
+}
+
+func parseCBOR(data []byte) (*Record, error) {
+	var fields []cbor.RawMessage
+	if err := cbor.Unmarshal(data, &fields); err != nil {
+		return nil, fmt.Errorf("error parsing cmw cbor record: %w", err)
+	}
+	if n := len(fields); n != 2 && n != 3 {
+		return nil, fmt.Errorf("cmw cbor record must have 2 or 3 elements, it has %d", n)
+	}
+
+	var r Record
+	if err := cbor.Unmarshal(fields[0], &r.MediaType); err != nil {
+		var cf uint
+		if cbor.Unmarshal(fields[0], &cf) == nil {
+			return nil, errors.New("cmw cbor records typed by a coap content-format are not supported")
+		}
+		return nil, fmt.Errorf("cmw cbor record type must be a media type string: %w", err)
+	}
+	if err := cbor.Unmarshal(fields[1], &r.Value); err != nil {
+		return nil, fmt.Errorf("cmw cbor record value must be a byte string: %w", err)
+	}
+	if len(fields) == 3 {
+		if err := cbor.Unmarshal(fields[2], &r.Indicator); err != nil {
+			return nil, fmt.Errorf("cmw cbor record indicator must be an unsigned integer: %w", err)
+		}
+	}
+	return r.validate()
+}
+
+func (r *Record) validate() (*Record, error) {
+	if r.MediaType == "" {
+		return nil, errors.New("cmw record type is empty")
+	}
+	if len(r.Value) == 0 {
+		return nil, errors.New("cmw record value is empty")
+	}
+	return r, nil
+}

+ 78 - 0
attestation/cmw/cmw_test.go

@@ -0,0 +1,78 @@
+package cmw
+
+import (
+	"testing"
+
+	"github.com/fxamacker/cbor/v2"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+func mustCBOR(t *testing.T, v any) []byte {
+	t.Helper()
+	b, err := cbor.Marshal(v)
+	require.NoError(t, err)
+	return b
+}
+
+func TestParse(t *testing.T) {
+	const mediaType = `application/vnd.veraison.tsm-report+json; provider="tdx_guest"`
+	value := []byte(`{"provider":"tdx_guest"}`)
+
+	tests := []struct {
+		name    string
+		data    []byte
+		want    *Record
+		wantErr string
+	}{
+		{"ok json", []byte(`["application/eat+jwt", "ZXlKaGJHY2lPaUpTVXpJMU5pSjku", 8]`),
+			&Record{MediaType: "application/eat+jwt", Value: []byte("eyJhbGciOiJSUzI1NiJ9."), Indicator: AttestationResults}, ""},
+		{"ok json padded", []byte(`["text/plain", "Zm9vYg=="]`),
+			&Record{MediaType: "text/plain", Value: []byte("foob")}, ""},
+		{"ok json whitespace", []byte("\n [\"text/plain\", \"Zm9v\", 4] \n"),
+			&Record{MediaType: "text/plain", Value: []byte("foo"), Indicator: Evidence}, ""},
+		{"ok cbor", mustCBOR(t, []any{mediaType, value, uint(4)}),
+			&Record{MediaType: mediaType, Value: value, Indicator: Evidence}, ""},
+		{"ok cbor no indicator", mustCBOR(t, []any{mediaType, value}),
+			&Record{MediaType: mediaType, Value: value}, ""},
+		{"fail empty", []byte(" "), nil, "cmw is empty"},
+		{"fail json collection", []byte(`{"a": ["text/plain", "Zm9v"]}`), nil, "collections are not supported"},
+		{"fail json syntax", []byte(`["text/plain", "Zm9v"`), nil, "error parsing cmw json record"},
+		{"fail json one element", []byte(`["text/plain"]`), nil, "must have 2 or 3 elements, it has 1"},
+		{"fail json four elements", []byte(`["text/plain", "Zm9v", 4, 1]`), nil, "must have 2 or 3 elements, it has 4"},
+		{"fail json type", []byte(`[1, "Zm9v"]`), nil, "type must be a media type string"},
+		{"fail json value type", []byte(`["text/plain", 1]`), nil, "value must be a base64url string"},
+		{"fail json value encoding", []byte(`["text/plain", "Zm9v+/"]`), nil, "value must be a base64url string"},
+		{"fail json indicator", []byte(`["text/plain", "Zm9v", -1]`), nil, "indicator must be an unsigned integer"},
+		{"fail json empty type", []byte(`["", "Zm9v"]`), nil, "type is empty"},
+		{"fail json empty value", []byte(`["text/plain", ""]`), nil, "value is empty"},
+		{"fail cbor collection", mustCBOR(t, map[string]any{"a": []any{mediaType, value}}), nil, "collections are not supported"},
+		{"fail cbor tag", mustCBOR(t, cbor.Tag{Number: 1668546817 + 10000, Content: value}), nil, "tag form is not supported"},
+		{"fail cbor content-format", mustCBOR(t, []any{uint(10000), value}), nil, "typed by a coap content-format are not supported"},
+		{"fail cbor type", mustCBOR(t, []any{[]byte("x"), value}), nil, "type must be a media type string"},
+		{"fail cbor value", mustCBOR(t, []any{mediaType, "text"}), nil, "value must be a byte string"},
+		{"fail cbor indicator", mustCBOR(t, []any{mediaType, value, "x"}), nil, "indicator must be an unsigned integer"},
+		{"fail cbor elements", mustCBOR(t, []any{mediaType}), nil, "must have 2 or 3 elements, it has 1"},
+		{"fail cbor trailing data", append(mustCBOR(t, []any{mediaType, value}), 0x00), nil, "error parsing cmw cbor record"},
+		{"fail neither", []byte{0x01}, nil, "neither a json nor a cbor record"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := Parse(tt.data)
+			if tt.wantErr != "" {
+				assert.ErrorContains(t, err, tt.wantErr)
+				assert.Nil(t, got)
+				return
+			}
+			require.NoError(t, err)
+			assert.Equal(t, tt.want, got)
+		})
+	}
+}
+
+func TestIndicator_Has(t *testing.T) {
+	assert.True(t, Evidence.Has(Evidence))
+	assert.True(t, (Evidence | Endorsements).Has(Evidence))
+	assert.False(t, Evidence.Has(AttestationResults))
+	assert.False(t, Indicator(0).Has(Evidence))
+}