-
Notifications
You must be signed in to change notification settings - Fork 582
/
Copy pathverify.go
1402 lines (1254 loc) · 44.3 KB
/
verify.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cosign
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/sha256"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
"github.com/digitorus/timestamp"
"github.com/go-openapi/runtime"
"github.com/nozzle/throttler"
"github.com/sigstore/cosign/v2/internal/pkg/cosign"
"github.com/sigstore/cosign/v2/pkg/blob"
cbundle "github.com/sigstore/cosign/v2/pkg/cosign/bundle"
"github.com/sigstore/cosign/v2/pkg/oci/static"
"github.com/sigstore/cosign/v2/pkg/types"
"github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
ssldsse "github.com/secure-systems-lab/go-securesystemslib/dsse"
ociexperimental "github.com/sigstore/cosign/v2/internal/pkg/oci/remote"
"github.com/sigstore/cosign/v2/internal/ui"
"github.com/sigstore/cosign/v2/pkg/oci"
"github.com/sigstore/cosign/v2/pkg/oci/layout"
ociremote "github.com/sigstore/cosign/v2/pkg/oci/remote"
"github.com/sigstore/rekor/pkg/generated/client"
"github.com/sigstore/rekor/pkg/generated/models"
rekor_types "github.com/sigstore/rekor/pkg/types"
dsse_v001 "github.com/sigstore/rekor/pkg/types/dsse/v0.0.1"
hashedrekord_v001 "github.com/sigstore/rekor/pkg/types/hashedrekord/v0.0.1"
intoto_v001 "github.com/sigstore/rekor/pkg/types/intoto/v0.0.1"
intoto_v002 "github.com/sigstore/rekor/pkg/types/intoto/v0.0.2"
rekord_v001 "github.com/sigstore/rekor/pkg/types/rekord/v0.0.1"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/dsse"
"github.com/sigstore/sigstore/pkg/signature/options"
"github.com/sigstore/sigstore/pkg/tuf"
tsaverification "github.com/sigstore/timestamp-authority/pkg/verification"
)
// Identity specifies an issuer/subject to verify a signature against.
// Both IssuerRegExp/SubjectRegExp support regexp while Issuer/Subject are for
// strict matching.
type Identity struct {
Issuer string
Subject string
IssuerRegExp string
SubjectRegExp string
}
// CheckOpts are the options for checking signatures.
type CheckOpts struct {
// RegistryClientOpts are the options for interacting with the container registry.
RegistryClientOpts []ociremote.Option
// Annotations optionally specifies image signature annotations to verify.
Annotations map[string]interface{}
// ClaimVerifier, if provided, verifies claims present in the oci.Signature.
ClaimVerifier func(sig oci.Signature, imageDigest v1.Hash, annotations map[string]interface{}) error
// RekorClient, if set, is used to make online tlog calls use to verify signatures and public keys.
RekorClient *client.Rekor
// RekorPubKeys, if set, is used to validate signatures on log entries from
// Rekor. It is a map from LogID to crypto.PublicKey. LogID is
// derived from the PublicKey (see RFC 6962 S3.2).
// Note that even though the type is of crypto.PublicKey, Rekor only allows
// for ecdsa.PublicKey: https://github.com/sigstore/cosign/issues/2540
RekorPubKeys *TrustedTransparencyLogPubKeys
// SigVerifier is used to verify signatures.
SigVerifier signature.Verifier
// PKOpts are the options provided to `SigVerifier.PublicKey()`.
PKOpts []signature.PublicKeyOption
// RootCerts are the root CA certs used to verify a signature's chained certificate.
RootCerts *x509.CertPool
// IntermediateCerts are the optional intermediate CA certs used to verify a certificate chain.
IntermediateCerts *x509.CertPool
// CertGithubWorkflowTrigger is the GitHub Workflow Trigger name expected for a certificate to be valid. The empty string means any certificate can be valid.
CertGithubWorkflowTrigger string
// CertGithubWorkflowSha is the GitHub Workflow SHA expected for a certificate to be valid. The empty string means any certificate can be valid.
CertGithubWorkflowSha string
// CertGithubWorkflowName is the GitHub Workflow Name expected for a certificate to be valid. The empty string means any certificate can be valid.
CertGithubWorkflowName string
// CertGithubWorkflowRepository is the GitHub Workflow Repository expected for a certificate to be valid. The empty string means any certificate can be valid.
CertGithubWorkflowRepository string
// CertGithubWorkflowRef is the GitHub Workflow Ref expected for a certificate to be valid. The empty string means any certificate can be valid.
CertGithubWorkflowRef string
// IgnoreSCT requires that a certificate contain an embedded SCT during verification. An SCT is proof of inclusion in a
// certificate transparency log.
IgnoreSCT bool
// Detached SCT. Optional, as the SCT is usually embedded in the certificate.
SCT []byte
// CTLogPubKeys, if set, is used to validate SCTs against those keys.
// It is a map from log id to LogIDMetadata. It is a map from LogID to crypto.PublicKey. LogID is derived from the PublicKey (see RFC 6962 S3.2).
CTLogPubKeys *TrustedTransparencyLogPubKeys
// SignatureRef is the reference to the signature file. PayloadRef should always be specified as well (though it’s possible for a _some_ signatures to be verified without it, with a warning).
SignatureRef string
// PayloadRef is a reference to the payload file. Applicable only if SignatureRef is set.
PayloadRef string
// Identities is an array of Identity (Subject, Issuer) matchers that have
// to be met for the signature to ve valid.
Identities []Identity
// Force offline verification of the signature
Offline bool
// Set of flags to verify an RFC3161 timestamp used for trusted timestamping
// TSACertificate is the certificate used to sign the timestamp. Optional, if provided in the timestamp
TSACertificate *x509.Certificate
// TSARootCertificates are the set of roots to verify the TSA certificate
TSARootCertificates []*x509.Certificate
// TSAIntermediateCertificates are the set of intermediates for chain building
TSAIntermediateCertificates []*x509.Certificate
// IgnoreTlog skip tlog verification
IgnoreTlog bool
// The amount of maximum workers for parallel executions.
// Defaults to 10.
MaxWorkers int
// Should the experimental OCI 1.1 behaviour be enabled or not.
// Defaults to false.
ExperimentalOCI11 bool
}
// This is a substitutable signature verification function that can be used for verifying
// attestations of blobs.
type signatureVerificationFn func(
ctx context.Context, verifier signature.Verifier, sig payloader) error
// For unit testing
type payloader interface {
// no-op for attestations
Base64Signature() (string, error)
Payload() ([]byte, error)
}
func verifyOCIAttestation(ctx context.Context, verifier signature.Verifier, att payloader) error {
payload, err := att.Payload()
if err != nil {
return err
}
env := ssldsse.Envelope{}
if err := json.Unmarshal(payload, &env); err != nil {
return err
}
if env.PayloadType != types.IntotoPayloadType {
return &VerificationFailure{
fmt.Errorf("invalid payloadType %s on envelope. Expected %s", env.PayloadType, types.IntotoPayloadType),
}
}
dssev, err := ssldsse.NewEnvelopeVerifier(&dsse.VerifierAdapter{SignatureVerifier: verifier})
if err != nil {
return err
}
_, err = dssev.Verify(ctx, &env)
return err
}
func verifyOCISignature(ctx context.Context, verifier signature.Verifier, sig payloader) error {
b64sig, err := sig.Base64Signature()
if err != nil {
return err
}
signature, err := base64.StdEncoding.DecodeString(b64sig)
if err != nil {
return err
}
payload, err := sig.Payload()
if err != nil {
return err
}
return verifier.VerifySignature(bytes.NewReader(signature), bytes.NewReader(payload), options.WithContext(ctx))
}
// ValidateAndUnpackCert creates a Verifier from a certificate. Veries that the certificate
// chains up to a trusted root. Optionally verifies the subject and issuer of the certificate.
func ValidateAndUnpackCert(cert *x509.Certificate, co *CheckOpts) (signature.Verifier, error) {
verifier, err := signature.LoadVerifier(cert.PublicKey, crypto.SHA256)
if err != nil {
return nil, fmt.Errorf("invalid certificate found on signature: %w", err)
}
// Handle certificates where the Subject Alternative Name is not set to a supported
// GeneralName (RFC 5280 4.2.1.6). Go only supports DNS, IP addresses, email addresses,
// or URIs as SANs. Fulcio can issue a certificate with an OtherName GeneralName, so
// remove the unhandled critical SAN extension before verifying.
if len(cert.UnhandledCriticalExtensions) > 0 {
var unhandledExts []asn1.ObjectIdentifier
for _, oid := range cert.UnhandledCriticalExtensions {
if !oid.Equal(cryptoutils.SANOID) {
unhandledExts = append(unhandledExts, oid)
}
}
cert.UnhandledCriticalExtensions = unhandledExts
}
// Now verify the cert, then the signature.
chains, err := TrustedCert(cert, co.RootCerts, co.IntermediateCerts)
if err != nil {
return nil, err
}
err = CheckCertificatePolicy(cert, co)
if err != nil {
return nil, err
}
// If IgnoreSCT is set, skip the SCT check
if co.IgnoreSCT {
return verifier, nil
}
contains, err := ContainsSCT(cert.Raw)
if err != nil {
return nil, err
}
if !contains && len(co.SCT) == 0 {
return nil, &VerificationFailure{
fmt.Errorf("certificate does not include required embedded SCT and no detached SCT was set"),
}
}
// handle if chains has more than one chain - grab first and print message
if len(chains) > 1 {
fmt.Fprintf(os.Stderr, "**Info** Multiple valid certificate chains found. Selecting the first to verify the SCT.\n")
}
if contains {
if err := VerifyEmbeddedSCT(context.Background(), chains[0], co.CTLogPubKeys); err != nil {
return nil, err
}
} else {
chain := chains[0]
if len(chain) < 2 {
return nil, errors.New("certificate chain must contain at least a certificate and its issuer")
}
certPEM, err := cryptoutils.MarshalCertificateToPEM(chain[0])
if err != nil {
return nil, err
}
chainPEM, err := cryptoutils.MarshalCertificatesToPEM(chain[1:])
if err != nil {
return nil, err
}
if err := VerifySCT(context.Background(), certPEM, chainPEM, co.SCT, co.CTLogPubKeys); err != nil {
return nil, err
}
}
return verifier, nil
}
// CheckCertificatePolicy checks that the certificate subject and issuer match
// the expected values.
func CheckCertificatePolicy(cert *x509.Certificate, co *CheckOpts) error {
ce := CertExtensions{Cert: cert}
if err := validateCertExtensions(ce, co); err != nil {
return err
}
oidcIssuer := ce.GetIssuer()
sans := cryptoutils.GetSubjectAlternateNames(cert)
// If there are identities given, go through them and if one of them
// matches, call that good, otherwise, return an error.
if len(co.Identities) > 0 {
for _, identity := range co.Identities {
issuerMatches := false
switch {
// Check the issuer first
case identity.IssuerRegExp != "":
if regex, err := regexp.Compile(identity.IssuerRegExp); err != nil {
return fmt.Errorf("malformed issuer in identity: %s : %w", identity.IssuerRegExp, err)
} else if regex.MatchString(oidcIssuer) {
issuerMatches = true
}
case identity.Issuer != "":
if identity.Issuer == oidcIssuer {
issuerMatches = true
}
default:
// No issuer constraint on this identity, so checks out
issuerMatches = true
}
// Then the subject
subjectMatches := false
switch {
case identity.SubjectRegExp != "":
regex, err := regexp.Compile(identity.SubjectRegExp)
if err != nil {
return fmt.Errorf("malformed subject in identity: %s : %w", identity.SubjectRegExp, err)
}
for _, san := range sans {
if regex.MatchString(san) {
subjectMatches = true
break
}
}
case identity.Subject != "":
for _, san := range sans {
if san == identity.Subject {
subjectMatches = true
break
}
}
default:
// No subject constraint on this identity, so checks out
subjectMatches = true
}
if subjectMatches && issuerMatches {
// If both issuer / subject match, return verified
return nil
}
}
return &VerificationFailure{
fmt.Errorf("none of the expected identities matched what was in the certificate, got subjects [%s] with issuer %s", strings.Join(sans, ", "), oidcIssuer),
}
}
return nil
}
func validateCertExtensions(ce CertExtensions, co *CheckOpts) error {
if co.CertGithubWorkflowTrigger != "" {
if ce.GetCertExtensionGithubWorkflowTrigger() != co.CertGithubWorkflowTrigger {
return &VerificationFailure{
fmt.Errorf("expected GitHub Workflow Trigger not found in certificate"),
}
}
}
if co.CertGithubWorkflowSha != "" {
if ce.GetExtensionGithubWorkflowSha() != co.CertGithubWorkflowSha {
return &VerificationFailure{
fmt.Errorf("expected GitHub Workflow SHA not found in certificate"),
}
}
}
if co.CertGithubWorkflowName != "" {
if ce.GetCertExtensionGithubWorkflowName() != co.CertGithubWorkflowName {
return &VerificationFailure{
fmt.Errorf("expected GitHub Workflow Name not found in certificate"),
}
}
}
if co.CertGithubWorkflowRepository != "" {
if ce.GetCertExtensionGithubWorkflowRepository() != co.CertGithubWorkflowRepository {
return &VerificationFailure{
fmt.Errorf("expected GitHub Workflow Repository not found in certificate"),
}
}
}
if co.CertGithubWorkflowRef != "" {
if ce.GetCertExtensionGithubWorkflowRef() != co.CertGithubWorkflowRef {
return &VerificationFailure{
fmt.Errorf("expected GitHub Workflow Ref not found in certificate"),
}
}
}
return nil
}
// ValidateAndUnpackCertWithChain creates a Verifier from a certificate. Verifies that the certificate
// chains up to the provided root. Chain should start with the parent of the certificate and end with the root.
// Optionally verifies the subject and issuer of the certificate.
func ValidateAndUnpackCertWithChain(cert *x509.Certificate, chain []*x509.Certificate, co *CheckOpts) (signature.Verifier, error) {
if len(chain) == 0 {
return nil, errors.New("no chain provided to validate certificate")
}
rootPool := x509.NewCertPool()
rootPool.AddCert(chain[len(chain)-1])
co.RootCerts = rootPool
subPool := x509.NewCertPool()
for _, c := range chain[:len(chain)-1] {
subPool.AddCert(c)
}
co.IntermediateCerts = subPool
return ValidateAndUnpackCert(cert, co)
}
func tlogValidateEntry(ctx context.Context, client *client.Rekor, rekorPubKeys *TrustedTransparencyLogPubKeys,
sig oci.Signature, pem []byte) (*models.LogEntryAnon, error) {
b64sig, err := sig.Base64Signature()
if err != nil {
return nil, err
}
payload, err := sig.Payload()
if err != nil {
return nil, err
}
tlogEntries, err := FindTlogEntry(ctx, client, b64sig, payload, pem)
if err != nil {
return nil, err
}
if len(tlogEntries) == 0 {
return nil, fmt.Errorf("no valid tlog entries found with proposed entry")
}
// Always return the earliest integrated entry. That
// always suffices for verification of signature time.
var earliestLogEntry models.LogEntryAnon
var earliestLogEntryTime *time.Time
entryVerificationErrs := make([]string, 0)
for _, e := range tlogEntries {
entry := e
if err := VerifyTLogEntryOffline(ctx, &entry, rekorPubKeys); err != nil {
entryVerificationErrs = append(entryVerificationErrs, err.Error())
continue
}
entryTime := time.Unix(*entry.IntegratedTime, 0)
if earliestLogEntryTime == nil || entryTime.Before(*earliestLogEntryTime) {
earliestLogEntryTime = &entryTime
earliestLogEntry = entry
}
}
if earliestLogEntryTime == nil {
return nil, fmt.Errorf("no valid tlog entries found %s", strings.Join(entryVerificationErrs, ", "))
}
return &earliestLogEntry, nil
}
type fakeOCISignatures struct {
oci.Signatures
signatures []oci.Signature
}
func (fos *fakeOCISignatures) Get() ([]oci.Signature, error) {
return fos.signatures, nil
}
// VerifyImageSignatures does all the main cosign checks in a loop, returning the verified signatures.
// If there were no valid signatures, we return an error.
// Note that if co.ExperimentlOCI11 is set, we will attempt to verify
// signatures using the experimental OCI 1.1 behavior.
func VerifyImageSignatures(ctx context.Context, signedImgRef name.Reference, co *CheckOpts) (checkedSignatures []oci.Signature, bundleVerified bool, err error) {
// Try first using OCI 1.1 behavior if experimental flag is set.
if co.ExperimentalOCI11 {
verified, bundleVerified, err := verifyImageSignaturesExperimentalOCI(ctx, signedImgRef, co)
if err == nil {
return verified, bundleVerified, nil
}
}
// Enforce this up front.
if co.RootCerts == nil && co.SigVerifier == nil {
return nil, false, errors.New("one of verifier or root certs is required")
}
// This is a carefully optimized sequence for fetching the signatures of the
// entity that minimizes registry requests when supplied with a digest input
digest, err := ociremote.ResolveDigest(signedImgRef, co.RegistryClientOpts...)
if err != nil {
if terr := (&transport.Error{}); errors.As(err, &terr) && terr.StatusCode == http.StatusNotFound {
return nil, false, &ErrImageTagNotFound{
fmt.Errorf("image tag not found: %w", err),
}
}
return nil, false, err
}
h, err := v1.NewHash(digest.Identifier())
if err != nil {
return nil, false, err
}
var sigs oci.Signatures
sigRef := co.SignatureRef
if sigRef == "" {
st, err := ociremote.SignatureTag(digest, co.RegistryClientOpts...)
if err != nil {
return nil, false, err
}
sigs, err = ociremote.Signatures(st, co.RegistryClientOpts...)
if err != nil {
return nil, false, err
}
} else {
sigs, err = loadSignatureFromFile(ctx, sigRef, signedImgRef, co)
if err != nil {
return nil, false, err
}
}
return verifySignatures(ctx, sigs, h, co)
}
// VerifyLocalImageSignatures verifies signatures from a saved, local image, without any network calls, returning the verified signatures.
// If there were no valid signatures, we return an error.
func VerifyLocalImageSignatures(ctx context.Context, path string, co *CheckOpts) (checkedSignatures []oci.Signature, bundleVerified bool, err error) {
// Enforce this up front.
if co.RootCerts == nil && co.SigVerifier == nil {
return nil, false, errors.New("one of verifier or root certs is required")
}
se, err := layout.SignedImageIndex(path)
if err != nil {
return nil, false, err
}
var h v1.Hash
// Verify either an image index or image.
ii, err := se.SignedImageIndex(v1.Hash{})
if err != nil {
return nil, false, err
}
i, err := se.SignedImage(v1.Hash{})
if err != nil {
return nil, false, err
}
switch {
case ii != nil:
h, err = ii.Digest()
if err != nil {
return nil, false, err
}
case i != nil:
h, err = i.Digest()
if err != nil {
return nil, false, err
}
default:
return nil, false, errors.New("must verify either an image index or image")
}
sigs, err := se.Signatures()
if err != nil {
return nil, false, err
}
if sigs == nil {
return nil, false, fmt.Errorf("no signatures associated with the image saved in %s", path)
}
return verifySignatures(ctx, sigs, h, co)
}
func verifySignatures(ctx context.Context, sigs oci.Signatures, h v1.Hash, co *CheckOpts) (checkedSignatures []oci.Signature, bundleVerified bool, err error) {
sl, err := sigs.Get()
if err != nil {
return nil, false, err
}
if len(sl) == 0 {
return nil, false, &ErrNoMatchingSignatures{
errors.New("no matching signatures"),
}
}
signatures := make([]oci.Signature, len(sl))
bundlesVerified := make([]bool, len(sl))
workers := co.MaxWorkers
if co.MaxWorkers == 0 {
workers = cosign.DefaultMaxWorkers
}
t := throttler.New(workers, len(sl))
for i, sig := range sl {
go func(sig oci.Signature, index int) {
sig, err := static.Copy(sig)
if err != nil {
t.Done(err)
return
}
verified, err := VerifyImageSignature(ctx, sig, h, co)
bundlesVerified[index] = verified
if err != nil {
t.Done(err)
return
}
signatures[index] = sig
t.Done(nil)
}(sig, i)
// wait till workers are available
t.Throttle()
}
for _, s := range signatures {
if s != nil {
checkedSignatures = append(checkedSignatures, s)
}
}
for _, verified := range bundlesVerified {
bundleVerified = bundleVerified || verified
}
if len(checkedSignatures) == 0 {
var combinedErrors []string
for _, err := range t.Errs() {
combinedErrors = append(combinedErrors, err.Error())
}
// TODO: ErrNoMatchingSignatures.Unwrap should return []error,
// or we should replace "...%s" strings.Join with "...%w", errors.Join.
return nil, false, &ErrNoMatchingSignatures{
fmt.Errorf("no matching signatures: %s", strings.Join(combinedErrors, "\n ")),
}
}
return checkedSignatures, bundleVerified, nil
}
// verifyInternal holds the main verification flow for signatures and attestations.
// 1. Verifies the signature using the provided verifier.
// 2. Checks for transparency log entry presence:
// a. Verifies the Rekor entry in the bundle, if provided. This works offline OR
// b. If we don't have a Rekor entry retrieved via cert, do an online lookup (assuming
// we are in experimental mode).
// 3. If a certificate is provided, check it's expiration using the transparency log timestamp.
func verifyInternal(ctx context.Context, sig oci.Signature, h v1.Hash,
verifyFn signatureVerificationFn, co *CheckOpts) (
bundleVerified bool, err error) {
var acceptableRFC3161Time, acceptableRekorBundleTime *time.Time // Timestamps for the signature we accept, or nil if not applicable.
acceptableRFC3161Timestamp, err := VerifyRFC3161Timestamp(sig, co)
if err != nil {
return false, fmt.Errorf("unable to verify RFC3161 timestamp bundle: %w", err)
}
if acceptableRFC3161Timestamp != nil {
acceptableRFC3161Time = &acceptableRFC3161Timestamp.Time
}
if !co.IgnoreTlog {
bundleVerified, err = VerifyBundle(sig, co)
if err != nil {
return false, fmt.Errorf("error verifying bundle: %w", err)
}
if bundleVerified {
// Update with the verified bundle's integrated time.
t, err := getBundleIntegratedTime(sig)
if err != nil {
return false, fmt.Errorf("error getting bundle integrated time: %w", err)
}
acceptableRekorBundleTime = &t
} else {
// If the --offline flag was specified, fail here. bundleVerified returns false with
// no error when there was no bundle provided.
if co.Offline {
return false, fmt.Errorf("offline verification failed")
}
// no Rekor client provided for an online lookup
if co.RekorClient == nil {
return false, fmt.Errorf("rekor client not provided for online verification")
}
pemBytes, err := keyBytes(sig, co)
if err != nil {
return false, err
}
e, err := tlogValidateEntry(ctx, co.RekorClient, co.RekorPubKeys, sig, pemBytes)
if err != nil {
return false, err
}
t := time.Unix(*e.IntegratedTime, 0)
acceptableRekorBundleTime = &t
}
}
verifier := co.SigVerifier
if verifier == nil {
// If we don't have a public key to check against, we can try a root cert.
cert, err := sig.Cert()
if err != nil {
return false, err
}
if cert == nil {
return false, &ErrNoCertificateFoundOnSignature{
fmt.Errorf("no certificate found on signature"),
}
}
// Create a certificate pool for intermediate CA certificates, excluding the root
chain, err := sig.Chain()
if err != nil {
return false, err
}
// If there is no chain annotation present, we preserve the pools set in the CheckOpts.
if len(chain) > 0 {
if len(chain) == 1 {
co.IntermediateCerts = nil
} else if co.IntermediateCerts == nil {
// If the intermediate certs have not been loaded in by TUF
pool := x509.NewCertPool()
for _, cert := range chain[:len(chain)-1] {
pool.AddCert(cert)
}
co.IntermediateCerts = pool
}
}
verifier, err = ValidateAndUnpackCert(cert, co)
if err != nil {
return false, err
}
}
// 1. Perform cryptographic verification of the signature using the certificate's public key.
if err := verifyFn(ctx, verifier, sig); err != nil {
return false, err
}
// We can't check annotations without claims, both require unmarshalling the payload.
if co.ClaimVerifier != nil {
if err := co.ClaimVerifier(sig, h, co.Annotations); err != nil {
return false, err
}
}
// 2. if a certificate was used, verify the certificate expiration against a time
cert, err := sig.Cert()
if err != nil {
return false, err
}
if cert != nil {
// use the provided Rekor bundle or RFC3161 timestamp to check certificate expiration
expirationChecked := false
if acceptableRFC3161Time != nil {
// Verify the cert against the timestamp time.
if err := CheckExpiry(cert, *acceptableRFC3161Time); err != nil {
return false, fmt.Errorf("checking expiry on certificate with timestamp: %w", err)
}
expirationChecked = true
}
if acceptableRekorBundleTime != nil {
if err := CheckExpiry(cert, *acceptableRekorBundleTime); err != nil {
return false, fmt.Errorf("checking expiry on certificate with bundle: %w", err)
}
expirationChecked = true
}
// if no timestamp has been provided, use the current time
if !expirationChecked {
if err := CheckExpiry(cert, time.Now()); err != nil {
// If certificate is expired and not signed timestamp was provided then error the following message. Otherwise throw an expiration error.
if co.IgnoreTlog && acceptableRFC3161Time == nil {
return false, &VerificationFailure{
fmt.Errorf("expected a signed timestamp to verify an expired certificate"),
}
}
return false, fmt.Errorf("checking expiry on certificate with bundle: %w", err)
}
}
}
return bundleVerified, nil
}
func keyBytes(sig oci.Signature, co *CheckOpts) ([]byte, error) {
cert, err := sig.Cert()
if err != nil {
return nil, err
}
// We have a public key.
if co.SigVerifier != nil {
pub, err := co.SigVerifier.PublicKey(co.PKOpts...)
if err != nil {
return nil, err
}
return cryptoutils.MarshalPublicKeyToPEM(pub)
}
return cryptoutils.MarshalCertificateToPEM(cert)
}
// VerifyBlobSignature verifies a blob signature.
func VerifyBlobSignature(ctx context.Context, sig oci.Signature, co *CheckOpts) (bundleVerified bool, err error) {
// The hash of the artifact is unused.
return verifyInternal(ctx, sig, v1.Hash{}, verifyOCISignature, co)
}
// VerifyImageSignature verifies a signature
func VerifyImageSignature(ctx context.Context, sig oci.Signature, h v1.Hash, co *CheckOpts) (bundleVerified bool, err error) {
return verifyInternal(ctx, sig, h, verifyOCISignature, co)
}
func loadSignatureFromFile(ctx context.Context, sigRef string, signedImgRef name.Reference, co *CheckOpts) (oci.Signatures, error) {
var b64sig string
targetSig, err := blob.LoadFileOrURL(sigRef)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
targetSig = []byte(sigRef)
}
_, err = base64.StdEncoding.DecodeString(string(targetSig))
if err == nil {
b64sig = string(targetSig)
} else {
b64sig = base64.StdEncoding.EncodeToString(targetSig)
}
var payload []byte
if co.PayloadRef != "" {
payload, err = blob.LoadFileOrURL(co.PayloadRef)
if err != nil {
return nil, err
}
} else {
digest, err := ociremote.ResolveDigest(signedImgRef, co.RegistryClientOpts...)
if err != nil {
return nil, err
}
payload, err = ObsoletePayload(ctx, digest)
if err != nil {
return nil, err
}
}
sig, err := static.NewSignature(payload, b64sig)
if err != nil {
return nil, err
}
return &fakeOCISignatures{
signatures: []oci.Signature{sig},
}, nil
}
// VerifyImageAttestations does all the main cosign checks in a loop, returning the verified attestations.
// If there were no valid attestations, we return an error.
func VerifyImageAttestations(ctx context.Context, signedImgRef name.Reference, co *CheckOpts) (checkedAttestations []oci.Signature, bundleVerified bool, err error) {
// Enforce this up front.
if co.RootCerts == nil && co.SigVerifier == nil {
return nil, false, errors.New("one of verifier or root certs is required")
}
// This is a carefully optimized sequence for fetching the attestations of
// the entity that minimizes registry requests when supplied with a digest
// input.
digest, err := ociremote.ResolveDigest(signedImgRef, co.RegistryClientOpts...)
if err != nil {
return nil, false, err
}
h, err := v1.NewHash(digest.Identifier())
if err != nil {
return nil, false, err
}
st, err := ociremote.AttestationTag(digest, co.RegistryClientOpts...)
if err != nil {
return nil, false, err
}
atts, err := ociremote.Signatures(st, co.RegistryClientOpts...)
if err != nil {
return nil, false, err
}
return VerifyImageAttestation(ctx, atts, h, co)
}
// VerifyLocalImageAttestations verifies attestations from a saved, local image, without any network calls,
// returning the verified attestations.
// If there were no valid signatures, we return an error.
func VerifyLocalImageAttestations(ctx context.Context, path string, co *CheckOpts) (checkedAttestations []oci.Signature, bundleVerified bool, err error) {
// Enforce this up front.
if co.RootCerts == nil && co.SigVerifier == nil {
return nil, false, errors.New("one of verifier or root certs is required")
}
se, err := layout.SignedImageIndex(path)
if err != nil {
return nil, false, err
}
var h v1.Hash
// Verify either an image index or image.
ii, err := se.SignedImageIndex(v1.Hash{})
if err != nil {
return nil, false, err
}
i, err := se.SignedImage(v1.Hash{})
if err != nil {
return nil, false, err
}
switch {
case ii != nil:
h, err = ii.Digest()
if err != nil {
return nil, false, err
}
case i != nil:
h, err = i.Digest()
if err != nil {
return nil, false, err
}
default:
return nil, false, errors.New("must verify either an image index or image")
}
atts, err := se.Attestations()
if err != nil {
return nil, false, err
}
return VerifyImageAttestation(ctx, atts, h, co)
}
func VerifyBlobAttestation(ctx context.Context, att oci.Signature, h v1.Hash, co *CheckOpts) (
bool, error) {
return verifyInternal(ctx, att, h, verifyOCIAttestation, co)
}
func VerifyImageAttestation(ctx context.Context, atts oci.Signatures, h v1.Hash, co *CheckOpts) (checkedAttestations []oci.Signature, bundleVerified bool, err error) {
sl, err := atts.Get()
if err != nil {
return nil, false, err
}
attestations := make([]oci.Signature, len(sl))
bundlesVerified := make([]bool, len(sl))
workers := co.MaxWorkers
if co.MaxWorkers == 0 {
workers = cosign.DefaultMaxWorkers
}
t := throttler.New(workers, len(sl))
for i, att := range sl {
go func(att oci.Signature, index int) {
att, err := static.Copy(att)
if err != nil {
t.Done(err)
return
}
if err := func(att oci.Signature) error {
verified, err := verifyInternal(ctx, att, h, verifyOCIAttestation, co)
bundlesVerified[index] = verified
return err
}(att); err != nil {
t.Done(err)
return
}
attestations[index] = att
t.Done(nil)
}(att, i)
// wait till workers are available
t.Throttle()
}
for _, a := range attestations {
if a != nil {
checkedAttestations = append(checkedAttestations, a)
}
}
for _, verified := range bundlesVerified {
bundleVerified = bundleVerified || verified
}
if len(checkedAttestations) == 0 {
var combinedErrors []string
for _, err := range t.Errs() {
combinedErrors = append(combinedErrors, err.Error())
}