Skip to content
Merged
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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ require (
github.com/bytecodealliance/wasmtime-go/v28 v28.0.0
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc
github.com/dominikbraun/graph v0.23.0
github.com/fxamacker/cbor/v2 v2.7.0
github.com/fxamacker/cbor/v2 v2.9.0
github.com/gagliardetto/utilz v0.1.3
github.com/go-json-experiment/json v0.0.0-20250223041408-d3c622f1b874
github.com/go-playground/validator/v10 v10.26.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum

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

3 changes: 3 additions & 0 deletions pkg/capabilities/v2/actions/confidentialrelay/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ type SecretsResponseResult struct {
// CapabilityRequestParams is the JSON-RPC params for "confidential.capability.execute".
type CapabilityRequestParams struct {
WorkflowID string `json:"workflow_id"`
Owner string `json:"owner,omitempty"`
ExecutionID string `json:"execution_id,omitempty"`
ReferenceID string `json:"reference_id,omitempty"`
CapabilityID string `json:"capability_id"`
Payload string `json:"payload"`
Attestation string `json:"attestation,omitempty"`
Expand Down
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")
}
218 changes: 218 additions & 0 deletions pkg/teeattestation/nitro/fake/fake.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// Package nitrofake provides an Attestor that produces structurally valid
// COSE Sign1 attestation documents. These documents pass the local Nitro
// attestation validator's full validation chain (CBOR parsing, cert chain,
// ECDSA signature, UserData, PCRs) without requiring real Nitro hardware.
package nitrofake

import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha512"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"fmt"
"math/big"
"time"

"github.com/fxamacker/cbor/v2"
)

// Attestor produces structurally valid COSE Sign1 attestation documents
// that pass the local Nitro validator with a custom CA root.
type Attestor struct {
rootKey *ecdsa.PrivateKey
rootCert *x509.Certificate
rootCertDER []byte
leafKey *ecdsa.PrivateKey
leafCert *x509.Certificate
leafCertDER []byte
pcrs map[uint][]byte
}

// NewAttestor generates a self-signed P-384 root CA, a leaf cert signed
// by that root, and deterministic 48-byte fake PCR values.
func NewAttestor() (*Attestor, 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 &Attestor{
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 *Attestor) CreateAttestation(userData []byte) ([]byte, error) {
doc := attestationDocument{
ModuleID: "fake-enclave-module",
Timestamp: uint64(time.Now().UnixMilli()), //nolint:gosec // timestamp is always positive
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 *Attestor) CARoots() *x509.CertPool {
pool := x509.NewCertPool()
pool.AddCert(f.rootCert)
return pool
}

// CARootsPEM returns the root CA certificate in PEM format.
func (f *Attestor) 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 *Attestor) TrustedPCRsJSON() []byte {
return []byte(fmt.Sprintf(`{"pcr0":"%s","pcr1":"%s","pcr2":"%s"}`,
hex.EncodeToString(f.pcrs[0]),
hex.EncodeToString(f.pcrs[1]),
hex.EncodeToString(f.pcrs[2]),
))
}

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"` //nolint:revive // idiomatic CBOR array encoding
Protected []byte
Unprotected cbor.RawMessage
Payload []byte
Signature []byte
}

type coseSignature struct {
_ struct{} `cbor:",toarray"` //nolint:revive // idiomatic CBOR array encoding
Context string
Protected []byte
ExternalAAD []byte
Payload []byte
}
42 changes: 42 additions & 0 deletions pkg/teeattestation/nitro/fake/fake_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package nitrofake

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/smartcontractkit/chainlink-common/pkg/teeattestation/nitro"
)

func TestAttestor_RoundTrip(t *testing.T) {
fa, err := NewAttestor()
require.NoError(t, err)

userData := []byte("test-user-data-12345")
attestation, err := fa.CreateAttestation(userData)
require.NoError(t, err)
require.NotEmpty(t, attestation)

err = nitro.ValidateAttestationWithRoots(attestation, userData, fa.TrustedPCRsJSON(), fa.CARootsPEM())
require.NoError(t, err)
}

func TestAttestor_TrustedPCRsJSON(t *testing.T) {
fa, err := NewAttestor()
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 TestAttestor_CARootsPEM(t *testing.T) {
fa, err := NewAttestor()
require.NoError(t, err)

pemStr := fa.CARootsPEM()
require.Contains(t, pemStr, "BEGIN CERTIFICATE")
require.Contains(t, pemStr, "END CERTIFICATE")
}
Loading
Loading