Debian Codegraph @

signature/internal/rekor_set.go

raw
1 package internal
2
3 import (
4 "bytes"
5 "crypto/ecdsa"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/hex"
9 "encoding/json"
10 "encoding/pem"
11 "fmt"
12 "time"
13
14 "github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer"
15 )
16
17 // This is the github.com/sigstore/rekor/pkg/generated/models.Hashedrekord.APIVersion for github.com/sigstore/rekor/pkg/generated/models.HashedrekordV001Schema.
18 // We could alternatively use github.com/sigstore/rekor/pkg/types/hashedrekord.APIVERSION, but that subpackage adds too many dependencies.
19 const RekorHashedRekordV001APIVersion = "0.0.1"
20
21 // UntrustedRekorSET is a parsed content of the sigstore-signature Rekor SET
22 // (note that this a signature-specific format, not a format directly used by the Rekor API).
23 // This corresponds to github.com/sigstore/cosign/bundle.RekorBundle, but we impose a stricter decoder.
24 type UntrustedRekorSET struct {
25 UntrustedSignedEntryTimestamp []byte // A signature over some canonical JSON form of UntrustedPayload
26 UntrustedPayload json.RawMessage
27 }
28
29 type UntrustedRekorPayload struct {
30 Body []byte // In cosign, this is an any, but only a string works
31 IntegratedTime int64
32 LogIndex int64
33 LogID string
34 }
35
36 // A compile-time check that UntrustedRekorSET implements json.Unmarshaler
37 var _ json.Unmarshaler = (*UntrustedRekorSET)(nil)
38
39 // UnmarshalJSON implements the json.Unmarshaler interface
40 func (s *UntrustedRekorSET) UnmarshalJSON(data []byte) error {
41 return JSONFormatToInvalidSignatureError(s.strictUnmarshalJSON(data))
42 }
43
44 // strictUnmarshalJSON is UnmarshalJSON, except that it may return the internal JSONFormatError error type.
45 // Splitting it into a separate function allows us to do the JSONFormatError → InvalidSignatureError in a single place, the caller.
46 func (s *UntrustedRekorSET) strictUnmarshalJSON(data []byte) error {
47 return ParanoidUnmarshalJSONObjectExactFields(data, map[string]any{
48 "SignedEntryTimestamp": &s.UntrustedSignedEntryTimestamp,
49 "Payload": &s.UntrustedPayload,
50 })
51 }
52
53 // A compile-time check that UntrustedRekorSET and *UntrustedRekorSET implements json.Marshaler
54 var _ json.Marshaler = UntrustedRekorSET{}
55 var _ json.Marshaler = (*UntrustedRekorSET)(nil)
56
57 // MarshalJSON implements the json.Marshaler interface.
58 func (s UntrustedRekorSET) MarshalJSON() ([]byte, error) {
59 return json.Marshal(map[string]any{
60 "SignedEntryTimestamp": s.UntrustedSignedEntryTimestamp,
61 "Payload": s.UntrustedPayload,
62 })
63 }
64
65 // A compile-time check that UntrustedRekorPayload implements json.Unmarshaler
66 var _ json.Unmarshaler = (*UntrustedRekorPayload)(nil)
67
68 // UnmarshalJSON implements the json.Unmarshaler interface
69 func (p *UntrustedRekorPayload) UnmarshalJSON(data []byte) error {
70 return JSONFormatToInvalidSignatureError(p.strictUnmarshalJSON(data))
71 }
72
73 // strictUnmarshalJSON is UnmarshalJSON, except that it may return the internal JSONFormatError error type.
74 // Splitting it into a separate function allows us to do the JSONFormatError → InvalidSignatureError in a single place, the caller.
75 func (p *UntrustedRekorPayload) strictUnmarshalJSON(data []byte) error {
76 return ParanoidUnmarshalJSONObjectExactFields(data, map[string]any{
77 "body": &p.Body,
78 "integratedTime": &p.IntegratedTime,
79 "logIndex": &p.LogIndex,
80 "logID": &p.LogID,
81 })
82 }
83
84 // A compile-time check that UntrustedRekorPayload and *UntrustedRekorPayload implements json.Marshaler
85 var _ json.Marshaler = UntrustedRekorPayload{}
86 var _ json.Marshaler = (*UntrustedRekorPayload)(nil)
87
88 // MarshalJSON implements the json.Marshaler interface.
89 func (p UntrustedRekorPayload) MarshalJSON() ([]byte, error) {
90 return json.Marshal(map[string]any{
91 "body": p.Body,
92 "integratedTime": p.IntegratedTime,
93 "logIndex": p.LogIndex,
94 "logID": p.LogID,
95 })
96 }
97
98 // VerifyRekorSET verifies that unverifiedRekorSET is correctly signed by publicKey and matches the rest of the data.
99 // Returns bundle upload time on success.
100 func VerifyRekorSET(publicKeys []*ecdsa.PublicKey, unverifiedRekorSET []byte, unverifiedKeyOrCertBytes []byte, unverifiedBase64Signature string, unverifiedPayloadBytes []byte) (time.Time, error) {
101 // FIXME: Should the publicKey parameter hard-code ecdsa?
102
103 // == Parse SET bytes
104 var untrustedSET UntrustedRekorSET
105 // Sadly. we need to parse and transform untrusted data before verifying a cryptographic signature...
106 if err := json.Unmarshal(unverifiedRekorSET, &untrustedSET); err != nil {
107 return time.Time{}, NewInvalidSignatureError(err.Error())
108 }
109 // == Verify SET signature
110 // Cosign unmarshals and re-marshals UntrustedPayload; that seems unnecessary,
111 // assuming jsoncanonicalizer is designed to operate on untrusted data.
112 untrustedSETPayloadCanonicalBytes, err := jsoncanonicalizer.Transform(untrustedSET.UntrustedPayload)
113 if err != nil {
114 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf("canonicalizing Rekor SET JSON: %v", err))
115 }
116 untrustedSETPayloadHash := sha256.Sum256(untrustedSETPayloadCanonicalBytes)
117 publicKeymatched := false
118 for _, pk := range publicKeys {
119 if ecdsa.VerifyASN1(pk, untrustedSETPayloadHash[:], untrustedSET.UntrustedSignedEntryTimestamp) {
120 publicKeymatched = true
121 break
122 }
123 }
124 if !publicKeymatched {
125 return time.Time{}, NewInvalidSignatureError("cryptographic signature verification of Rekor SET failed")
126 }
127
128 // == Parse SET payload
129 // Parse the cryptographically-verified canonicalized variant, NOT the originally-delivered representation,
130 // to decrease risk of exploiting the JSON parser. Note that if there were an arbitrary execution vulnerability, the attacker
131 // could have exploited the parsing of unverifiedRekorSET above already; so this, at best, ensures more consistent processing
132 // of the SET payload.
133 var rekorPayload UntrustedRekorPayload
134 if err := json.Unmarshal(untrustedSETPayloadCanonicalBytes, &rekorPayload); err != nil {
135 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf("parsing Rekor SET payload: %v", err.Error()))
136 }
137 // FIXME: Consider being much more strict about decoding JSON.
138 var hashedRekord RekorHashedrekord
139 if err := json.Unmarshal(rekorPayload.Body, &hashedRekord); err != nil {
140 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf("decoding the body of a Rekor SET payload: %v", err))
141 }
142 // The decode of HashedRekord validates the "kind": "hashedrecord" field, which is otherwise invisible to us.
143 if hashedRekord.APIVersion == nil {
144 return time.Time{}, NewInvalidSignatureError("missing Rekor SET Payload API version")
145 }
146 if *hashedRekord.APIVersion != RekorHashedRekordV001APIVersion {
147 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf("unsupported Rekor SET Payload hashedrekord version %#v", hashedRekord.APIVersion))
148 }
149 var hashedRekordV001 RekorHashedrekordV001Schema
150 if err := json.Unmarshal(hashedRekord.Spec, &hashedRekordV001); err != nil {
151 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf("decoding hashedrekod spec: %v", err))
152 }
153
154 // == Match unverifiedKeyOrCertBytes
155 if hashedRekordV001.Signature == nil {
156 return time.Time{}, NewInvalidSignatureError(`Missing "signature" field in hashedrekord`)
157 }
158 if hashedRekordV001.Signature.PublicKey == nil {
159 return time.Time{}, NewInvalidSignatureError(`Missing "signature.publicKey" field in hashedrekord`)
160
161 }
162 rekorKeyOrCertPEM, rest := pem.Decode(hashedRekordV001.Signature.PublicKey.Content)
163 if rekorKeyOrCertPEM == nil {
164 return time.Time{}, NewInvalidSignatureError("publicKey in Rekor SET is not in PEM format")
165 }
166 if len(rest) != 0 {
167 return time.Time{}, NewInvalidSignatureError("publicKey in Rekor SET has trailing data")
168 }
169 // FIXME: For public keys, let the caller provide the DER-formatted blob instead
170 // of round-tripping through PEM.
171 unverifiedKeyOrCertPEM, rest := pem.Decode(unverifiedKeyOrCertBytes)
172 if unverifiedKeyOrCertPEM == nil {
173 return time.Time{}, NewInvalidSignatureError("public key or cert to be matched against publicKey in Rekor SET is not in PEM format")
174 }
175 if len(rest) != 0 {
176 return time.Time{}, NewInvalidSignatureError("public key or cert to be matched against publicKey in Rekor SET has trailing data")
177 }
178 // NOTE: This compares the PEM payload, but not the object type or headers.
179 if !bytes.Equal(rekorKeyOrCertPEM.Bytes, unverifiedKeyOrCertPEM.Bytes) {
180 return time.Time{}, NewInvalidSignatureError("publicKey in Rekor SET does not match")
181 }
182 // == Match unverifiedSignatureBytes
183 unverifiedSignatureBytes, err := base64.StdEncoding.DecodeString(unverifiedBase64Signature)
184 if err != nil {
185 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf("decoding signature base64: %v", err))
186 }
187 if !bytes.Equal(hashedRekordV001.Signature.Content, unverifiedSignatureBytes) {
188 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf("signature in Rekor SET does not match: %#v vs. %#v",
189 string(hashedRekordV001.Signature.Content), string(unverifiedSignatureBytes)))
190 }
191
192 // == Match unverifiedPayloadBytes
193 if hashedRekordV001.Data == nil {
194 return time.Time{}, NewInvalidSignatureError(`Missing "data" field in hashedrekord`)
195 }
196 if hashedRekordV001.Data.Hash == nil {
197 return time.Time{}, NewInvalidSignatureError(`Missing "data.hash" field in hashedrekord`)
198 }
199 if hashedRekordV001.Data.Hash.Algorithm == nil {
200 return time.Time{}, NewInvalidSignatureError(`Missing "data.hash.algorithm" field in hashedrekord`)
201 }
202 // FIXME: Rekor 1.3.5 has added SHA-386 and SHA-512 as recognized values.
203 // Eventually we should support them as well.
204 // Short-term, Cosign (as of 2024-02 and Cosign 2.2.3) only produces and accepts SHA-256, so right now that’s not a compatibility
205 // issue.
206 if *hashedRekordV001.Data.Hash.Algorithm != RekorHashedrekordV001SchemaDataHashAlgorithmSha256 {
207 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf(`Unexpected "data.hash.algorithm" value %#v`, *hashedRekordV001.Data.Hash.Algorithm))
208 }
209 if hashedRekordV001.Data.Hash.Value == nil {
210 return time.Time{}, NewInvalidSignatureError(`Missing "data.hash.value" field in hashedrekord`)
211 }
212 rekorPayloadHash, err := hex.DecodeString(*hashedRekordV001.Data.Hash.Value)
213 if err != nil {
214 return time.Time{}, NewInvalidSignatureError(fmt.Sprintf(`Invalid "data.hash.value" field in hashedrekord: %v`, err))
215
216 }
217 unverifiedPayloadHash := sha256.Sum256(unverifiedPayloadBytes)
218 if !bytes.Equal(rekorPayloadHash, unverifiedPayloadHash[:]) {
219 return time.Time{}, NewInvalidSignatureError("payload in Rekor SET does not match")
220 }
221
222 // == All OK; return the relevant time.
223 return time.Unix(rekorPayload.IntegratedTime, 0), nil
224 }