Debian Codegraph @

attest/attest_simulated_test.go

raw
1 // Copyright 2019 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 //go:build !localtest && cgo && !gofuzz
16 // +build !localtest,cgo,!gofuzz
17
18 // NOTE: simulator requires cgo, hence the build tag.
19
20 package attest
21
22 import (
23 "bytes"
24 "crypto"
25 "crypto/ecdsa"
26 "crypto/rand"
27 "crypto/rsa"
28 "crypto/sha256"
29 "crypto/x509"
30 "crypto/x509/pkix"
31 "fmt"
32 "io"
33 "math/big"
34 "testing"
35 "time"
36
37 "github.com/google/go-cmp/cmp"
38 "github.com/google/go-tpm-tools/simulator"
39 "github.com/google/go-tpm/legacy/tpm2"
40 )
41
42 func setupSimulatedTPM(t *testing.T) (*simulator.Simulator, *TPM) {
43 t.Helper()
44 tpm, err := simulator.Get()
45 if err != nil {
46 t.Fatal(err)
47 }
48 attestTPM, err := OpenTPM(&OpenConfig{CommandChannel: &fakeCmdChannel{tpm}})
49 if err != nil {
50 t.Fatal(err)
51 }
52 return tpm, attestTPM
53 }
54
55 func setupSimulatedTPMWithECCEK(t *testing.T) (*simulator.Simulator, *TPM) {
56 t.Helper()
57 sim, err := simulator.Get()
58 if err != nil {
59 t.Fatal(err)
60 }
61 if err := provisionECCEK(sim); err != nil {
62 sim.Close()
63 t.Fatalf("failed to provision ECC EK: %v", err)
64 }
65 attestTPM, err := OpenTPM(&OpenConfig{CommandChannel: &fakeCmdChannel{sim}})
66 if err != nil {
67 sim.Close()
68 t.Fatal(err)
69 }
70 return sim, attestTPM
71 }
72
73 func provisionECCEK(sim io.ReadWriter) error {
74 ekHnd, pubKey, err := tpm2.CreatePrimary(sim, tpm2.HandleEndorsement, tpm2.PCRSelection{}, "", "", defaultECCEKTemplate)
75 if err != nil {
76 return fmt.Errorf("CreatePrimary failed: %v", err)
77 }
78 defer tpm2.FlushContext(sim, ekHnd)
79
80 err = tpm2.EvictControl(sim, "", tpm2.HandleOwner, ekHnd, commonECCEkEquivalentHandle)
81 if err != nil {
82 return fmt.Errorf("EvictControl failed: %v", err)
83 }
84
85 ecdsaPub, ok := pubKey.(*ecdsa.PublicKey)
86 if !ok {
87 return fmt.Errorf("expected *ecdsa.PublicKey, got %T", pubKey)
88 }
89
90 certDer, err := generateDummyCert(ecdsaPub)
91 if err != nil {
92 return fmt.Errorf("generateDummyCert failed: %v", err)
93 }
94
95 attrs := tpm2.AttrOwnerWrite | tpm2.AttrAuthRead
96 err = tpm2.NVDefineSpace(sim, tpm2.HandleOwner, nvramECCCertIndex, "", "", nil, attrs, uint16(len(certDer)))
97 if err != nil {
98 return fmt.Errorf("NVDefineSpace failed: %v", err)
99 }
100
101 err = tpm2.NVWrite(sim, tpm2.HandleOwner, nvramECCCertIndex, "", certDer, 0)
102 if err != nil {
103 return fmt.Errorf("NVWrite failed: %v", err)
104 }
105
106 return nil
107 }
108
109 func generateDummyCert(pub crypto.PublicKey) ([]byte, error) {
110 caPriv, err := rsa.GenerateKey(rand.Reader, 2048)
111 if err != nil {
112 return nil, err
113 }
114 caTemplate := &x509.Certificate{
115 SerialNumber: big.NewInt(1),
116 Subject: pkix.Name{
117 Organization: []string{"Dummy CA"},
118 },
119 NotBefore: time.Now(),
120 NotAfter: time.Now().Add(365 * 24 * time.Hour),
121 IsCA: true,
122 KeyUsage: x509.KeyUsageCertSign,
123 BasicConstraintsValid: true,
124 }
125 caDer, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caPriv.PublicKey, caPriv)
126 if err != nil {
127 return nil, err
128 }
129 caCert, err := x509.ParseCertificate(caDer)
130 if err != nil {
131 return nil, err
132 }
133
134 template := &x509.Certificate{
135 SerialNumber: big.NewInt(2),
136 Subject: pkix.Name{
137 Organization: []string{"Dummy Subject"},
138 },
139 NotBefore: time.Now(),
140 NotAfter: time.Now().Add(365 * 24 * time.Hour),
141 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
142 BasicConstraintsValid: true,
143 }
144
145 der, err := x509.CreateCertificate(rand.Reader, template, caCert, pub, caPriv)
146 if err != nil {
147 return nil, err
148 }
149 return der, nil
150 }
151
152 func TestSimEK(t *testing.T) {
153 sim, tpm := setupSimulatedTPM(t)
154 defer sim.Close()
155
156 eks, err := tpm.EKs()
157 if err != nil {
158 t.Errorf("EKs() failed: %v", err)
159 }
160 if len(eks) == 0 || (eks[0].Public == nil) {
161 t.Errorf("EKs() = %v, want at least 1 EK with populated fields", eks)
162 }
163 }
164
165 func TestSimWrappedtpmEKCertificatesInternal(t *testing.T) {
166 sim, tpm := setupSimulatedTPM(t)
167 defer sim.Close()
168
169 eks, err := tpm.EKCertificates()
170 if err != nil {
171 t.Errorf("EKCertfificates() failed: %v", err)
172 }
173 if len(eks) != 0 {
174 t.Errorf("simlator returned an ekCertificate this should not happen")
175 }
176 // Since the tpmsimulator does not have ek certificates we will
177 // test some of the internal logic here, in particular search
178 // and injection of missing 2k rsa key.
179 // Because of this, the test dependent on internal apis which
180 // is not optimal.
181
182 // Use a wrappedTPM with the simulator as the tpm
183 wtpm := &wrappedTPM20{
184 interf: TPMInterfaceCommandChannel,
185 rwc: &fakeCmdChannel{sim},
186 }
187 eks, err = wtpm.ekCertificates()
188 if err != nil {
189 t.Errorf("wtpm ekCertificates failed")
190 }
191 if len(eks) != 0 {
192 t.Fatalf("should have returned with no EKs")
193 }
194 // Now we inject a single key and search for it
195 _, handleFoundMap, err := wtpm.getKeyHandleKeyMap()
196 if err != nil {
197 t.Fatal(err)
198 }
199 if len(handleFoundMap) != 0 {
200 t.Fatal("the simulator should be empty at this time")
201 }
202 injected2khandle, err := wtpm.create2048RSAEKInAvailableSlot(handleFoundMap)
203 if err != nil {
204 t.Fatal(err)
205 }
206 if injected2khandle != commonRSAEkEquivalentHandle {
207 t.Errorf("injected cert at not default handle when empty")
208 }
209 _, handleFoundMap, err = wtpm.getKeyHandleKeyMap()
210 if err != nil {
211 t.Fatal(err)
212 }
213 _, ok := handleFoundMap[commonRSAEkEquivalentHandle]
214 if !ok {
215 t.Fatalf("injected key notfound")
216 }
217 }
218
219 func TestSimInfo(t *testing.T) {
220 sim, tpm := setupSimulatedTPM(t)
221 defer sim.Close()
222
223 if _, err := tpm.Info(); err != nil {
224 t.Errorf("tpm.Info() failed: %v", err)
225 }
226 }
227
228 func TestSimAKCreateAndLoad(t *testing.T) {
229 sim, tpm := setupSimulatedTPM(t)
230 defer sim.Close()
231 for _, test := range []struct {
232 name string
233 opts *AKConfig
234 }{
235 {
236 name: "NoConfig",
237 opts: nil,
238 },
239 {
240 name: "EmptyConfig",
241 opts: &AKConfig{},
242 },
243 {
244 name: "RSA",
245 opts: &AKConfig{Algorithm: RSA},
246 },
247 {
248 name: "ECDSA",
249 opts: &AKConfig{Algorithm: ECDSA},
250 },
251 } {
252 t.Run(test.name, func(t *testing.T) {
253 ak, err := tpm.NewAK(test.opts)
254 if err != nil {
255 t.Fatalf("NewAK() failed: %v", err)
256 }
257
258 enc, err := ak.Marshal()
259 if err != nil {
260 ak.Close(tpm)
261 t.Fatalf("ak.Marshal() failed: %v", err)
262 }
263 if err := ak.Close(tpm); err != nil {
264 t.Fatalf("ak.Close() failed: %v", err)
265 }
266
267 loaded, err := tpm.LoadAK(enc)
268 if err != nil {
269 t.Fatalf("LoadAK() failed: %v", err)
270 }
271 defer loaded.Close(tpm)
272
273 k1, k2 := ak.ak.(*wrappedKey20), loaded.ak.(*wrappedKey20)
274
275 if !bytes.Equal(k1.public, k2.public) {
276 t.Error("Original & loaded AK public blobs did not match.")
277 t.Logf("Original = %v", k1.public)
278 t.Logf("Loaded = %v", k2.public)
279 }
280 })
281 }
282 }
283
284 func TestSimActivateCredential(t *testing.T) {
285 testActivateCredential(t, false)
286 }
287
288 func TestSimActivateCredentialWithEK(t *testing.T) {
289 testActivateCredential(t, true)
290 }
291
292 func testActivateCredential(t *testing.T, useEK bool) {
293 sim, tpm := setupSimulatedTPM(t)
294 defer sim.Close()
295
296 EKs, err := tpm.EKs()
297 if err != nil {
298 t.Fatalf("EKs() failed: %v", err)
299 }
300 if len(EKs) == 0 {
301 t.Fatalf("No suitable EK found")
302 }
303 ek := EKs[0]
304
305 ak, err := tpm.NewAK(nil)
306 if err != nil {
307 t.Fatalf("NewAK() failed: %v", err)
308 }
309 defer ak.Close(tpm)
310
311 ap := ActivationParameters{
312 AK: ak.AttestationParameters(),
313 EK: ek.Public,
314 }
315 secret, challenge, err := ap.Generate()
316 if err != nil {
317 t.Fatalf("Generate() failed: %v", err)
318 }
319
320 var decryptedSecret []byte
321 if useEK {
322 decryptedSecret, err = ak.ActivateCredentialWithEK(tpm, *challenge, ek)
323 } else {
324 decryptedSecret, err = ak.ActivateCredential(tpm, *challenge)
325 }
326 if err != nil {
327 t.Errorf("ak.ActivateCredential() failed: %v", err)
328 }
329 if !bytes.Equal(secret, decryptedSecret) {
330 t.Error("secret does not match decrypted secret")
331 t.Logf("Secret = %v", secret)
332 t.Logf("Decrypted secret = %v", decryptedSecret)
333 }
334 }
335
336 func TestParseAKPublic(t *testing.T) {
337 sim, tpm := setupSimulatedTPM(t)
338 defer sim.Close()
339
340 ak, err := tpm.NewAK(nil)
341 if err != nil {
342 t.Fatalf("NewAK() failed: %v", err)
343 }
344 defer ak.Close(tpm)
345 params := ak.AttestationParameters()
346 if _, err := ParseAKPublic(params.Public); err != nil {
347 t.Errorf("parsing AK public blob: %v", err)
348 }
349 }
350
351 func TestSimQuoteAndVerifyAll(t *testing.T) {
352 sim, tpm := setupSimulatedTPM(t)
353 defer sim.Close()
354 for _, test := range []struct {
355 name string
356 opts *AKConfig
357 }{
358 {
359 name: "RSA",
360 opts: &AKConfig{Algorithm: RSA},
361 },
362 {
363 name: "ECDSA",
364 opts: &AKConfig{Algorithm: ECDSA},
365 },
366 } {
367 t.Run(test.name, func(t *testing.T) {
368 ak, err := tpm.NewAK(test.opts)
369 if err != nil {
370 t.Fatalf("NewAK() failed: %v", err)
371 }
372 defer ak.Close(tpm)
373
374 nonce := []byte{1, 2, 3, 4, 5, 6, 7, 8}
375 algos := []HashAlg{HashSHA1, HashSHA256, HashSHA384, HashSHA512}
376 var quotes []Quote
377 for _, algo := range algos {
378 quote, err := ak.Quote(tpm, nonce, algo)
379 if err != nil {
380 t.Fatalf("ak.Quote(%v) failed: %v", algo, err)
381 }
382 quotes = append(quotes, *quote)
383 }
384
385 // Providing both PCR banks to AKPublic.Verify() ensures we can handle
386 // the case where extra PCRs of a different digest algorithm are provided.
387 var pcrs []PCR
388 for _, alg := range algos {
389 p, err := tpm.PCRs(alg)
390 if err != nil {
391 t.Fatalf("tpm.PCRs(%v) failed: %v", alg, err)
392 }
393 pcrs = append(pcrs, p...)
394 }
395
396 pub, err := ParseAKPublic(ak.AttestationParameters().Public)
397 if err != nil {
398 t.Fatalf("ParseAKPublic() failed: %v", err)
399 }
400
401 // Ensure VerifyAll fails if a quote is missing and hence not all PCR
402 // banks are covered.
403 if err := pub.VerifyAll(quotes[:1], pcrs, nonce); err == nil {
404 t.Error("VerifyAll().err returned nil, expected failure")
405 }
406
407 if err := pub.VerifyAll(quotes, pcrs, nonce); err != nil {
408 t.Errorf("quote verification failed: %v", err)
409 }
410 })
411 }
412 }
413
414 func TestSimAttestPlatform(t *testing.T) {
415 sim, tpm := setupSimulatedTPM(t)
416 defer sim.Close()
417
418 ak, err := tpm.NewAK(nil)
419 if err != nil {
420 t.Fatalf("NewAK() failed: %v", err)
421 }
422 defer ak.Close(tpm)
423
424 nonce := []byte{1, 2, 3, 4, 5, 6, 7, 8}
425 attestation, err := tpm.attestPlatform(ak, nonce, nil)
426 if err != nil {
427 t.Fatalf("AttestPlatform() failed: %v", err)
428 }
429
430 pub, err := ParseAKPublic(attestation.Public)
431 if err != nil {
432 t.Fatalf("ParseAKPublic() failed: %v", err)
433 }
434 if err := pub.VerifyAll(attestation.Quotes, attestation.PCRs, nonce); err != nil {
435 t.Errorf("quote verification failed: %v", err)
436 }
437 }
438
439 func testEventLogHelper(t *testing.T, tpm *TPM, wantAlgs []HashAlg) {
440 ml, err := tpm.MeasurementLog()
441 if err != nil {
442 t.Fatalf("MeasurementLog() failed: %v", err)
443 }
444 if len(ml) == 0 {
445 t.Fatalf("Event log is empty")
446 }
447 el, err := ParseEventLog(ml)
448 if err != nil {
449 t.Errorf("Failed to parse event log: %v", err)
450 }
451 if diff := cmp.Diff(wantAlgs, el.Algs); diff != "" {
452 t.Errorf("Event log has unexpected algorithms (-want +got):\n%s", diff)
453 }
454 }
455
456 func TestSimEventLog(t *testing.T) {
457 sim, tpm := setupSimulatedTPM(t)
458 defer sim.Close()
459
460 wantAlgs := []HashAlg{HashSHA1, HashSHA256, HashSHA384, HashSHA512}
461 testEventLogHelper(t, tpm, wantAlgs)
462 }
463
464 func fetchPCRBanksOrDie(t *testing.T, tpm io.ReadWriter) []tpm2.PCRSelection {
465 vals, _, err := tpm2.GetCapability(tpm, tpm2.CapabilityPCRs, 1024, 0)
466 if err != nil {
467 t.Fatalf("failed to get TPM available PCR banks: %v", err)
468 }
469
470 var pcrs []tpm2.PCRSelection
471
472 for i, v := range vals {
473 pcrb, ok := v.(tpm2.PCRSelection)
474 if !ok {
475 t.Fatalf("failed to convert value %d to tpm2.PCRSelection: %v", i, v)
476 continue
477 }
478
479 pcrs = append(pcrs, pcrb)
480 }
481 if len(pcrs) < 4 {
482 t.Fatalf("Expecting at least 4 PCR banks, got %d: %+v", len(pcrs), pcrs)
483 }
484 return pcrs
485 }
486
487 func updatePCRBanksOrDie(t *testing.T, tpm *simulator.Simulator, pcrs []tpm2.PCRSelection) {
488 // Allocate the new PCR banks on the TPM
489 auth := tpm2.AuthCommand{Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession}
490 err := tpm2.PCRAllocate(tpm, tpm2.HandlePlatform, auth, pcrs)
491 if err != nil {
492 t.Fatalf("failed to allocate PCR bank: %v", err)
493 }
494
495 // Reset is needed after sending TPM2_PCR_Allocate.
496 err = tpm.Reset()
497 if err != nil {
498 t.Fatalf("failed to reset TPM: %v", err)
499 }
500 }
501
502 func TestSimEventLogPCRBanks(t *testing.T) {
503 // Fetch all PCR banks from the TPM.
504 // Close the TPM simulator after fetching the PCR banks, so that each test can start with a clean TPM.
505 pcrs := func() []tpm2.PCRSelection {
506 sim, _ := setupSimulatedTPM(t)
507 defer sim.Close()
508 // Fetch all PCR banks from the TPM.
509 return fetchPCRBanksOrDie(t, sim)
510 }()
511
512 for _, pcr := range pcrs {
513 t.Run(fmt.Sprintf("Disable %s", pcr.Hash.String()), func(t *testing.T) {
514 sim, tpm := setupSimulatedTPM(t)
515 defer sim.Close()
516
517 // Generate a new list of PCR banks with the PCR bank pcr.Hash disabled.
518 var newPCRs []tpm2.PCRSelection
519 var wantAlgs []HashAlg
520 for _, p := range pcrs {
521 if p.Hash == pcr.Hash {
522 disabled := tpm2.PCRSelection{Hash: p.Hash, PCRs: []int{}}
523 newPCRs = append(newPCRs, disabled)
524 continue
525 }
526 newPCRs = append(newPCRs, p)
527 alg, err := FromTPMAlg(p.Hash)
528 if err != nil {
529 t.Fatalf("PCR bank %s has no corresponding HashAlg: %v", p.Hash.String(), err)
530 }
531 wantAlgs = append(wantAlgs, alg)
532 }
533 updatePCRBanksOrDie(t, sim, newPCRs)
534
535 testEventLogHelper(t, tpm, wantAlgs)
536 })
537 }
538 }
539
540 func TestSimPCRs(t *testing.T) {
541 sim, tpm := setupSimulatedTPM(t)
542 defer sim.Close()
543
544 for _, algo := range []HashAlg{HashSHA1, HashSHA256, HashSHA384, HashSHA512} {
545 cryptoHash, err := algo.cryptoHash()
546 if err != nil {
547 t.Fatalf("Failed to get crypto.Hash for %v: %v", algo, err)
548 }
549 t.Run(cryptoHash.String(), func(t *testing.T) {
550 PCRs, err := tpm.PCRs(algo)
551 if err != nil {
552 t.Fatalf("PCRs() failed: %v", err)
553 }
554 if len(PCRs) != 24 {
555 t.Errorf("len(PCRs) = %d, want %d", len(PCRs), 24)
556 }
557
558 for i, pcr := range PCRs {
559 if len(pcr.Digest) != pcr.DigestAlg.Size() {
560 t.Errorf("PCR %d len(digest) = %d, expected match with digest algorithm size (%d)", pcr.Index, len(pcr.Digest), pcr.DigestAlg.Size())
561 }
562 if pcr.Index != i {
563 t.Errorf("PCR index %d does not match map index %d", pcr.Index, i)
564 }
565 if pcr.DigestAlg != cryptoHash {
566 t.Errorf("pcr.DigestAlg = %v, expected %v", pcr.DigestAlg, cryptoHash)
567 }
568 }
569 })
570 }
571 }
572
573 func TestSimPersistenceSRK(t *testing.T) {
574 testPersistenceSRK(t, defaultParentConfig)
575 }
576
577 func TestSimPersistenceECCSRK(t *testing.T) {
578 parentConfig := ParentKeyConfig{
579 Algorithm: ECDSA,
580 Handle: 0x81000002,
581 }
582 testPersistenceSRK(t, parentConfig)
583 }
584
585 func testPersistenceSRK(t *testing.T, parentConfig ParentKeyConfig) {
586 sim, tpm := setupSimulatedTPM(t)
587 defer sim.Close()
588
589 srkHnd, _, err := tpm.tpm.(*wrappedTPM20).getStorageRootKeyHandle(parentConfig)
590 if err != nil {
591 t.Fatalf("getStorageRootKeyHandle() failed: %v", err)
592 }
593 if srkHnd != parentConfig.Handle {
594 t.Fatalf("bad SRK-equivalent handle: got 0x%x, wanted 0x%x", srkHnd, parentConfig.Handle)
595 }
596
597 srkHnd, p, err := tpm.tpm.(*wrappedTPM20).getStorageRootKeyHandle(parentConfig)
598 if err != nil {
599 t.Fatalf("second getStorageRootKeyHandle() failed: %v", err)
600 }
601 if srkHnd != parentConfig.Handle {
602 t.Fatalf("bad SRK-equivalent handle: got 0x%x, wanted 0x%x", srkHnd, parentConfig.Handle)
603 }
604 if p {
605 t.Fatalf("generated a new key the second time; that shouldn't happen")
606 }
607 }
608
609 func TestSimPersistenceEK(t *testing.T) {
610 sim, tpm := setupSimulatedTPM(t)
611 defer sim.Close()
612
613 eks, err := tpm.EKs()
614 if err != nil {
615 t.Errorf("EKs() failed: %v", err)
616 }
617 if len(eks) == 0 || (eks[0].Public == nil) {
618 t.Errorf("EKs() = %v, want at least 1 EK with populated fields", eks)
619 }
620
621 ek := eks[0]
622 ekHnd, _, err := tpm.tpm.(*wrappedTPM20).getEndorsementKeyHandle(&ek)
623 if err != nil {
624 t.Fatalf("getStorageRootKeyHandle() failed: %v", err)
625 }
626 if ekHnd != ek.handle {
627 t.Fatalf("bad EK-equivalent handle: got 0x%x, wanted 0x%x", ekHnd, ek.handle)
628 }
629
630 ekHnd, p, err := tpm.tpm.(*wrappedTPM20).getEndorsementKeyHandle(&ek)
631 if err != nil {
632 t.Fatalf("second getEndorsementKeyHandle() failed: %v", err)
633 }
634 if ekHnd != ek.handle {
635 t.Fatalf("bad EK-equivalent handle: got 0x%x, wanted 0x%x", ekHnd, ek.handle)
636 }
637 if p {
638 t.Fatalf("generated a new key the second time; that shouldn't happen")
639 }
640 }
641
642 func TestTPMHash(t *testing.T) {
643 sim, tpm := setupSimulatedTPM(t)
644 defer sim.Close()
645
646 sizes := []int{
647 tpm2BMaxBufferSize / 2,
648 tpm2BMaxBufferSize - 1,
649 tpm2BMaxBufferSize,
650 tpm2BMaxBufferSize + 1,
651 tpm2BMaxBufferSize * 1.5,
652 tpm2BMaxBufferSize*2 - 1,
653 tpm2BMaxBufferSize * 2,
654 tpm2BMaxBufferSize*2 + 1,
655 }
656
657 for _, size := range sizes {
658 t.Run(fmt.Sprintf("size=%d", size), func(t *testing.T) {
659 msg := make([]byte, size)
660 rand.Read(msg)
661
662 digest, validation, err := tpmHash(tpm.tpm.(*wrappedTPM20).rwc, msg, crypto.SHA256)
663 if err != nil {
664 t.Fatalf("Hash() failed: %v", err)
665 }
666
667 trueDigest := sha256.Sum256(msg)
668 if !bytes.Equal(digest, trueDigest[:]) {
669 t.Errorf("Hash() = %v, want %v", digest, trueDigest[:])
670 }
671
672 if validation.Hierarchy == tpm2.HandleNull {
673 t.Errorf("Hash() validation.Hierarchy = tpm2.HandleNull")
674 }
675 })
676 }
677 }
678
679 func TestTPMHashMsgTooShort(t *testing.T) {
680 sim, tpm := setupSimulatedTPM(t)
681 defer sim.Close()
682
683 // TPM will refuse to hash a message that is too short.
684 sizes := []int{0, 1, 2}
685
686 for _, size := range sizes {
687 t.Run(fmt.Sprintf("size=%d", size), func(t *testing.T) {
688 msg := make([]byte, size)
689 _, _, err := tpmHash(tpm.tpm.(*wrappedTPM20).rwc, msg, crypto.SHA256)
690 if err == nil {
691 t.Errorf("Hash() succeeded, want error")
692 }
693 })
694 }
695 }
696
697 func TestSignMsg(t *testing.T) {
698 sim, tpm := setupSimulatedTPM(t)
699 defer sim.Close()
700
701 ak, err := tpm.NewAK(nil)
702 if err != nil {
703 t.Fatalf("NewAK() failed: %v", err)
704 }
705
706 msg := []byte("hello world")
707 hashed := sha256.Sum256(msg)
708
709 sig, err := ak.SignMsg(tpm, msg, crypto.SHA256)
710 if err != nil {
711 t.Fatalf("SignMsg() failed: %v", err)
712 }
713
714 if err := rsa.VerifyPKCS1v15(ak.Public().(*rsa.PublicKey), crypto.SHA256, hashed[:], sig); err != nil {
715 t.Errorf("rsa.VerifyPKCS1v15() failed: %v", err)
716 }
717 }
718
719 func TestSimCertifyWithDecryptionEk(t *testing.T) {
720 sim, tpm := setupSimulatedTPM(t)
721 defer sim.Close()
722
723 EKs, err := tpm.EKs()
724 if err != nil {
725 t.Fatalf("EKs() failed: %v", err)
726 }
727 if len(EKs) == 0 {
728 t.Fatalf("No suitable EK found")
729 }
730 var rsaEk *EK
731 for _, ek := range EKs {
732 if _, ok := ek.Public.(*rsa.PublicKey); ok {
733 rsaEk = &ek
734 break
735 }
736 }
737 if rsaEk == nil {
738 t.Fatalf("No suitable RSA EK found")
739 }
740
741 ak, err := tpm.NewAK(nil)
742 if err != nil {
743 t.Fatalf("NewAK() failed: %v", err)
744 }
745 defer ak.Close(tpm)
746
747 challenge, hmacKey, err := GenerateEkChallenge(rsaEk.Public)
748 if err != nil {
749 t.Fatalf("GenerateEkChallenge() failed: %v", err)
750 }
751
752 certParams, err := ak.CertifyWithDecryptionEk(tpm, rsaEk, *challenge)
753 if err != nil {
754 t.Fatalf("CertifyWithDecryptionEk() failed: %v", err)
755 }
756
757 if err := VerifySolvedDecryptionEkChallenge(ak.AttestationParameters().Public, certParams, *hmacKey); err != nil {
758 t.Fatalf("VerifySolvedDecryptionEkChallenge() failed: %v", err)
759 }
760 }
761
762 func TestSimCertifyWithDecryptionEkECC(t *testing.T) {
763 sim, tpm := setupSimulatedTPMWithECCEK(t)
764 defer sim.Close()
765
766 EKs, err := tpm.EKCertificates()
767 if err != nil {
768 t.Fatalf("EKCertificates() failed: %v", err)
769 }
770 if len(EKs) == 0 {
771 t.Fatalf("No EK certificates found")
772 }
773 var eccEk *EK
774 for _, ek := range EKs {
775 if _, ok := ek.Public.(*ecdsa.PublicKey); ok {
776 eccEk = &ek
777 break
778 }
779 }
780 if eccEk == nil {
781 t.Fatalf("No suitable ECC EK found")
782 }
783
784 ak, err := tpm.NewAK(nil)
785 if err != nil {
786 t.Fatalf("NewAK() failed: %v", err)
787 }
788 defer ak.Close(tpm)
789
790 challenge, hmacKey, err := GenerateEkChallenge(eccEk.Public)
791 if err != nil {
792 t.Fatalf("GenerateEkChallenge() failed: %v", err)
793 }
794
795 certParams, err := ak.CertifyWithDecryptionEk(tpm, eccEk, *challenge)
796 if err != nil {
797 t.Fatalf("CertifyWithDecryptionEk() failed: %v", err)
798 }
799
800 if err := VerifySolvedDecryptionEkChallenge(ak.AttestationParameters().Public, certParams, *hmacKey); err != nil {
801 t.Fatalf("VerifySolvedDecryptionEkChallenge() failed: %v", err)
802 }
803 }