Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions pkg/teeattestation/go.mod
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
)
17 changes: 17 additions & 0 deletions pkg/teeattestation/go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions pkg/teeattestation/hash.go
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)
}
54 changes: 54 additions & 0 deletions pkg/teeattestation/hash_test.go
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")
}
222 changes: 222 additions & 0 deletions pkg/teeattestation/nitro/fake/fake.go
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 {

Check failure on line 26 in pkg/teeattestation/nitro/fake/fake.go

View workflow job for this annotation

GitHub Actions / lint-module (pkg/teeattestation)

exported: type name will be used as fake.FakeAttestor by other packages, and that stutters; consider calling this Attestor (revive)
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()),

Check failure on line 105 in pkg/teeattestation/nitro/fake/fake.go

View workflow job for this annotation

GitHub Actions / lint-module (pkg/teeattestation)

G115: integer overflow conversion int64 -> uint64 (gosec)
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)
Copy link
Contributor Author

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).

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"`

Check failure on line 209 in pkg/teeattestation/nitro/fake/fake.go

View workflow job for this annotation

GitHub Actions / lint-module (pkg/teeattestation)

struct-tag: tag on not-exported field _ (revive)
Protected []byte
Unprotected cbor.RawMessage
Payload []byte
Signature []byte
}

type coseSignature struct {
_ struct{} `cbor:",toarray"`

Check failure on line 217 in pkg/teeattestation/nitro/fake/fake.go

View workflow job for this annotation

GitHub Actions / lint-module (pkg/teeattestation)

struct-tag: tag on not-exported field _ (revive)
Context string
Protected []byte
ExternalAAD []byte
Payload []byte
}
53 changes: 53 additions & 0 deletions pkg/teeattestation/nitro/fake/fake_test.go
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
Copy link
Contributor Author

Choose a reason for hiding this comment

The 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")
}
Loading
Loading