-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathrekor.go
350 lines (302 loc) · 10.7 KB
/
rekor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package gha
import (
"bytes"
"context"
"crypto"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"os"
"strings"
"time"
cjson "github.com/docker/go/canonical/json"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/sigstore/cosign/cmd/cosign/cli/fulcio"
"github.com/sigstore/cosign/pkg/cosign"
"github.com/sigstore/rekor/pkg/generated/client"
"github.com/sigstore/rekor/pkg/generated/client/entries"
"github.com/sigstore/rekor/pkg/generated/client/index"
"github.com/sigstore/rekor/pkg/generated/models"
"github.com/sigstore/rekor/pkg/sharding"
"github.com/sigstore/rekor/pkg/types"
intotod "github.com/sigstore/rekor/pkg/types/intoto/v0.0.1"
rverify "github.com/sigstore/rekor/pkg/verify"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/dsse"
"github.com/slsa-framework/slsa-github-generator/signing/envelope"
serrors "github.com/slsa-framework/slsa-verifier/errors"
)
const (
defaultRekorAddr = "https://rekor.sigstore.dev"
)
func verifyTlogEntryByUUID(ctx context.Context, rekorClient *client.Rekor, entryUUID string) (
*models.LogEntryAnon, error) {
params := entries.NewGetLogEntryByUUIDParamsWithContext(ctx)
params.EntryUUID = entryUUID
lep, err := rekorClient.Entries.GetLogEntryByUUID(params)
if err != nil {
return nil, err
}
if len(lep.Payload) != 1 {
return nil, errors.New("UUID value can not be extracted")
}
uuid, err := sharding.GetUUIDFromIDString(params.EntryUUID)
if err != nil {
return nil, err
}
for k, entry := range lep.Payload {
returnUUID, err := sharding.GetUUIDFromIDString(k)
if err != nil {
return nil, err
}
// Validate that the request matches the response
if returnUUID != uuid {
return nil, errors.New("expected matching UUID")
}
// Validate the entry response.
return verifyTlogEntry(ctx, rekorClient, entry)
}
return nil, serrors.ErrorRekorSearch
}
func verifyTlogEntry(ctx context.Context, rekorClient *client.Rekor, e models.LogEntryAnon) (
*models.LogEntryAnon, error) {
// Verify the root hash against the current Signed Entry Tree Head
pubs, err := cosign.GetRekorPubs(ctx, nil)
if err != nil {
return nil, fmt.Errorf("%w: %s", err, "unable to fetch Rekor public keys from TUF repository")
}
verifier, err := signature.LoadECDSAVerifier(pubs[*e.LogID].PubKey, crypto.SHA256)
if err != nil {
return nil, fmt.Errorf("%w: %s", err, "unable to load a ECDSA verifier")
}
// This function verifies the inclusion proof, the signature on the root hash of the
// inclusion proof, and the SignedEntryTimestamp.
if err := rverify.VerifyLogEntry(ctx, &e, verifier); err != nil {
return nil, fmt.Errorf("%w: %s", err, "unable to verify a log entry")
}
return &e, nil
}
func extractCert(e *models.LogEntryAnon) (*x509.Certificate, error) {
b, err := base64.StdEncoding.DecodeString(e.Body.(string))
if err != nil {
return nil, err
}
pe, err := models.UnmarshalProposedEntry(bytes.NewReader(b), runtime.JSONConsumer())
if err != nil {
return nil, err
}
eimpl, err := types.UnmarshalEntry(pe)
if err != nil {
return nil, err
}
var publicKeyB64 []byte
switch e := eimpl.(type) {
case *intotod.V001Entry:
publicKeyB64, err = e.IntotoObj.PublicKey.MarshalText()
if err != nil {
return nil, err
}
default:
return nil, errors.New("unexpected tlog entry type")
}
publicKey, err := base64.StdEncoding.DecodeString(string(publicKeyB64))
if err != nil {
return nil, err
}
certs, err := cryptoutils.UnmarshalCertificatesFromPEM(publicKey)
if err != nil {
return nil, err
}
if len(certs) != 1 {
return nil, errors.New("unexpected number of cert pem tlog entry")
}
return certs[0], err
}
func intotoEntry(certPem []byte, provenance []byte) (*intotod.V001Entry, error) {
if len(certPem) == 0 {
return nil, fmt.Errorf("no signing certificate found in intoto envelope")
}
cert := strfmt.Base64(certPem)
return &intotod.V001Entry{
IntotoObj: models.IntotoV001Schema{
Content: &models.IntotoV001SchemaContent{
Envelope: string(provenance),
},
PublicKey: &cert,
},
}, nil
}
// getUUIDsByArtifactDigest finds all entry UUIDs by the digest of the artifact binary.
func getUUIDsByArtifactDigest(rClient *client.Rekor, artifactHash string) ([]string, error) {
// Use search index to find rekor entry UUIDs that match Subject Digest.
params := index.NewSearchIndexParams()
params.Query = &models.SearchIndex{Hash: fmt.Sprintf("sha256:%v", artifactHash)}
resp, err := rClient.Index.SearchIndex(params)
if err != nil {
return nil, fmt.Errorf("%w: %s", serrors.ErrorRekorSearch, err.Error())
}
if len(resp.Payload) == 0 {
return nil, fmt.Errorf("%w: no matching entries found", serrors.ErrorRekorSearch)
}
return resp.GetPayload(), nil
}
// GetValidSignedAttestationWithCert finds and validates the matching entry UUIDs with
// the full intoto attestation.
// The attestation generated by the slsa-github-generator libraries contain a signing certificate.
func GetValidSignedAttestationWithCert(rClient *client.Rekor, provenance []byte) (*SignedAttestation, error) {
// Use intoto attestation to find rekor entry UUIDs.
params := entries.NewSearchLogQueryParams()
searchLogQuery := models.SearchLogQuery{}
certPem, err := envelope.GetCertFromEnvelope(provenance)
if err != nil {
return nil, fmt.Errorf("error getting certificate from provenance: %w", err)
}
e, err := intotoEntry(certPem, provenance)
if err != nil {
return nil, fmt.Errorf("error creating intoto entry: %w", err)
}
entry := models.Intoto{
APIVersion: swag.String(e.APIVersion()),
Spec: e.IntotoObj,
}
entries := []models.ProposedEntry{&entry}
searchLogQuery.SetEntries(entries)
params.SetEntry(&searchLogQuery)
resp, err := rClient.Entries.SearchLogQuery(params)
if err != nil {
return nil, fmt.Errorf("%w: %s", serrors.ErrorRekorSearch, err.Error())
}
if len(resp.GetPayload()) != 1 {
return nil, fmt.Errorf("%w: %s", serrors.ErrorRekorSearch, "no matching rekor entries")
}
logEntry := resp.Payload[0]
var rekorEntry models.LogEntryAnon
for uuid, e := range logEntry {
if _, err := verifyTlogEntry(context.Background(), rClient, e); err != nil {
return nil, fmt.Errorf("error verifying tlog entry: %w", err)
}
rekorEntry = e
url := fmt.Sprintf("%v/%v/%v", defaultRekorAddr, "api/v1/log/entries", uuid)
fmt.Fprintf(os.Stderr, "Verified signature against tlog entry index %d at URL: %s\n", *e.LogIndex, url)
}
certs, err := cryptoutils.UnmarshalCertificatesFromPEM(certPem)
if err != nil {
return nil, err
}
if len(certs) != 1 {
return nil, fmt.Errorf("error unmarshaling certificate from pem")
}
env, err := EnvelopeFromBytes(provenance)
if err != nil {
return nil, err
}
proposedSignedAtt := &SignedAttestation{
SigningCert: certs[0],
Envelope: env,
RekorEntry: &rekorEntry,
}
if err := verifySignedAttestation(proposedSignedAtt); err != nil {
return nil, err
}
return proposedSignedAtt, nil
}
// SearchValidSignedAttestation searches for a valid signing certificate using the Rekor
// Redis search index by using the artifact digest.
func SearchValidSignedAttestation(ctx context.Context, artifactHash string, provenance []byte,
rClient *client.Rekor) (*SignedAttestation, error) {
// Get Rekor UUIDs by artifact digest.
uuids, err := getUUIDsByArtifactDigest(rClient, artifactHash)
if err != nil {
return nil, err
}
env, err := EnvelopeFromBytes(provenance)
if err != nil {
return nil, err
}
// Iterate through each matching UUID and perform:
// * Verify TLOG entry (inclusion and signed entry timestamp against Rekor pubkey).
// * Verify the signing certificate against the Fulcio root CA.
// * Verify dsse envelope signature against signing certificate.
// * Check signature expiration against IntegratedTime in entry.
// * If all succeed, return the signing certificate.
var errs []string
for _, uuid := range uuids {
entry, err := verifyTlogEntryByUUID(ctx, rClient, uuid)
if err != nil {
// this is unexpected, hold on to this error.
errs = append(errs, fmt.Sprintf("%s: verifying tlog entry %s", err, uuid))
continue
}
cert, err := extractCert(entry)
if err != nil {
// this is unexpected, hold on to this error.
errs = append(errs, fmt.Sprintf("%s: extracting certificate from %s", err, uuid))
continue
}
proposedSignedAtt := &SignedAttestation{
Envelope: env,
SigningCert: cert,
RekorEntry: entry,
}
err = verifySignedAttestation(proposedSignedAtt)
if errors.Is(err, serrors.ErrorInternal) {
// Return on an internal error
return nil, err
} else if err != nil {
errs = append(errs, err.Error())
continue
}
// success!
url := fmt.Sprintf("%v/%v/%v", defaultRekorAddr, "api/v1/log/entries", uuid)
fmt.Fprintf(os.Stderr, "Verified signature against tlog entry index %d at URL: %s\n", *entry.LogIndex, url)
return proposedSignedAtt, nil
}
return nil, fmt.Errorf("%w: got unexpected errors %s", serrors.ErrorNoValidRekorEntries, strings.Join(errs, ", "))
}
// verifyAttestationSignature validates the signature on the attestation
// given a certificate and a validated signature time.
// The certificate is verified up to Fulcio, the signature is validated
// using the certificate, and the signature generation time is checked
// to be within the certificate validity period.
func verifySignedAttestation(signedAtt *SignedAttestation) error {
cert := signedAtt.SigningCert
attBytes, err := cjson.MarshalCanonical(signedAtt.Envelope)
if err != nil {
return err
}
signatureTimestamp := time.Unix(*signedAtt.RekorEntry.IntegratedTime, 0)
// 1. Verify certificate chain.
roots, err := fulcio.GetRoots()
if err != nil {
// this is unexpected, hold on to this error.
return fmt.Errorf("%w: %s", serrors.ErrorInternal, err)
}
intermediates, err := fulcio.GetIntermediates()
if err != nil {
// this is unexpected, hold on to this error.
return fmt.Errorf("%w: %s", serrors.ErrorInternal, err)
}
co := &cosign.CheckOpts{
RootCerts: roots,
IntermediateCerts: intermediates,
CertOidcIssuer: certOidcIssuer,
}
verifier, err := cosign.ValidateAndUnpackCert(signedAtt.SigningCert, co)
if err != nil {
return fmt.Errorf("%w: %s", serrors.ErrorInvalidSignature, err)
}
// 2. Verify signature using validated certificate.
verifier = dsse.WrapVerifier(verifier)
if err := verifier.VerifySignature(bytes.NewReader(attBytes), bytes.NewReader(attBytes)); err != nil {
return fmt.Errorf("%w: %s", serrors.ErrorInvalidSignature, err)
}
// 3. Verify signature was creating during certificate validity period.
if err := cosign.CheckExpiry(cert, signatureTimestamp); err != nil {
return fmt.Errorf("%w: %s", serrors.ErrorInvalidSignature, err)
}
return nil
}