-
Notifications
You must be signed in to change notification settings - Fork 25
Add teeattestation package for TEE attestation validation #1899
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nadahalli
wants to merge
1
commit into
main
Choose a base branch
from
tejaswi/tee-attestation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| module github.com/smartcontractkit/chainlink-common/pkg/teeattestation | ||
|
|
||
| go 1.25.3 | ||
|
|
||
| require ( | ||
| github.com/fxamacker/cbor/v2 v2.9.0 | ||
| github.com/hf/nitrite v0.0.0-20241225144000-c2d5d3c4f303 | ||
| github.com/stretchr/testify v1.11.1 | ||
| ) | ||
|
|
||
| require ( | ||
| github.com/davecgh/go-spew v1.1.1 // indirect | ||
| github.com/pmezard/go-difflib v1.0.0 // indirect | ||
| github.com/x448/float16 v0.8.4 // indirect | ||
| gopkg.in/yaml.v3 v3.0.1 // indirect | ||
| ) |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| // Package teeattestation provides platform-agnostic primitives for TEE | ||
| // attestation validation. Platform-specific validators (e.g. AWS Nitro) | ||
| // live in subpackages. | ||
| package teeattestation | ||
|
|
||
| import "crypto/sha256" | ||
|
|
||
| // DomainSeparator is prepended to attestation payloads before hashing. | ||
| const DomainSeparator = "CONFIDENTIAL_COMPUTE_PAYLOAD" | ||
|
|
||
| // DomainHash computes SHA-256 over DomainSeparator + "\n" + tag + "\n" + data. | ||
| // This is the standard domain-separated hash used for attestation UserData | ||
| // throughout the system. | ||
| func DomainHash(tag string, data []byte) []byte { | ||
| h := sha256.New() | ||
| h.Write([]byte(DomainSeparator)) | ||
| h.Write([]byte("\n" + tag + "\n")) | ||
| h.Write(data) | ||
| return h.Sum(nil) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| package teeattestation | ||
|
|
||
| import ( | ||
| "crypto/sha256" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestDomainHash(t *testing.T) { | ||
| tag := "TestTag" | ||
| data := []byte(`{"key":"value"}`) | ||
|
|
||
| got := DomainHash(tag, data) | ||
|
|
||
| h := sha256.New() | ||
| h.Write([]byte(DomainSeparator)) | ||
| h.Write([]byte("\n" + tag + "\n")) | ||
| h.Write(data) | ||
| want := h.Sum(nil) | ||
|
|
||
| if len(got) != sha256.Size { | ||
| t.Fatalf("expected %d bytes, got %d", sha256.Size, len(got)) | ||
| } | ||
| for i := range want { | ||
| if got[i] != want[i] { | ||
| t.Fatalf("hash mismatch at byte %d: want %x, got %x", i, want, got) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestDomainHash_DifferentTags(t *testing.T) { | ||
| data := []byte("same-data") | ||
| h1 := DomainHash("Tag1", data) | ||
| h2 := DomainHash("Tag2", data) | ||
|
|
||
| for i := range h1 { | ||
| if h1[i] != h2[i] { | ||
| return | ||
| } | ||
| } | ||
| t.Fatal("different tags should produce different hashes") | ||
| } | ||
|
|
||
| func TestDomainHash_DifferentData(t *testing.T) { | ||
| tag := "SameTag" | ||
| h1 := DomainHash(tag, []byte("data-a")) | ||
| h2 := DomainHash(tag, []byte("data-b")) | ||
|
|
||
| for i := range h1 { | ||
| if h1[i] != h2[i] { | ||
| return | ||
| } | ||
| } | ||
| t.Fatal("different data should produce different hashes") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,222 @@ | ||
| // Package fake provides a FakeAttestor that produces structurally valid | ||
| // COSE Sign1 attestation documents. These documents pass nitrite.Verify's | ||
| // full validation chain (CBOR parsing, cert chain, ECDSA signature, UserData, | ||
| // PCRs) without requiring real Nitro hardware. | ||
| package fake | ||
|
|
||
| import ( | ||
| "crypto/ecdsa" | ||
| "crypto/elliptic" | ||
| "crypto/rand" | ||
| "crypto/sha512" | ||
| "crypto/x509" | ||
| "crypto/x509/pkix" | ||
| "encoding/hex" | ||
| "encoding/json" | ||
| "encoding/pem" | ||
| "fmt" | ||
| "math/big" | ||
| "time" | ||
|
|
||
| "github.com/fxamacker/cbor/v2" | ||
| ) | ||
|
|
||
| // FakeAttestor produces structurally valid COSE Sign1 attestation documents | ||
| // that pass nitrite.Verify with a custom CA root. | ||
| type FakeAttestor struct { | ||
| rootKey *ecdsa.PrivateKey | ||
| rootCert *x509.Certificate | ||
| rootCertDER []byte | ||
| leafKey *ecdsa.PrivateKey | ||
| leafCert *x509.Certificate | ||
| leafCertDER []byte | ||
| pcrs map[uint][]byte | ||
| } | ||
|
|
||
| // NewFakeAttestor generates a self-signed P-384 root CA, a leaf cert signed | ||
| // by that root, and deterministic 48-byte fake PCR values. | ||
| func NewFakeAttestor() (*FakeAttestor, error) { | ||
| rootKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("generate root key: %w", err) | ||
| } | ||
| rootTemplate := &x509.Certificate{ | ||
| SerialNumber: big.NewInt(1), | ||
| Subject: pkix.Name{CommonName: "Fake Nitro Root CA"}, | ||
| NotBefore: time.Now().Add(-1 * time.Hour), | ||
| NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), | ||
| KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, | ||
| IsCA: true, | ||
| BasicConstraintsValid: true, | ||
| } | ||
| rootCertDER, err := x509.CreateCertificate(rand.Reader, rootTemplate, rootTemplate, &rootKey.PublicKey, rootKey) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("create root cert: %w", err) | ||
| } | ||
| rootCert, err := x509.ParseCertificate(rootCertDER) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("parse root cert: %w", err) | ||
| } | ||
|
|
||
| leafKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("generate leaf key: %w", err) | ||
| } | ||
| leafTemplate := &x509.Certificate{ | ||
| SerialNumber: big.NewInt(2), | ||
| Subject: pkix.Name{CommonName: "Fake Nitro Enclave"}, | ||
| NotBefore: time.Now().Add(-1 * time.Hour), | ||
| NotAfter: time.Now().Add(24 * time.Hour), | ||
| KeyUsage: x509.KeyUsageDigitalSignature, | ||
| ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageAny}, | ||
| SignatureAlgorithm: x509.ECDSAWithSHA384, | ||
| } | ||
| leafCertDER, err := x509.CreateCertificate(rand.Reader, leafTemplate, rootCert, &leafKey.PublicKey, rootKey) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("create leaf cert: %w", err) | ||
| } | ||
| leafCert, err := x509.ParseCertificate(leafCertDER) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("parse leaf cert: %w", err) | ||
| } | ||
|
|
||
| pcrs := map[uint][]byte{ | ||
| 0: sha384Sum([]byte("fake-pcr-0")), | ||
| 1: sha384Sum([]byte("fake-pcr-1")), | ||
| 2: sha384Sum([]byte("fake-pcr-2")), | ||
| } | ||
|
|
||
| return &FakeAttestor{ | ||
| rootKey: rootKey, | ||
| rootCert: rootCert, | ||
| rootCertDER: rootCertDER, | ||
| leafKey: leafKey, | ||
| leafCert: leafCert, | ||
| leafCertDER: leafCertDER, | ||
| pcrs: pcrs, | ||
| }, nil | ||
| } | ||
|
|
||
| // CreateAttestation builds a COSE Sign1 document encoding a Nitro-like | ||
| // attestation with the given userData. | ||
| func (f *FakeAttestor) CreateAttestation(userData []byte) ([]byte, error) { | ||
| doc := attestationDocument{ | ||
| ModuleID: "fake-enclave-module", | ||
| Timestamp: uint64(time.Now().UnixMilli()), | ||
| Digest: "SHA384", | ||
| PCRs: f.pcrs, | ||
| Certificate: f.leafCertDER, | ||
| CABundle: [][]byte{f.rootCertDER}, | ||
| UserData: userData, | ||
| } | ||
|
|
||
| payloadBytes, err := cbor.Marshal(doc) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("cbor encode document: %w", err) | ||
| } | ||
|
|
||
| header := coseHeader{Alg: int64(-35)} | ||
| protectedBytes, err := cbor.Marshal(header) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("cbor encode protected header: %w", err) | ||
| } | ||
|
|
||
| sigStruct := coseSignature{ | ||
| Context: "Signature1", | ||
| Protected: protectedBytes, | ||
| ExternalAAD: []byte{}, | ||
| Payload: payloadBytes, | ||
| } | ||
| sigStructBytes, err := cbor.Marshal(sigStruct) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("cbor encode sig structure: %w", err) | ||
| } | ||
|
|
||
| hash := sha512.Sum384(sigStructBytes) | ||
| r, s, err := ecdsa.Sign(rand.Reader, f.leafKey, hash[:]) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("ecdsa sign: %w", err) | ||
| } | ||
|
|
||
| signature := make([]byte, 96) | ||
| rBytes := r.Bytes() | ||
| sBytes := s.Bytes() | ||
| copy(signature[48-len(rBytes):48], rBytes) | ||
| copy(signature[96-len(sBytes):96], sBytes) | ||
|
|
||
| outer := cosePayload{ | ||
| Protected: protectedBytes, | ||
| Payload: payloadBytes, | ||
| Signature: signature, | ||
| } | ||
| result, err := cbor.Marshal(outer) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("cbor encode cose sign1: %w", err) | ||
| } | ||
| return result, nil | ||
| } | ||
|
|
||
| // CARoots returns an x509.CertPool containing the fake root CA certificate. | ||
| func (f *FakeAttestor) CARoots() *x509.CertPool { | ||
| pool := x509.NewCertPool() | ||
| pool.AddCert(f.rootCert) | ||
| return pool | ||
| } | ||
|
|
||
| // CARootsPEM returns the root CA certificate in PEM format. | ||
| func (f *FakeAttestor) CARootsPEM() string { | ||
| return string(pem.EncodeToMemory(&pem.Block{ | ||
| Type: "CERTIFICATE", | ||
| Bytes: f.rootCertDER, | ||
| })) | ||
| } | ||
|
|
||
| // TrustedPCRsJSON returns the PCR values as a JSON object matching the | ||
| // format expected by the attestation validator. | ||
| func (f *FakeAttestor) TrustedPCRsJSON() []byte { | ||
| m := map[string]string{ | ||
| "pcr0": hex.EncodeToString(f.pcrs[0]), | ||
| "pcr1": hex.EncodeToString(f.pcrs[1]), | ||
| "pcr2": hex.EncodeToString(f.pcrs[2]), | ||
| } | ||
| // json.Marshal on map[string]string cannot fail. | ||
| b, _ := json.Marshal(m) | ||
| return b | ||
| } | ||
|
|
||
| func sha384Sum(data []byte) []byte { | ||
| h := sha512.Sum384(data) | ||
| return h[:] | ||
| } | ||
|
|
||
| type attestationDocument struct { | ||
| ModuleID string `cbor:"module_id"` | ||
| Timestamp uint64 `cbor:"timestamp"` | ||
| Digest string `cbor:"digest"` | ||
| PCRs map[uint][]byte `cbor:"pcrs"` | ||
| Certificate []byte `cbor:"certificate"` | ||
| CABundle [][]byte `cbor:"cabundle"` | ||
| PublicKey []byte `cbor:"public_key,omitempty"` | ||
| UserData []byte `cbor:"user_data,omitempty"` | ||
| Nonce []byte `cbor:"nonce,omitempty"` | ||
| } | ||
|
|
||
| type coseHeader struct { | ||
| Alg int64 `cbor:"1,keyasint"` | ||
| } | ||
|
|
||
| type cosePayload struct { | ||
| _ struct{} `cbor:",toarray"` | ||
| Protected []byte | ||
| Unprotected cbor.RawMessage | ||
| Payload []byte | ||
| Signature []byte | ||
| } | ||
|
|
||
| type coseSignature struct { | ||
| _ struct{} `cbor:",toarray"` | ||
| Context string | ||
| Protected []byte | ||
| ExternalAAD []byte | ||
| Payload []byte | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| package fake | ||
|
|
||
| import ( | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/hf/nitrite" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestFakeAttestor_RoundTrip(t *testing.T) { | ||
| fa, err := NewFakeAttestor() | ||
| require.NoError(t, err) | ||
|
|
||
| userData := []byte("test-user-data-12345") | ||
| attestation, err := fa.CreateAttestation(userData) | ||
| require.NoError(t, err) | ||
| require.NotEmpty(t, attestation) | ||
|
|
||
| result, err := nitrite.Verify(attestation, nitrite.VerifyOptions{ | ||
| CurrentTime: time.Now(), | ||
| Roots: fa.CARoots(), | ||
| }) | ||
| require.NoError(t, err) | ||
| require.True(t, result.SignatureOK, "ECDSA signature should be valid") | ||
| require.Equal(t, userData, result.Document.UserData) | ||
|
Comment on lines
+11
to
+26
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added. validate_test.go now has three integration tests using FakeAttestor + ValidateAttestation: success, wrong user data, wrong PCRs. |
||
| require.Equal(t, "SHA384", result.Document.Digest) | ||
| require.Equal(t, "fake-enclave-module", result.Document.ModuleID) | ||
| require.Len(t, result.Document.PCRs, 3) | ||
| require.Len(t, result.Document.PCRs[0], 48) | ||
| require.Len(t, result.Document.PCRs[1], 48) | ||
| require.Len(t, result.Document.PCRs[2], 48) | ||
| } | ||
|
|
||
| func TestFakeAttestor_TrustedPCRsJSON(t *testing.T) { | ||
| fa, err := NewFakeAttestor() | ||
| require.NoError(t, err) | ||
|
|
||
| pcrsJSON := fa.TrustedPCRsJSON() | ||
| require.NotEmpty(t, pcrsJSON) | ||
| require.Contains(t, string(pcrsJSON), `"pcr0"`) | ||
| require.Contains(t, string(pcrsJSON), `"pcr1"`) | ||
| require.Contains(t, string(pcrsJSON), `"pcr2"`) | ||
| } | ||
|
|
||
| func TestFakeAttestor_CARootsPEM(t *testing.T) { | ||
| fa, err := NewFakeAttestor() | ||
| require.NoError(t, err) | ||
|
|
||
| pemStr := fa.CARootsPEM() | ||
| require.Contains(t, pemStr, "BEGIN CERTIFICATE") | ||
| require.Contains(t, pemStr, "END CERTIFICATE") | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added a comment. Changing the signature would break callers for an error that can't happen (json.Marshal on map[string]string).