Debian Codegraph @

server/verify_test.go

raw
1 package server
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/rsa"
7 "crypto/sha256"
8 "crypto/x509"
9 "crypto/x509/pkix"
10 _ "embed"
11 "encoding/asn1"
12 "encoding/pem"
13 "fmt"
14 "io"
15 "os"
16 "strings"
17 "testing"
18
19 "github.com/google/go-tpm-tools/client"
20 "github.com/google/go-tpm-tools/internal"
21 "github.com/google/go-tpm-tools/internal/test"
22 attestpb "github.com/google/go-tpm-tools/proto/attest"
23 "github.com/google/go-tpm/legacy/tpm2"
24 "github.com/google/go-tpm/tpmutil"
25 "github.com/google/logger"
26 "google.golang.org/protobuf/proto"
27 )
28
29 func getDigestHash(input string) []byte {
30 inputDigestHash := sha256.New()
31 inputDigestHash.Write([]byte(input))
32 return inputDigestHash.Sum(nil)
33 }
34
35 func extendPCRsRandomly(rwc io.ReadWriteCloser, selpcr tpm2.PCRSelection) error {
36 var pcrExtendValue []byte
37 if selpcr.Hash == tpm2.AlgSHA256 {
38 pcrExtendValue = make([]byte, 32)
39 } else if selpcr.Hash == tpm2.AlgSHA1 {
40 pcrExtendValue = make([]byte, 20)
41 }
42
43 for _, v := range selpcr.PCRs {
44 _, err := rand.Read(pcrExtendValue)
45 if err != nil {
46 return fmt.Errorf("random bytes read fail %v", err)
47 }
48 err = tpm2.PCRExtend(rwc, tpmutil.Handle(v), selpcr.Hash, pcrExtendValue, "")
49 if err != nil {
50 return fmt.Errorf("PCR extend fail %v", err)
51 }
52 }
53 return nil
54 }
55
56 func TestMain(m *testing.M) {
57 logger.Init("TestLog", false, false, os.Stderr)
58 os.Exit(m.Run())
59 }
60
61 func TestVerifyHappyCases(t *testing.T) {
62 rwc := test.GetTPM(t)
63 defer client.CheckedClose(t, rwc)
64
65 onePCR := []int{test.DebugPCR}
66 twoPCR := append(onePCR, test.ApplicationPCR)
67 dupePCR := append(twoPCR, twoPCR...)
68
69 subtests := []struct {
70 name string
71 getKey func(io.ReadWriter) (*client.Key, error)
72 pcrHashAlgo tpm2.Algorithm
73 quotePCRList []int
74 extraData []byte
75 }{
76 {"AK-RSA_SHA1_2PCRs_nonce", client.AttestationKeyRSA, tpm2.AlgSHA1, twoPCR, getDigestHash("test")},
77 {"AK-RSA_SHA1_1PCR_nonce", client.AttestationKeyRSA, tpm2.AlgSHA1, onePCR, getDigestHash("t")},
78 {"AK-RSA_SHA1_1PCR_no-nonce", client.AttestationKeyRSA, tpm2.AlgSHA1, onePCR, nil},
79 {"AK-RSA_SHA256_2PCRs_nonce", client.AttestationKeyRSA, tpm2.AlgSHA256, twoPCR, getDigestHash("test")},
80 {"AK-RSA_SHA256_2PCR_empty-nonce", client.AttestationKeyRSA, tpm2.AlgSHA256, twoPCR, []byte{}},
81 {"AK-RSA_SHA256_dupePCrSel_nonce", client.AttestationKeyRSA, tpm2.AlgSHA256, dupePCR, getDigestHash("")},
82
83 {"AK-ECC_SHA1_2PCRs_nonce", client.AttestationKeyECC, tpm2.AlgSHA1, twoPCR, getDigestHash("test")},
84 {"AK-ECC_SHA1_1PCR_nonce", client.AttestationKeyECC, tpm2.AlgSHA1, onePCR, getDigestHash("t")},
85 {"AK-ECC_SHA1_1PCR_no-nonce", client.AttestationKeyECC, tpm2.AlgSHA1, onePCR, nil},
86 {"AK-ECC_SHA256_2PCRs_nonce", client.AttestationKeyECC, tpm2.AlgSHA256, twoPCR, getDigestHash("test")},
87 {"AK-ECC_SHA256_2PCR_empty-nonce", client.AttestationKeyECC, tpm2.AlgSHA256, twoPCR, []byte{}},
88 {"AK-ECC_SHA256_dupePCrSel_nonce", client.AttestationKeyECC, tpm2.AlgSHA256, dupePCR, getDigestHash("")},
89 }
90 for _, subtest := range subtests {
91 t.Run(subtest.name, func(t *testing.T) {
92 ak, err := subtest.getKey(rwc)
93 if err != nil {
94 t.Errorf("failed to generate AK: %v", err)
95 }
96 defer ak.Close()
97
98 selpcr := tpm2.PCRSelection{
99 Hash: subtest.pcrHashAlgo,
100 PCRs: subtest.quotePCRList,
101 }
102 err = extendPCRsRandomly(rwc, selpcr)
103 if err != nil {
104 t.Fatalf("failed to extend test PCRs: %v", err)
105 }
106 quote, err := ak.Quote(selpcr, subtest.extraData)
107 if err != nil {
108 t.Fatalf("failed to quote: %v", err)
109 }
110 err = internal.VerifyQuote(quote, ak.PublicKey(), subtest.extraData)
111 if err != nil {
112 t.Fatalf("failed to verify: %v", err)
113 }
114 })
115 }
116 }
117
118 func TestVerifyPCRChanged(t *testing.T) {
119 rwc := test.GetTPM(t)
120 defer client.CheckedClose(t, rwc)
121
122 ak, err := client.AttestationKeyRSA(rwc)
123 if err != nil {
124 t.Errorf("failed to generate AK: %v", err)
125 }
126 defer ak.Close()
127
128 selpcr := tpm2.PCRSelection{
129 Hash: tpm2.AlgSHA256,
130 PCRs: []int{test.DebugPCR},
131 }
132 err = extendPCRsRandomly(rwc, selpcr)
133 if err != nil {
134 t.Errorf("failed to extend test PCRs: %v", err)
135 }
136 nonce := getDigestHash("test")
137 quote, err := ak.Quote(selpcr, nonce)
138 if err != nil {
139 t.Error(err)
140 }
141
142 // change the PCR value
143 err = extendPCRsRandomly(rwc, selpcr)
144 if err != nil {
145 t.Errorf("failed to extend test PCRs: %v", err)
146 }
147
148 quote.Pcrs, err = client.ReadPCRs(rwc, selpcr)
149 if err != nil {
150 t.Errorf("failed to read PCRs: %v", err)
151 }
152 err = internal.VerifyQuote(quote, ak.PublicKey(), nonce)
153 if err == nil {
154 t.Errorf("Verify should fail as Verify read a modified PCR")
155 }
156 }
157
158 func TestVerifyUsingDifferentPCR(t *testing.T) {
159 rwc := test.GetTPM(t)
160 defer client.CheckedClose(t, rwc)
161
162 ak, err := client.AttestationKeyRSA(rwc)
163 if err != nil {
164 t.Errorf("failed to generate AK: %v", err)
165 }
166 defer ak.Close()
167
168 err = extendPCRsRandomly(rwc, tpm2.PCRSelection{
169 Hash: tpm2.AlgSHA256,
170 PCRs: []int{test.DebugPCR, test.ApplicationPCR},
171 })
172 if err != nil {
173 t.Errorf("failed to extend test PCRs: %v", err)
174 }
175
176 nonce := getDigestHash("test")
177 quote, err := ak.Quote(tpm2.PCRSelection{
178 Hash: tpm2.AlgSHA256,
179 PCRs: []int{test.DebugPCR},
180 }, nonce)
181 if err != nil {
182 t.Error(err)
183 }
184
185 quote.Pcrs, err = client.ReadPCRs(rwc, tpm2.PCRSelection{
186 Hash: tpm2.AlgSHA256,
187 PCRs: []int{test.ApplicationPCR},
188 })
189 if err != nil {
190 t.Errorf("failed to read PCRs: %v", err)
191 }
192 err = internal.VerifyQuote(quote, ak.PublicKey(), nonce)
193 if err == nil {
194 t.Errorf("Verify should fail as Verify read a different PCR")
195 }
196 }
197
198 func TestVerifyWithTrustedAK(t *testing.T) {
199 rwc := test.GetTPM(t)
200 defer client.CheckedClose(t, rwc)
201
202 ak, err := client.AttestationKeyRSA(rwc)
203 if err != nil {
204 t.Fatalf("failed to generate AK: %v", err)
205 }
206 defer ak.Close()
207
208 nonce := []byte("super secret nonce")
209 attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce})
210 if err != nil {
211 t.Fatalf("failed to attest: %v", err)
212 }
213
214 opts := VerifyOpts{
215 Nonce: nonce,
216 TrustedAKs: []crypto.PublicKey{ak.PublicKey()},
217 }
218 _, err = VerifyAttestation(attestation, opts)
219 if err != nil {
220 t.Errorf("failed to verify: %v", err)
221 }
222 }
223
224 func TestVerifySHA1Attestation(t *testing.T) {
225 // If running against a real TPM which supports less usual hash algos, this test might fail.
226 rwc := test.GetTPM(t)
227 defer client.CheckedClose(t, rwc)
228
229 ak, err := client.AttestationKeyRSA(rwc)
230 if err != nil {
231 t.Fatalf("failed to generate AK: %v", err)
232 }
233 defer ak.Close()
234
235 nonce := []byte("super secret nonce")
236 attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce})
237 if err != nil {
238 t.Fatalf("failed to attest: %v", err)
239 }
240
241 // We should at least get a SHA-256 state, even if we allow SHA-1
242 opts := VerifyOpts{
243 Nonce: nonce,
244 TrustedAKs: []crypto.PublicKey{ak.PublicKey()},
245 AllowSHA1: true,
246 }
247 state, err := VerifyAttestation(attestation, opts)
248 if err != nil {
249 t.Errorf("failed to verify: %v", err)
250 }
251 h := tpm2.Algorithm(state.GetHash())
252 if h != tpm2.AlgSHA256 && h != tpm2.AlgSHA384 && h != tpm2.AlgSHA512 {
253 t.Errorf("expected at least a non SHA-1 state, got: %v", h)
254 }
255
256 // Now we mess up all other states to force SHA-1 fallback
257 for _, quote := range attestation.GetQuotes() {
258 if tpm2.Algorithm(quote.GetPcrs().GetHash()) == tpm2.AlgSHA256 ||
259 tpm2.Algorithm(quote.GetPcrs().GetHash()) == tpm2.AlgSHA384 ||
260 tpm2.Algorithm(quote.GetPcrs().GetHash()) == tpm2.AlgSHA512 {
261 quote.Quote = nil
262 }
263 }
264 state, err = VerifyAttestation(attestation, opts)
265 if err != nil {
266 t.Errorf("failed to verify: %v", err)
267 }
268 h = tpm2.Algorithm(state.GetHash())
269 if h != tpm2.AlgSHA1 {
270 t.Errorf("expected SHA-1 state, got: %v", h)
271 }
272
273 // SHA-1 fallback can then be disabled
274 opts.AllowSHA1 = false
275 if _, err = VerifyAttestation(attestation, opts); err == nil {
276 t.Error("expected attestation to fail with only SHA-1")
277 }
278 }
279
280 func TestVerifyAttestationWithCerts(t *testing.T) {
281 tests := []struct {
282 name string
283 attestation []byte
284 nonce []byte
285 }{
286 {
287 "no-nonce",
288 test.COS85NoNonce,
289 nil,
290 },
291 {
292 "nonce-9009",
293 test.COS85Nonce9009,
294 []byte{0x90, 0x09},
295 },
296 }
297 for _, test := range tests {
298 t.Run(test.name, func(t *testing.T) {
299 attestBytes := test.attestation
300 att := &attestpb.Attestation{}
301 if err := proto.Unmarshal(attestBytes, att); err != nil {
302 t.Fatalf("failed to unmarshal attestation: %v", err)
303 }
304
305 if _, err := VerifyAttestation(att, VerifyOpts{
306 Nonce: test.nonce,
307 TrustedRootCerts: GceEKRoots,
308 IntermediateCerts: GceEKIntermediates,
309 }); err != nil {
310 t.Errorf("failed to VerifyAttestation with AKCert: %v", err)
311 }
312 })
313 }
314 }
315
316 func TestVerifyAutomaticallyUsesIntermediatesInAttestation(t *testing.T) {
317 attestBytes := test.COS85Nonce9009
318 att := &attestpb.Attestation{}
319 if err := proto.Unmarshal(attestBytes, att); err != nil {
320 t.Fatalf("failed to unmarshal attestation: %v", err)
321 }
322 att.IntermediateCerts = [][]byte{gceEKIntermediateCA2}
323
324 if _, err := VerifyAttestation(att, VerifyOpts{
325 Nonce: []byte{0x90, 0x09},
326 TrustedRootCerts: GceEKRoots,
327 }); err != nil {
328 t.Errorf("failed to VerifyAttestation with intermediates provided in attestation: %v", err)
329 }
330 }
331
332 func TestVerifySucceedsWithOverlappingIntermediatesInOptionsAndAttestation(t *testing.T) {
333 attestBytes := test.COS85Nonce9009
334 att := &attestpb.Attestation{}
335 if err := proto.Unmarshal(attestBytes, att); err != nil {
336 t.Fatalf("failed to unmarshal attestation: %v", err)
337 }
338 att.IntermediateCerts = [][]byte{gceEKIntermediateCA2}
339
340 if _, err := VerifyAttestation(att, VerifyOpts{
341 Nonce: []byte{0x90, 0x09},
342 TrustedRootCerts: GceEKRoots,
343 IntermediateCerts: GceEKIntermediates,
344 }); err != nil {
345 t.Errorf("failed to VerifyAttestation with overlapping intermediates provided in attestation and options: %v", err)
346 }
347 }
348
349 func TestValidateOptsFailWithCertsAndPubkey(t *testing.T) {
350 priv, err := rsa.GenerateKey(rand.Reader, 2048)
351 if err != nil {
352 t.Fatal(err)
353 }
354 opts := VerifyOpts{
355 Nonce: nil,
356 TrustedRootCerts: GceEKRoots,
357 IntermediateCerts: GceEKIntermediates,
358 TrustedAKs: []crypto.PublicKey{priv.Public()},
359 }
360 if err := validateOpts(opts); err == nil {
361 t.Error("Verified attestation even with multiple trust methods")
362 }
363 }
364
365 func TestValidateAK(t *testing.T) {
366 attestBytes := test.COS85NoNonce
367 att := &attestpb.Attestation{}
368 if err := proto.Unmarshal(attestBytes, att); err != nil {
369 t.Fatalf("failed to unmarshal attestation: %v", err)
370 }
371
372 rwc := test.GetTPM(t)
373 t.Cleanup(func() { client.CheckedClose(t, rwc) })
374
375 ak, err := client.AttestationKeyRSA(rwc)
376 if err != nil {
377 t.Fatalf("failed to generate AK: %v", err)
378 }
379 t.Cleanup(ak.Close)
380
381 testCases := []struct {
382 name string
383 att func() *attestpb.Attestation
384 opts VerifyOpts
385 wantPass bool
386 }{
387 {
388 name: "success with validateAKCert",
389 att: func() *attestpb.Attestation { return att },
390 opts: VerifyOpts{
391 TrustedRootCerts: GceEKRoots,
392 IntermediateCerts: GceEKIntermediates,
393 },
394 wantPass: true,
395 },
396 {
397 name: "success with validateAKPub",
398 att: func() *attestpb.Attestation {
399 nonce := []byte("super secret nonce")
400 attestation, err := ak.Attest(client.AttestOpts{Nonce: nonce})
401 if err != nil {
402 t.Fatalf("failed to attest: %v", err)
403 }
404 return attestation
405 },
406 opts: VerifyOpts{TrustedAKs: []crypto.PublicKey{ak.PublicKey()}},
407 wantPass: true,
408 },
409 {
410 name: "failed with empty roots and intermediates",
411 att: func() *attestpb.Attestation { return att },
412 opts: VerifyOpts{
413 TrustedRootCerts: nil,
414 IntermediateCerts: nil,
415 },
416 wantPass: false,
417 },
418 {
419 name: "failed with empty VerifyOpts",
420 att: func() *attestpb.Attestation { return att },
421 opts: VerifyOpts{},
422 wantPass: false,
423 },
424 {
425 name: "failed with missing roots",
426 att: func() *attestpb.Attestation { return att },
427 opts: VerifyOpts{IntermediateCerts: GceEKIntermediates},
428 wantPass: false,
429 },
430 {
431 name: "failed with missing intermediates",
432 att: func() *attestpb.Attestation { return att },
433 opts: VerifyOpts{TrustedRootCerts: GceEKRoots},
434 wantPass: false,
435 },
436 {
437 name: "failed with wrong trusted AKs",
438 att: func() *attestpb.Attestation { return att },
439 opts: VerifyOpts{TrustedAKs: []crypto.PublicKey{ak.PublicKey()}},
440 wantPass: false,
441 },
442 }
443
444 for _, tc := range testCases {
445 t.Run(tc.name, func(t *testing.T) {
446 _, _, err := validateAK(tc.att(), tc.opts)
447 if gotPass := (err == nil); gotPass != tc.wantPass {
448 t.Errorf("ValidateAK failed, got pass %v, but want %v", gotPass, tc.wantPass)
449 }
450 })
451 }
452
453 }
454
455 func TestVerifyIgnoreAKPubWithAKCert(t *testing.T) {
456 // Make sure that we ignore the AKPub if the AKCert is presented
457 rwc := test.GetTPM(t)
458 defer client.CheckedClose(t, rwc)
459
460 ak, err := client.AttestationKeyRSA(rwc)
461 if err != nil {
462 t.Fatalf("failed to generate AK: %v", err)
463 }
464 defer ak.Close()
465
466 nonce := []byte{0x90, 0x09}
467 badAtt, err := ak.Attest(client.AttestOpts{Nonce: nonce})
468 if err != nil {
469 t.Fatalf("failed to attest: %v", err)
470 }
471 // Copy "good" certificate into "bad" attestation
472 goodAtt := &attestpb.Attestation{}
473 if err := proto.Unmarshal(test.COS85Nonce9009, goodAtt); err != nil {
474 t.Fatalf("failed to unmarshal attestation: %v", err)
475 }
476 badAtt.AkCert = goodAtt.GetAkCert()
477
478 opts := VerifyOpts{
479 Nonce: nonce,
480 TrustedRootCerts: GceEKRoots,
481 IntermediateCerts: GceEKIntermediates,
482 }
483 if _, err := VerifyAttestation(badAtt, opts); err == nil {
484 t.Error("expected error when calling VerifyAttestation, because the cert is replaced")
485 }
486 }
487
488 func TestVerifyFailsWithMalformedIntermediatesInAttestation(t *testing.T) {
489 attestBytes := test.COS85Nonce9009
490 att := &attestpb.Attestation{}
491 if err := proto.Unmarshal(attestBytes, att); err != nil {
492 t.Fatalf("failed to unmarshal attestation: %v", err)
493 }
494 att.IntermediateCerts = [][]byte{[]byte("Not an intermediate cert.")}
495
496 if _, err := VerifyAttestation(att, VerifyOpts{
497 Nonce: []byte{0x90, 0x09},
498 TrustedRootCerts: GceEKRoots,
499 }); err == nil {
500 t.Error("expected error when calling VerifyAttestation with malformed intermediate")
501 }
502 }
503
504 func TestGetInstanceInfo(t *testing.T) {
505 expectedInstanceInfo := &attestpb.GCEInstanceInfo{
506 Zone: "expected zone",
507 ProjectId: "expected project id",
508 ProjectNumber: 0,
509 InstanceName: "expected instance name",
510 InstanceId: 1,
511 }
512
513 extStruct := gceInstanceInfo{
514 Zone: expectedInstanceInfo.Zone,
515 ProjectID: expectedInstanceInfo.ProjectId,
516 ProjectNumber: int64(expectedInstanceInfo.ProjectNumber),
517 InstanceName: expectedInstanceInfo.InstanceName,
518 InstanceID: int64(expectedInstanceInfo.InstanceId),
519 SecurityProperties: gceSecurityProperties{
520 SecurityVersion: 0,
521 IsProduction: true,
522 },
523 }
524
525 marshaledExt, err := asn1.Marshal(extStruct)
526 if err != nil {
527 t.Fatalf("Error marshaling test extension: %v", err)
528 }
529
530 ext := []pkix.Extension{{
531 Id: cloudComputeInstanceIdentifierOID,
532 Value: marshaledExt,
533 }}
534
535 instanceInfo, err := getInstanceInfoFromExtensions(ext)
536 if err != nil {
537 t.Fatalf("getInstanceInfo returned with error: %v", err)
538 }
539 if instanceInfo == nil {
540 t.Fatal("getInstanceInfo returned nil instance info.")
541 }
542
543 if !proto.Equal(instanceInfo, expectedInstanceInfo) {
544 t.Errorf("getInstanceInfo did not return expected instance info: got %v, want %v", instanceInfo, expectedInstanceInfo)
545 }
546 }
547
548 func TestGetInstanceInfoReturnsNil(t *testing.T) {
549 extStruct := gceInstanceInfo{
550 Zone: "zone",
551 ProjectID: "project id",
552 ProjectNumber: 0,
553 InstanceName: "instance name",
554 InstanceID: 1,
555 SecurityProperties: gceSecurityProperties{IsProduction: false},
556 }
557
558 marshaledExt, err := asn1.Marshal(extStruct)
559 if err != nil {
560 t.Fatalf("Error marshaling test extension: %v", err)
561 }
562
563 testcases := []struct {
564 name string
565 ext []pkix.Extension
566 }{
567 {
568 name: "No extension with expected OID",
569 ext: []pkix.Extension{{
570 Id: asn1.ObjectIdentifier([]int{1, 2, 3, 4}),
571 Value: []byte("fake extension"),
572 }},
573 },
574 {
575 name: "IsProduction is false",
576 ext: []pkix.Extension{{
577 Id: cloudComputeInstanceIdentifierOID,
578 Value: marshaledExt,
579 }},
580 },
581 }
582
583 for _, tc := range testcases {
584 t.Run(tc.name, func(t *testing.T) {
585 instanceInfo, err := getInstanceInfoFromExtensions(tc.ext)
586 if err != nil {
587 t.Fatalf("getInstanceInfo returned with error: %v", err)
588 }
589
590 if instanceInfo != nil {
591 t.Error("getInstanceInfo returned instance information, expected nil")
592 }
593 })
594 }
595 }
596
597 func TestGetInstanceInfoError(t *testing.T) {
598 testcases := []struct {
599 name string
600 instanceInfo *gceInstanceInfo
601 }{
602 {
603 name: "Extension value is not valid ASN1",
604 instanceInfo: nil,
605 },
606 {
607 name: "Negative ProjectNumber",
608 instanceInfo: &gceInstanceInfo{
609 Zone: "zone",
610 ProjectID: "project id",
611 ProjectNumber: -1,
612 InstanceName: "instance name",
613 InstanceID: 1,
614 SecurityProperties: gceSecurityProperties{IsProduction: false},
615 },
616 },
617 {
618 name: "Negative InstanceID",
619 instanceInfo: &gceInstanceInfo{
620 Zone: "zone",
621 ProjectID: "project id",
622 ProjectNumber: 0,
623 InstanceName: "instance name",
624 InstanceID: -1,
625 SecurityProperties: gceSecurityProperties{IsProduction: false},
626 },
627 },
628 {
629 name: "Negative SecurityVersion",
630 instanceInfo: &gceInstanceInfo{
631 Zone: "zone",
632 ProjectID: "project id",
633 ProjectNumber: 0,
634 InstanceName: "instance name",
635 InstanceID: 1,
636 SecurityProperties: gceSecurityProperties{
637 SecurityVersion: -1,
638 IsProduction: false,
639 },
640 },
641 },
642 }
643
644 for _, tc := range testcases {
645 t.Run(tc.name, func(t *testing.T) {
646 var extensionVal []byte
647 var err error
648 if tc.instanceInfo != nil {
649 extensionVal, err = asn1.Marshal(*tc.instanceInfo)
650 if err != nil {
651 t.Fatalf("Error marshaling test extension: %v", err)
652 }
653 } else {
654 extensionVal = []byte("Not a valid ASN1 extension.")
655 }
656
657 _, err = getInstanceInfoFromExtensions([]pkix.Extension{{
658 Id: cloudComputeInstanceIdentifierOID,
659 Value: extensionVal,
660 }})
661
662 if err == nil {
663 t.Error("getInstanceInfo returned successfully, expected error")
664 }
665 })
666 }
667
668 ext := []pkix.Extension{{
669 Id: cloudComputeInstanceIdentifierOID,
670 Value: []byte("not valid ASN1"),
671 }}
672
673 _, err := getInstanceInfoFromExtensions(ext)
674 if err == nil {
675 t.Error("getInstanceInfo returned successfully, expected error")
676 }
677 }
678
679 func TestGetInstanceInfoASN(t *testing.T) {
680 expectedInstanceInfo := &attestpb.GCEInstanceInfo{
681 Zone: "us-west1-b",
682 ProjectId: "jiankun-vm-test",
683 ProjectNumber: 620438545889,
684 InstanceName: "jkltest42102",
685 InstanceId: 3560342035431930290,
686 }
687
688 // The payload is extract from a real AK cert, the ASN1 encoding requires gceSecurityProperties
689 // to have explicit ASN tag.
690 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}
691
692 ext := []pkix.Extension{{
693 Id: cloudComputeInstanceIdentifierOID,
694 Value: extPayload,
695 }}
696
697 instanceInfo, err := getInstanceInfoFromExtensions(ext)
698 if err != nil {
699 t.Fatalf("getInstanceInfo returned with error: %v", err)
700 }
701 if instanceInfo == nil {
702 t.Fatal("getInstanceInfo returned nil instance info.")
703 }
704
705 if !proto.Equal(instanceInfo, expectedInstanceInfo) {
706 t.Errorf("getInstanceInfo did not return expected instance info: got %v, want %v", instanceInfo, expectedInstanceInfo)
707 }
708 }
709
710 func TestValidateAKGCEAndGetGCEInstanceInfo(t *testing.T) {
711 testCases := []struct {
712 name string
713 certPEM []byte
714 rootCertDER []byte
715 intermediateDER []byte
716 }{
717 {
718 name: "GCE UCA AK ECC",
719 certPEM: test.GCESignECCCertUCA,
720 rootCertDER: gceEKRootCA,
721 intermediateDER: gceEKIntermediateCA3,
722 },
723 {
724 name: "GCE UCA AK RSA",
725 certPEM: test.GCESignRSACertUCA,
726 rootCertDER: gceEKRootCA,
727 intermediateDER: gceEKIntermediateCA3,
728 },
729 {
730 name: "GCE UCA EK ECC",
731 certPEM: test.GCEEncryptECCCertUCA,
732 rootCertDER: gceEKRootCA,
733 intermediateDER: gceEKIntermediateCA3,
734 },
735 {
736 name: "GCE UCA EK RSA",
737 certPEM: test.GCEEncryptRSACertUCA,
738 rootCertDER: gceEKRootCA,
739 intermediateDER: gceEKIntermediateCA3,
740 },
741 {
742 name: "GCE CAS AK ECC",
743 certPEM: test.GCESignECCCertPCA,
744 rootCertDER: gcpCASEKRootCA,
745 intermediateDER: gcpCASEKIntermediateCA3,
746 },
747 {
748 name: "GCE CAS AK RSA",
749 certPEM: test.GCESignRSACertPCA,
750 rootCertDER: gcpCASEKRootCA,
751 intermediateDER: gcpCASEKIntermediateCA3,
752 },
753 {
754 name: "GCE CAS EK ECC",
755 certPEM: test.GCEEncryptECCCertPCA,
756 rootCertDER: gcpCASEKRootCA,
757 intermediateDER: gcpCASEKIntermediateCA3,
758 },
759 {
760 name: "GCE CAS EK RSA",
761 certPEM: test.GCEEncryptRSACertPCA,
762 rootCertDER: gcpCASEKRootCA,
763 intermediateDER: gcpCASEKIntermediateCA3,
764 },
765 }
766 for _, tc := range testCases {
767 t.Run(tc.name, func(t *testing.T) {
768 crtBlock, _ := pem.Decode(tc.certPEM)
769 if crtBlock.Bytes == nil {
770 t.Fatalf("failed to pem.Decode(tc.certPEM)")
771 }
772
773 akCrt, err := x509.ParseCertificate(crtBlock.Bytes)
774 if err != nil {
775 t.Fatalf("x509.ParseCertificate(crtBlock.Bytes): %v", err)
776 }
777 root, err := x509.ParseCertificate(tc.rootCertDER)
778 if err != nil {
779 t.Fatalf("x509.ParseCertificate(tc.rootCertDER): %v", err)
780 }
781 intermediate, err := x509.ParseCertificate(tc.intermediateDER)
782 if err != nil {
783 t.Fatalf("x509.ParseCertificate(tc.intermediateDER): %v", err)
784 }
785
786 if err := VerifyAKCert(akCrt, []*x509.Certificate{root}, []*x509.Certificate{intermediate}); err != nil {
787 t.Errorf("ValidateAKCert(%v): %v)", tc.name, err)
788 }
789
790 if gceInfo, err := GetGCEInstanceInfo(akCrt); err != nil {
791 t.Errorf("GetGCEInstanceInfo(akCrt): %v", err)
792 } else {
793 t.Log(gceInfo)
794 fmt.Print(gceInfo)
795 }
796 })
797 }
798 }
799
800 func TestVerifyAttestationHashAlgo(t *testing.T) {
801 tests := []struct {
802 name string
803 allowSHA1 bool
804 hashAlgo tpm2.Algorithm
805 wantErrStr string
806 }{
807 {
808 "SHA1, Allowed",
809 true,
810 tpm2.AlgSHA1,
811 "",
812 },
813 {
814 "SHA1, Not Allowed",
815 false,
816 tpm2.AlgSHA1,
817 errSHA1NotAllowed.Error(),
818 },
819 {
820 "SHA256",
821 false,
822 tpm2.AlgSHA256,
823 "",
824 },
825 {
826 "SHA384",
827 false,
828 tpm2.AlgSHA384,
829 "",
830 },
831 {
832 "SHA256, SHA1 Allowed",
833 true,
834 tpm2.AlgSHA256,
835 "",
836 },
837 {
838 "SHA384, SHA1 Allowed",
839 true,
840 tpm2.AlgSHA384,
841 "",
842 },
843 {
844 "SHA512",
845 false,
846 tpm2.AlgSHA512,
847 errNoSupportedQuote.Error(),
848 },
849 {
850 "AES",
851 false,
852 tpm2.AlgAES,
853 "hash algorithm AES is not supported",
854 },
855 }
856 for _, tc := range tests {
857 t.Run(tc.name, func(t *testing.T) {
858 attestBytes := test.COS85NoNonce
859 att := &attestpb.Attestation{}
860 if err := proto.Unmarshal(attestBytes, att); err != nil {
861 t.Fatalf("failed to unmarshal attestation: %v", err)
862 }
863
864 _, err := VerifyAttestation(att, VerifyOpts{
865 AllowSHA1: tc.allowSHA1,
866 HashAlgo: tc.hashAlgo,
867 TrustedRootCerts: GceEKRoots,
868 IntermediateCerts: GceEKIntermediates,
869 })
870 if tc.wantErrStr == "" {
871 if err != nil {
872 t.Errorf("VerifyAttestation(%v) unexpected error: %v", tc.name, err)
873 }
874 } else {
875 if err == nil || !strings.Contains(err.Error(), tc.wantErrStr) {
876 t.Errorf("VerifyAttestation(%v) err = %v, want substring = %v", tc.name, err, tc.wantErrStr)
877 }
878 }
879 })
880 }
881 }