diff --git a/pki/pki.go b/pki/pki.go index cd96aad51..d2b9a0c16 100644 --- a/pki/pki.go +++ b/pki/pki.go @@ -57,6 +57,9 @@ type TLSScheme interface { func UnmarshalPEMPublicKey(data []byte) (sign.PublicKey, error) { block, rest := pem.Decode(data) + if block == nil { + return nil, errors.New("no pem block found") + } if len(rest) != 0 { return nil, errors.New("trailing data") } @@ -87,6 +90,9 @@ func UnmarshalPKIXPublicKey(data []byte) (sign.PublicKey, error) { func UnmarshalPEMPrivateKey(data []byte) (sign.PrivateKey, error) { block, rest := pem.Decode(data) + if block == nil { + return nil, errors.New("no pem block found") + } if len(rest) != 0 { return nil, errors.New("trailing") } diff --git a/pki/pki_test.go b/pki/pki_test.go index 29942d460..0b5a328cb 100644 --- a/pki/pki_test.go +++ b/pki/pki_test.go @@ -113,3 +113,14 @@ func TestMLDSA(t *testing.T) { testMLDSASad(t, "bad-ML-DSA-44-1.priv.gz") } + +func TestUnmarshalPEMNoBlock(t *testing.T) { + for _, in := range [][]byte{nil, {}, []byte("not pem"), []byte("-----BEGIN GARBAGE")} { + if _, err := pki.UnmarshalPEMPublicKey(in); err == nil { + t.Errorf("UnmarshalPEMPublicKey(%q) expected error, got nil", in) + } + if _, err := pki.UnmarshalPEMPrivateKey(in); err == nil { + t.Errorf("UnmarshalPEMPrivateKey(%q) expected error, got nil", in) + } + } +}