forked from google/go-tpm-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverify_test.go
944 lines (848 loc) · 27 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
package server
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
_ "embed"
"encoding/asn1"
"encoding/pem"
"fmt"
"io"
"os"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-tpm-tools/cel"
"github.com/google/go-tpm-tools/client"
"github.com/google/go-tpm-tools/internal"
"github.com/google/go-tpm-tools/internal/test"
attestpb "github.com/google/go-tpm-tools/proto/attest"
"github.com/google/go-tpm/legacy/tpm2"
"github.com/google/go-tpm/tpmutil"
"github.com/google/logger"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
)
var measuredHashes = []crypto.Hash{crypto.SHA1, crypto.SHA256}
func getDigestHash(input string) []byte {
inputDigestHash := sha256.New()
inputDigestHash.Write([]byte(input))
return inputDigestHash.Sum(nil)
}
func extendPCRsRandomly(rwc io.ReadWriteCloser, selpcr tpm2.PCRSelection) error {
var pcrExtendValue []byte
if selpcr.Hash == tpm2.AlgSHA256 {
pcrExtendValue = make([]byte, 32)
} else if selpcr.Hash == tpm2.AlgSHA1 {
pcrExtendValue = make([]byte, 20)
}
for _, v := range selpcr.PCRs {
_, err := rand.Read(pcrExtendValue)
if err != nil {
return fmt.Errorf("random bytes read fail %v", err)
}
err = tpm2.PCRExtend(rwc, tpmutil.Handle(v), selpcr.Hash, pcrExtendValue, "")
if err != nil {
return fmt.Errorf("PCR extend fail %v", err)
}
}
return nil
}
func TestMain(m *testing.M) {
logger.Init("TestLog", false, false, os.Stderr)
os.Exit(m.Run())
}
func TestVerifyHappyCases(t *testing.T) {
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
onePCR := []int{test.DebugPCR}
twoPCR := append(onePCR, test.ApplicationPCR)
dupePCR := append(twoPCR, twoPCR...)
subtests := []struct {
name string
getKey func(io.ReadWriter) (*client.Key, error)
pcrHashAlgo tpm2.Algorithm
quotePCRList []int
extraData []byte
}{
{"AK-RSA_SHA1_2PCRs_nonce", client.AttestationKeyRSA, tpm2.AlgSHA1, twoPCR, getDigestHash("test")},
{"AK-RSA_SHA1_1PCR_nonce", client.AttestationKeyRSA, tpm2.AlgSHA1, onePCR, getDigestHash("t")},
{"AK-RSA_SHA1_1PCR_no-nonce", client.AttestationKeyRSA, tpm2.AlgSHA1, onePCR, nil},
{"AK-RSA_SHA256_2PCRs_nonce", client.AttestationKeyRSA, tpm2.AlgSHA256, twoPCR, getDigestHash("test")},
{"AK-RSA_SHA256_2PCR_empty-nonce", client.AttestationKeyRSA, tpm2.AlgSHA256, twoPCR, []byte{}},
{"AK-RSA_SHA256_dupePCrSel_nonce", client.AttestationKeyRSA, tpm2.AlgSHA256, dupePCR, getDigestHash("")},
{"AK-ECC_SHA1_2PCRs_nonce", client.AttestationKeyECC, tpm2.AlgSHA1, twoPCR, getDigestHash("test")},
{"AK-ECC_SHA1_1PCR_nonce", client.AttestationKeyECC, tpm2.AlgSHA1, onePCR, getDigestHash("t")},
{"AK-ECC_SHA1_1PCR_no-nonce", client.AttestationKeyECC, tpm2.AlgSHA1, onePCR, nil},
{"AK-ECC_SHA256_2PCRs_nonce", client.AttestationKeyECC, tpm2.AlgSHA256, twoPCR, getDigestHash("test")},
{"AK-ECC_SHA256_2PCR_empty-nonce", client.AttestationKeyECC, tpm2.AlgSHA256, twoPCR, []byte{}},
{"AK-ECC_SHA256_dupePCrSel_nonce", client.AttestationKeyECC, tpm2.AlgSHA256, dupePCR, getDigestHash("")},
}
for _, subtest := range subtests {
t.Run(subtest.name, func(t *testing.T) {
ak, err := subtest.getKey(rwc)
if err != nil {
t.Errorf("failed to generate AK: %v", err)
}
defer ak.Close()
selpcr := tpm2.PCRSelection{
Hash: subtest.pcrHashAlgo,
PCRs: subtest.quotePCRList,
}
err = extendPCRsRandomly(rwc, selpcr)
if err != nil {
t.Fatalf("failed to extend test PCRs: %v", err)
}
quote, err := ak.Quote(selpcr, subtest.extraData)
if err != nil {
t.Fatalf("failed to quote: %v", err)
}
err = internal.VerifyQuote(quote, ak.PublicKey(), subtest.extraData)
if err != nil {
t.Fatalf("failed to verify: %v", err)
}
})
}
}
func TestVerifyPCRChanged(t *testing.T) {
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Errorf("failed to generate AK: %v", err)
}
defer ak.Close()
selpcr := tpm2.PCRSelection{
Hash: tpm2.AlgSHA256,
PCRs: []int{test.DebugPCR},
}
err = extendPCRsRandomly(rwc, selpcr)
if err != nil {
t.Errorf("failed to extend test PCRs: %v", err)
}
nonce := getDigestHash("test")
quote, err := ak.Quote(selpcr, nonce)
if err != nil {
t.Error(err)
}
// change the PCR value
err = extendPCRsRandomly(rwc, selpcr)
if err != nil {
t.Errorf("failed to extend test PCRs: %v", err)
}
quote.Pcrs, err = client.ReadPCRs(rwc, selpcr)
if err != nil {
t.Errorf("failed to read PCRs: %v", err)
}
err = internal.VerifyQuote(quote, ak.PublicKey(), nonce)
if err == nil {
t.Errorf("Verify should fail as Verify read a modified PCR")
}
}
func TestVerifyUsingDifferentPCR(t *testing.T) {
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Errorf("failed to generate AK: %v", err)
}
defer ak.Close()
err = extendPCRsRandomly(rwc, tpm2.PCRSelection{
Hash: tpm2.AlgSHA256,
PCRs: []int{test.DebugPCR, test.ApplicationPCR},
})
if err != nil {
t.Errorf("failed to extend test PCRs: %v", err)
}
nonce := getDigestHash("test")
quote, err := ak.Quote(tpm2.PCRSelection{
Hash: tpm2.AlgSHA256,
PCRs: []int{test.DebugPCR},
}, nonce)
if err != nil {
t.Error(err)
}
quote.Pcrs, err = client.ReadPCRs(rwc, tpm2.PCRSelection{
Hash: tpm2.AlgSHA256,
PCRs: []int{test.ApplicationPCR},
})
if err != nil {
t.Errorf("failed to read PCRs: %v", err)
}
err = internal.VerifyQuote(quote, ak.PublicKey(), nonce)
if err == nil {
t.Errorf("Verify should fail as Verify read a different PCR")
}
}
func TestVerifyWithTrustedAK(t *testing.T) {
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Fatalf("failed to generate AK: %v", err)
}
defer ak.Close()
nonce := []byte("super secret nonce")
attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce})
if err != nil {
t.Fatalf("failed to attest: %v", err)
}
opts := VerifyOpts{
Nonce: nonce,
TrustedAKs: []crypto.PublicKey{ak.PublicKey()},
}
_, err = VerifyAttestation(attestation, opts)
if err != nil {
t.Errorf("failed to verify: %v", err)
}
}
func TestVerifySHA1Attestation(t *testing.T) {
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Fatalf("failed to generate AK: %v", err)
}
defer ak.Close()
nonce := []byte("super secret nonce")
attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce})
if err != nil {
t.Fatalf("failed to attest: %v", err)
}
// We should get a SHA-256 state, even if we allow SHA-1
opts := VerifyOpts{
Nonce: nonce,
TrustedAKs: []crypto.PublicKey{ak.PublicKey()},
AllowSHA1: true,
}
state, err := VerifyAttestation(attestation, opts)
if err != nil {
t.Errorf("failed to verify: %v", err)
}
h := tpm2.Algorithm(state.GetHash())
if h != tpm2.AlgSHA256 {
t.Errorf("expected SHA-256 state, got: %v", h)
}
// Now we mess up the SHA-256 state to force SHA-1 fallback
for _, quote := range attestation.GetQuotes() {
if tpm2.Algorithm(quote.GetPcrs().GetHash()) == tpm2.AlgSHA256 {
quote.Quote = nil
}
}
state, err = VerifyAttestation(attestation, opts)
if err != nil {
t.Errorf("failed to verify: %v", err)
}
h = tpm2.Algorithm(state.GetHash())
if h != tpm2.AlgSHA1 {
t.Errorf("expected SHA-1 state, got: %v", h)
}
// SHA-1 fallback can then be disabled
opts.AllowSHA1 = false
if _, err = VerifyAttestation(attestation, opts); err == nil {
t.Error("expected attestation to fail with only SHA-1")
}
}
func TestVerifyAttestationWithCEL(t *testing.T) {
test.SkipForRealTPM(t)
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Fatalf("failed to generate AK: %v", err)
}
defer ak.Close()
coscel := &cel.CEL{}
testEvents := []struct {
cosNestedEventType cel.CosType
pcr int
eventPayload []byte
}{
{cel.ImageRefType, cel.CosEventPCR, []byte("docker.io/bazel/experimental/test:latest")},
{cel.ImageDigestType, cel.CosEventPCR, []byte("sha256:781d8dfdd92118436bd914442c8339e653b83f6bf3c1a7a98efcfb7c4fed7483")},
{cel.RestartPolicyType, cel.CosEventPCR, []byte(attestpb.RestartPolicy_Never.String())},
{cel.ImageIDType, cel.CosEventPCR, []byte("sha256:5DF4A1AC347DCF8CF5E9D0ABC04B04DB847D1B88D3B1CC1006F0ACB68E5A1F4B")},
{cel.EnvVarType, cel.CosEventPCR, []byte("foo=bar")},
{cel.EnvVarType, cel.CosEventPCR, []byte("bar=baz")},
{cel.EnvVarType, cel.CosEventPCR, []byte("baz=foo=bar")},
{cel.EnvVarType, cel.CosEventPCR, []byte("empty=")},
{cel.ArgType, cel.CosEventPCR, []byte("--x")},
{cel.ArgType, cel.CosEventPCR, []byte("--y")},
{cel.OverrideArgType, cel.CosEventPCR, []byte("--x")},
{cel.OverrideEnvType, cel.CosEventPCR, []byte("empty=")},
{cel.MemoryMonitorType, cel.CosEventPCR, []byte{1}},
}
for _, testEvent := range testEvents {
cosEvent := cel.CosTlv{EventType: testEvent.cosNestedEventType, EventContent: testEvent.eventPayload}
if err := coscel.AppendEventPCR(rwc, testEvent.pcr, measuredHashes, cosEvent); err != nil {
t.Fatal(err)
}
}
var buf bytes.Buffer
if err := coscel.EncodeCEL(&buf); err != nil {
t.Fatal(err)
}
nonce := []byte("super secret nonce")
attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce, CanonicalEventLog: buf.Bytes()})
if err != nil {
t.Fatalf("failed to attest: %v", err)
}
opts := VerifyOpts{
Nonce: nonce,
TrustedAKs: []crypto.PublicKey{ak.PublicKey()},
}
state, err := VerifyAttestation(attestation, opts)
if err != nil {
t.Fatalf("failed to verify: %v", err)
}
expectedEnvVars := make(map[string]string)
expectedEnvVars["foo"] = "bar"
expectedEnvVars["bar"] = "baz"
expectedEnvVars["baz"] = "foo=bar"
expectedEnvVars["empty"] = ""
expectedOverriddenEnvVars := make(map[string]string)
expectedOverriddenEnvVars["empty"] = ""
wantContainerState := attestpb.ContainerState{
ImageReference: string(testEvents[0].eventPayload),
ImageDigest: string(testEvents[1].eventPayload),
RestartPolicy: attestpb.RestartPolicy_Never,
ImageId: string(testEvents[3].eventPayload),
EnvVars: expectedEnvVars,
Args: []string{string(testEvents[8].eventPayload), string(testEvents[9].eventPayload)},
OverriddenEnvVars: expectedOverriddenEnvVars,
OverriddenArgs: []string{string(testEvents[10].eventPayload)},
}
enabled := true
wantHealthMonitoringState := attestpb.HealthMonitoringState{
MemoryEnabled: &enabled,
}
if diff := cmp.Diff(state.Cos.Container, &wantContainerState, protocmp.Transform()); diff != "" {
t.Errorf("unexpected container state difference:\n%v", diff)
}
if diff := cmp.Diff(state.Cos.HealthMonitoring, &wantHealthMonitoringState, protocmp.Transform()); diff != "" {
t.Errorf("unexpected health monitoring state difference:\n%v", diff)
}
}
func TestVerifyFailWithTamperedCELContent(t *testing.T) {
test.SkipForRealTPM(t)
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Fatalf("failed to generate AK: %v", err)
}
defer ak.Close()
c := &cel.CEL{}
cosEvent := cel.CosTlv{EventType: cel.ImageRefType, EventContent: []byte("docker.io/bazel/experimental/test:latest")}
cosEvent2 := cel.CosTlv{EventType: cel.ImageDigestType, EventContent: []byte("sha256:781d8dfdd92118436bd914442c8339e653b83f6bf3c1a7a98efcfb7c4fed7483")}
if err := c.AppendEventPCR(rwc, cel.CosEventPCR, measuredHashes, cosEvent); err != nil {
t.Fatalf("failed to append event: %v", err)
}
if err := c.AppendEventPCR(rwc, cel.CosEventPCR, measuredHashes, cosEvent2); err != nil {
t.Fatalf("failed to append event: %v", err)
}
// modify the first record content, but not the record digest
modifiedRecord := cel.CosTlv{EventType: cel.ImageDigestType, EventContent: []byte("sha256:000000000000000000000000000000000000000000000000000000000000000")}
modifiedTLV, err := modifiedRecord.GetTLV()
if err != nil {
t.Fatal(err)
}
c.Records[0].Content = modifiedTLV
var buf bytes.Buffer
if err := c.EncodeCEL(&buf); err != nil {
t.Fatal(err)
}
nonce := []byte("super secret nonce")
attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce, CanonicalEventLog: buf.Bytes()})
if err != nil {
t.Fatalf("failed to attest: %v", err)
}
opts := VerifyOpts{
Nonce: nonce,
TrustedAKs: []crypto.PublicKey{ak.PublicKey()},
}
if _, err := VerifyAttestation(attestation, opts); err == nil {
t.Fatalf("VerifyAttestation should fail due to modified content")
} else if !strings.Contains(err.Error(), "CEL record content digest verification failed") {
t.Fatalf("expect to get digest verification failed error, but got %v", err)
}
}
func TestVerifyAttestationWithCerts(t *testing.T) {
tests := []struct {
name string
attestation []byte
nonce []byte
}{
{
"no-nonce",
test.COS85NoNonce,
nil,
},
{
"nonce-9009",
test.COS85Nonce9009,
[]byte{0x90, 0x09},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
attestBytes := test.attestation
att := &attestpb.Attestation{}
if err := proto.Unmarshal(attestBytes, att); err != nil {
t.Fatalf("failed to unmarshal attestation: %v", err)
}
if _, err := VerifyAttestation(att, VerifyOpts{
Nonce: test.nonce,
TrustedRootCerts: GceEKRoots,
IntermediateCerts: GceEKIntermediates,
}); err != nil {
t.Errorf("failed to VerifyAttestation with AKCert: %v", err)
}
})
}
}
func TestVerifyAutomaticallyUsesIntermediatesInAttestation(t *testing.T) {
attestBytes := test.COS85Nonce9009
att := &attestpb.Attestation{}
if err := proto.Unmarshal(attestBytes, att); err != nil {
t.Fatalf("failed to unmarshal attestation: %v", err)
}
att.IntermediateCerts = [][]byte{gceEKIntermediateCA2}
if _, err := VerifyAttestation(att, VerifyOpts{
Nonce: []byte{0x90, 0x09},
TrustedRootCerts: GceEKRoots,
}); err != nil {
t.Errorf("failed to VerifyAttestation with intermediates provided in attestation: %v", err)
}
}
func TestVerifySucceedsWithOverlappingIntermediatesInOptionsAndAttestation(t *testing.T) {
attestBytes := test.COS85Nonce9009
att := &attestpb.Attestation{}
if err := proto.Unmarshal(attestBytes, att); err != nil {
t.Fatalf("failed to unmarshal attestation: %v", err)
}
att.IntermediateCerts = [][]byte{gceEKIntermediateCA2}
if _, err := VerifyAttestation(att, VerifyOpts{
Nonce: []byte{0x90, 0x09},
TrustedRootCerts: GceEKRoots,
IntermediateCerts: GceEKIntermediates,
}); err != nil {
t.Errorf("failed to VerifyAttestation with overlapping intermediates provided in attestation and options: %v", err)
}
}
func TestValidateOptsFailWithCertsAndPubkey(t *testing.T) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
opts := VerifyOpts{
Nonce: nil,
TrustedRootCerts: GceEKRoots,
IntermediateCerts: GceEKIntermediates,
TrustedAKs: []crypto.PublicKey{priv.Public()},
}
if err := validateOpts(opts); err == nil {
t.Error("Verified attestation even with multiple trust methods")
}
}
func TestValidateAK(t *testing.T) {
attestBytes := test.COS85NoNonce
att := &attestpb.Attestation{}
if err := proto.Unmarshal(attestBytes, att); err != nil {
t.Fatalf("failed to unmarshal attestation: %v", err)
}
rwc := test.GetTPM(t)
t.Cleanup(func() { client.CheckedClose(t, rwc) })
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Fatalf("failed to generate AK: %v", err)
}
t.Cleanup(ak.Close)
testCases := []struct {
name string
att func() *attestpb.Attestation
opts VerifyOpts
wantPass bool
}{
{
name: "success with validateAKCert",
att: func() *attestpb.Attestation { return att },
opts: VerifyOpts{
TrustedRootCerts: GceEKRoots,
IntermediateCerts: GceEKIntermediates,
},
wantPass: true,
},
{
name: "success with validateAKPub",
att: func() *attestpb.Attestation {
nonce := []byte("super secret nonce")
attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce})
if err != nil {
t.Fatalf("failed to attest: %v", err)
}
return attestation
},
opts: VerifyOpts{TrustedAKs: []crypto.PublicKey{ak.PublicKey()}},
wantPass: true,
},
{
name: "failed with empty roots and intermediates",
att: func() *attestpb.Attestation { return att },
opts: VerifyOpts{
TrustedRootCerts: nil,
IntermediateCerts: nil,
},
wantPass: false,
},
{
name: "failed with empty VerifyOpts",
att: func() *attestpb.Attestation { return att },
opts: VerifyOpts{},
wantPass: false,
},
{
name: "failed with missing roots",
att: func() *attestpb.Attestation { return att },
opts: VerifyOpts{IntermediateCerts: GceEKIntermediates},
wantPass: false,
},
{
name: "failed with missing intermediates",
att: func() *attestpb.Attestation { return att },
opts: VerifyOpts{TrustedRootCerts: GceEKRoots},
wantPass: false,
},
{
name: "failed with wrong trusted AKs",
att: func() *attestpb.Attestation { return att },
opts: VerifyOpts{TrustedAKs: []crypto.PublicKey{ak.PublicKey()}},
wantPass: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
_, _, err := validateAK(tc.att(), tc.opts)
if gotPass := (err == nil); gotPass != tc.wantPass {
t.Errorf("ValidateAK failed, got pass %v, but want %v", gotPass, tc.wantPass)
}
})
}
}
func TestVerifyIgnoreAKPubWithAKCert(t *testing.T) {
// Make sure that we ignore the AKPub if the AKCert is presented
rwc := test.GetTPM(t)
defer client.CheckedClose(t, rwc)
ak, err := client.AttestationKeyRSA(rwc)
if err != nil {
t.Fatalf("failed to generate AK: %v", err)
}
defer ak.Close()
nonce := []byte{0x90, 0x09}
badAtt, err := ak.Attest(client.AttestOpts{Nonce: nonce})
if err != nil {
t.Fatalf("failed to attest: %v", err)
}
// Copy "good" certificate into "bad" attestation
goodAtt := &attestpb.Attestation{}
if err := proto.Unmarshal(test.COS85Nonce9009, goodAtt); err != nil {
t.Fatalf("failed to unmarshal attestation: %v", err)
}
badAtt.AkCert = goodAtt.GetAkCert()
opts := VerifyOpts{
Nonce: nonce,
TrustedRootCerts: GceEKRoots,
IntermediateCerts: GceEKIntermediates,
}
if _, err := VerifyAttestation(badAtt, opts); err == nil {
t.Error("expected error when calling VerifyAttestation, because the cert is replaced")
}
}
func TestVerifyFailsWithMalformedIntermediatesInAttestation(t *testing.T) {
attestBytes := test.COS85Nonce9009
att := &attestpb.Attestation{}
if err := proto.Unmarshal(attestBytes, att); err != nil {
t.Fatalf("failed to unmarshal attestation: %v", err)
}
att.IntermediateCerts = [][]byte{[]byte("Not an intermediate cert.")}
if _, err := VerifyAttestation(att, VerifyOpts{
Nonce: []byte{0x90, 0x09},
TrustedRootCerts: GceEKRoots,
}); err == nil {
t.Error("expected error when calling VerifyAttestation with malformed intermediate")
}
}
func TestGetInstanceInfo(t *testing.T) {
expectedInstanceInfo := &attestpb.GCEInstanceInfo{
Zone: "expected zone",
ProjectId: "expected project id",
ProjectNumber: 0,
InstanceName: "expected instance name",
InstanceId: 1,
}
extStruct := gceInstanceInfo{
Zone: expectedInstanceInfo.Zone,
ProjectID: expectedInstanceInfo.ProjectId,
ProjectNumber: int64(expectedInstanceInfo.ProjectNumber),
InstanceName: expectedInstanceInfo.InstanceName,
InstanceID: int64(expectedInstanceInfo.InstanceId),
SecurityProperties: gceSecurityProperties{
SecurityVersion: 0,
IsProduction: true,
},
}
marshaledExt, err := asn1.Marshal(extStruct)
if err != nil {
t.Fatalf("Error marshaling test extension: %v", err)
}
ext := []pkix.Extension{{
Id: cloudComputeInstanceIdentifierOID,
Value: marshaledExt,
}}
instanceInfo, err := getInstanceInfoFromExtensions(ext)
if err != nil {
t.Fatalf("getInstanceInfo returned with error: %v", err)
}
if instanceInfo == nil {
t.Fatal("getInstanceInfo returned nil instance info.")
}
if !proto.Equal(instanceInfo, expectedInstanceInfo) {
t.Errorf("getInstanceInfo did not return expected instance info: got %v, want %v", instanceInfo, expectedInstanceInfo)
}
}
func TestGetInstanceInfoReturnsNil(t *testing.T) {
extStruct := gceInstanceInfo{
Zone: "zone",
ProjectID: "project id",
ProjectNumber: 0,
InstanceName: "instance name",
InstanceID: 1,
SecurityProperties: gceSecurityProperties{IsProduction: false},
}
marshaledExt, err := asn1.Marshal(extStruct)
if err != nil {
t.Fatalf("Error marshaling test extension: %v", err)
}
testcases := []struct {
name string
ext []pkix.Extension
}{
{
name: "No extension with expected OID",
ext: []pkix.Extension{{
Id: asn1.ObjectIdentifier([]int{1, 2, 3, 4}),
Value: []byte("fake extension"),
}},
},
{
name: "IsProduction is false",
ext: []pkix.Extension{{
Id: cloudComputeInstanceIdentifierOID,
Value: marshaledExt,
}},
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
instanceInfo, err := getInstanceInfoFromExtensions(tc.ext)
if err != nil {
t.Fatalf("getInstanceInfo returned with error: %v", err)
}
if instanceInfo != nil {
t.Error("getInstanceInfo returned instance information, expected nil")
}
})
}
}
func TestGetInstanceInfoError(t *testing.T) {
testcases := []struct {
name string
instanceInfo *gceInstanceInfo
}{
{
name: "Extension value is not valid ASN1",
instanceInfo: nil,
},
{
name: "Negative ProjectNumber",
instanceInfo: &gceInstanceInfo{
Zone: "zone",
ProjectID: "project id",
ProjectNumber: -1,
InstanceName: "instance name",
InstanceID: 1,
SecurityProperties: gceSecurityProperties{IsProduction: false},
},
},
{
name: "Negative InstanceID",
instanceInfo: &gceInstanceInfo{
Zone: "zone",
ProjectID: "project id",
ProjectNumber: 0,
InstanceName: "instance name",
InstanceID: -1,
SecurityProperties: gceSecurityProperties{IsProduction: false},
},
},
{
name: "Negative SecurityVersion",
instanceInfo: &gceInstanceInfo{
Zone: "zone",
ProjectID: "project id",
ProjectNumber: 0,
InstanceName: "instance name",
InstanceID: 1,
SecurityProperties: gceSecurityProperties{
SecurityVersion: -1,
IsProduction: false,
},
},
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
var extensionVal []byte
var err error
if tc.instanceInfo != nil {
extensionVal, err = asn1.Marshal(*tc.instanceInfo)
if err != nil {
t.Fatalf("Error marshaling test extension: %v", err)
}
} else {
extensionVal = []byte("Not a valid ASN1 extension.")
}
_, err = getInstanceInfoFromExtensions([]pkix.Extension{{
Id: cloudComputeInstanceIdentifierOID,
Value: extensionVal,
}})
if err == nil {
t.Error("getInstanceInfo returned successfully, expected error")
}
})
}
ext := []pkix.Extension{{
Id: cloudComputeInstanceIdentifierOID,
Value: []byte("not valid ASN1"),
}}
_, err := getInstanceInfoFromExtensions(ext)
if err == nil {
t.Error("getInstanceInfo returned successfully, expected error")
}
}
func TestGetInstanceInfoASN(t *testing.T) {
expectedInstanceInfo := &attestpb.GCEInstanceInfo{
Zone: "us-west1-b",
ProjectId: "jiankun-vm-test",
ProjectNumber: 620438545889,
InstanceName: "jkltest42102",
InstanceId: 3560342035431930290,
}
// The payload is extract from a real AK cert, the ASN1 encoding requires gceSecurityProperties
// to have explicit ASN tag.
extPayload := []byte{48, 95, 12, 10, 117, 115, 45, 119, 101, 115, 116, 49, 45, 98, 2, 6, 0, 144, 117, 4, 229, 225, 12, 15, 106, 105, 97, 110, 107, 117, 110, 45, 118, 109, 45, 116, 101, 115, 116, 2, 8, 49, 104, 224, 55, 188, 207, 185, 178, 12, 12, 106, 107, 108, 116, 101, 115, 116, 52, 50, 49, 48, 50, 160, 32, 48, 30, 160, 3, 2, 1, 0, 161, 3, 1, 1, 255, 162, 3, 1, 1, 0, 163, 3, 1, 1, 0, 164, 3, 1, 1, 0, 165, 3, 1, 1, 0}
ext := []pkix.Extension{{
Id: cloudComputeInstanceIdentifierOID,
Value: extPayload,
}}
instanceInfo, err := getInstanceInfoFromExtensions(ext)
if err != nil {
t.Fatalf("getInstanceInfo returned with error: %v", err)
}
if instanceInfo == nil {
t.Fatal("getInstanceInfo returned nil instance info.")
}
if !proto.Equal(instanceInfo, expectedInstanceInfo) {
t.Errorf("getInstanceInfo did not return expected instance info: got %v, want %v", instanceInfo, expectedInstanceInfo)
}
}
func TestValidateAKGCEAndGetGCEInstanceInfo(t *testing.T) {
testCases := []struct {
name string
certPEM []byte
rootCertDER []byte
intermediateDER []byte
}{
{
name: "GCE UCA AK ECC",
certPEM: test.GCESignECCCertUCA,
rootCertDER: gceEKRootCA,
intermediateDER: gceEKIntermediateCA3,
},
{
name: "GCE UCA AK RSA",
certPEM: test.GCESignRSACertUCA,
rootCertDER: gceEKRootCA,
intermediateDER: gceEKIntermediateCA3,
},
{
name: "GCE UCA EK ECC",
certPEM: test.GCEEncryptECCCertUCA,
rootCertDER: gceEKRootCA,
intermediateDER: gceEKIntermediateCA3,
},
{
name: "GCE UCA EK RSA",
certPEM: test.GCEEncryptRSACertUCA,
rootCertDER: gceEKRootCA,
intermediateDER: gceEKIntermediateCA3,
},
{
name: "GCE CAS AK ECC",
certPEM: test.GCESignECCCertPCA,
rootCertDER: gcpCASEKRootCA,
intermediateDER: gcpCASEKIntermediateCA3,
},
{
name: "GCE CAS AK RSA",
certPEM: test.GCESignRSACertPCA,
rootCertDER: gcpCASEKRootCA,
intermediateDER: gcpCASEKIntermediateCA3,
},
{
name: "GCE CAS EK ECC",
certPEM: test.GCEEncryptECCCertPCA,
rootCertDER: gcpCASEKRootCA,
intermediateDER: gcpCASEKIntermediateCA3,
},
{
name: "GCE CAS EK RSA",
certPEM: test.GCEEncryptRSACertPCA,
rootCertDER: gcpCASEKRootCA,
intermediateDER: gcpCASEKIntermediateCA3,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
crtBlock, _ := pem.Decode(tc.certPEM)
if crtBlock.Bytes == nil {
t.Fatalf("failed to pem.Decode(tc.certPEM)")
}
akCrt, err := x509.ParseCertificate(crtBlock.Bytes)
if err != nil {
t.Fatalf("x509.ParseCertificate(crtBlock.Bytes): %v", err)
}
root, err := x509.ParseCertificate(tc.rootCertDER)
if err != nil {
t.Fatalf("x509.ParseCertificate(tc.rootCertDER): %v", err)
}
intermediate, err := x509.ParseCertificate(tc.intermediateDER)
if err != nil {
t.Fatalf("x509.ParseCertificate(tc.intermediateDER): %v", err)
}
if err := VerifyAKCert(akCrt, []*x509.Certificate{root}, []*x509.Certificate{intermediate}); err != nil {
t.Errorf("ValidateAKCert(%v): %v)", tc.name, err)
}
if gceInfo, err := GetGCEInstanceInfo(akCrt); err != nil {
t.Errorf("GetGCEInstanceInfo(akCrt): %v", err)
} else {
t.Log(gceInfo)
fmt.Print(gceInfo)
}
})
}
}