From 66e0ab1e7e31c54ed83f9dd21607582e8574bd3f Mon Sep 17 00:00:00 2001 From: dlorenc Date: Tue, 19 Oct 2021 07:24:31 -0500 Subject: [PATCH] Fix a bug in x509 certificate handling. (#461) The CryptoPubKey function only returned the key value, but we should retrieve it from the cert if set. This fixes the rest of #918. Signed-off-by: Dan Lorenc --- pkg/pki/x509/x509.go | 3 +++ pkg/types/intoto/v0.0.1/entry_test.go | 28 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/pkg/pki/x509/x509.go b/pkg/pki/x509/x509.go index d2500e80f..4933d3a1b 100644 --- a/pkg/pki/x509/x509.go +++ b/pkg/pki/x509/x509.go @@ -139,6 +139,9 @@ func (k PublicKey) CanonicalValue() (encoded []byte, err error) { } func (k PublicKey) CryptoPubKey() crypto.PublicKey { + if k.cert != nil { + return k.cert.c.PublicKey + } return k.key } diff --git a/pkg/types/intoto/v0.0.1/entry_test.go b/pkg/types/intoto/v0.0.1/entry_test.go index 8b695ff43..513d892dd 100644 --- a/pkg/types/intoto/v0.0.1/entry_test.go +++ b/pkg/types/intoto/v0.0.1/entry_test.go @@ -27,6 +27,7 @@ import ( "encoding/json" "encoding/pem" "fmt" + "math/big" "reflect" "testing" @@ -90,6 +91,23 @@ func TestV001Entry_Unmarshal(t *testing.T) { Type: "PUBLIC KEY", }) + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + + ca := &x509.Certificate{ + SerialNumber: big.NewInt(1), + } + caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &priv.PublicKey, priv) + if err != nil { + t.Fatal(err) + } + pemBytes := pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Bytes: caBytes, + }) + invalid, err := json.Marshal(dsse.Envelope{ Payload: "hello", Signatures: []dsse.Signature{ @@ -139,6 +157,16 @@ func TestV001Entry_Unmarshal(t *testing.T) { }, wantErr: false, }, + { + name: "cert", + it: &models.IntotoV001Schema{ + PublicKey: p([]byte(pemBytes)), + Content: &models.IntotoV001SchemaContent{ + Envelope: envelope(t, priv, validPayload, "text"), + }, + }, + wantErr: false, + }, { name: "invalid", it: &models.IntotoV001Schema{