Use a Factory to create signature verifiers at policy evaluation time (#165)
* Make verifiers composable * fix: remove unused code and improve signature verification logic * fix: simplify abstractions and renamed some things * fix: improve tl interface. * fix: sort out signer/verifier
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwr
|
||||
kBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==
|
||||
-----END PUBLIC KEY-----
|
||||
61
tlog/mock.go
61
tlog/mock.go
@@ -2,6 +2,7 @@ package tlog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -15,36 +16,48 @@ const (
|
||||
TestEntry = `{"body":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiI5Zjg2ZDA4MTg4NGM3ZDY1OWEyZmVhYTBjNTVhZDAxNWEzYmY0ZjFiMmIwYjgyMmNkMTVkNmMxNWIwZjAwYTA4In19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJQUlyVUZGUzBIYmNzZjc5L08yajVXdHl2R2Vvd1NVSXpZcDlBM2IwWnREVUFpQVQxZU42ZjFyVmVWa011REFlN3dxWkJ2bE5LY2VsajNVVDNmaWhyQjZSY2c9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVSlZla05DSzJGQlJFRm5SVU5CWjBWQ1RVRnZSME5EY1VkVFRUUTVRa0ZOUTAxQk9IaEVWRUZNUW1kT1ZrSkJUVlJDU0ZKc1l6TlJkMGhvWTA0S1RXcE5lRTFxU1ROTlZHdDVUWHBWTlZkb1kwNU5hbEY0VFdwSk1rMVVhM2xOZWxVMVYycEJVRTFSTUhkRGQxbEVWbEZSUkVWM1VqQmFXRTR3VFVacmR3cEZkMWxJUzI5YVNYcHFNRU5CVVZsSlMyOWFTWHBxTUVSQlVXTkVVV2RCUlVRMFZpdFNSV2g0SzJGeFYwZzNlV3hOVFVSSVlXaE9UVzVOVEZOUFNsQXZDamxyUVcwNWJIQXJNMjF4V1ZSQmFGVlNjbUUyVDBRMVVYZzRXbUprSzJWMVVIbFFhemw1SzNjdloxZEhSRUk1ZW00dlNXd3hTMDVIVFVWUmQwUm5XVVFLVmxJd1VFRlJTQzlDUVZGRVFXZGxRVTFDVFVkQk1WVmtTbEZSVFUxQmIwZERRM05IUVZGVlJrSjNUVVJOUVhkSFFURlZaRVYzUlVJdmQxRkRUVUZCZHdwRWQxbEVWbEl3VWtKQlozZENiMGxGWkVkV2VtUkVRVXRDWjJkeGFHdHFUMUJSVVVSQlowNUtRVVJDUjBGcFJVRTNOMjFFTDFSbVJtRlJVemxrWlhRMENqbFhaRk41YURKT1VTOUZiMVJtYVVGdFFtaHVWblpEVTNSUVowTkpVVU1yZDNSdllpOU9iMUp4T0c5cU4wZDNibTVKYUZKVGRDOVJNbmtyVXpoUkwzSUthRkpVYW5GaE9HZExRVDA5Q2kwdExTMHRSVTVFSUVORlVsUkpSa2xEUVZSRkxTMHRMUzBLIn19fX0=","integratedTime":1703705039,"logID":"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d","logIndex":59674396,"verification":{"inclusionProof":{"checkpoint":"rekor.sigstore.dev - 2605736670972794746\n55510966\nJCi1O53Xmdi9lXnui4Q5SQ+MJSMnWr1Bxn+Q2Qf22tU=\nTimestamp: 1703705040158839214\n\n— rekor.sigstore.dev wNI9ajBFAiAXgtjFDVqCSgiSP04TQzELrz4+EyBwyYVL2EEULTCy0AIhAI9peLU76ZUD1tvU8qvzBJBo77IYD1rc+A1MPc35AeVK\n","hashes":["fb77ee213b48f4b18dc81c6e634c570abf99b257713561f174f2e0f4c039af67","6cb113bbefadecbbb8b89b1c08232438a6125071790b6a062cff8c1ccfdcb91e","6fbe1424e264e4590ca502d671b7a036c87f7a90d1f57534b98eb781144160bf","077b606720a6478200f6c3ed08a68e9b01b1cae192cb120888ddcc95521601bd","b6f8e8bc21ae0cde82b92422a4b4f37b28a43185821e468a4e65b6c79ed8f5b7","89332533fac54e9bc68c7353c42f6ebb9fe38039f67910332ff95082072068d4","0814d6f707a75fb3334bab14ab5466bd8b9a64ae7be7cd4d53a428c64932bc66","e883e826f10329c63a4a2ed21156037a050df43b9d74079296beac6968ed4150","d79230703257b7e4a8a61b032b6980d1a0bdbc7ae96ca838b525b3751785fe48","2f4a77e5288462cd3b75084d37f1502dcbe0943d18dd95cb247fc1ebbabc0aad","38562c253d3536d0d00e3547c880b6b0251a25ac69605b50c9eaa1a27186cc7a","9dea192350ff8b3c0f5ccda38261cb38ebd61869281c3928912332d1144e0a04","2c4d25ba59aa573ab2c79c2d3cd9e1d74789b10632432724d63112ce50b44874","98c486feb5d87092a78a46c4b5be04868654900affc2e86ffb20074dc73a883a","6969c49bd73f19bf28a5eaeabd331ddd60502defb2cd3d96e17b741c80adec6c"],"logIndex":55510965,"rootHash":"2428b53b9dd799d8bd9579ee8b8439490f8c2523275abd41c67f90d907f6dad5","treeSize":55510966},"signedEntryTimestamp":"MEUCIQCG9PRI8PcvtJyE9pbcculZipze6NEWR1Nk8EYocto3BwIgYu5gqgjW80HMjSjUxUNJLp0wlVTesnJCeByUBySc59w="}}`
|
||||
)
|
||||
|
||||
func GetMockTL() TL {
|
||||
unmarshalEntry := func(entry []byte) (*models.LogEntryAnon, error) {
|
||||
le := new(models.LogEntryAnon)
|
||||
err := le.UnmarshalBinary(entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error failed to unmarshal TL entry: %w", err)
|
||||
}
|
||||
return le, nil
|
||||
}
|
||||
|
||||
return &MockTL{
|
||||
UploadLogEntryFunc: func(_ context.Context, _ string, _ []byte, _ []byte, _ dsse.SignerVerifier) ([]byte, error) {
|
||||
return []byte(TestEntry), nil
|
||||
func GetMockTL() TransparencyLog {
|
||||
return &MockTransparencyLog{
|
||||
UploadLogEntryFunc: func(_ context.Context, _ string, _ []byte, _ []byte, _ dsse.SignerVerifier) (*DockerTLExtension, error) {
|
||||
return &DockerTLExtension{
|
||||
Kind: "Mock",
|
||||
Data: json.RawMessage(TestEntry),
|
||||
}, nil
|
||||
},
|
||||
VerifyLogEntryFunc: func(_ context.Context, entryBytes []byte) (time.Time, error) {
|
||||
VerifyLogEntryFunc: func(_ context.Context, ext *DockerTLExtension, _, _ []byte) (time.Time, error) {
|
||||
// return the integrated time in the log entry without any checking
|
||||
le, err := unmarshalEntry(entryBytes)
|
||||
entry := new(models.LogEntryAnon)
|
||||
entryBytes, err := json.Marshal(ext.Data)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
return time.Time{}, fmt.Errorf("error failed to marshal TL entry: %w", err)
|
||||
}
|
||||
if le.IntegratedTime == nil {
|
||||
err = entry.UnmarshalBinary(entryBytes)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("error failed to unmarshal TL entry: %w", err)
|
||||
}
|
||||
if entry.IntegratedTime == nil {
|
||||
return time.Time{}, fmt.Errorf("error missing integrated time in TL entry")
|
||||
}
|
||||
return time.Unix(*le.IntegratedTime, 0), nil
|
||||
},
|
||||
VerifyEntryPayloadFunc: func(_, _, _ []byte) error {
|
||||
return nil
|
||||
},
|
||||
UnmarshalEntryFunc: func(entry []byte) (any, error) {
|
||||
return unmarshalEntry(entry)
|
||||
return time.Unix(*entry.IntegratedTime, 0), nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type MockTransparencyLog struct {
|
||||
UploadLogEntryFunc func(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) (*DockerTLExtension, error)
|
||||
VerifyLogEntryFunc func(ctx context.Context, ext *DockerTLExtension, payload, publicKey []byte) (time.Time, error)
|
||||
}
|
||||
|
||||
func (tl *MockTransparencyLog) UploadEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) (*DockerTLExtension, error) {
|
||||
if tl.UploadLogEntryFunc != nil {
|
||||
return tl.UploadLogEntryFunc(ctx, subject, payload, signature, signer)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (tl *MockTransparencyLog) VerifyEntry(ctx context.Context, ext *DockerTLExtension, payload, publicKey []byte) (time.Time, error) {
|
||||
if tl.VerifyLogEntryFunc != nil {
|
||||
return tl.VerifyLogEntryFunc(ctx, ext, payload, publicKey)
|
||||
}
|
||||
return time.Time{}, nil
|
||||
}
|
||||
|
||||
229
tlog/rekor.go
Normal file
229
tlog/rekor.go
Normal file
@@ -0,0 +1,229 @@
|
||||
package tlog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/docker/attest/internal/util"
|
||||
"github.com/docker/attest/signerverifier"
|
||||
"github.com/docker/attest/tuf"
|
||||
"github.com/docker/attest/useragent"
|
||||
"github.com/go-openapi/runtime"
|
||||
"github.com/go-openapi/strfmt"
|
||||
"github.com/secure-systems-lab/go-securesystemslib/dsse"
|
||||
"github.com/sigstore/cosign/v2/pkg/cosign"
|
||||
rclient "github.com/sigstore/rekor/pkg/client"
|
||||
"github.com/sigstore/rekor/pkg/generated/models"
|
||||
"github.com/sigstore/rekor/pkg/types"
|
||||
hashedrekord_v001 "github.com/sigstore/rekor/pkg/types/hashedrekord/v0.0.1"
|
||||
|
||||
stuf "github.com/sigstore/sigstore/pkg/tuf"
|
||||
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
const RekorTLExtKind = "Rekor"
|
||||
|
||||
// ensure it has all the necessary methods.
|
||||
var _ TransparencyLog = (*Rekor)(nil)
|
||||
|
||||
const defaultPublicKeysDir = "rekor"
|
||||
|
||||
type Rekor struct {
|
||||
publicKeys *cosign.TrustedTransparencyLogPubKeys
|
||||
tufDownloader tuf.Downloader
|
||||
publicKeysDir string
|
||||
}
|
||||
|
||||
//go:embed keys/c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d.pem
|
||||
var rekorPublicKey []byte
|
||||
|
||||
func WithTUFDownloader(tufDownloader tuf.Downloader) func(*Rekor) {
|
||||
return func(r *Rekor) {
|
||||
r.tufDownloader = tufDownloader
|
||||
}
|
||||
}
|
||||
|
||||
func WithTUFPublicKeysDir(dir string) func(*Rekor) {
|
||||
return func(r *Rekor) {
|
||||
r.publicKeysDir = dir
|
||||
}
|
||||
}
|
||||
|
||||
func NewRekorLog(options ...func(*Rekor)) (*Rekor, error) {
|
||||
pk, err := signerverifier.ParsePublicKey(rekorPublicKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error parsing rekor public key: %w", err)
|
||||
}
|
||||
kid, err := signerverifier.KeyID(pk)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error getting keyid: %w", err)
|
||||
}
|
||||
keys := map[string]cosign.TransparencyLogPubKey{
|
||||
kid: {
|
||||
PubKey: pk,
|
||||
Status: stuf.Active,
|
||||
},
|
||||
}
|
||||
rekor := &Rekor{
|
||||
publicKeys: &cosign.TrustedTransparencyLogPubKeys{
|
||||
Keys: keys,
|
||||
},
|
||||
publicKeysDir: defaultPublicKeysDir,
|
||||
}
|
||||
for _, opt := range options {
|
||||
opt(rekor)
|
||||
}
|
||||
return rekor, nil
|
||||
}
|
||||
|
||||
// UploadEntry submits a PK token signature to the transparency log.
|
||||
func (tl *Rekor) UploadEntry(ctx context.Context, subject string, encPayload, signature []byte, signer dsse.SignerVerifier) (*DockerTLExtension, error) {
|
||||
// generate self-signed x509 cert
|
||||
pubCert, err := CreateX509Cert(subject, signer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error creating x509 cert: %w", err)
|
||||
}
|
||||
|
||||
// generate hash of payload
|
||||
hasher := sha256.New()
|
||||
hasher.Write(encPayload)
|
||||
|
||||
// upload entry
|
||||
rekorClient, err := rclient.GetRekorClient(DefaultRekorURL, rclient.WithUserAgent(useragent.Get(ctx)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error creating rekor client: %w", err)
|
||||
}
|
||||
entry, err := cosign.TLogUpload(ctx, rekorClient, signature, hasher, pubCert)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error uploading tlog: %w", err)
|
||||
}
|
||||
|
||||
return &DockerTLExtension{
|
||||
Kind: RekorTLExtKind,
|
||||
Data: entry, // transparency log entry metadata
|
||||
}, nil
|
||||
}
|
||||
|
||||
// VerifyEntry verifies a transparency log entry.
|
||||
func (tl *Rekor) VerifyEntry(ctx context.Context, ext *DockerTLExtension, encPayload, publicKey []byte) (time.Time, error) {
|
||||
zeroTime := time.Time{}
|
||||
// because the Data field has been unmarsalled into a map[string]interface{} we need to marshal it back to bytes
|
||||
// for the unmarshaler to work correctly
|
||||
entryBytes, err := json.Marshal(ext.Data)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("error failed to marshal TL entry: %w", err)
|
||||
}
|
||||
|
||||
entry, err := tl.UnmarshalEntry(entryBytes)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("error unmarshaling TL entry: %w", err)
|
||||
}
|
||||
|
||||
err = entry.Validate(strfmt.Default)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("TL entry failed validation: %w", err)
|
||||
}
|
||||
// check if tl.publicKeys containers le.LogId
|
||||
_, ok := tl.publicKeys.Keys[*entry.LogID]
|
||||
if !ok {
|
||||
// otherwise check TUF
|
||||
pkTarget, err := tl.tufDownloader.DownloadTarget(filepath.Join(tl.publicKeysDir, fmt.Sprintf("%s.pem", *entry.LogID)), "")
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("error downloading rekor public key %s: %w", *entry.LogID, err)
|
||||
}
|
||||
pk, err := signerverifier.ParsePublicKey(pkTarget.Data)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("error parsing public key: %w", err)
|
||||
}
|
||||
tl.publicKeys.Keys[*entry.LogID] = cosign.TransparencyLogPubKey{
|
||||
PubKey: pk,
|
||||
Status: stuf.Active,
|
||||
}
|
||||
}
|
||||
err = cosign.VerifyTLogEntryOffline(ctx, entry, tl.publicKeys)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("TL entry failed verification: %w", err)
|
||||
}
|
||||
|
||||
integratedTime := time.Unix(*entry.IntegratedTime, 0)
|
||||
|
||||
err = tl.VerifyEntryPayload(entry, encPayload, publicKey)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("error verifying TL entry payload: %w", err)
|
||||
}
|
||||
return integratedTime, nil
|
||||
}
|
||||
|
||||
// VerifyEntryPayload checks that the TL entry payload matches envelope payload.
|
||||
func (tl *Rekor) VerifyEntryPayload(entry *models.LogEntryAnon, payload, publicKey []byte) error {
|
||||
tlBody, ok := entry.Body.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected tl body to be of type string, got %T", entry)
|
||||
}
|
||||
rekord, err := extractHashedRekord(tlBody)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error extract HashedRekord from TL entry: %w", err)
|
||||
}
|
||||
|
||||
// compare payload hashes
|
||||
payloadHash := util.SHA256Hex(payload)
|
||||
if rekord.Hash != payloadHash {
|
||||
return fmt.Errorf("error payload and tl entry hash mismatch")
|
||||
}
|
||||
|
||||
// compare public keys
|
||||
cert, err := base64.StdEncoding.Strict().DecodeString(rekord.PublicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode public key: %w", err)
|
||||
}
|
||||
p, _ := pem.Decode(cert)
|
||||
result, err := x509.ParseCertificate(p.Bytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse certificate: %w", err)
|
||||
}
|
||||
if !bytes.Equal(result.RawSubjectPublicKeyInfo, publicKey) {
|
||||
return fmt.Errorf("error payload and tl entry public key mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tl *Rekor) UnmarshalEntry(entry []byte) (*models.LogEntryAnon, error) {
|
||||
le := new(models.LogEntryAnon)
|
||||
err := le.UnmarshalBinary(entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error failed to unmarshal Rekor entry: %w", err)
|
||||
}
|
||||
return le, nil
|
||||
}
|
||||
|
||||
func extractHashedRekord(body string) (*Payload, error) {
|
||||
sig := new(Payload)
|
||||
pe, err := models.UnmarshalProposedEntry(base64.NewDecoder(base64.StdEncoding, strings.NewReader(body)), runtime.JSONConsumer())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
impl, err := types.UnmarshalEntry(pe)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch entry := impl.(type) {
|
||||
case *hashedrekord_v001.V001Entry:
|
||||
sig.Algorithm = *entry.HashedRekordObj.Data.Hash.Algorithm
|
||||
sig.Hash = *entry.HashedRekordObj.Data.Hash.Value
|
||||
sig.Signature = entry.HashedRekordObj.Signature.Content.String()
|
||||
sig.PublicKey = entry.HashedRekordObj.Signature.PublicKey.Content.String()
|
||||
return sig, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("failed to extract haskedrekord, unsupported type: %T", entry)
|
||||
}
|
||||
}
|
||||
64
tlog/rekor_test.go
Normal file
64
tlog/rekor_test.go
Normal file
@@ -0,0 +1,64 @@
|
||||
//go:build e2e
|
||||
|
||||
package tlog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
_ "embed"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/docker/attest/internal/test"
|
||||
"github.com/docker/attest/internal/util"
|
||||
"github.com/docker/attest/signerverifier"
|
||||
"github.com/docker/attest/tuf"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// NOTE: these are only run on CI to protect Rekor, but work just fine locally.
|
||||
func TestRekor(t *testing.T) {
|
||||
// message digest
|
||||
payload := []byte("test")
|
||||
hash := util.SHA256(payload)
|
||||
// generate ephemeral keys to sign message digest
|
||||
signer, err := signerverifier.GenKeyPair()
|
||||
assert.NoError(t, err)
|
||||
sig, err := signer.Sign(context.Background(), hash)
|
||||
assert.NoError(t, err)
|
||||
tests := []struct {
|
||||
name string
|
||||
tufDownloader tuf.Downloader
|
||||
pubKeysDir string
|
||||
}{
|
||||
{name: "TestRekor (no tuf)"},
|
||||
{name: "TestRekor (with tuf)", tufDownloader: tuf.NewMockTufClient("."), pubKeysDir: "keys"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pk := signer.Public()
|
||||
publicKey, err := x509.MarshalPKIXPublicKey(pk)
|
||||
if tt.tufDownloader != nil {
|
||||
// set to incorrect public key to test TUF flow
|
||||
keyStr, err := test.PublicKeyToPEM(pk)
|
||||
require.NoError(t, err)
|
||||
rekorPublicKey = []byte(keyStr)
|
||||
}
|
||||
|
||||
rekor, err := NewRekorLog(WithTUFDownloader(tt.tufDownloader), WithTUFPublicKeysDir(tt.pubKeysDir))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, rekor)
|
||||
ext, err := rekor.UploadEntry(context.Background(), "test", payload, sig, signer)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, ext)
|
||||
assert.Equal(t, RekorTLExtKind, ext.Kind)
|
||||
assert.NotEmpty(t, ext.Data)
|
||||
|
||||
when, err := rekor.VerifyEntry(context.Background(), ext, payload, publicKey)
|
||||
require.NoError(t, err)
|
||||
assert.WithinDuration(t, time.Now(), when, 5*time.Second)
|
||||
})
|
||||
}
|
||||
}
|
||||
218
tlog/tl.go
218
tlog/tl.go
@@ -1,162 +1,38 @@
|
||||
package tlog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/docker/attest/internal/util"
|
||||
"github.com/docker/attest/signerverifier"
|
||||
"github.com/docker/attest/useragent"
|
||||
"github.com/go-openapi/runtime"
|
||||
"github.com/go-openapi/strfmt"
|
||||
"github.com/secure-systems-lab/go-securesystemslib/dsse"
|
||||
"github.com/sigstore/cosign/v2/pkg/cosign"
|
||||
rclient "github.com/sigstore/rekor/pkg/client"
|
||||
"github.com/sigstore/rekor/pkg/generated/models"
|
||||
"github.com/sigstore/rekor/pkg/types"
|
||||
hashedrekord_v001 "github.com/sigstore/rekor/pkg/types/hashedrekord/v0.0.1"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultRekorURL = "https://rekor.sigstore.dev"
|
||||
)
|
||||
|
||||
type tlCtxKeyType struct{}
|
||||
|
||||
var TLCtxKey tlCtxKeyType
|
||||
|
||||
// sets TL in context.
|
||||
func WithTL(ctx context.Context, tl TL) context.Context {
|
||||
return context.WithValue(ctx, TLCtxKey, tl)
|
||||
type TransparencyLog interface {
|
||||
UploadEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) (*DockerTLExtension, error)
|
||||
VerifyEntry(ctx context.Context, entry *DockerTLExtension, payload, publicKey []byte) (time.Time, error)
|
||||
}
|
||||
|
||||
// gets TL from context, defaults to Rekor TL if not set.
|
||||
func GetTL(ctx context.Context) TL {
|
||||
t, ok := ctx.Value(TLCtxKey).(TL)
|
||||
if !ok {
|
||||
t = &RekorTL{}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
type TLPayload struct {
|
||||
type Payload struct {
|
||||
Algorithm string
|
||||
Hash string
|
||||
Signature string
|
||||
PublicKey string
|
||||
}
|
||||
|
||||
type TL interface {
|
||||
UploadLogEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error)
|
||||
VerifyLogEntry(ctx context.Context, entryBytes []byte) (time.Time, error)
|
||||
VerifyEntryPayload(entryBytes, payload, publicKey []byte) error
|
||||
UnmarshalEntry(entryBytes []byte) (any, error)
|
||||
}
|
||||
|
||||
type MockTL struct {
|
||||
UploadLogEntryFunc func(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error)
|
||||
VerifyLogEntryFunc func(ctx context.Context, entryBytes []byte) (time.Time, error)
|
||||
VerifyEntryPayloadFunc func(entryBytes, payload, publicKey []byte) error
|
||||
UnmarshalEntryFunc func(entryBytes []byte) (any, error)
|
||||
}
|
||||
|
||||
func (tl *MockTL) UploadLogEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error) {
|
||||
if tl.UploadLogEntryFunc != nil {
|
||||
return tl.UploadLogEntryFunc(ctx, subject, payload, signature, signer)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (tl *MockTL) VerifyLogEntry(ctx context.Context, entryBytes []byte) (time.Time, error) {
|
||||
if tl.VerifyLogEntryFunc != nil {
|
||||
return tl.VerifyLogEntryFunc(ctx, entryBytes)
|
||||
}
|
||||
return time.Time{}, nil
|
||||
}
|
||||
|
||||
func (tl *MockTL) VerifyEntryPayload(entryBytes, payload, publicKey []byte) error {
|
||||
if tl.VerifyEntryPayloadFunc != nil {
|
||||
return tl.VerifyEntryPayloadFunc(entryBytes, payload, publicKey)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tl *MockTL) UnmarshalEntry(entryBytes []byte) (any, error) {
|
||||
if tl.UnmarshalEntryFunc != nil {
|
||||
return tl.UnmarshalEntryFunc(entryBytes)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type RekorTL struct{}
|
||||
|
||||
// UploadLogEntry submits a PK token signature to the transparency log.
|
||||
func (tl *RekorTL) UploadLogEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error) {
|
||||
// generate self-signed x509 cert
|
||||
pubCert, err := CreateX509Cert(subject, signer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error creating x509 cert: %w", err)
|
||||
}
|
||||
|
||||
// generate hash of payload
|
||||
hasher := sha256.New()
|
||||
hasher.Write(payload)
|
||||
|
||||
// upload entry
|
||||
rekorClient, err := rclient.GetRekorClient(DefaultRekorURL, rclient.WithUserAgent(useragent.Get(ctx)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error creating rekor client: %w", err)
|
||||
}
|
||||
entry, err := cosign.TLogUpload(ctx, rekorClient, signature, hasher, pubCert)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error uploading tlog: %w", err)
|
||||
}
|
||||
entryBytes, err := entry.MarshalBinary()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error marshaling TL entry: %w", err)
|
||||
}
|
||||
return entryBytes, nil
|
||||
}
|
||||
|
||||
// VerifyLogEntry verifies a transparency log entry.
|
||||
func (tl *RekorTL) VerifyLogEntry(ctx context.Context, entryBytes []byte) (time.Time, error) {
|
||||
zeroTime := time.Time{}
|
||||
entry, err := tl.UnmarshalEntry(entryBytes)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("error failed to unmarshal TL entry: %w", err)
|
||||
}
|
||||
le, ok := entry.(*models.LogEntryAnon)
|
||||
if !ok {
|
||||
return zeroTime, fmt.Errorf("expected entry to be of type *models.LogEntryAnon, got %T", entry)
|
||||
}
|
||||
err = le.Validate(strfmt.Default)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("TL entry failed validation: %w", err)
|
||||
}
|
||||
|
||||
// TODO: get rekor public keys from TUF (ours or theirs?), and/or embed the public key in the binary
|
||||
rekorPubKeys, err := cosign.GetRekorPubs(ctx)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("error failed to get rekor public keys: %w", err)
|
||||
}
|
||||
err = cosign.VerifyTLogEntryOffline(ctx, le, rekorPubKeys)
|
||||
if err != nil {
|
||||
return zeroTime, fmt.Errorf("TL entry failed verification: %w", err)
|
||||
}
|
||||
|
||||
integratedTime := time.Unix(*le.IntegratedTime, 0)
|
||||
|
||||
return integratedTime, nil
|
||||
type DockerTLExtension struct {
|
||||
Kind string `json:"kind"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
// CreateX509Cert generates a self-signed x509 cert for TL submission.
|
||||
@@ -182,87 +58,15 @@ func CreateX509Cert(subject string, signer dsse.SignerVerifier) ([]byte, error)
|
||||
|
||||
// dsse.SignerVerifier doesn't implement cypto.Signer exactly
|
||||
|
||||
csigner, ok := signer.(*signerverifier.ECDSA256SignerVerifier)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("expected signer to be of type *signerverifier.ECDSA_SignerVerifier, got %T", signer)
|
||||
csigner, err := signerverifier.AsCryptoSigner(signer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error converting signer to crypto.Signer: %w", err)
|
||||
}
|
||||
// create a self-signed X.509 certificate
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, signer.Public(), csigner.Signer)
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, signer.Public(), csigner)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating X.509 certificate: %w", err)
|
||||
}
|
||||
certBlock := &pem.Block{Type: "CERTIFICATE", Bytes: certDER}
|
||||
return pem.EncodeToMemory(certBlock), nil
|
||||
}
|
||||
|
||||
// VerifyEntryPayload checks that the TL entry payload matches envelope payload.
|
||||
func (tl *RekorTL) VerifyEntryPayload(entryBytes, payload, publicKey []byte) error {
|
||||
entry, err := tl.UnmarshalEntry(entryBytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error failed to unmarshal TL entry: %w", err)
|
||||
}
|
||||
le, ok := entry.(*models.LogEntryAnon)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected tl entry to be of type *models.LogEntryAnon, got %T", entry)
|
||||
}
|
||||
tlBody, ok := le.Body.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected tl body to be of type string, got %T", entry)
|
||||
}
|
||||
rekord, err := extractHashedRekord(tlBody)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error extract HashedRekord from TL entry: %w", err)
|
||||
}
|
||||
|
||||
// compare payload hashes
|
||||
payloadHash := util.SHA256Hex(payload)
|
||||
if rekord.Hash != payloadHash {
|
||||
return fmt.Errorf("error payload and tl entry hash mismatch")
|
||||
}
|
||||
|
||||
// compare public keys
|
||||
cert, err := base64.StdEncoding.Strict().DecodeString(rekord.PublicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode public key: %w", err)
|
||||
}
|
||||
p, _ := pem.Decode(cert)
|
||||
result, err := x509.ParseCertificate(p.Bytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse certificate: %w", err)
|
||||
}
|
||||
if !bytes.Equal(result.RawSubjectPublicKeyInfo, publicKey) {
|
||||
return fmt.Errorf("error payload and tl entry public key mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tl *RekorTL) UnmarshalEntry(entry []byte) (any, error) {
|
||||
le := new(models.LogEntryAnon)
|
||||
err := le.UnmarshalBinary(entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error failed to unmarshal TL entry: %w", err)
|
||||
}
|
||||
return le, nil
|
||||
}
|
||||
|
||||
func extractHashedRekord(body string) (*TLPayload, error) {
|
||||
sig := new(TLPayload)
|
||||
pe, err := models.UnmarshalProposedEntry(base64.NewDecoder(base64.StdEncoding, strings.NewReader(body)), runtime.JSONConsumer())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
impl, err := types.UnmarshalEntry(pe)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch entry := impl.(type) {
|
||||
case *hashedrekord_v001.V001Entry:
|
||||
sig.Algorithm = *entry.HashedRekordObj.Data.Hash.Algorithm
|
||||
sig.Hash = *entry.HashedRekordObj.Data.Hash.Value
|
||||
sig.Signature = entry.HashedRekordObj.Signature.Content.String()
|
||||
sig.PublicKey = entry.HashedRekordObj.Signature.PublicKey.Content.String()
|
||||
return sig, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("failed to extract haskedrekord, unsupported type: %T", entry)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,42 +52,31 @@ func TestUploadAndVerifyLogEntry(t *testing.T) {
|
||||
sig, err := signer.Sign(context.Background(), hash)
|
||||
assert.NoError(t, err)
|
||||
|
||||
var tl TL
|
||||
var tl TransparencyLog
|
||||
if UseMockTL {
|
||||
tl = &MockTL{
|
||||
UploadLogEntryFunc: func(_ context.Context, _ string, _ []byte, _ []byte, _ dsse.SignerVerifier) ([]byte, error) {
|
||||
return []byte(TestEntry), nil
|
||||
tl = &MockTransparencyLog{
|
||||
UploadLogEntryFunc: func(_ context.Context, _ string, _ []byte, _ []byte, _ dsse.SignerVerifier) (*DockerTLExtension, error) {
|
||||
return &DockerTLExtension{
|
||||
Kind: RekorTLExtKind,
|
||||
Data: []byte(TestEntry),
|
||||
}, nil
|
||||
},
|
||||
VerifyLogEntryFunc: func(_ context.Context, _ []byte) (time.Time, error) {
|
||||
VerifyLogEntryFunc: func(_ context.Context, _ *DockerTLExtension, _, _ []byte) (time.Time, error) {
|
||||
return time.Time{}, nil
|
||||
},
|
||||
VerifyEntryPayloadFunc: func(_, _, _ []byte) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
} else {
|
||||
tl = &RekorTL{}
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
// test upload log entry
|
||||
ctx := WithTL(context.Background(), tl)
|
||||
entry, err := tl.UploadLogEntry(ctx, "test", payload, sig, signer)
|
||||
ctx := context.Background()
|
||||
entry, err := tl.UploadEntry(ctx, "test", payload, sig, signer)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// test verify log entry
|
||||
_, err = tl.VerifyLogEntry(ctx, entry)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// verify TL entry payload
|
||||
// verify TL entry
|
||||
ecPub, err := x509.MarshalPKIXPublicKey(signer.Public())
|
||||
assert.NoError(t, err)
|
||||
err = tl.VerifyEntryPayload(entry, payload, ecPub)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestVerifyEntryPayload(t *testing.T) {
|
||||
tl := &RekorTL{}
|
||||
p, _ := pem.Decode([]byte(TestPublicKey))
|
||||
err := tl.VerifyEntryPayload([]byte(TestEntry), []byte(TestPayload), p.Bytes)
|
||||
_, err = tl.VerifyEntry(ctx, entry, payload, ecPub)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user