Debian Codegraph @

tpm2/test/policy_test.go

raw
1 package tpm2test
2
3 import (
4 "bytes"
5 "crypto/sha1"
6 "crypto/sha256"
7 "testing"
8
9 . "github.com/google/go-tpm/tpm2"
10 "github.com/google/go-tpm/tpm2/transport"
11 "github.com/google/go-tpm/tpm2/transport/simulator"
12 )
13
14 // This test isn't interesting, but it checks that you can omit the handles on `StartAuthSession`.
15 func TestCreatePolicySession(t *testing.T) {
16 for _, tc := range []struct {
17 name string
18 typ TPMSE
19 }{
20 {
21 "trial",
22 TPMSETrial,
23 },
24 {
25 "policy",
26 TPMSEPolicy,
27 },
28 } {
29 t.Run(tc.name, func(t *testing.T) {
30 thetpm, err := simulator.OpenSimulator()
31 if err != nil {
32 t.Fatalf("could not connect to TPM simulator: %v", err)
33 }
34 defer thetpm.Close()
35
36 sas, err := StartAuthSession{
37 SessionType: tc.typ,
38 AuthHash: TPMAlgSHA256,
39 NonceCaller: TPM2BNonce{
40 Buffer: make([]byte, 16),
41 },
42 }.Execute(thetpm)
43 if err != nil {
44 t.Fatalf("StartAuthSession() = %v", err)
45 }
46
47 pgd, err := PolicyGetDigest{
48 PolicySession: sas.SessionHandle,
49 }.Execute(thetpm)
50 if err != nil {
51 t.Fatalf("PolicyGetDigest() = %v", err)
52 }
53 if digest := pgd.PolicyDigest.Buffer; !bytes.Equal(digest, make([]byte, len(digest))) {
54 t.Errorf("PolicyGetDigest() = %x, want all zeros", digest)
55 }
56
57 _, err = FlushContext{
58 FlushHandle: sas.SessionHandle,
59 }.Execute(thetpm)
60 if err != nil {
61 t.Errorf("FlushContext() = %v", err)
62 }
63 })
64 }
65 }
66
67 func signingKey(t *testing.T, thetpm transport.TPM) (NamedHandle, func()) {
68 t.Helper()
69 createPrimary := CreatePrimary{
70 PrimaryHandle: TPMRHOwner,
71 InPublic: New2B(TPMTPublic{
72 Type: TPMAlgECC,
73 NameAlg: TPMAlgSHA256,
74 ObjectAttributes: TPMAObject{
75 FixedTPM: true,
76 FixedParent: true,
77 SensitiveDataOrigin: true,
78 UserWithAuth: true,
79 SignEncrypt: true,
80 },
81 Parameters: NewTPMUPublicParms(
82 TPMAlgECC,
83 &TPMSECCParms{
84 Scheme: TPMTECCScheme{
85 Scheme: TPMAlgECDSA,
86 Details: NewTPMUAsymScheme(
87 TPMAlgECDSA,
88 &TPMSSigSchemeECDSA{
89 HashAlg: TPMAlgSHA256,
90 },
91 ),
92 },
93 CurveID: TPMECCNistP256,
94 },
95 ),
96 }),
97 }
98 rsp, err := createPrimary.Execute(thetpm)
99 if err != nil {
100 t.Fatalf("could not create key: %v", err)
101 }
102 cleanup := func() {
103 t.Helper()
104 flush := FlushContext{
105 FlushHandle: rsp.ObjectHandle,
106 }
107 if _, err := flush.Execute(thetpm); err != nil {
108 t.Errorf("could not flush signing key: %v", err)
109 }
110 }
111 return NamedHandle{
112 Handle: rsp.ObjectHandle,
113 Name: rsp.Name,
114 }, cleanup
115 }
116
117 func nvIndex(t *testing.T, thetpm transport.TPM) (NamedHandle, func()) {
118 t.Helper()
119 defSpace := NVDefineSpace{
120 AuthHandle: TPMRHOwner,
121 PublicInfo: New2B(
122 TPMSNVPublic{
123 NVIndex: 0x01800001,
124 NameAlg: TPMAlgSHA256,
125 Attributes: TPMANV{
126 OwnerWrite: true,
127 AuthRead: true,
128 NT: TPMNTOrdinary,
129 },
130 }),
131 }
132 if _, err := defSpace.Execute(thetpm); err != nil {
133 t.Fatalf("could not create NV index: %v", err)
134 }
135 pub, err := defSpace.PublicInfo.Contents()
136 if err != nil {
137 t.Fatalf("%v", err)
138 }
139 readPub := NVReadPublic{
140 NVIndex: pub.NVIndex,
141 }
142 readRsp, err := readPub.Execute(thetpm)
143 if err != nil {
144 t.Fatalf("could not read NV index public info: %v", err)
145 }
146 cleanup := func() {
147 t.Helper()
148 undefine := NVUndefineSpace{
149 AuthHandle: TPMRHOwner,
150 NVIndex: NamedHandle{
151 Handle: pub.NVIndex,
152 Name: readRsp.NVName,
153 },
154 }
155 if _, err := undefine.Execute(thetpm); err != nil {
156 t.Errorf("could not undefine NV index: %v", err)
157 }
158 }
159 return NamedHandle{
160 Handle: pub.NVIndex,
161 Name: readRsp.NVName,
162 }, cleanup
163 }
164
165 func primaryRSASRK(t *testing.T, thetpm transport.TPM) (NamedHandle, func()) {
166 t.Helper()
167 createPrimary := CreatePrimary{
168 PrimaryHandle: TPMRHOwner,
169 InPublic: New2B(RSASRKTemplate),
170 }
171 rsp, err := createPrimary.Execute(thetpm)
172 if err != nil {
173 t.Fatalf("could not create primary key: %v", err)
174 }
175 cleanup := func() {
176 t.Helper()
177 flush := FlushContext{
178 FlushHandle: rsp.ObjectHandle,
179 }
180 if _, err := flush.Execute(thetpm); err != nil {
181 t.Errorf("could not flush primary key: %v", err)
182 }
183 }
184 return NamedHandle{
185 Handle: rsp.ObjectHandle,
186 Name: rsp.Name,
187 }, cleanup
188 }
189
190 func primaryRSAEK(t *testing.T, thetpm transport.TPM) (NamedHandle, func()) {
191 t.Helper()
192 createPrimary := CreatePrimary{
193 PrimaryHandle: TPMRHEndorsement,
194 InPublic: New2B(RSAEKTemplate),
195 }
196 rsp, err := createPrimary.Execute(thetpm)
197 if err != nil {
198 t.Fatalf("could not create primary key: %v", err)
199 }
200 cleanup := func() {
201 t.Helper()
202 flush := FlushContext{
203 FlushHandle: rsp.ObjectHandle,
204 }
205 if _, err := flush.Execute(thetpm); err != nil {
206 t.Errorf("could not flush primary key: %v", err)
207 }
208 }
209 return NamedHandle{
210 Handle: rsp.ObjectHandle,
211 Name: rsp.Name,
212 }, cleanup
213 }
214
215 func TestPolicySignedUpdate(t *testing.T) {
216 thetpm, err := simulator.OpenSimulator()
217 if err != nil {
218 t.Fatalf("could not connect to TPM simulator: %v", err)
219 }
220 defer thetpm.Close()
221
222 sk, cleanup := signingKey(t, thetpm)
223 defer cleanup()
224
225 // Use a trial session to calculate this policy
226 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
227 if err != nil {
228 t.Fatalf("setting up policy session: %v", err)
229 }
230 defer func() {
231 t.Helper()
232 if err := cleanup2(); err != nil {
233 t.Errorf("cleaning up policy session: %v", err)
234 }
235 }()
236
237 policySigned := PolicySigned{
238 AuthObject: sk,
239 PolicySession: sess.Handle(),
240 PolicyRef: TPM2BNonce{Buffer: []byte{5, 6, 7, 8}},
241 Auth: TPMTSignature{
242 SigAlg: TPMAlgECDSA,
243 Signature: NewTPMUSignature(
244 TPMAlgECDSA,
245 &TPMSSignatureECC{
246 Hash: TPMAlgSHA256,
247 },
248 ),
249 },
250 }
251
252 if _, err := policySigned.Execute(thetpm); err != nil {
253 t.Fatalf("executing PolicySigned: %v", err)
254 }
255
256 pgd := PolicyGetDigest{
257 PolicySession: sess.Handle(),
258 }
259 want, err := pgd.Execute(thetpm)
260 if err != nil {
261 t.Fatalf("executing PolicyGetDigest: %v", err)
262 }
263
264 // Use the policy helper to calculate the same policy
265 pol, err := NewPolicyCalculator(TPMAlgSHA256)
266 if err != nil {
267 t.Fatalf("creating policy calculator: %v", err)
268 }
269 policySigned.Update(pol)
270 got := pol.Hash()
271
272 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
273 t.Errorf("policySigned.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
274 }
275 }
276
277 func TestPolicySecretUpdate(t *testing.T) {
278 thetpm, err := simulator.OpenSimulator()
279 if err != nil {
280 t.Fatalf("could not connect to TPM simulator: %v", err)
281 }
282 defer thetpm.Close()
283
284 sk, cleanup := signingKey(t, thetpm)
285 defer cleanup()
286
287 // Use a trial session to calculate this policy
288 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
289 if err != nil {
290 t.Fatalf("setting up policy session: %v", err)
291 }
292 defer func() {
293 t.Helper()
294 if err := cleanup2(); err != nil {
295 t.Errorf("cleaning up policy session: %v", err)
296 }
297 }()
298
299 policySecret := PolicySecret{
300 AuthHandle: NamedHandle{
301 Handle: sk.Handle,
302 Name: sk.Name,
303 },
304 PolicySession: sess.Handle(),
305 PolicyRef: TPM2BNonce{Buffer: []byte{5, 6, 7, 8}},
306 }
307
308 if _, err := policySecret.Execute(thetpm); err != nil {
309 t.Fatalf("executing PolicySecret: %v", err)
310 }
311
312 pgd := PolicyGetDigest{
313 PolicySession: sess.Handle(),
314 }
315 want, err := pgd.Execute(thetpm)
316 if err != nil {
317 t.Fatalf("executing PolicyGetDigest: %v", err)
318 }
319
320 // Use the policy helper to calculate the same policy
321 pol, err := NewPolicyCalculator(TPMAlgSHA256)
322 if err != nil {
323 t.Fatalf("creating policy calculator: %v", err)
324 }
325 policySecret.Update(pol)
326 got := pol.Hash()
327
328 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
329 t.Errorf("policySecret.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
330 }
331 }
332
333 func TestPolicyOrUpdate(t *testing.T) {
334 thetpm, err := simulator.OpenSimulator()
335 if err != nil {
336 t.Fatalf("could not connect to TPM simulator: %v", err)
337 }
338 defer thetpm.Close()
339
340 // Use a trial session to calculate this policy
341 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
342 if err != nil {
343 t.Fatalf("setting up policy session: %v", err)
344 }
345 defer func() {
346 t.Helper()
347 if err := cleanup2(); err != nil {
348 t.Errorf("cleaning up policy session: %v", err)
349 }
350 }()
351
352 policyOr := PolicyOr{
353 PolicySession: sess.Handle(),
354 PHashList: TPMLDigest{
355 Digests: []TPM2BDigest{
356 {Buffer: []byte{1, 2, 3}},
357 {Buffer: []byte{4, 5, 6}},
358 },
359 },
360 }
361
362 if _, err := policyOr.Execute(thetpm); err != nil {
363 t.Fatalf("executing PolicyOr: %v", err)
364 }
365
366 pgd := PolicyGetDigest{
367 PolicySession: sess.Handle(),
368 }
369 want, err := pgd.Execute(thetpm)
370 if err != nil {
371 t.Fatalf("executing PolicyGetDigest: %v", err)
372 }
373
374 // Use the policy helper to calculate the same policy
375 pol, err := NewPolicyCalculator(TPMAlgSHA256)
376 if err != nil {
377 t.Fatalf("creating policy calculator: %v", err)
378 }
379 policyOr.Update(pol)
380 got := pol.Hash()
381
382 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
383 t.Errorf("policyOr.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
384 }
385 }
386
387 func getExpectedPCRDigest(t *testing.T, thetpm transport.TPM, selection TPMLPCRSelection, hashAlg TPMAlgID) []byte {
388 t.Helper()
389 pcrRead := PCRRead{
390 PCRSelectionIn: selection,
391 }
392
393 pcrReadRsp, err := pcrRead.Execute(thetpm)
394 if err != nil {
395 t.Fatalf("failed to read PCRs")
396 }
397
398 var expectedVal []byte
399 for _, digest := range pcrReadRsp.PCRValues.Digests {
400 expectedVal = append(expectedVal, digest.Buffer...)
401 }
402
403 cryptoHashAlg, err := hashAlg.Hash()
404 if err != nil {
405 t.Fatalf("failed to get crypto hash")
406 }
407
408 hash := cryptoHashAlg.New()
409 hash.Write(expectedVal)
410 return hash.Sum(nil)
411 }
412
413 func TestPolicyPCR(t *testing.T) {
414 thetpm, err := simulator.OpenSimulator()
415 if err != nil {
416 t.Fatalf("could not connect to TPM simulator: %v", err)
417 }
418 defer thetpm.Close()
419
420 selection := TPMLPCRSelection{
421 PCRSelections: []TPMSPCRSelection{
422 {
423 Hash: TPMAlgSHA1,
424 PCRSelect: PCClientCompatible.PCRs(0, 1, 2, 3, 7),
425 },
426 },
427 }
428
429 expectedDigest := getExpectedPCRDigest(t, thetpm, selection, TPMAlgSHA1)
430
431 wrongDigest := sha1.Sum(expectedDigest[:])
432
433 tests := []struct {
434 name string
435 authOption []AuthOption
436 pcrDigest []byte
437 callShouldSucceed bool
438 }{
439 {"TrialCorrect", []AuthOption{Trial()}, expectedDigest, true},
440 {"TrialIncorrect", []AuthOption{Trial()}, wrongDigest[:], true},
441 {"TrialEmpty", []AuthOption{Trial()}, nil, true},
442 {"RealCorrect", nil, expectedDigest, true},
443 {"RealIncorrect", nil, wrongDigest[:], false},
444 {"RealEmpty", nil, nil, true},
445 }
446
447 for _, tt := range tests {
448 t.Run(tt.name, func(t *testing.T) {
449 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA1, 16, tt.authOption...)
450
451 if err != nil {
452 t.Fatalf("setting up policy session: %v", err)
453 }
454
455 policyPCR := PolicyPCR{
456 PolicySession: sess.Handle(),
457 PcrDigest: TPM2BDigest{
458 Buffer: tt.pcrDigest,
459 },
460 Pcrs: selection,
461 }
462
463 _, err = policyPCR.Execute(thetpm)
464 if tt.callShouldSucceed {
465 if err != nil {
466 t.Fatalf("executing PolicyPCR: %v", err)
467 }
468 } else {
469 if err == nil {
470 t.Fatalf("expected PolicyPCR to return error, got nil")
471 }
472 return
473 }
474
475 pgd := PolicyGetDigest{
476 PolicySession: sess.Handle(),
477 }
478 want, err := pgd.Execute(thetpm)
479 if err != nil {
480 t.Fatalf("executing PolicyGetDigest: %v", err)
481 }
482
483 // If the pcrDigest is empty: see TPM 2.0 Part 3, 23.7.
484 if tt.pcrDigest == nil {
485 expectedDigest := getExpectedPCRDigest(t, thetpm, selection, TPMAlgSHA1)
486 t.Logf("expectedDigest=%x", expectedDigest)
487
488 // Create a populated policyPCR for the PolicyCalculator
489 policyPCR.PcrDigest.Buffer = expectedDigest[:]
490 }
491
492 // Use the policy helper to calculate the same policy
493 pol, err := NewPolicyCalculator(TPMAlgSHA1)
494 if err != nil {
495 t.Fatalf("creating policy calculator: %v", err)
496 }
497 policyPCR.Update(pol)
498 got := pol.Hash()
499
500 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
501 t.Errorf("policyPCR.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
502 }
503
504 if err := cleanup2(); err != nil {
505 t.Errorf("cleaning up policy session: %v", err)
506 }
507 })
508 }
509
510 }
511
512 func TestPolicyCpHashUpdate(t *testing.T) {
513 thetpm, err := simulator.OpenSimulator()
514 if err != nil {
515 t.Fatalf("could not connect to TPM simulator: %v", err)
516 }
517 defer thetpm.Close()
518
519 // Use a trial session to calculate this policy
520 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
521 if err != nil {
522 t.Fatalf("setting up policy session: %v", err)
523 }
524 defer func() {
525 t.Helper()
526 if err := cleanup2(); err != nil {
527 t.Errorf("cleaning up policy session: %v", err)
528 }
529 }()
530
531 policyCpHash := PolicyCPHash{
532 PolicySession: sess.Handle(),
533 CPHashA: TPM2BDigest{Buffer: []byte{
534 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
535 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}},
536 }
537
538 if _, err := policyCpHash.Execute(thetpm); err != nil {
539 t.Fatalf("executing PolicyCpHash: %v", err)
540 }
541
542 pgd := PolicyGetDigest{
543 PolicySession: sess.Handle(),
544 }
545 want, err := pgd.Execute(thetpm)
546 if err != nil {
547 t.Fatalf("executing PolicyGetDigest: %v", err)
548 }
549
550 // Use the policy helper to calculate the same policy
551 pol, err := NewPolicyCalculator(TPMAlgSHA256)
552 if err != nil {
553 t.Fatalf("creating policy calculator: %v", err)
554 }
555 policyCpHash.Update(pol)
556 got := pol.Hash()
557
558 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
559 t.Errorf("policyCpHash.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
560 }
561 }
562
563 func TestPolicyAuthorizeUpdate(t *testing.T) {
564 thetpm, err := simulator.OpenSimulator()
565 if err != nil {
566 t.Fatalf("could not connect to TPM simulator: %v", err)
567 }
568 defer thetpm.Close()
569
570 // Use a trial session to calculate this policy
571 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
572 if err != nil {
573 t.Fatalf("setting up policy session: %v", err)
574 }
575 defer func() {
576 t.Helper()
577 if err := cleanup2(); err != nil {
578 t.Errorf("cleaning up policy session: %v", err)
579 }
580 }()
581
582 sk, cleanup := signingKey(t, thetpm)
583 defer cleanup()
584
585 policyAuthorize := PolicyAuthorize{
586 PolicySession: sess.Handle(),
587 PolicyRef: TPM2BDigest{Buffer: []byte{5, 6, 7, 8}},
588 KeySign: sk.Name,
589 CheckTicket: TPMTTKVerified{
590 Tag: TPMSTVerified,
591 Hierarchy: TPMRHEndorsement,
592 },
593 }
594
595 if _, err := policyAuthorize.Execute(thetpm); err != nil {
596 t.Fatalf("executing PolicyAuthorize: %v", err)
597 }
598
599 pgd := PolicyGetDigest{
600 PolicySession: sess.Handle(),
601 }
602 want, err := pgd.Execute(thetpm)
603 if err != nil {
604 t.Fatalf("executing PolicyGetDigest: %v", err)
605 }
606
607 // Use the policy helper to calculate the same policy
608 pol, err := NewPolicyCalculator(TPMAlgSHA256)
609 if err != nil {
610 t.Fatalf("creating policy calculator: %v", err)
611 }
612 policyAuthorize.Update(pol)
613 got := pol.Hash()
614
615 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
616 t.Errorf("policyAuthorize.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
617 }
618 }
619
620 func TestPolicyNVWrittenUpdate(t *testing.T) {
621 thetpm, err := simulator.OpenSimulator()
622 if err != nil {
623 t.Fatalf("could not connect to TPM simulator: %v", err)
624 }
625 defer thetpm.Close()
626
627 // Use a trial session to calculate this policy
628 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
629 if err != nil {
630 t.Fatalf("setting up policy session: %v", err)
631 }
632 defer func() {
633 t.Helper()
634 if err := cleanup2(); err != nil {
635 t.Errorf("cleaning up policy session: %v", err)
636 }
637 }()
638
639 policyNVWritten := PolicyNVWritten{
640 PolicySession: sess.Handle(),
641 WrittenSet: true,
642 }
643
644 if _, err := policyNVWritten.Execute(thetpm); err != nil {
645 t.Fatalf("executing PolicyNVWritten: %v", err)
646 }
647
648 pgd := PolicyGetDigest{
649 PolicySession: sess.Handle(),
650 }
651 want, err := pgd.Execute(thetpm)
652 if err != nil {
653 t.Fatalf("executing PolicyGetDigest: %v", err)
654 }
655
656 // Use the policy helper to calculate the same policy
657 pol, err := NewPolicyCalculator(TPMAlgSHA256)
658 if err != nil {
659 t.Fatalf("creating policy calculator: %v", err)
660 }
661 policyNVWritten.Update(pol)
662 got := pol.Hash()
663
664 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
665 t.Errorf("PolicyNVWritten.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
666 }
667 }
668
669 func TestPolicyNVUpdate(t *testing.T) {
670 thetpm, err := simulator.OpenSimulator()
671 if err != nil {
672 t.Fatalf("could not connect to TPM simulator: %v", err)
673 }
674 defer thetpm.Close()
675
676 nv, cleanup := nvIndex(t, thetpm)
677 defer cleanup()
678
679 // Use a trial session to calculate this policy
680 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
681 if err != nil {
682 t.Fatalf("setting up policy session: %v", err)
683 }
684 defer func() {
685 t.Helper()
686 if err := cleanup2(); err != nil {
687 t.Errorf("cleaning up policy session: %v", err)
688 }
689 }()
690
691 policyNV := PolicyNV{
692 AuthHandle: NamedHandle{Handle: nv.Handle, Name: nv.Name},
693 PolicySession: sess.Handle(),
694 NVIndex: nv,
695 OperandB: TPM2BOperand{Buffer: []byte("operandB")},
696 Offset: 2,
697 Operation: TPMEOSignedLE,
698 }
699
700 if _, err := policyNV.Execute(thetpm); err != nil {
701 t.Fatalf("executing PolicyAuthorizeNV: %v", err)
702 }
703
704 pgd := PolicyGetDigest{
705 PolicySession: sess.Handle(),
706 }
707 want, err := pgd.Execute(thetpm)
708 if err != nil {
709 t.Fatalf("executing PolicyGetDigest: %v", err)
710 }
711
712 // Use the policy helper to calculate the same policy
713 pol, err := NewPolicyCalculator(TPMAlgSHA256)
714 if err != nil {
715 t.Fatalf("creating policy calculator: %v", err)
716 }
717 policyNV.Update(pol)
718 got := pol.Hash()
719
720 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
721 t.Errorf("PolicyAuthorizeNV.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
722 }
723 }
724
725 func TestPolicyAuthorizeNVUpdate(t *testing.T) {
726 thetpm, err := simulator.OpenSimulator()
727 if err != nil {
728 t.Fatalf("could not connect to TPM simulator: %v", err)
729 }
730 defer thetpm.Close()
731
732 nv, cleanup := nvIndex(t, thetpm)
733 defer cleanup()
734
735 // Use a trial session to calculate this policy
736 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
737 if err != nil {
738 t.Fatalf("setting up policy session: %v", err)
739 }
740 defer func() {
741 t.Helper()
742 if err := cleanup2(); err != nil {
743 t.Errorf("cleaning up policy session: %v", err)
744 }
745 }()
746
747 policyAuthorizeNV := PolicyAuthorizeNV{
748 AuthHandle: NamedHandle{Handle: nv.Handle, Name: nv.Name},
749 PolicySession: sess.Handle(),
750 NVIndex: nv,
751 }
752
753 if _, err := policyAuthorizeNV.Execute(thetpm); err != nil {
754 t.Fatalf("executing PolicyAuthorizeNV: %v", err)
755 }
756
757 pgd := PolicyGetDigest{
758 PolicySession: sess.Handle(),
759 }
760 want, err := pgd.Execute(thetpm)
761 if err != nil {
762 t.Fatalf("executing PolicyGetDigest: %v", err)
763 }
764
765 // Use the policy helper to calculate the same policy
766 pol, err := NewPolicyCalculator(TPMAlgSHA256)
767 if err != nil {
768 t.Fatalf("creating policy calculator: %v", err)
769 }
770 policyAuthorizeNV.Update(pol)
771 got := pol.Hash()
772
773 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
774 t.Errorf("PolicyAuthorizeNV.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
775 }
776 }
777
778 func TestPolicyCommandCodeUpdate(t *testing.T) {
779 thetpm, err := simulator.OpenSimulator()
780 if err != nil {
781 t.Fatalf("could not connect to TPM simulator: %v", err)
782 }
783 defer thetpm.Close()
784
785 // Use a trial session to calculate this policy
786 sess, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
787 if err != nil {
788 t.Fatalf("setting up policy session: %v", err)
789 }
790 defer func() {
791 t.Helper()
792 if err := cleanup2(); err != nil {
793 t.Errorf("cleaning up policy session: %v", err)
794 }
795 }()
796
797 pcc := PolicyCommandCode{
798 PolicySession: sess.Handle(),
799 Code: TPMCCCreate,
800 }
801 if _, err := pcc.Execute(thetpm); err != nil {
802 t.Fatalf("executing PolicyCommandCode: %v", err)
803 }
804
805 pgd := PolicyGetDigest{
806 PolicySession: sess.Handle(),
807 }
808 want, err := pgd.Execute(thetpm)
809 if err != nil {
810 t.Fatalf("executing PolicyGetDigest: %v", err)
811 }
812
813 // Use the policy helper to calculate the same policy
814 pol, err := NewPolicyCalculator(TPMAlgSHA256)
815 if err != nil {
816 t.Fatalf("creating policy calculator: %v", err)
817 }
818 pcc.Update(pol)
819 got := pol.Hash()
820
821 if !bytes.Equal(got.Digest, want.PolicyDigest.Buffer) {
822 t.Errorf("PolicyCommandCode.Hash() = %x,\nwant %x", got.Digest, want.PolicyDigest.Buffer)
823 }
824 }
825
826 func TestPolicyAuthValue(t *testing.T) {
827 thetpm, err := simulator.OpenSimulator()
828 if err != nil {
829 t.Fatalf("could not connect to TPM simulator: %v", err)
830 }
831 defer thetpm.Close()
832
833 password := []byte("foo")
834 wrongPassword := []byte("bar")
835
836 tests := []struct {
837 name string
838 password []byte
839 authOption []AuthOption
840 callShouldSucceed bool
841 }{
842 {"PasswordCorrect", password, []AuthOption{Auth(password)}, true},
843 {"PasswordIncorrect", wrongPassword, []AuthOption{Auth(password)}, false},
844 {"PasswordEmpty", nil, []AuthOption{Auth(password)}, false},
845 {"AuthOptionEmpty", password, []AuthOption{}, false},
846 }
847
848 for _, tt := range tests {
849 t.Run(tt.name, func(t *testing.T) {
850
851 pk, pkcleanup := primaryRSASRK(t, thetpm)
852 defer pkcleanup()
853
854 // create a trial policy with PolicyAuthValue
855 sess, cleanup1, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
856 if err != nil {
857 t.Fatalf("setting up trial session: %v", err)
858 }
859 defer func() {
860 t.Helper()
861 if err := cleanup1(); err != nil {
862 t.Errorf("cleaning up trial session: %v", err)
863 }
864 }()
865
866 pav := PolicyAuthValue{
867 PolicySession: sess.Handle(),
868 }
869 _, err = pav.Execute(thetpm)
870 if err != nil {
871 t.Fatalf("error executing policyAuthValue: %v", err)
872 }
873
874 // verify the digest
875 pgd, err := PolicyGetDigest{
876 PolicySession: sess.Handle(),
877 }.Execute(thetpm)
878 if err != nil {
879 t.Fatalf("error executing PolicyGetDigest: %v", pgd)
880 }
881
882 // Use the policy helper to calculate the same policy
883 pol, err := NewPolicyCalculator(TPMAlgSHA256)
884 if err != nil {
885 t.Fatalf("creating policy calculator: %v", err)
886 }
887 pav.Update(pol)
888 got := pol.Hash()
889
890 if !bytes.Equal(got.Digest, pgd.PolicyDigest.Buffer) {
891 t.Errorf("PolicyAuthValue.Hash() = %x,\nwant %x", got.Digest, pgd.PolicyDigest.Buffer)
892 }
893
894 // now apply the policy to a new key
895 rsaTemplate := TPMTPublic{
896 Type: TPMAlgRSA,
897 NameAlg: TPMAlgSHA256,
898 ObjectAttributes: TPMAObject{
899 SignEncrypt: true,
900 FixedTPM: true,
901 FixedParent: true,
902 SensitiveDataOrigin: true,
903 UserWithAuth: true,
904 },
905 AuthPolicy: pgd.PolicyDigest,
906 Parameters: NewTPMUPublicParms(
907 TPMAlgRSA,
908 &TPMSRSAParms{
909 Scheme: TPMTRSAScheme{
910 Scheme: TPMAlgRSASSA,
911 Details: NewTPMUAsymScheme(
912 TPMAlgRSASSA,
913 &TPMSSigSchemeRSASSA{
914 HashAlg: TPMAlgSHA256,
915 },
916 ),
917 },
918 KeyBits: 2048,
919 },
920 ),
921 }
922
923 k, err := CreateLoaded{
924 ParentHandle: AuthHandle{
925 Handle: pk.Handle,
926 Name: pk.Name,
927 Auth: PasswordAuth(nil),
928 },
929 InPublic: New2BTemplate(&rsaTemplate),
930 InSensitive: TPM2BSensitiveCreate{
931 Sensitive: &TPMSSensitiveCreate{
932 UserAuth: TPM2BAuth{
933 Buffer: tt.password,
934 },
935 },
936 },
937 }.Execute(thetpm)
938 if err != nil {
939 t.Fatalf("error creating key %v", err)
940 }
941 defer func() {
942 t.Helper()
943 _, err := FlushContext{
944 FlushHandle: k.ObjectHandle,
945 }.Execute(thetpm)
946 if err != nil {
947 t.Errorf("error cleaning up key: %v", err)
948 }
949 }()
950
951 // create a real policy session and use the password through the authOption
952 sess2, cleanup2, err := PolicySession(thetpm, TPMAlgSHA256, 16, tt.authOption...)
953 if err != nil {
954 t.Fatalf("setting up policy session: %v", err)
955 }
956 defer cleanup2()
957
958 policyAuthValue2 := PolicyAuthValue{
959 PolicySession: sess2.Handle(),
960 }
961
962 _, err = policyAuthValue2.Execute(thetpm)
963 if err != nil {
964 t.Fatalf("executing policyAuthValue: %v", err)
965 }
966
967 // sign some data with the key using the session
968 data := []byte("somedata")
969 digest := sha256.Sum256(data)
970
971 sign := Sign{
972 KeyHandle: AuthHandle{
973 Handle: k.ObjectHandle,
974 Name: k.Name,
975 Auth: sess2,
976 },
977 Digest: TPM2BDigest{
978 Buffer: digest[:],
979 },
980 InScheme: TPMTSigScheme{
981 Scheme: TPMAlgRSASSA,
982 Details: NewTPMUSigScheme(
983 TPMAlgRSASSA,
984 &TPMSSchemeHash{
985 HashAlg: TPMAlgSHA256,
986 },
987 ),
988 },
989 Validation: TPMTTKHashCheck{
990 Tag: TPMSTHashCheck,
991 },
992 }
993
994 _, err = sign.Execute(thetpm)
995 if tt.callShouldSucceed {
996 if err != nil {
997 t.Fatalf("expected no error for PolicyAuthValue but got: %v", err)
998 }
999 } else {
1000 if err == nil {
1001 t.Fatalf("expected error for PolicyAuthValue, got nil")
1002 }
1003 return
1004 }
1005 })
1006 }
1007
1008 }
1009
1010 func TestPolicyDuplicationSelectUpdate(t *testing.T) {
1011 thetpm, err := simulator.OpenSimulator()
1012 if err != nil {
1013 t.Fatalf("could not connect to TPM simulator: %v", err)
1014 }
1015 defer thetpm.Close()
1016
1017 ek, ekcleanup := primaryRSAEK(t, thetpm)
1018 defer ekcleanup()
1019
1020 pk, pkcleanup := primaryRSASRK(t, thetpm)
1021 defer pkcleanup()
1022
1023 k, err := CreateLoaded{
1024 ParentHandle: AuthHandle{
1025 Handle: pk.Handle,
1026 Name: pk.Name,
1027 Auth: PasswordAuth(nil),
1028 },
1029 InPublic: New2BTemplate(&TPMTPublic{
1030 Type: TPMAlgRSA,
1031 NameAlg: TPMAlgSHA256,
1032 ObjectAttributes: TPMAObject{
1033 FixedTPM: false,
1034 FixedParent: false,
1035 SensitiveDataOrigin: true,
1036 UserWithAuth: true,
1037 SignEncrypt: true,
1038 },
1039 Parameters: NewTPMUPublicParms(
1040 TPMAlgRSA,
1041 &TPMSRSAParms{
1042 Scheme: TPMTRSAScheme{
1043 Scheme: TPMAlgRSASSA,
1044 Details: NewTPMUAsymScheme(
1045 TPMAlgRSASSA,
1046 &TPMSSigSchemeRSASSA{
1047 HashAlg: TPMAlgSHA256,
1048 },
1049 ),
1050 },
1051 KeyBits: 2048,
1052 },
1053 ),
1054 }),
1055 }.Execute(thetpm)
1056 if err != nil {
1057 t.Fatalf("error creating key %v", err)
1058 }
1059 defer func() {
1060 t.Helper()
1061 _, err := FlushContext{
1062 FlushHandle: k.ObjectHandle,
1063 }.Execute(thetpm)
1064 if err != nil {
1065 t.Errorf("error cleaning up key: %v", err)
1066 }
1067 }()
1068
1069 tests := []struct {
1070 name string
1071 objectName TPM2BName
1072 includeObject bool
1073 }{
1074 {"IncludeObjectFalse", TPM2BName{}, false},
1075 {"IncludeObjectTrue", k.Name, true},
1076 }
1077
1078 for _, tt := range tests {
1079 t.Run(tt.name, func(t *testing.T) {
1080
1081 // create a trial policy with PolicyDuplicationSelect
1082 sess, cleanup1, err := PolicySession(thetpm, TPMAlgSHA256, 16, Trial())
1083 if err != nil {
1084 t.Fatalf("error setting up trial session: %v", err)
1085 }
1086 defer func() {
1087 t.Helper()
1088 if err := cleanup1(); err != nil {
1089 t.Errorf("error cleaning up trial session: %v", err)
1090 }
1091 }()
1092
1093 pds := PolicyDuplicationSelect{
1094 PolicySession: sess.Handle(),
1095 NewParentName: ek.Name,
1096 ObjectName: tt.objectName,
1097 IncludeObject: tt.includeObject,
1098 }
1099 _, err = pds.Execute(thetpm)
1100 if err != nil {
1101 t.Fatalf("error executing PolicyDuplicationSelect: %v", err)
1102 }
1103
1104 pdr, err := PolicyGetDigest{
1105 PolicySession: sess.Handle(),
1106 }.Execute(thetpm)
1107 if err != nil {
1108 t.Fatalf("error executing PolicyGetDigest: %v", pdr)
1109 }
1110
1111 // Use the policy helper to calculate the same policy
1112 pol, err := NewPolicyCalculator(TPMAlgSHA256)
1113 if err != nil {
1114 t.Fatalf("creating policy calculator: %v", err)
1115 }
1116 err = pds.Update(pol)
1117 if err != nil {
1118 t.Fatalf("error updating policy calculator: %v", err)
1119 }
1120 got := pol.Hash()
1121
1122 if !bytes.Equal(got.Digest, pdr.PolicyDigest.Buffer) {
1123 t.Errorf("PolicyAuthValue.Hash() = %x,\nwant %x", got.Digest, pdr.PolicyDigest.Buffer)
1124 }
1125 })
1126 }
1127 }