forked from sigstore/cosign
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify_test.go
972 lines (830 loc) · 34.6 KB
/
verify_test.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
// 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/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"io"
"net"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer"
"github.com/go-openapi/strfmt"
"github.com/google/certificate-transparency-go/testdata"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/in-toto/in-toto-golang/in_toto"
"github.com/secure-systems-lab/go-securesystemslib/dsse"
"github.com/sigstore/cosign/internal/pkg/cosign/rekor/mock"
"github.com/sigstore/cosign/pkg/cosign/bundle"
"github.com/sigstore/cosign/pkg/oci/static"
"github.com/sigstore/cosign/pkg/types"
"github.com/sigstore/cosign/test"
"github.com/sigstore/rekor/pkg/generated/client"
"github.com/sigstore/rekor/pkg/generated/models"
rtypes "github.com/sigstore/rekor/pkg/types"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/options"
"github.com/stretchr/testify/require"
"github.com/transparency-dev/merkle/rfc6962"
)
type mockVerifier struct {
shouldErr bool
}
func (m *mockVerifier) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, error) {
return nil, nil
}
func (m *mockVerifier) VerifySignature(signature, message io.Reader, opts ...signature.VerifyOption) error {
if m.shouldErr {
return errors.New("failure")
}
return nil
}
var _ signature.Verifier = (*mockVerifier)(nil)
type mockAttestation struct {
payload interface{}
}
var _ payloader = (*mockAttestation)(nil)
func (m *mockAttestation) Annotations() (map[string]string, error) {
return nil, nil
}
func (m *mockAttestation) Payload() ([]byte, error) {
return json.Marshal(m.payload)
}
func appendSlices(slices [][]byte) []byte {
var tmp []byte
for _, s := range slices {
tmp = append(tmp, s...)
}
return tmp
}
func Test_verifyOCIAttestation(t *testing.T) {
stmt, err := json.Marshal(in_toto.ProvenanceStatement{})
if err != nil {
t.Fatal(err)
}
valid := map[string]interface{}{
"payloadType": types.IntotoPayloadType,
"payload": stmt,
"signatures": []dsse.Signature{{Sig: base64.StdEncoding.EncodeToString([]byte("foobar"))}},
}
// Should Verify
if err := verifyOCIAttestation(context.TODO(), &mockVerifier{}, &mockAttestation{payload: valid}); err != nil {
t.Errorf("verifyOCIAttestation() error = %v", err)
}
invalid := map[string]interface{}{
"payloadType": "not valid type",
"payload": stmt,
"signatures": []dsse.Signature{{Sig: base64.StdEncoding.EncodeToString([]byte("foobar"))}},
}
// Should Not Verify
if err := verifyOCIAttestation(context.TODO(), &mockVerifier{}, &mockAttestation{payload: invalid}); err == nil {
t.Error("verifyOCIAttestation() expected invalid payload type error, got nil")
}
if err := verifyOCIAttestation(context.TODO(), &mockVerifier{shouldErr: true}, &mockAttestation{payload: valid}); err == nil {
t.Error("verifyOCIAttestation() expected invalid payload type error, got nil")
}
}
func TestVerifyImageSignature(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
subCert, subKey, _ := test.GenerateSubordinateCa(rootCert, rootKey)
leafCert, privKey, _ := test.GenerateLeafCert("subject", "oidc-issuer", subCert, subKey)
pemRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootCert.Raw})
pemSub := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: subCert.Raw})
pemLeaf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafCert.Raw})
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
payload := []byte{1, 2, 3, 4}
h := sha256.Sum256(payload)
signature, _ := privKey.Sign(rand.Reader, h[:], crypto.SHA256)
ociSig, _ := static.NewSignature(payload,
base64.StdEncoding.EncodeToString(signature),
static.WithCertChain(pemLeaf, appendSlices([][]byte{pemSub, pemRoot})))
verified, err := VerifyImageSignature(context.TODO(), ociSig, v1.Hash{}, &CheckOpts{RootCerts: rootPool})
if err != nil {
t.Fatalf("unexpected error while verifying signature, expected no error, got %v", err)
}
// TODO: Create fake bundle and test verification
if verified == true {
t.Fatalf("expected verified=false, got verified=true")
}
}
func TestVerifyImageSignatureMultipleSubs(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
subCert1, subKey1, _ := test.GenerateSubordinateCa(rootCert, rootKey)
subCert2, subKey2, _ := test.GenerateSubordinateCa(subCert1, subKey1)
subCert3, subKey3, _ := test.GenerateSubordinateCa(subCert2, subKey2)
leafCert, privKey, _ := test.GenerateLeafCert("subject", "oidc-issuer", subCert3, subKey3)
pemRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootCert.Raw})
pemSub1 := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: subCert1.Raw})
pemSub2 := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: subCert2.Raw})
pemSub3 := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: subCert3.Raw})
pemLeaf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafCert.Raw})
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
payload := []byte{1, 2, 3, 4}
h := sha256.Sum256(payload)
signature, _ := privKey.Sign(rand.Reader, h[:], crypto.SHA256)
ociSig, _ := static.NewSignature(payload,
base64.StdEncoding.EncodeToString(signature), static.WithCertChain(pemLeaf, appendSlices([][]byte{pemSub3, pemSub2, pemSub1, pemRoot})))
verified, err := VerifyImageSignature(context.TODO(), ociSig, v1.Hash{}, &CheckOpts{RootCerts: rootPool})
if err != nil {
t.Fatalf("unexpected error while verifying signature, expected no error, got %v", err)
}
// TODO: Create fake bundle and test verification
if verified == true {
t.Fatalf("expected verified=false, got verified=true")
}
}
func signEntry(ctx context.Context, t *testing.T, signer signature.Signer, entry bundle.RekorPayload) []byte {
payload, err := json.Marshal(entry)
if err != nil {
t.Fatalf("marshalling error: %v", err)
}
canonicalized, err := jsoncanonicalizer.Transform(payload)
if err != nil {
t.Fatalf("canonicalizing error: %v", err)
}
signature, err := signer.SignMessage(bytes.NewReader(canonicalized), options.WithContext(ctx))
if err != nil {
t.Fatalf("signing error: %v", err)
}
return signature
}
func CreateTestBundle(ctx context.Context, t *testing.T, rekor signature.Signer, leaf []byte) *bundle.RekorBundle {
// generate log ID according to rekor public key
pk, _ := rekor.PublicKey(nil)
keyID, _ := getLogID(pk)
pyld := bundle.RekorPayload{
Body: base64.StdEncoding.EncodeToString(leaf),
IntegratedTime: time.Now().Unix(),
LogIndex: 693591,
LogID: keyID,
}
// Sign with root.
signature := signEntry(ctx, t, rekor, pyld)
b := &bundle.RekorBundle{
SignedEntryTimestamp: strfmt.Base64(signature),
Payload: pyld,
}
return b
}
func TestVerifyImageSignatureWithNoChain(t *testing.T) {
ctx := context.Background()
rootCert, rootKey, _ := test.GenerateRootCa()
sv, _, err := signature.NewECDSASignerVerifier(elliptic.P256(), rand.Reader, crypto.SHA256)
if err != nil {
t.Fatalf("creating signer: %v", err)
}
leafCert, privKey, _ := test.GenerateLeafCert("subject", "oidc-issuer", rootCert, rootKey)
pemLeaf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafCert.Raw})
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
payload := []byte{1, 2, 3, 4}
h := sha256.Sum256(payload)
signature, _ := privKey.Sign(rand.Reader, h[:], crypto.SHA256)
// Create a fake bundle
pe, _ := proposedEntry(base64.StdEncoding.EncodeToString(signature), payload, pemLeaf)
entry, _ := rtypes.UnmarshalEntry(pe[0])
leaf, _ := entry.Canonicalize(ctx)
rekorBundle := CreateTestBundle(ctx, t, sv, leaf)
opts := []static.Option{static.WithCertChain(pemLeaf, []byte{}), static.WithBundle(rekorBundle)}
ociSig, _ := static.NewSignature(payload, base64.StdEncoding.EncodeToString(signature), opts...)
// TODO(asraa): Re-enable passing test when Rekor public keys can be set in CheckOpts,
// instead of relying on the singleton TUF instance.
verified, err := VerifyImageSignature(context.TODO(), ociSig, v1.Hash{}, &CheckOpts{RootCerts: rootPool})
if err == nil {
t.Fatalf("expected error due to custom Rekor public key")
}
if verified == true {
t.Fatalf("expected verified=false, got verified=true")
}
}
func TestVerifyImageSignatureWithOnlyRoot(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, privKey, _ := test.GenerateLeafCert("subject", "oidc-issuer", rootCert, rootKey)
pemRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootCert.Raw})
pemLeaf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafCert.Raw})
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
payload := []byte{1, 2, 3, 4}
h := sha256.Sum256(payload)
signature, _ := privKey.Sign(rand.Reader, h[:], crypto.SHA256)
ociSig, _ := static.NewSignature(payload, base64.StdEncoding.EncodeToString(signature), static.WithCertChain(pemLeaf, pemRoot))
verified, err := VerifyImageSignature(context.TODO(), ociSig, v1.Hash{}, &CheckOpts{RootCerts: rootPool})
if err != nil {
t.Fatalf("unexpected error while verifying signature, expected no error, got %v", err)
}
// TODO: Create fake bundle and test verification
if verified == true {
t.Fatalf("expected verified=false, got verified=true")
}
}
func TestVerifyImageSignatureWithMissingSub(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
subCert, subKey, _ := test.GenerateSubordinateCa(rootCert, rootKey)
leafCert, privKey, _ := test.GenerateLeafCert("subject", "oidc-issuer", subCert, subKey)
pemRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootCert.Raw})
pemLeaf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafCert.Raw})
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
payload := []byte{1, 2, 3, 4}
h := sha256.Sum256(payload)
signature, _ := privKey.Sign(rand.Reader, h[:], crypto.SHA256)
ociSig, _ := static.NewSignature(payload, base64.StdEncoding.EncodeToString(signature), static.WithCertChain(pemLeaf, pemRoot))
verified, err := VerifyImageSignature(context.TODO(), ociSig, v1.Hash{}, &CheckOpts{RootCerts: rootPool})
if err == nil {
t.Fatal("expected error while verifying signature")
}
if !strings.Contains(err.Error(), "certificate signed by unknown authority") {
t.Fatal("expected error while verifying signature")
}
// TODO: Create fake bundle and test verification
if verified == true {
t.Fatalf("expected verified=false, got verified=true")
}
}
func TestVerifyImageSignatureWithExistingSub(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
subCert, subKey, _ := test.GenerateSubordinateCa(rootCert, rootKey)
leafCert, privKey, _ := test.GenerateLeafCert("subject", "oidc-issuer", subCert, subKey)
pemRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootCert.Raw})
pemSub := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: subCert.Raw})
pemLeaf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafCert.Raw})
otherSubCert, _, _ := test.GenerateSubordinateCa(rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
subPool := x509.NewCertPool()
// Load in different sub cert so the chain doesn't verify
rootPool.AddCert(otherSubCert)
payload := []byte{1, 2, 3, 4}
h := sha256.Sum256(payload)
signature, _ := privKey.Sign(rand.Reader, h[:], crypto.SHA256)
ociSig, _ := static.NewSignature(payload,
base64.StdEncoding.EncodeToString(signature),
static.WithCertChain(pemLeaf, appendSlices([][]byte{pemSub, pemRoot})))
verified, err := VerifyImageSignature(context.TODO(), ociSig, v1.Hash{}, &CheckOpts{RootCerts: rootPool, IntermediateCerts: subPool})
if err == nil {
t.Fatal("expected error while verifying signature")
}
if !strings.Contains(err.Error(), "certificate signed by unknown authority") {
t.Fatal("expected error while verifying signature")
}
// TODO: Create fake bundle and test verification
if verified == true {
t.Fatalf("expected verified=false, got verified=true")
}
}
var (
lea = models.LogEntryAnon{
Attestation: &models.LogEntryAnonAttestation{},
Body: base64.StdEncoding.EncodeToString([]byte("asdf")),
IntegratedTime: new(int64),
LogID: new(string),
LogIndex: new(int64),
Verification: &models.LogEntryAnonVerification{
InclusionProof: &models.InclusionProof{
RootHash: new(string),
TreeSize: new(int64),
LogIndex: new(int64),
},
},
}
data = models.LogEntry{
uuid(lea): lea,
}
)
// uuid generates the UUID for the given LogEntry.
// This is effectively a reimplementation of
// pkg/cosign/tlog.go -> verifyUUID / ComputeLeafHash, but separated
// to avoid a circular dependency.
// TODO?: Perhaps we should refactor the tlog libraries into a separate
// package?
func uuid(e models.LogEntryAnon) string {
entryBytes, err := base64.StdEncoding.DecodeString(e.Body.(string))
if err != nil {
panic(err)
}
return hex.EncodeToString(rfc6962.DefaultHasher.HashLeaf(entryBytes))
}
// This test ensures that image signature validation fails properly if we are
// using a SigVerifier with Rekor.
// See https://github.com/sigstore/cosign/issues/1816 for more details.
func TestVerifyImageSignatureWithSigVerifierAndRekor(t *testing.T) {
sv, privKey, err := signature.NewDefaultECDSASignerVerifier()
if err != nil {
t.Fatalf("error generating verifier: %v", err)
}
payload := []byte{1, 2, 3, 4}
h := sha256.Sum256(payload)
sig, _ := privKey.Sign(rand.Reader, h[:], crypto.SHA256)
ociSig, _ := static.NewSignature(payload, base64.StdEncoding.EncodeToString(sig))
// Add a fake rekor client - this makes it look like there's a matching
// tlog entry for the signature during validation (even though it does not
// match the underlying data / key)
mClient := new(client.Rekor)
mClient.Entries = &mock.EntriesClient{
Entries: &data,
}
if _, err := VerifyImageSignature(context.TODO(), ociSig, v1.Hash{}, &CheckOpts{
SigVerifier: sv,
RekorClient: mClient,
}); err == nil || !strings.Contains(err.Error(), "verifying inclusion proof") {
// TODO(wlynch): This is a weak test, since this is really failing because
// there is no inclusion proof for the Rekor entry rather than failing to
// validate the Rekor public key itself. At the very least this ensures
// that we're hitting tlog validation during signature checking,
// but we should look into improving this once there is an in-memory
// Rekor client that is capable of performing inclusion proof validation
// in unit tests.
t.Fatal("expected error while verifying signature")
}
}
func TestValidateAndUnpackCertSuccess(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
if err != nil {
t.Errorf("ValidateAndUnpackCert expected no error, got err = %v", err)
}
err = CheckCertificatePolicy(leafCert, co)
if err != nil {
t.Errorf("CheckCertificatePolicy expected no error, got err = %v", err)
}
}
func TestValidateAndUnpackCertSuccessAllowAllValues(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
}
_, err := ValidateAndUnpackCert(leafCert, co)
if err != nil {
t.Errorf("ValidateAndUnpackCert expected no error, got err = %v", err)
}
err = CheckCertificatePolicy(leafCert, co)
if err != nil {
t.Errorf("CheckCertificatePolicy expected no error, got err = %v", err)
}
}
func TestValidateAndUnpackCertWithSCT(t *testing.T) {
chain, err := cryptoutils.UnmarshalCertificatesFromPEM([]byte(testdata.TestEmbeddedCertPEM + testdata.CACertPEM))
if err != nil {
t.Fatalf("error unmarshalling certificate chain: %v", err)
}
rootPool := x509.NewCertPool()
rootPool.AddCert(chain[1])
co := &CheckOpts{
RootCerts: rootPool,
}
// write SCT verification key to disk
tmpPrivFile, err := os.CreateTemp(t.TempDir(), "cosign_verify_sct_*.key")
if err != nil {
t.Fatalf("failed to create temp key file: %v", err)
}
defer tmpPrivFile.Close()
if _, err := tmpPrivFile.Write([]byte(testdata.LogPublicKeyPEM)); err != nil {
t.Fatalf("failed to write key file: %v", err)
}
os.Setenv("SIGSTORE_CT_LOG_PUBLIC_KEY_FILE", tmpPrivFile.Name())
defer os.Unsetenv("SIGSTORE_CT_LOG_PUBLIC_KEY_FILE")
_, err = ValidateAndUnpackCert(chain[0], co)
if err != nil {
t.Errorf("ValidateAndUnpackCert expected no error, got err = %v", err)
}
// validate again, explicitly setting enforce SCT
co.EnforceSCT = true
_, err = ValidateAndUnpackCert(chain[0], co)
if err != nil {
t.Errorf("ValidateAndUnpackCert expected no error, got err = %v", err)
}
}
func TestValidateAndUnpackCertWithoutRequiredSCT(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertOidcIssuer: oidcIssuer,
EnforceSCT: true,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "certificate does not include required embedded SCT")
}
func TestValidateAndUnpackCertInvalidRoot(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
otherRoot, _, _ := test.GenerateRootCa()
rootPool := x509.NewCertPool()
rootPool.AddCert(otherRoot)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "certificate signed by unknown authority")
}
func TestValidateAndUnpackCertInvalidOidcIssuer(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertOidcIssuer: "other",
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "expected oidc issuer not found in certificate")
err = CheckCertificatePolicy(leafCert, co)
require.Contains(t, err.Error(), "expected oidc issuer not found in certificate")
}
func TestValidateAndUnpackCertInvalidEmail(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: "other",
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "expected email not found in certificate")
err = CheckCertificatePolicy(leafCert, co)
require.Contains(t, err.Error(), "expected email not found in certificate")
}
func TestValidateAndUnpackCertInvalidGithubWorkflowTrigger(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
githubWorkFlowTrigger := "myTrigger"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCertWithGitHubOIDs(subject, oidcIssuer, githubWorkFlowTrigger, "", "", "", "", rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertGithubWorkflowTrigger: "otherTrigger",
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Trigger not found in certificate")
err = CheckCertificatePolicy(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Trigger not found in certificate")
}
func TestValidateAndUnpackCertInvalidGithubWorkflowSHA(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
githubWorkFlowSha := "mySHA"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCertWithGitHubOIDs(subject, oidcIssuer, "", githubWorkFlowSha, "", "", "", rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertGithubWorkflowSha: "otherSHA",
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow SHA not found in certificate")
err = CheckCertificatePolicy(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow SHA not found in certificate")
}
func TestValidateAndUnpackCertInvalidGithubWorkflowName(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
githubWorkFlowName := "myName"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCertWithGitHubOIDs(subject, oidcIssuer, "", "", githubWorkFlowName, "", "", rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertGithubWorkflowName: "otherName",
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Name not found in certificate")
err = CheckCertificatePolicy(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Name not found in certificate")
}
func TestValidateAndUnpackCertInvalidGithubWorkflowRepository(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
githubWorkFlowRepository := "myRepository"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCertWithGitHubOIDs(subject, oidcIssuer, "", "", "", githubWorkFlowRepository, "", rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertGithubWorkflowRepository: "otherRepository",
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Repository not found in certificate")
err = CheckCertificatePolicy(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Repository not found in certificate")
}
func TestValidateAndUnpackCertInvalidGithubWorkflowRef(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
githubWorkFlowRef := "myRef"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCertWithGitHubOIDs(subject, oidcIssuer, "", "", "", "", githubWorkFlowRef, rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
CertEmail: subject,
CertGithubWorkflowRef: "otherRef",
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCert(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Ref not found in certificate")
err = CheckCertificatePolicy(leafCert, co)
require.Contains(t, err.Error(), "expected GitHub Workflow Ref not found in certificate")
}
func TestValidateAndUnpackCertWithChainSuccess(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
subCert, subKey, _ := test.GenerateSubordinateCa(rootCert, rootKey)
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, subCert, subKey)
co := &CheckOpts{
CertEmail: subject,
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCertWithChain(leafCert, []*x509.Certificate{subCert, leafCert}, co)
if err != nil {
t.Errorf("ValidateAndUnpackCert expected no error, got err = %v", err)
}
}
func TestValidateAndUnpackCertWithChainSuccessWithRoot(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
co := &CheckOpts{
CertEmail: subject,
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCertWithChain(leafCert, []*x509.Certificate{rootCert}, co)
if err != nil {
t.Errorf("ValidateAndUnpackCert expected no error, got err = %v", err)
}
}
func TestValidateAndUnpackCertWithChainFailsWithoutChain(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
co := &CheckOpts{
CertEmail: subject,
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCertWithChain(leafCert, []*x509.Certificate{}, co)
if err == nil || err.Error() != "no chain provided to validate certificate" {
t.Errorf("expected error without chain, got %v", err)
}
}
func TestValidateAndUnpackCertWithChainFailsWithInvalidChain(t *testing.T) {
subject := "email@email"
oidcIssuer := "https://accounts.google.com"
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert(subject, oidcIssuer, rootCert, rootKey)
rootCertOther, _, _ := test.GenerateRootCa()
co := &CheckOpts{
CertEmail: subject,
CertOidcIssuer: oidcIssuer,
}
_, err := ValidateAndUnpackCertWithChain(leafCert, []*x509.Certificate{rootCertOther}, co)
if err == nil || !strings.Contains(err.Error(), "certificate signed by unknown authority") {
t.Errorf("expected error without valid chain, got %v", err)
}
}
func TestValidateAndUnpackCertWithIdentities(t *testing.T) {
u, err := url.Parse("http://url.example.com")
if err != nil {
t.Fatal("failed to parse url", err)
}
emailSubject := "email@example.com"
dnsSubjects := []string{"dnssubject.example.com"}
ipSubjects := []net.IP{net.ParseIP("1.2.3.4")}
uriSubjects := []*url.URL{u}
oidcIssuer := "https://accounts.google.com"
tests := []struct {
identities []Identity
wantErrSubstring string
dnsNames []string
emailAddresses []string
ipAddresses []net.IP
uris []*url.URL
}{
{identities: nil /* No matches required, checks out */},
{identities: []Identity{ // Strict match on both
{Subject: emailSubject, Issuer: oidcIssuer}},
emailAddresses: []string{emailSubject}},
{identities: []Identity{ // just issuer
{Issuer: oidcIssuer}},
emailAddresses: []string{emailSubject}},
{identities: []Identity{ // just subject
{Subject: emailSubject}},
emailAddresses: []string{emailSubject}},
{identities: []Identity{ // mis-match
{Subject: "wrongsubject", Issuer: oidcIssuer},
{Subject: emailSubject, Issuer: "wrongissuer"}},
emailAddresses: []string{emailSubject},
wantErrSubstring: "none of the expected identities matched"},
{identities: []Identity{ // one good identity, other does not match
{Subject: "wrongsubject", Issuer: "wrongissuer"},
{Subject: emailSubject, Issuer: oidcIssuer}},
emailAddresses: []string{emailSubject}},
{identities: []Identity{ // illegal regex for subject
{SubjectRegExp: "****", Issuer: oidcIssuer}},
emailAddresses: []string{emailSubject},
wantErrSubstring: "malformed subject in identity"},
{identities: []Identity{ // illegal regex for issuer
{Subject: emailSubject, IssuerRegExp: "****"}},
wantErrSubstring: "malformed issuer in identity"},
{identities: []Identity{ // regex matches
{SubjectRegExp: ".*example.com", IssuerRegExp: ".*accounts.google.*"}},
emailAddresses: []string{emailSubject},
wantErrSubstring: ""},
{identities: []Identity{ // regex matches dnsNames
{SubjectRegExp: ".*ubject.example.com", IssuerRegExp: ".*accounts.google.*"}},
dnsNames: dnsSubjects,
wantErrSubstring: ""},
{identities: []Identity{ // regex matches ip
{SubjectRegExp: "1.2.3.*", IssuerRegExp: ".*accounts.google.*"}},
ipAddresses: ipSubjects,
wantErrSubstring: ""},
{identities: []Identity{ // regex matches urls
{SubjectRegExp: ".*url.examp.*", IssuerRegExp: ".*accounts.google.*"}},
uris: uriSubjects,
wantErrSubstring: ""},
}
for _, tc := range tests {
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCertWithSubjectAlternateNames(tc.dnsNames, tc.emailAddresses, tc.ipAddresses, tc.uris, oidcIssuer, rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
co := &CheckOpts{
RootCerts: rootPool,
Identities: tc.identities,
}
_, err := ValidateAndUnpackCert(leafCert, co)
if err == nil && tc.wantErrSubstring != "" {
t.Errorf("Expected error %s got none", tc.wantErrSubstring)
} else if err != nil {
if tc.wantErrSubstring == "" {
t.Errorf("Did not expect an error, got err = %v", err)
} else if !strings.Contains(err.Error(), tc.wantErrSubstring) {
t.Errorf("Did not get the expected error %s, got err = %v", tc.wantErrSubstring, err)
}
}
// Test CheckCertificatePolicy
err = CheckCertificatePolicy(leafCert, co)
if err == nil && tc.wantErrSubstring != "" {
t.Errorf("Expected error %s got none", tc.wantErrSubstring)
} else if err != nil {
if tc.wantErrSubstring == "" {
t.Errorf("Did not expect an error, got err = %v", err)
} else if !strings.Contains(err.Error(), tc.wantErrSubstring) {
t.Errorf("Did not get the expected error %s, got err = %v", tc.wantErrSubstring, err)
}
}
}
}
func TestCompareSigs(t *testing.T) {
// TODO(nsmith5): Add test cases for invalid signature, missing signature etc
tests := []struct {
description string
b64sig string
bundleBody string
shouldErr bool
}{
{
description: "sigs match",
b64sig: "MEQCIDO3XHbLovPWK+bk8ItCig2cwlr/8MXbLvz3UFzxMGIMAiA1lqdM9IqqUvCUqzOjufTq3sKU3qSn7R5tPqPz0ddNwQ==",
bundleBody: `eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIzODE1MmQxZGQzMjZhZjQwNWY4OTlkYmNjMmNlMzUwYjVmMTZkNDVkZjdmMjNjNDg4ZjQ4NTBhZmExY2Q4NmQxIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJRE8zWEhiTG92UFdLK2JrOEl0Q2lnMmN3bHIvOE1YYkx2ejNVRnp4TUdJTUFpQTFscWRNOUlxcVV2Q1Vxek9qdWZUcTNzS1UzcVNuN1I1dFBxUHowZGROd1E9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCUVZVSk1TVU1nUzBWWkxTMHRMUzBLVFVacmQwVjNXVWhMYjFwSmVtb3dRMEZSV1VsTGIxcEplbW93UkVGUlkwUlJaMEZGVUN0RVIyb3ZXWFV4VG5vd01XVjVSV2hVZDNRMlQya3hXV3BGWXdwSloxRldjRlZTTjB0bUwwSm1hVk16Y1ZReFVHd3dkbGh3ZUZwNVMyWkpSMHMyZWxoQ04ybE5aV3RFVTA1M1dHWldPSEpKYUdaMmRrOW5QVDBLTFMwdExTMUZUa1FnVUZWQ1RFbERJRXRGV1MwdExTMHRDZz09In19fX0=`,
},
{
description: "sigs don't match",
b64sig: "bm9wZQo=",
bundleBody: `eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIzODE1MmQxZGQzMjZhZjQwNWY4OTlkYmNjMmNlMzUwYjVmMTZkNDVkZjdmMjNjNDg4ZjQ4NTBhZmExY2Q4NmQxIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJRE8zWEhiTG92UFdLK2JrOEl0Q2lnMmN3bHIvOE1YYkx2ejNVRnp4TUdJTUFpQTFscWRNOUlxcVV2Q1Vxek9qdWZUcTNzS1UzcVNuN1I1dFBxUHowZGROd1E9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCUVZVSk1TVU1nUzBWWkxTMHRMUzBLVFVacmQwVjNXVWhMYjFwSmVtb3dRMEZSV1VsTGIxcEplbW93UkVGUlkwUlJaMEZGVUN0RVIyb3ZXWFV4VG5vd01XVjVSV2hVZDNRMlQya3hXV3BGWXdwSloxRldjRlZTTjB0bUwwSm1hVk16Y1ZReFVHd3dkbGh3ZUZwNVMyWkpSMHMyZWxoQ04ybE5aV3RFVTA1M1dHWldPSEpKYUdaMmRrOW5QVDBLTFMwdExTMUZUa1FnVUZWQ1RFbERJRXRGV1MwdExTMHRDZz09In19fX0=`,
shouldErr: true,
},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
sig, err := static.NewSignature([]byte("payload"), test.b64sig)
if err != nil {
t.Fatalf("failed to create static signature: %v", err)
}
err = compareSigs(test.bundleBody, sig)
if err == nil && test.shouldErr {
t.Fatal("test should have errored")
}
if err != nil && !test.shouldErr {
t.Fatal(err)
}
})
}
}
func TestTrustedCertSuccess(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
subCert, subKey, _ := test.GenerateSubordinateCa(rootCert, rootKey)
leafCert, _, _ := test.GenerateLeafCert("subject", "oidc-issuer", subCert, subKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
subPool := x509.NewCertPool()
subPool.AddCert(subCert)
chains, err := TrustedCert(leafCert, rootPool, subPool)
if err != nil {
t.Fatalf("expected no error verifying certificate, got %v", err)
}
if len(chains) != 1 {
t.Fatalf("unexpected number of chains found, expected 1, got %v", len(chains))
}
if len(chains[0]) != 3 {
t.Fatalf("unexpected number of certs in chain, expected 3, got %v", len(chains[0]))
}
}
func TestTrustedCertSuccessNoIntermediates(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert("subject", "oidc-issuer", rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
_, err := TrustedCert(leafCert, rootPool, nil)
if err != nil {
t.Fatalf("expected no error verifying certificate, got %v", err)
}
}
// Tests that verification succeeds if both a root and subordinate pool are
// present, but a chain is built with only the leaf and root certificates.
func TestTrustedCertSuccessChainFromRoot(t *testing.T) {
rootCert, rootKey, _ := test.GenerateRootCa()
leafCert, _, _ := test.GenerateLeafCert("subject", "oidc-issuer", rootCert, rootKey)
subCert, _, _ := test.GenerateSubordinateCa(rootCert, rootKey)
rootPool := x509.NewCertPool()
rootPool.AddCert(rootCert)
subPool := x509.NewCertPool()
subPool.AddCert(subCert)
_, err := TrustedCert(leafCert, rootPool, subPool)
if err != nil {
t.Fatalf("expected no error verifying certificate, got %v", err)
}
}