Debian Codegraph @

tpm2/crypto_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package tpm2
2
3 import (
4 "crypto"
5 "crypto/ecdsa"
6 "crypto/elliptic"
7 "crypto/rand"
8 "crypto/rsa"
9 "crypto/sha256"
10 "math/big"
11 "reflect"
12 "testing"
13
14 "github.com/google/go-tpm/tpm2/transport"
15 "github.com/google/go-tpm/tpm2/transport/simulator"
16 )
17
18 // Subtle: Some RSA crypto libraries compute D (the private exponent)
19 // based on phi(N) (Euler's totient function). Phi(N) is the order of the
20 // multiplicative group of integers modulo N.
21 // Other libraries compute lambda(N), the Carmichael function: the
22 // minimum order among all the elements of the multiplicative group of
23 // integers modulo N. Lambda(N) divides phi(N).
24 // This test isn't intended to ensure that the underlying crypto
25 // implementation chooses one or the other, or that it agrees with the
26 // implementation of the tpm2.Priv() function. So, we compare RSA private keys
27 // in tests by checking that the public exponent, modulus, and primes are the
28 // same. We also have tests to ensure that signatures produced by the TPM and
29 // by the software implementation validate (which has the effect of confirming
30 // that the private exponents are correct).
31 func areRSAPrivateKeysEqual(a, b *rsa.PrivateKey) bool {
32 return a.E == b.E &&
33 a.N.Cmp(b.N) == 0 &&
34 reflect.DeepEqual(a.Primes, b.Primes)
35 }
36
37 func TestPriv(t *testing.T) {
38
39 t.Parallel()
40
41 rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048)
42 ecdsaKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
43
44 seed := make([]byte, crypto.SHA256.New().Size())
45 rand.Read(seed)
46
47 tests := map[string]struct {
48 sensitive TPMTSensitive
49 public TPMTPublic
50 result bool
51 }{
52 "valid rsa": {
53 sensitive: TPMTSensitive{
54 SensitiveType: TPMAlgRSA,
55 AuthValue: TPM2BAuth{
56 Buffer: nil,
57 },
58 SeedValue: TPM2BDigest{
59 Buffer: seed,
60 },
61 Sensitive: NewTPMUSensitiveComposite(
62 TPMAlgRSA,
63 &TPM2BPrivateKeyRSA{
64 Buffer: rsaKey.Primes[0].Bytes(),
65 },
66 ),
67 },
68 public: TPMTPublic{
69 Type: TPMAlgRSA,
70 NameAlg: TPMAlgSHA256,
71 ObjectAttributes: TPMAObject{
72 FixedTPM: true,
73 STClear: false,
74 FixedParent: true,
75 SensitiveDataOrigin: true,
76 UserWithAuth: true,
77 AdminWithPolicy: false,
78 NoDA: false,
79 EncryptedDuplication: false,
80 Restricted: true,
81 Decrypt: true,
82 SignEncrypt: false,
83 },
84 Parameters: NewTPMUPublicParms(
85 TPMAlgRSA,
86 &TPMSRSAParms{
87 KeyBits: TPMKeyBits(rsaKey.PublicKey.N.BitLen()),
88 Exponent: 0,
89 Symmetric: TPMTSymDefObject{
90 Algorithm: TPMAlgAES,
91 Mode: NewTPMUSymMode(
92 TPMAlgAES,
93 TPMAlgCFB,
94 ),
95 KeyBits: NewTPMUSymKeyBits(
96 TPMAlgAES,
97 TPMKeyBits(128),
98 ),
99 },
100 },
101 ),
102 Unique: NewTPMUPublicID(
103 TPMAlgRSA,
104 &TPM2BPublicKeyRSA{
105 Buffer: rsaKey.PublicKey.N.Bytes(),
106 },
107 ),
108 },
109 result: true,
110 },
111 "valid ecdsa": {
112 sensitive: TPMTSensitive{
113 SensitiveType: TPMAlgECC,
114 AuthValue: TPM2BAuth{
115 Buffer: nil,
116 },
117 SeedValue: TPM2BDigest{
118 Buffer: seed,
119 },
120 Sensitive: NewTPMUSensitiveComposite(
121 TPMAlgECC,
122 &TPM2BECCParameter{Buffer: ecdsaKey.D.FillBytes(make([]byte, len(ecdsaKey.D.Bytes())))},
123 ),
124 },
125 public: TPMTPublic{
126 Type: TPMAlgECC,
127 NameAlg: TPMAlgSHA256,
128 ObjectAttributes: TPMAObject{
129 FixedTPM: true,
130 STClear: false,
131 FixedParent: true,
132 SensitiveDataOrigin: true,
133 UserWithAuth: true,
134 AdminWithPolicy: false,
135 NoDA: false,
136 EncryptedDuplication: false,
137 Restricted: true,
138 Decrypt: true,
139 SignEncrypt: false,
140 },
141 Parameters: NewTPMUPublicParms(
142 TPMAlgECC,
143 &TPMSECCParms{
144 CurveID: TPMECCNistP256,
145 Scheme: TPMTECCScheme{
146 Scheme: TPMAlgECDSA,
147 Details: NewTPMUAsymScheme(
148 TPMAlgECDSA,
149 &TPMSSigSchemeECDSA{
150 HashAlg: TPMAlgSHA256,
151 },
152 ),
153 },
154 },
155 ),
156 Unique: NewTPMUPublicID(
157 TPMAlgECC,
158 &TPMSECCPoint{
159 X: TPM2BECCParameter{
160 Buffer: ecdsaKey.X.Bytes(),
161 },
162 Y: TPM2BECCParameter{
163 Buffer: ecdsaKey.Y.Bytes(),
164 },
165 },
166 ),
167 },
168 result: true,
169 },
170 "public error": {
171 sensitive: TPMTSensitive{},
172 public: TPMTPublic{
173 Type: TPMAlgAES,
174 },
175 result: false,
176 },
177 }
178
179 for name, test := range tests {
180 test := test
181
182 t.Run(name, func(t *testing.T) {
183 t.Parallel()
184
185 key, err := Priv(test.public, test.sensitive)
186
187 if (key != nil) != test.result {
188 t.Errorf("Not equal: \n"+
189 "expected: %v\n"+
190 "actual : %v",
191 test.result,
192 key != nil,
193 )
194 }
195
196 if (err == nil) != test.result {
197 t.Errorf("Not equal: \n"+
198 "expected: %v\n"+
199 "actual : %v",
200 test.result,
201 err == nil,
202 )
203 }
204
205 if key != nil {
206 switch key := key.(type) {
207 case *rsa.PrivateKey:
208 if !areRSAPrivateKeysEqual(rsaKey, key) {
209 t.Errorf("Not equal: \n"+
210 "expected: %v\n"+
211 "actual : %v",
212 rsaKey,
213 key,
214 )
215 }
216 case *ecdsa.PrivateKey:
217 if !reflect.DeepEqual(ecdsaKey, key) {
218 t.Errorf("Not equal: \n"+
219 "expected: %v\n"+
220 "actual : %v",
221 ecdsaKey,
222 key,
223 )
224 }
225 default:
226 t.Fatalf("unexpected case")
227 }
228 }
229 })
230 }
231 }
232
233 func TestPub(t *testing.T) {
234
235 t.Parallel()
236
237 rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048)
238 ecdsaKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
239
240 tests := map[string]struct {
241 public TPMTPublic
242 result bool
243 }{
244 "valid rsa": {
245 public: TPMTPublic{
246 Type: TPMAlgRSA,
247 NameAlg: TPMAlgSHA256,
248 ObjectAttributes: TPMAObject{
249 FixedTPM: true,
250 STClear: false,
251 FixedParent: true,
252 SensitiveDataOrigin: true,
253 UserWithAuth: true,
254 AdminWithPolicy: false,
255 NoDA: false,
256 EncryptedDuplication: false,
257 Restricted: true,
258 Decrypt: true,
259 SignEncrypt: false,
260 },
261 Parameters: NewTPMUPublicParms(
262 TPMAlgRSA,
263 &TPMSRSAParms{
264 KeyBits: TPMKeyBits(rsaKey.PublicKey.N.BitLen()),
265 Exponent: 0,
266 Symmetric: TPMTSymDefObject{
267 Algorithm: TPMAlgAES,
268 Mode: NewTPMUSymMode(
269 TPMAlgAES,
270 TPMAlgCFB,
271 ),
272 KeyBits: NewTPMUSymKeyBits(
273 TPMAlgAES,
274 TPMKeyBits(128),
275 ),
276 },
277 },
278 ),
279 Unique: NewTPMUPublicID(
280 TPMAlgRSA,
281 &TPM2BPublicKeyRSA{
282 Buffer: rsaKey.PublicKey.N.Bytes(),
283 },
284 ),
285 },
286 result: true,
287 },
288 "valid ecdsa": {
289 public: TPMTPublic{
290 Type: TPMAlgECC,
291 NameAlg: TPMAlgSHA256,
292 ObjectAttributes: TPMAObject{
293 FixedTPM: true,
294 STClear: false,
295 FixedParent: true,
296 SensitiveDataOrigin: true,
297 UserWithAuth: true,
298 AdminWithPolicy: false,
299 NoDA: false,
300 EncryptedDuplication: false,
301 Restricted: true,
302 Decrypt: true,
303 SignEncrypt: false,
304 },
305 Parameters: NewTPMUPublicParms(
306 TPMAlgECC,
307 &TPMSECCParms{
308 CurveID: TPMECCNistP256,
309 Scheme: TPMTECCScheme{
310 Scheme: TPMAlgECDSA,
311 Details: NewTPMUAsymScheme(
312 TPMAlgECDSA,
313 &TPMSSigSchemeECDSA{
314 HashAlg: TPMAlgSHA256,
315 },
316 ),
317 },
318 },
319 ),
320 Unique: NewTPMUPublicID(
321 TPMAlgECC,
322 &TPMSECCPoint{
323 X: TPM2BECCParameter{
324 Buffer: ecdsaKey.X.Bytes(),
325 },
326 Y: TPM2BECCParameter{
327 Buffer: ecdsaKey.Y.Bytes(),
328 },
329 },
330 ),
331 },
332 result: true,
333 },
334 "unsupported algorithm": {
335 public: TPMTPublic{
336 Type: TPMAlgAES,
337 },
338 result: false,
339 },
340 }
341
342 for name, test := range tests {
343 test := test
344
345 t.Run(name, func(t *testing.T) {
346 t.Parallel()
347
348 key, err := Pub(test.public)
349
350 if (key != nil) != test.result {
351 t.Errorf("Not equal: \n"+
352 "expected: %v\n"+
353 "actual : %v",
354 test.result,
355 key != nil,
356 )
357 }
358
359 if (err == nil) != test.result {
360 t.Errorf("Not equal: \n"+
361 "expected: %v\n"+
362 "actual : %v",
363 test.result,
364 err == nil,
365 )
366 }
367
368 if key != nil {
369 switch key := key.(type) {
370 case *rsa.PublicKey:
371 if !reflect.DeepEqual(rsaKey.PublicKey, *key) {
372 t.Errorf("Not equal: \n"+
373 "expected: %v\n"+
374 "actual : %v",
375 rsaKey.PublicKey,
376 key,
377 )
378 }
379 case *ecdsa.PublicKey:
380 if !reflect.DeepEqual(ecdsaKey.PublicKey, *key) {
381 t.Errorf("Not equal: \n"+
382 "expected: %v\n"+
383 "actual : %v",
384 ecdsaKey.PublicKey,
385 key,
386 )
387 }
388 default:
389 t.Fatalf("unexpected case")
390 }
391 }
392 })
393 }
394 }
395
396 // A duplication policy callback.
397 func duplicationPolicy(tpm transport.TPM, handle TPMISHPolicy, _ TPM2BNonce) error {
398 _, err := PolicyCommandCode{
399 PolicySession: handle,
400 Code: TPMCCDuplicate,
401 }.Execute(tpm)
402 return err
403 }
404
405 func duplicationPolicyHash() TPM2BDigest {
406 pc, err := NewPolicyCalculator(TPMAlgSHA256)
407 if err != nil {
408 panic(err)
409 }
410 pcc := PolicyCommandCode{
411 Code: TPMCCDuplicate,
412 }
413 if err := pcc.Update(pc); err != nil {
414 panic(err)
415 }
416 return TPM2BDigest{
417 Buffer: pc.Hash().Digest,
418 }
419 }
420
421 func TestRoundTrip(t *testing.T) {
422 tpm, err := simulator.OpenSimulator()
423 if err != nil {
424 t.Fatalf("could not connect to TPM simulator: %v", err)
425 }
426 defer tpm.Close()
427
428 srkCreate, err := CreatePrimary{
429 PrimaryHandle: TPMRHOwner,
430 InPublic: New2B(ECCSRKTemplate),
431 }.Execute(tpm)
432 if err != nil {
433 t.Fatalf("could not create SRK: %v", err)
434 }
435
436 defer FlushContext{
437 FlushHandle: srkCreate.ObjectHandle,
438 }.Execute(tpm)
439
440 for _, tc := range []struct {
441 name string
442 alg TPMAlgID
443 pub TPM2BPublic
444 }{
445 {
446 name: "rsa_2k_pkcs",
447 alg: TPMAlgRSA,
448 pub: New2B(TPMTPublic{
449 Type: TPMAlgRSA,
450 NameAlg: TPMAlgSHA256,
451 ObjectAttributes: TPMAObject{
452 FixedTPM: false,
453 STClear: false,
454 FixedParent: false,
455 SensitiveDataOrigin: true,
456 UserWithAuth: true,
457 AdminWithPolicy: true,
458 NoDA: true,
459 EncryptedDuplication: false,
460 Restricted: false,
461 Decrypt: false,
462 SignEncrypt: true,
463 },
464 AuthPolicy: duplicationPolicyHash(),
465 Parameters: NewTPMUPublicParms(
466 TPMAlgRSA,
467 &TPMSRSAParms{
468 KeyBits: 2048,
469 Scheme: TPMTRSAScheme{
470 Scheme: TPMAlgRSASSA,
471 Details: NewTPMUAsymScheme(
472 TPMAlgRSASSA,
473 &TPMSSigSchemeRSASSA{
474 HashAlg: TPMAlgSHA256,
475 },
476 ),
477 },
478 },
479 ),
480 }),
481 },
482 {
483 name: "ecdsa_p256",
484 alg: TPMAlgECDSA,
485 pub: New2B(TPMTPublic{
486 Type: TPMAlgECC,
487 NameAlg: TPMAlgSHA256,
488 ObjectAttributes: TPMAObject{
489 FixedTPM: false,
490 STClear: false,
491 FixedParent: false,
492 SensitiveDataOrigin: true,
493 UserWithAuth: true,
494 AdminWithPolicy: true,
495 NoDA: true,
496 EncryptedDuplication: false,
497 Restricted: false,
498 Decrypt: false,
499 SignEncrypt: true,
500 },
501 AuthPolicy: duplicationPolicyHash(),
502 Parameters: NewTPMUPublicParms(
503 TPMAlgECC,
504 &TPMSECCParms{
505 CurveID: TPMECCNistP256,
506 Scheme: TPMTECCScheme{
507 Scheme: TPMAlgECDSA,
508 Details: NewTPMUAsymScheme(
509 TPMAlgECDSA,
510 &TPMSSigSchemeECDSA{
511 HashAlg: TPMAlgSHA256,
512 },
513 ),
514 },
515 },
516 ),
517 }),
518 },
519 } {
520 t.Run(tc.name, func(t *testing.T) {
521 // Create an exportable signing key and then export it.
522 create, err := Create{
523 ParentHandle: NamedHandle{
524 Handle: srkCreate.ObjectHandle,
525 Name: srkCreate.Name,
526 },
527 InPublic: tc.pub,
528 }.Execute(tpm)
529 if err != nil {
530 t.Fatalf("could not create key: %v", err)
531 }
532
533 load, err := Load{
534 ParentHandle: NamedHandle{
535 Handle: srkCreate.ObjectHandle,
536 Name: srkCreate.Name,
537 },
538 InPrivate: create.OutPrivate,
539 InPublic: create.OutPublic,
540 }.Execute(tpm)
541 if err != nil {
542 t.Fatalf("could not load key: %v", err)
543 }
544 defer FlushContext{
545 FlushHandle: load.ObjectHandle,
546 }.Execute(tpm)
547
548 pub, priv := duplicateToSoftware(t, tpm, load.ObjectHandle)
549 checkSignVerify(t, tpm, NamedHandle{
550 Handle: load.ObjectHandle,
551 Name: load.Name,
552 }, tc.alg, pub, priv)
553 })
554 }
555 }
556
557 // Uses the `Pub` and `Priv` helpers to import the public and private key.
558 // Note that in practice, one could just use `crypto.PrivateKey.Public()` to
559 // derive the public key from the private key. This helper uses the `Pub`
560 // routine to validate that function specifically while we test the rest.
561 func duplicateToSoftware(t *testing.T, tpm transport.TPM, h TPMHandle) (crypto.PublicKey, crypto.PrivateKey) {
562 t.Helper()
563
564 readPublic, err := ReadPublic{
565 ObjectHandle: h,
566 }.Execute(tpm)
567 if err != nil {
568 t.Fatalf("could not ReadPublic: %v", err)
569 }
570
571 pub, err := readPublic.OutPublic.Contents()
572 if err != nil {
573 t.Fatalf("could not unmarshal TPMT_PUBLIC: %v", err)
574 }
575
576 publicKey, err := Pub(*pub)
577 if err != nil {
578 t.Fatalf("could not load public key: %v", err)
579 }
580
581 dup, err := Duplicate{
582 ObjectHandle: AuthHandle{
583 Handle: h,
584 Name: readPublic.Name,
585 Auth: Policy(TPMAlgSHA256, 16, duplicationPolicy),
586 },
587 NewParentHandle: TPMRHNull,
588 }.Execute(tpm)
589 if err != nil {
590 t.Fatalf("could not duplicate key: %v", err)
591 }
592
593 sens, err := Unmarshal[TPM2BSensitive](dup.Duplicate.Buffer)
594 if err != nil {
595 t.Fatalf("could not unmarshal TPM2B_SENSITIVE: %v", err)
596 }
597
598 priv, err := sens.Contents()
599 if err != nil {
600 t.Fatalf("could not unmarshal TPMT_SENSITIVE: %v", err)
601 }
602
603 privateKey, err := Priv(*pub, *priv)
604 if err != nil {
605 t.Fatalf("could not load private key: %v", err)
606 }
607 return publicKey, privateKey
608 }
609
610 func checkSignVerify(t *testing.T, tpm transport.TPM, h NamedHandle, alg TPMAlgID, pub crypto.PublicKey, priv crypto.PrivateKey) {
611 t.Helper()
612
613 msg := "Something I signed."
614 msgDigest := sha256.Sum256([]byte(msg))
615
616 // Sign with the TPM and with software.
617 sign, err := Sign{
618 KeyHandle: h,
619 Digest: TPM2BDigest{
620 Buffer: msgDigest[:],
621 },
622 Validation: TPMTTKHashCheck{
623 Tag: TPMSTHashCheck,
624 Hierarchy: TPMRHNull,
625 },
626 }.Execute(tpm)
627 if err != nil {
628 t.Fatalf("could not Sign: %v", err)
629 }
630 tpmSig := sign.Signature
631
632 swSig := signSoftware(t, msgDigest[:], priv)
633
634 // Verify the software signature with the TPM.
635 _, err = VerifySignature{
636 KeyHandle: h,
637 Digest: TPM2BDigest{
638 Buffer: msgDigest[:],
639 },
640 Signature: *swSig,
641 }.Execute(tpm)
642 if err != nil {
643 t.Errorf("TPM2_VerifySignature = %v", err)
644 }
645
646 // Verify the TPM signature with software.
647 verify(t, msgDigest[:], &tpmSig, pub, alg)
648 }
649
650 func signSoftware(t *testing.T, digest []byte, priv crypto.PrivateKey) *TPMTSignature {
651 t.Helper()
652
653 switch v := priv.(type) {
654 case *rsa.PrivateKey:
655 sig, err := rsa.SignPKCS1v15(rand.Reader, v, crypto.SHA256, digest)
656 if err != nil {
657 t.Fatalf("could not sign RSA in software: %v", err)
658 }
659 return tpmSignatureFromSignatureRSA(t, sig)
660 case *ecdsa.PrivateKey:
661 r, s, err := ecdsa.Sign(rand.Reader, v, digest)
662 if err != nil {
663 t.Fatalf("could not sign ECDSA in software: %v", err)
664 }
665 return tpmSignatureFromSignatureECDSA(t, r, s)
666 default:
667 t.Fatalf("unsupported algorithm")
668 }
669 return nil
670 }
671
672 func tpmSignatureFromSignatureRSA(t *testing.T, sig []byte) *TPMTSignature {
673 t.Helper()
674
675 return &TPMTSignature{
676 SigAlg: TPMAlgRSASSA,
677 Signature: NewTPMUSignature(
678 TPMAlgRSASSA,
679 &TPMSSignatureRSA{
680 Hash: TPMAlgSHA256,
681 Sig: TPM2BPublicKeyRSA{
682 Buffer: sig,
683 },
684 },
685 ),
686 }
687 }
688
689 func tpmSignatureFromSignatureECDSA(t *testing.T, r, s *big.Int) *TPMTSignature {
690 t.Helper()
691
692 return &TPMTSignature{
693 SigAlg: TPMAlgECDSA,
694 Signature: NewTPMUSignature(
695 TPMAlgECDSA,
696 &TPMSSignatureECC{
697 Hash: TPMAlgSHA256,
698 SignatureR: TPM2BECCParameter{
699 Buffer: r.FillBytes(make([]byte, 32)),
700 },
701 SignatureS: TPM2BECCParameter{
702 Buffer: s.FillBytes(make([]byte, 32)),
703 },
704 },
705 ),
706 }
707 }
708
709 func verify(t *testing.T, msgDigest []byte, sig *TPMTSignature, pub crypto.PublicKey, alg TPMAlgID) {
710 t.Helper()
711
712 switch alg {
713 case TPMAlgRSA:
714 verifyRSA(t, msgDigest, sig, pub)
715 case TPMAlgECDSA:
716 verifyECDSA(t, msgDigest, sig, pub)
717 default:
718 t.Fatalf("unsupported signature algorithm %v", alg)
719 }
720 }
721
722 func verifyRSA(t *testing.T, msgDigest []byte, sig *TPMTSignature, pub crypto.PublicKey) {
723 t.Helper()
724
725 rsaPub, ok := pub.(*rsa.PublicKey)
726 if !ok {
727 t.Fatalf("not an RSA public key")
728 }
729 rsaSig, err := sig.Signature.RSASSA()
730 if err != nil {
731 t.Fatalf("not an RSASSA signature: %v", err)
732 }
733
734 if err := rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, msgDigest, rsaSig.Sig.Buffer); err != nil {
735 t.Errorf("rsa.VerifyPKCS1v15() = %v", err)
736 }
737 }
738
739 func verifyECDSA(t *testing.T, msgDigest []byte, sig *TPMTSignature, pub crypto.PublicKey) {
740 t.Helper()
741
742 eccPub, ok := pub.(*ecdsa.PublicKey)
743 if !ok {
744 t.Fatalf("not an RSA public key")
745 }
746 eccSig, err := sig.Signature.ECDSA()
747 if err != nil {
748 t.Fatalf("not an ECDSA signature: %v", err)
749 }
750 r := new(big.Int).SetBytes(eccSig.SignatureR.Buffer)
751 s := new(big.Int).SetBytes(eccSig.SignatureS.Buffer)
752
753 if !ecdsa.Verify(eccPub, msgDigest, r, s) {
754 t.Error("ecdsa.Verify() = false")
755 }
756 }