Debian Codegraph @

tpm2/crypto_test.go

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