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/rand"
26 "crypto/rsa"
27 "crypto/sha256"
28 "fmt"
29 "io"
30 "testing"
31
32 "github.com/google/go-cmp/cmp"
33 "github.com/google/go-tpm-tools/simulator"
34 "github.com/google/go-tpm/legacy/tpm2"
35 )
36
37 func setupSimulatedTPM(t *testing.T) (*simulator.Simulator, *TPM) {
38 t.Helper()
39 tpm, err := simulator.Get()
40 if err != nil {
41 t.Fatal(err)
42 }
43 attestTPM, err := OpenTPM(&OpenConfig{CommandChannel: &fakeCmdChannel{tpm}})
44 if err != nil {
45 t.Fatal(err)
46 }
47 return tpm, attestTPM
48 }
49
50 func TestSimEK(t *testing.T) {
51 sim, tpm := setupSimulatedTPM(t)
52 defer sim.Close()
53
54 eks, err := tpm.EKs()
55 if err != nil {
56 t.Errorf("EKs() failed: %v", err)
57 }
58 if len(eks) == 0 || (eks[0].Public == nil) {
59 t.Errorf("EKs() = %v, want at least 1 EK with populated fields", eks)
60 }
61 }
62
63 func TestSimWrappedtpmEKCertificatesInternal(t *testing.T) {
64 sim, tpm := setupSimulatedTPM(t)
65 defer sim.Close()
66
67 eks, err := tpm.EKCertificates()
68 if err != nil {
69 t.Errorf("EKCertfificates() failed: %v", err)
70 }
71 if len(eks) != 0 {
72 t.Errorf("simlator returned an ekCertificate this should not happen")
73 }
74 // Since the tpmsimulator does not have ek certificates we will
75 // test some of the internal logic here, in particular search
76 // and injection of missing 2k rsa key.
77 // Because of this, the test dependent on internal apis which
78 // is not optimal.
79
80 // Use a wrappedTPM with the simulator as the tpm
81 wtpm := &wrappedTPM20{
82 interf: TPMInterfaceCommandChannel,
83 rwc: &fakeCmdChannel{sim},
84 }
85 eks, err = wtpm.ekCertificates()
86 if err != nil {
87 t.Errorf("wtpm ekCertificates failed")
88 }
89 if len(eks) != 0 {
90 t.Fatalf("should have returned with no EKs")
91 }
92 // Now we inject a single key and search for it
93 _, handleFoundMap, err := wtpm.getKeyHandleKeyMap()
94 if err != nil {
95 t.Fatal(err)
96 }
97 if len(handleFoundMap) != 0 {
98 t.Fatal("the simulator should be empty at this time")
99 }
100 injected2khandle, err := wtpm.create2048RSAEKInAvailableSlot(handleFoundMap)
101 if err != nil {
102 t.Fatal(err)
103 }
104 if injected2khandle != commonRSAEkEquivalentHandle {
105 t.Errorf("injected cert at not default handle when empty")
106 }
107 _, handleFoundMap, err = wtpm.getKeyHandleKeyMap()
108 if err != nil {
109 t.Fatal(err)
110 }
111 _, ok := handleFoundMap[commonRSAEkEquivalentHandle]
112 if !ok {
113 t.Fatalf("injected key notfound")
114 }
115 }
116
117 func TestSimInfo(t *testing.T) {
118 sim, tpm := setupSimulatedTPM(t)
119 defer sim.Close()
120
121 if _, err := tpm.Info(); err != nil {
122 t.Errorf("tpm.Info() failed: %v", err)
123 }
124 }
125
126 func TestSimAKCreateAndLoad(t *testing.T) {
127 sim, tpm := setupSimulatedTPM(t)
128 defer sim.Close()
129 for _, test := range []struct {
130 name string
131 opts *AKConfig
132 }{
133 {
134 name: "NoConfig",
135 opts: nil,
136 },
137 {
138 name: "EmptyConfig",
139 opts: &AKConfig{},
140 },
141 {
142 name: "RSA",
143 opts: &AKConfig{Algorithm: RSA},
144 },
145 {
146 name: "ECDSA",
147 opts: &AKConfig{Algorithm: ECDSA},
148 },
149 } {
150 t.Run(test.name, func(t *testing.T) {
151 ak, err := tpm.NewAK(test.opts)
152 if err != nil {
153 t.Fatalf("NewAK() failed: %v", err)
154 }
155
156 enc, err := ak.Marshal()
157 if err != nil {
158 ak.Close(tpm)
159 t.Fatalf("ak.Marshal() failed: %v", err)
160 }
161 if err := ak.Close(tpm); err != nil {
162 t.Fatalf("ak.Close() failed: %v", err)
163 }
164
165 loaded, err := tpm.LoadAK(enc)
166 if err != nil {
167 t.Fatalf("LoadAK() failed: %v", err)
168 }
169 defer loaded.Close(tpm)
170
171 k1, k2 := ak.ak.(*wrappedKey20), loaded.ak.(*wrappedKey20)
172
173 if !bytes.Equal(k1.public, k2.public) {
174 t.Error("Original & loaded AK public blobs did not match.")
175 t.Logf("Original = %v", k1.public)
176 t.Logf("Loaded = %v", k2.public)
177 }
178 })
179 }
180 }
181
182 func TestSimActivateCredential(t *testing.T) {
183 testActivateCredential(t, false)
184 }
185
186 func TestSimActivateCredentialWithEK(t *testing.T) {
187 testActivateCredential(t, true)
188 }
189
190 func testActivateCredential(t *testing.T, useEK bool) {
191 sim, tpm := setupSimulatedTPM(t)
192 defer sim.Close()
193
194 EKs, err := tpm.EKs()
195 if err != nil {
196 t.Fatalf("EKs() failed: %v", err)
197 }
198 if len(EKs) == 0 {
199 t.Fatalf("No suitable EK found")
200 }
201 ek := EKs[0]
202
203 ak, err := tpm.NewAK(nil)
204 if err != nil {
205 t.Fatalf("NewAK() failed: %v", err)
206 }
207 defer ak.Close(tpm)
208
209 ap := ActivationParameters{
210 AK: ak.AttestationParameters(),
211 EK: ek.Public,
212 }
213 secret, challenge, err := ap.Generate()
214 if err != nil {
215 t.Fatalf("Generate() failed: %v", err)
216 }
217
218 var decryptedSecret []byte
219 if useEK {
220 decryptedSecret, err = ak.ActivateCredentialWithEK(tpm, *challenge, ek)
221 } else {
222 decryptedSecret, err = ak.ActivateCredential(tpm, *challenge)
223 }
224 if err != nil {
225 t.Errorf("ak.ActivateCredential() failed: %v", err)
226 }
227 if !bytes.Equal(secret, decryptedSecret) {
228 t.Error("secret does not match decrypted secret")
229 t.Logf("Secret = %v", secret)
230 t.Logf("Decrypted secret = %v", decryptedSecret)
231 }
232 }
233
234 func TestParseAKPublic(t *testing.T) {
235 sim, tpm := setupSimulatedTPM(t)
236 defer sim.Close()
237
238 ak, err := tpm.NewAK(nil)
239 if err != nil {
240 t.Fatalf("NewAK() failed: %v", err)
241 }
242 defer ak.Close(tpm)
243 params := ak.AttestationParameters()
244 if _, err := ParseAKPublic(params.Public); err != nil {
245 t.Errorf("parsing AK public blob: %v", err)
246 }
247 }
248
249 func TestSimQuoteAndVerifyAll(t *testing.T) {
250 sim, tpm := setupSimulatedTPM(t)
251 defer sim.Close()
252 for _, test := range []struct {
253 name string
254 opts *AKConfig
255 }{
256 {
257 name: "RSA",
258 opts: &AKConfig{Algorithm: RSA},
259 },
260 {
261 name: "ECDSA",
262 opts: &AKConfig{Algorithm: ECDSA},
263 },
264 } {
265 t.Run(test.name, func(t *testing.T) {
266 ak, err := tpm.NewAK(test.opts)
267 if err != nil {
268 t.Fatalf("NewAK() failed: %v", err)
269 }
270 defer ak.Close(tpm)
271
272 nonce := []byte{1, 2, 3, 4, 5, 6, 7, 8}
273 algos := []HashAlg{HashSHA1, HashSHA256, HashSHA384, HashSHA512}
274 var quotes []Quote
275 for _, algo := range algos {
276 quote, err := ak.Quote(tpm, nonce, algo)
277 if err != nil {
278 t.Fatalf("ak.Quote(%v) failed: %v", algo, err)
279 }
280 quotes = append(quotes, *quote)
281 }
282
283 // Providing both PCR banks to AKPublic.Verify() ensures we can handle
284 // the case where extra PCRs of a different digest algorithm are provided.
285 var pcrs []PCR
286 for _, alg := range algos {
287 p, err := tpm.PCRs(alg)
288 if err != nil {
289 t.Fatalf("tpm.PCRs(%v) failed: %v", alg, err)
290 }
291 pcrs = append(pcrs, p...)
292 }
293
294 pub, err := ParseAKPublic(ak.AttestationParameters().Public)
295 if err != nil {
296 t.Fatalf("ParseAKPublic() failed: %v", err)
297 }
298
299 // Ensure VerifyAll fails if a quote is missing and hence not all PCR
300 // banks are covered.
301 if err := pub.VerifyAll(quotes[:1], pcrs, nonce); err == nil {
302 t.Error("VerifyAll().err returned nil, expected failure")
303 }
304
305 if err := pub.VerifyAll(quotes, pcrs, nonce); err != nil {
306 t.Errorf("quote verification failed: %v", err)
307 }
308 })
309 }
310 }
311
312 func TestSimAttestPlatform(t *testing.T) {
313 sim, tpm := setupSimulatedTPM(t)
314 defer sim.Close()
315
316 ak, err := tpm.NewAK(nil)
317 if err != nil {
318 t.Fatalf("NewAK() failed: %v", err)
319 }
320 defer ak.Close(tpm)
321
322 nonce := []byte{1, 2, 3, 4, 5, 6, 7, 8}
323 attestation, err := tpm.attestPlatform(ak, nonce, nil)
324 if err != nil {
325 t.Fatalf("AttestPlatform() failed: %v", err)
326 }
327
328 pub, err := ParseAKPublic(attestation.Public)
329 if err != nil {
330 t.Fatalf("ParseAKPublic() failed: %v", err)
331 }
332 if err := pub.VerifyAll(attestation.Quotes, attestation.PCRs, nonce); err != nil {
333 t.Errorf("quote verification failed: %v", err)
334 }
335 }
336
337 func testEventLogHelper(t *testing.T, tpm *TPM, wantAlgs []HashAlg) {
338 ml, err := tpm.MeasurementLog()
339 if err != nil {
340 t.Fatalf("MeasurementLog() failed: %v", err)
341 }
342 if len(ml) == 0 {
343 t.Fatalf("Event log is empty")
344 }
345 el, err := ParseEventLog(ml)
346 if err != nil {
347 t.Errorf("Failed to parse event log: %v", err)
348 }
349 if diff := cmp.Diff(wantAlgs, el.Algs); diff != "" {
350 t.Errorf("Event log has unexpected algorithms (-want +got):\n%s", diff)
351 }
352 }
353
354 func TestSimEventLog(t *testing.T) {
355 sim, tpm := setupSimulatedTPM(t)
356 defer sim.Close()
357
358 wantAlgs := []HashAlg{HashSHA1, HashSHA256, HashSHA384, HashSHA512}
359 testEventLogHelper(t, tpm, wantAlgs)
360 }
361
362 func fetchPCRBanksOrDie(t *testing.T, tpm io.ReadWriter) []tpm2.PCRSelection {
363 vals, _, err := tpm2.GetCapability(tpm, tpm2.CapabilityPCRs, 1024, 0)
364 if err != nil {
365 t.Fatalf("failed to get TPM available PCR banks: %v", err)
366 }
367
368 var pcrs []tpm2.PCRSelection
369
370 for i, v := range vals {
371 pcrb, ok := v.(tpm2.PCRSelection)
372 if !ok {
373 t.Fatalf("failed to convert value %d to tpm2.PCRSelection: %v", i, v)
374 continue
375 }
376
377 pcrs = append(pcrs, pcrb)
378 }
379 if len(pcrs) < 4 {
380 t.Fatalf("Expecting at least 4 PCR banks, got %d: %+v", len(pcrs), pcrs)
381 }
382 return pcrs
383 }
384
385 func updatePCRBanksOrDie(t *testing.T, tpm *simulator.Simulator, pcrs []tpm2.PCRSelection) {
386 // Allocate the new PCR banks on the TPM
387 auth := tpm2.AuthCommand{Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession}
388 err := tpm2.PCRAllocate(tpm, tpm2.HandlePlatform, auth, pcrs)
389 if err != nil {
390 t.Fatalf("failed to allocate PCR bank: %v", err)
391 }
392
393 // Reset is needed after sending TPM2_PCR_Allocate.
394 err = tpm.Reset()
395 if err != nil {
396 t.Fatalf("failed to reset TPM: %v", err)
397 }
398 }
399
400 func TestSimEventLogPCRBanks(t *testing.T) {
401 // Fetch all PCR banks from the TPM.
402 // Close the TPM simulator after fetching the PCR banks, so that each test can start with a clean TPM.
403 pcrs := func() []tpm2.PCRSelection {
404 sim, _ := setupSimulatedTPM(t)
405 defer sim.Close()
406 // Fetch all PCR banks from the TPM.
407 return fetchPCRBanksOrDie(t, sim)
408 }()
409
410 for _, pcr := range pcrs {
411 t.Run(fmt.Sprintf("Disable %s", pcr.Hash.String()), func(t *testing.T) {
412 sim, tpm := setupSimulatedTPM(t)
413 defer sim.Close()
414
415 // Generate a new list of PCR banks with the PCR bank pcr.Hash disabled.
416 var newPCRs []tpm2.PCRSelection
417 var wantAlgs []HashAlg
418 for _, p := range pcrs {
419 if p.Hash == pcr.Hash {
420 disabled := tpm2.PCRSelection{Hash: p.Hash, PCRs: []int{}}
421 newPCRs = append(newPCRs, disabled)
422 continue
423 }
424 newPCRs = append(newPCRs, p)
425 alg, err := FromTPMAlg(p.Hash)
426 if err != nil {
427 t.Fatalf("PCR bank %s has no corresponding HashAlg: %v", p.Hash.String(), err)
428 }
429 wantAlgs = append(wantAlgs, alg)
430 }
431 updatePCRBanksOrDie(t, sim, newPCRs)
432
433 testEventLogHelper(t, tpm, wantAlgs)
434 })
435 }
436 }
437
438 func TestSimPCRs(t *testing.T) {
439 sim, tpm := setupSimulatedTPM(t)
440 defer sim.Close()
441
442 for _, algo := range []HashAlg{HashSHA1, HashSHA256, HashSHA384, HashSHA512} {
443 cryptoHash, err := algo.cryptoHash()
444 if err != nil {
445 t.Fatalf("Failed to get crypto.Hash for %v: %v", algo, err)
446 }
447 t.Run(cryptoHash.String(), func(t *testing.T) {
448 PCRs, err := tpm.PCRs(algo)
449 if err != nil {
450 t.Fatalf("PCRs() failed: %v", err)
451 }
452 if len(PCRs) != 24 {
453 t.Errorf("len(PCRs) = %d, want %d", len(PCRs), 24)
454 }
455
456 for i, pcr := range PCRs {
457 if len(pcr.Digest) != pcr.DigestAlg.Size() {
458 t.Errorf("PCR %d len(digest) = %d, expected match with digest algorithm size (%d)", pcr.Index, len(pcr.Digest), pcr.DigestAlg.Size())
459 }
460 if pcr.Index != i {
461 t.Errorf("PCR index %d does not match map index %d", pcr.Index, i)
462 }
463 if pcr.DigestAlg != cryptoHash {
464 t.Errorf("pcr.DigestAlg = %v, expected %v", pcr.DigestAlg, cryptoHash)
465 }
466 }
467 })
468 }
469 }
470
471 func TestSimPersistenceSRK(t *testing.T) {
472 testPersistenceSRK(t, defaultParentConfig)
473 }
474
475 func TestSimPersistenceECCSRK(t *testing.T) {
476 parentConfig := ParentKeyConfig{
477 Algorithm: ECDSA,
478 Handle: 0x81000002,
479 }
480 testPersistenceSRK(t, parentConfig)
481 }
482
483 func testPersistenceSRK(t *testing.T, parentConfig ParentKeyConfig) {
484 sim, tpm := setupSimulatedTPM(t)
485 defer sim.Close()
486
487 srkHnd, _, err := tpm.tpm.(*wrappedTPM20).getStorageRootKeyHandle(parentConfig)
488 if err != nil {
489 t.Fatalf("getStorageRootKeyHandle() failed: %v", err)
490 }
491 if srkHnd != parentConfig.Handle {
492 t.Fatalf("bad SRK-equivalent handle: got 0x%x, wanted 0x%x", srkHnd, parentConfig.Handle)
493 }
494
495 srkHnd, p, err := tpm.tpm.(*wrappedTPM20).getStorageRootKeyHandle(parentConfig)
496 if err != nil {
497 t.Fatalf("second getStorageRootKeyHandle() failed: %v", err)
498 }
499 if srkHnd != parentConfig.Handle {
500 t.Fatalf("bad SRK-equivalent handle: got 0x%x, wanted 0x%x", srkHnd, parentConfig.Handle)
501 }
502 if p {
503 t.Fatalf("generated a new key the second time; that shouldn't happen")
504 }
505 }
506
507 func TestSimPersistenceEK(t *testing.T) {
508 sim, tpm := setupSimulatedTPM(t)
509 defer sim.Close()
510
511 eks, err := tpm.EKs()
512 if err != nil {
513 t.Errorf("EKs() failed: %v", err)
514 }
515 if len(eks) == 0 || (eks[0].Public == nil) {
516 t.Errorf("EKs() = %v, want at least 1 EK with populated fields", eks)
517 }
518
519 ek := eks[0]
520 ekHnd, _, err := tpm.tpm.(*wrappedTPM20).getEndorsementKeyHandle(&ek)
521 if err != nil {
522 t.Fatalf("getStorageRootKeyHandle() failed: %v", err)
523 }
524 if ekHnd != ek.handle {
525 t.Fatalf("bad EK-equivalent handle: got 0x%x, wanted 0x%x", ekHnd, ek.handle)
526 }
527
528 ekHnd, p, err := tpm.tpm.(*wrappedTPM20).getEndorsementKeyHandle(&ek)
529 if err != nil {
530 t.Fatalf("second getEndorsementKeyHandle() failed: %v", err)
531 }
532 if ekHnd != ek.handle {
533 t.Fatalf("bad EK-equivalent handle: got 0x%x, wanted 0x%x", ekHnd, ek.handle)
534 }
535 if p {
536 t.Fatalf("generated a new key the second time; that shouldn't happen")
537 }
538 }
539
540 func TestTPMHash(t *testing.T) {
541 sim, tpm := setupSimulatedTPM(t)
542 defer sim.Close()
543
544 sizes := []int{
545 tpm2BMaxBufferSize / 2,
546 tpm2BMaxBufferSize - 1,
547 tpm2BMaxBufferSize,
548 tpm2BMaxBufferSize + 1,
549 tpm2BMaxBufferSize * 1.5,
550 tpm2BMaxBufferSize*2 - 1,
551 tpm2BMaxBufferSize * 2,
552 tpm2BMaxBufferSize*2 + 1,
553 }
554
555 for _, size := range sizes {
556 t.Run(fmt.Sprintf("size=%d", size), func(t *testing.T) {
557 msg := make([]byte, size)
558 rand.Read(msg)
559
560 digest, validation, err := tpmHash(tpm.tpm.(*wrappedTPM20).rwc, msg, crypto.SHA256)
561 if err != nil {
562 t.Fatalf("Hash() failed: %v", err)
563 }
564
565 trueDigest := sha256.Sum256(msg)
566 if !bytes.Equal(digest, trueDigest[:]) {
567 t.Errorf("Hash() = %v, want %v", digest, trueDigest[:])
568 }
569
570 if validation.Hierarchy == tpm2.HandleNull {
571 t.Errorf("Hash() validation.Hierarchy = tpm2.HandleNull")
572 }
573 })
574 }
575 }
576
577 func TestTPMHashMsgTooShort(t *testing.T) {
578 sim, tpm := setupSimulatedTPM(t)
579 defer sim.Close()
580
581 // TPM will refuse to hash a message that is too short.
582 sizes := []int{0, 1, 2}
583
584 for _, size := range sizes {
585 t.Run(fmt.Sprintf("size=%d", size), func(t *testing.T) {
586 msg := make([]byte, size)
587 _, _, err := tpmHash(tpm.tpm.(*wrappedTPM20).rwc, msg, crypto.SHA256)
588 if err == nil {
589 t.Errorf("Hash() succeeded, want error")
590 }
591 })
592 }
593 }
594
595 func TestSignMsg(t *testing.T) {
596 sim, tpm := setupSimulatedTPM(t)
597 defer sim.Close()
598
599 ak, err := tpm.NewAK(nil)
600 if err != nil {
601 t.Fatalf("NewAK() failed: %v", err)
602 }
603
604 msg := []byte("hello world")
605 hashed := sha256.Sum256(msg)
606
607 sig, err := ak.SignMsg(tpm, msg, crypto.SHA256)
608 if err != nil {
609 t.Fatalf("SignMsg() failed: %v", err)
610 }
611
612 if err := rsa.VerifyPKCS1v15(ak.Public().(*rsa.PublicKey), crypto.SHA256, hashed[:], sig); err != nil {
613 t.Errorf("rsa.VerifyPKCS1v15() failed: %v", err)
614 }
615 }