Debian Codegraph @

legacy/tpm2/test/tpm2_test.go

raw
1 // Copyright (c) 2018, Google LLC All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of 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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package tpm2
16
17 import (
18 "bytes"
19 "crypto"
20 "crypto/ecdsa"
21 "crypto/elliptic"
22 "crypto/rand"
23 "crypto/rsa"
24 "crypto/sha1"
25 "crypto/sha256"
26 "encoding/binary"
27 "flag"
28 "fmt"
29 "hash"
30 "io"
31 "math"
32 "math/big"
33 "reflect"
34 "strings"
35 "testing"
36
37 "github.com/google/go-tpm-tools/simulator"
38 . "github.com/google/go-tpm/legacy/tpm2"
39 "github.com/google/go-tpm/tpmutil"
40 )
41
42 var (
43 runClear = flag.Bool("run-clear", false, "Set to run tests which will clear hierarchy and lockout authorizations")
44 )
45
46 func init() {
47 testing.Init()
48 flag.Parse()
49 }
50
51 func openTPM(tb testing.TB) io.ReadWriteCloser {
52 tb.Helper()
53 if useDeviceTPM() {
54 return openDeviceTPM(tb)
55 }
56 simulator, err := simulator.Get()
57 if err != nil {
58 tb.Fatalf("Simulator initialization failed: %v", err)
59 }
60 return simulator
61 }
62
63 var (
64 // PCR7 is for SecureBoot.
65 pcrSelection7 = PCRSelection{Hash: AlgSHA1, PCRs: []int{7}}
66 pcrSelectionAll = PCRSelection{Hash: AlgSHA1, PCRs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}}
67 defaultKeyParams = Public{
68 Type: AlgRSA,
69 NameAlg: AlgSHA1,
70 Attributes: FlagStorageDefault,
71 RSAParameters: &RSAParams{
72 Symmetric: &SymScheme{
73 Alg: AlgAES,
74 KeyBits: 128,
75 Mode: AlgCFB,
76 },
77 KeyBits: 2048,
78 ExponentRaw: 1<<16 + 1,
79 },
80 }
81 defaultPassword = "\x01\x02\x03\x04"
82 emptyPassword = ""
83 defaultRsaSignerParams = Public{
84 Type: AlgRSA,
85 NameAlg: AlgSHA256,
86 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
87 RSAParameters: &RSAParams{
88 Sign: &SigScheme{
89 Alg: AlgRSASSA,
90 Hash: AlgSHA256,
91 },
92 KeyBits: 2048,
93 },
94 }
95 defaultEccSignerParams = Public{
96 Type: AlgECC,
97 NameAlg: AlgSHA256,
98 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
99 ECCParameters: &ECCParams{
100 Sign: &SigScheme{
101 Alg: AlgECDSA,
102 Hash: AlgSHA256,
103 },
104 CurveID: CurveNISTP256,
105 },
106 }
107 nullTicketSigned = Ticket{Type: TagAuthSigned, Hierarchy: HandleNull}
108 nullTicketSecret = Ticket{Type: TagAuthSecret, Hierarchy: HandleNull}
109 )
110
111 func min(a, b int) int {
112 if a < b {
113 return a
114 }
115 return b
116 }
117
118 func TestGetRandom(t *testing.T) {
119 rw := openTPM(t)
120 defer rw.Close()
121
122 if _, err := GetRandom(rw, 16); err != nil {
123 t.Fatalf("GetRandom failed: %v", err)
124 }
125 }
126
127 func TestReadPCRs(t *testing.T) {
128 rw := openTPM(t)
129 defer rw.Close()
130
131 pcrs, err := ReadPCRs(rw, pcrSelection7)
132 if err != nil {
133 t.Errorf("ReadPCRs failed: %s", err)
134 }
135 if !useDeviceTPM() {
136 return // PCR 7 is initialized to 0 in the simulator.
137 }
138 for pcr, val := range pcrs {
139 if empty := make([]byte, len(val)); reflect.DeepEqual(empty, val) {
140 t.Errorf("Value of PCR %d is empty", pcr)
141 }
142 }
143 }
144
145 func TestReadAllPCRs(t *testing.T) {
146 rw := openTPM(t)
147 defer rw.Close()
148
149 numPCRs := len(pcrSelectionAll.PCRs)
150 out := map[uint32][]byte{}
151
152 for i := 0; i < numPCRs; i += 8 {
153 // Build a selection structure, specifying 8 PCRs at a time
154 end := min(i+8, numPCRs)
155 pcrSel := PCRSelection{
156 Hash: pcrSelectionAll.Hash,
157 PCRs: pcrSelectionAll.PCRs[i:end],
158 }
159
160 // Ask the TPM for those PCR values.
161 ret, err := ReadPCRs(rw, pcrSel)
162 if err != nil {
163 t.Errorf("ReadPCRs(%+v) failed: %v", pcrSel, err)
164 }
165
166 // Keep track of the PCRs we were actually given.
167 for pcr, digest := range ret {
168 out[uint32(pcr)] = digest
169 }
170 }
171
172 if len(out) != numPCRs {
173 t.Errorf("Failed to read all PCRs, only read %d", len(out))
174 }
175 }
176
177 func TestReadClock(t *testing.T) {
178 rw := openTPM(t)
179 defer rw.Close()
180
181 if _, _, err := ReadClock(rw); err != nil {
182 t.Fatalf("ReadClock failed: %s", err)
183 }
184
185 }
186
187 func TestGetCapability(t *testing.T) {
188 rw := openTPM(t)
189 defer rw.Close()
190
191 for _, tt := range []struct {
192 capa Capability
193 count uint32
194 property uint32
195 typ interface{}
196 }{
197 {CapabilityHandles, 1, uint32(HandleTypeTransient) << 24, tpmutil.Handle(0)},
198 {CapabilityAlgs, 1, 0, AlgorithmDescription{}},
199 {CapabilityTPMProperties, 1, uint32(NVMaxBufferSize), TaggedProperty{}},
200 } {
201 l, _, err := GetCapability(rw, tt.capa, tt.count, tt.property)
202 if err != nil {
203 t.Fatalf("GetCapability(%v, %d, %d) = _, %v; want _, nil", tt.capa, tt.count, tt.property, err)
204 }
205 for _, i := range l {
206 if reflect.TypeOf(i) != reflect.TypeOf(tt.typ) {
207 t.Fatalf("GetCapability(%v, %d, %d) returned an element with the wrong type: %v; want %v", tt.capa, tt.count, tt.property, reflect.TypeOf(i), reflect.TypeOf(tt.typ))
208 }
209 }
210 }
211 }
212
213 func TestCombinedKeyTest(t *testing.T) {
214 rw := openTPM(t)
215 defer rw.Close()
216
217 parentHandle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, defaultKeyParams)
218 if err != nil {
219 t.Fatalf("CreatePrimary failed: %s", err)
220 }
221 defer FlushContext(rw, parentHandle)
222
223 privateBlob, publicBlob, _, _, _, err := CreateKey(rw, parentHandle, pcrSelection7, defaultPassword, defaultPassword, defaultKeyParams)
224 if err != nil {
225 t.Fatalf("CreateKey failed: %s", err)
226 }
227
228 keyHandle, name, err := Load(rw, parentHandle, defaultPassword, publicBlob, privateBlob)
229 if err != nil {
230 t.Fatalf("Load failed: %s", err)
231 }
232 defer FlushContext(rw, keyHandle)
233
234 if _, err := DecodeName(bytes.NewBuffer(name)); err != nil {
235 t.Errorf("DecodeName failed: %v", err)
236 }
237 if _, _, _, err := ReadPublic(rw, keyHandle); err != nil {
238 t.Fatalf("ReadPublic failed: %s", err)
239 }
240 }
241
242 func TestCombinedEndorsementTest(t *testing.T) {
243 rw := openTPM(t)
244 defer rw.Close()
245
246 parentHandle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, emptyPassword, defaultKeyParams)
247 if err != nil {
248 t.Fatalf("CreatePrimary failed: %s", err)
249 }
250 defer FlushContext(rw, parentHandle)
251
252 privateBlob, publicBlob, _, _, _, err := CreateKey(rw, parentHandle, pcrSelection7, emptyPassword, defaultPassword, defaultKeyParams)
253 if err != nil {
254 t.Fatalf("CreateKey failed: %s", err)
255 }
256
257 keyHandle, nameData, err := Load(rw, parentHandle, emptyPassword, publicBlob, privateBlob)
258 if err != nil {
259 t.Fatalf("Load failed: %s", err)
260 }
261 defer FlushContext(rw, keyHandle)
262
263 if _, err := DecodeName(bytes.NewBuffer(nameData)); err != nil {
264 t.Errorf("DecodeName failed: %v", err)
265 }
266 _, name, _, err := ReadPublic(rw, keyHandle)
267 if err != nil {
268 t.Fatalf("ReadPublic failed: %s", err)
269 }
270
271 // Generate Credential
272 credential := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10}
273 credBlob, encryptedSecret0, err := MakeCredential(rw, parentHandle, credential, name)
274 if err != nil {
275 t.Fatalf("MakeCredential failed: %v", err)
276 }
277
278 recoveredCredential1, err := ActivateCredential(rw, keyHandle, parentHandle, defaultPassword, emptyPassword, credBlob, encryptedSecret0)
279 if err != nil {
280 t.Fatalf("ActivateCredential failed: %v", err)
281 }
282 if !bytes.Equal(credential, recoveredCredential1) {
283 t.Fatalf("Credential and recovered credential differ: got %v, want %v", recoveredCredential1, credential)
284 }
285
286 recoveredCredential2, err := ActivateCredentialUsingAuth(rw, []AuthCommand{
287 {Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(defaultPassword)},
288 {Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(emptyPassword)},
289 }, keyHandle, parentHandle, credBlob, encryptedSecret0)
290 if err != nil {
291 t.Fatalf("ActivateCredentialWithAuth failed: %v", err)
292 }
293 if !bytes.Equal(credential, recoveredCredential2) {
294 t.Errorf("Credential and recovered credential differ: got %v, want %v", recoveredCredential2, credential)
295 }
296
297 _, err = ActivateCredentialUsingAuth(rw, []AuthCommand{
298 {Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte("incorrect password")},
299 {Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(emptyPassword)},
300 }, keyHandle, parentHandle, credBlob, encryptedSecret0)
301 if err == nil {
302 t.Fatal("ActivateCredentialUsingAuth: error == nil, expected authorization failure")
303 }
304 if !strings.Contains(err.Error(), "the authorization HMAC check failed") {
305 t.Errorf("ActivateCredentialUsingAuth: error = %v, expected authorization failure", err)
306 }
307
308 _, err = ActivateCredentialUsingAuth(rw, []AuthCommand{
309 {Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(emptyPassword)},
310 }, keyHandle, parentHandle, credBlob, encryptedSecret0)
311 if err == nil {
312 t.Fatal("ActivateCredentialUsingAuth: error == nil, expected response status 0x98e (authorization failure)")
313 }
314 if !strings.Contains(err.Error(), "len(auth) = 1, want 2") {
315 t.Errorf("ActivateCredentialUsingAuth: error = %v, expected len(auth) = 1, want 2", err)
316 }
317 }
318
319 func TestCreatePrimaryEx(t *testing.T) {
320 rw := openTPM(t)
321 defer rw.Close()
322
323 keyHandle, pub1, creation, _, _, name, err := CreatePrimaryEx(rw, HandleOwner, pcrSelection7, emptyPassword, emptyPassword, defaultKeyParams)
324 if err != nil {
325 t.Fatalf("CreatePrimary failed: %v", err)
326 }
327 defer FlushContext(rw, keyHandle)
328
329 pub, _, _, err := ReadPublic(rw, keyHandle)
330 if err != nil {
331 t.Fatalf("ReadPublic failed: %s", err)
332 }
333 pub2, err := pub.Encode()
334 if err != nil {
335 t.Fatalf("Failed to encode public: %v", err)
336 }
337
338 if !bytes.Equal(pub1, pub2) {
339 t.Error("Mismatch between public returned from CreatePrimaryEx() & ReadPublic()")
340 t.Logf("CreatePrimaryEx: %v", pub1)
341 t.Logf("ReadPublic: %v", pub2)
342 }
343
344 if _, err := DecodeName(bytes.NewBuffer(name)); err != nil {
345 t.Errorf("Failed to decode name: %v", err)
346 }
347 if _, err := DecodeCreationData(creation); err != nil {
348 t.Fatalf("DecodeCreationData() returned err: %v", err)
349 }
350 }
351
352 func TestCombinedContextTest(t *testing.T) {
353 rw := openTPM(t)
354 defer rw.Close()
355
356 rootHandle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, emptyPassword, defaultKeyParams)
357 if err != nil {
358 t.Fatalf("CreatePrimary failed: %v", err)
359 }
360 defer FlushContext(rw, rootHandle)
361
362 // CreateKey (Quote Key)
363 quotePrivate, quotePublic, _, _, _, err := CreateKey(rw, rootHandle, pcrSelection7, emptyPassword, emptyPassword, defaultKeyParams)
364 if err != nil {
365 t.Fatalf("CreateKey failed: %v", err)
366 }
367
368 quoteHandle, _, err := Load(rw, rootHandle, emptyPassword, quotePublic, quotePrivate)
369 if err != nil {
370 t.Fatalf("Load failed: %v", err)
371 }
372 defer FlushContext(rw, quoteHandle)
373
374 saveArea, err := ContextSave(rw, quoteHandle)
375 if err != nil {
376 t.Fatalf("ContextSave failed: %v", err)
377 }
378 FlushContext(rw, quoteHandle)
379
380 if _, err = ContextLoad(rw, saveArea); err != nil {
381 t.Fatalf("Load failed: %v", err)
382 }
383 }
384
385 func TestEvictControl(t *testing.T) {
386 rw := openTPM(t)
387 defer rw.Close()
388
389 rootHandle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, emptyPassword, defaultKeyParams)
390 if err != nil {
391 t.Fatalf("CreatePrimary failed: %v", err)
392 }
393 defer FlushContext(rw, rootHandle)
394
395 // CreateKey (Quote Key)
396 quotePrivate, quotePublic, _, _, _, err := CreateKey(rw, rootHandle, pcrSelection7, emptyPassword, emptyPassword, defaultKeyParams)
397 if err != nil {
398 t.Fatalf("CreateKey failed: %v", err)
399 }
400
401 quoteHandle, _, err := Load(rw, rootHandle, emptyPassword, quotePublic, quotePrivate)
402 if err != nil {
403 t.Fatalf("Load failed: %v", err)
404 }
405 defer FlushContext(rw, quoteHandle)
406
407 persistentHandle := tpmutil.Handle(0x817FFFFF)
408 // Evict persistent key, if there is one already (e.g. last test run failed).
409 if err := EvictControl(rw, emptyPassword, HandleOwner, persistentHandle, persistentHandle); err != nil {
410 t.Logf("(expected) EvictControl failed: %v", err)
411 }
412 // Make key persistent.
413 if err := EvictControl(rw, emptyPassword, HandleOwner, quoteHandle, persistentHandle); err != nil {
414 t.Fatalf("EvictControl failed: %v", err)
415 }
416 // Evict persistent key.
417 if err := EvictControl(rw, emptyPassword, HandleOwner, persistentHandle, persistentHandle); err != nil {
418 t.Fatalf("EvictControl failed: %v", err)
419 }
420 }
421
422 func TestHash(t *testing.T) {
423 rw := openTPM(t)
424 defer rw.Close()
425
426 run := func(t *testing.T, data []byte, hierarchy tpmutil.Handle, wantValidation bool) {
427 gotDigest, gotValidation, err := Hash(rw, AlgSHA256, data, hierarchy)
428 if err != nil {
429 t.Fatalf("Hash failed: %v", err)
430 }
431 wantDigest := sha256.Sum256(data)
432
433 if !bytes.Equal(gotDigest, wantDigest[:]) {
434 t.Errorf("Hash(%q) returned digest %x, want %x", data, gotDigest, wantDigest)
435 }
436 if wantValidation && len(gotValidation.Digest) == 0 {
437 t.Errorf("Hash(%q) unexpectedly returned empty validation ticket", data)
438 }
439 if !wantValidation && len(gotValidation.Digest) != 0 {
440 t.Errorf("Hash(%q) unexpectedly returned non-empty validation ticket", data)
441 }
442 }
443 t.Run("Null hierarchy", func(t *testing.T) {
444 run(t, []byte("foobarbaz"), HandleNull, false)
445 })
446 t.Run("Owner hierarchy", func(t *testing.T) {
447 run(t, []byte("foobarbaz"), HandleOwner, true)
448 })
449 t.Run("Starts with TPM_GENERATED_VALUE", func(t *testing.T) {
450 run(t, []byte("\xffTCGbarbaz"), HandleOwner, false)
451 })
452 }
453
454 func testHashSequence(t *testing.T, rw io.ReadWriter, hierarchy tpmutil.Handle, hashAlg Algorithm, data []byte) ([]byte, *Ticket) {
455 const (
456 maxDigestBuffer = 1024
457 seqAuth = ""
458 )
459
460 seq, err := HashSequenceStart(rw, seqAuth, hashAlg)
461 if err != nil {
462 t.Fatalf("HashSequenceStart failed: %v", err)
463 }
464 defer FlushContext(rw, seq)
465
466 for len(data) > maxDigestBuffer {
467 if err = SequenceUpdate(rw, seqAuth, seq, data[:maxDigestBuffer]); err != nil {
468 t.Fatalf("SequenceUpdate failed: %v", err)
469 }
470 data = data[maxDigestBuffer:]
471 }
472
473 digest, ticket, err := SequenceComplete(rw, seqAuth, seq, hierarchy, data)
474 if err != nil {
475 t.Fatalf("SequenceComplete failed: %v", err)
476 }
477 return digest, ticket
478 }
479
480 func TestHashSequence(t *testing.T) {
481 rw := openTPM(t)
482 defer rw.Close()
483
484 run := func(t *testing.T, data []byte, hierarchy tpmutil.Handle, wantValidation bool) {
485 gotDigest, gotValidation := testHashSequence(t, rw, hierarchy, AlgSHA256, data)
486 wantDigest := sha256.Sum256(data)
487
488 if !bytes.Equal(gotDigest, wantDigest[:]) {
489 t.Errorf("Hash(%q) returned digest %x, want %x", data, gotDigest, wantDigest)
490 }
491 if wantValidation && len(gotValidation.Digest) == 0 {
492 t.Errorf("Hash(%q) unexpectedly returned empty validation ticket", data)
493 }
494 if !wantValidation && len(gotValidation.Digest) != 0 {
495 t.Errorf("Hash(%q) unexpectedly returned non-empty validation ticket", data)
496 }
497 }
498
499 bufferSizes := []int{512, 1024, 2048, 4096}
500 for _, bufferSize := range bufferSizes {
501 buffer := make([]byte, bufferSize)
502
503 if _, err := rand.Read(buffer); err != nil {
504 t.Fatalf("rand.Read failed: %v", err)
505 }
506
507 t.Run(fmt.Sprintf("Null hierarchy [bufferSize=%d]", bufferSize), func(t *testing.T) {
508 run(t, buffer, HandleNull, false)
509 })
510 t.Run(fmt.Sprintf("Owner hierarchy [bufferSize=%d]", bufferSize), func(t *testing.T) {
511 run(t, buffer, HandleOwner, true)
512 })
513
514 // TCG generated values from now on
515 copy(buffer, []byte("\xffTCG"))
516
517 t.Run(fmt.Sprintf("Starts with TPM_GENERATED_VALUE [bufferSize=%d]", bufferSize), func(t *testing.T) {
518 run(t, buffer, HandleOwner, false)
519 })
520 }
521 }
522
523 func skipOnUnsupportedAlg(t testing.TB, rw io.ReadWriter, alg Algorithm) {
524 moreData := true
525 for i := uint32(0); moreData; i++ {
526 var err error
527 var descs []interface{}
528 descs, moreData, err = GetCapability(rw, CapabilityAlgs, 1, i)
529 if err != nil {
530 t.Fatalf("Could not get TPM algorithm capability: %v", err)
531 }
532 for _, desc := range descs {
533 if desc.(AlgorithmDescription).ID == alg {
534 return
535 }
536 }
537 if !moreData {
538 break
539 }
540 }
541 t.Skipf("Algorithm %v is not supported by the TPM", alg)
542 }
543
544 func TestLoadExternalPublicKey(t *testing.T) {
545 rw := openTPM(t)
546 defer rw.Close()
547
548 run := func(t *testing.T, public Public, private Private) {
549 t.Helper()
550
551 h, _, err := LoadExternal(rw, public, private, HandleNull)
552 if err != nil {
553 t.Fatal(err)
554 }
555 defer FlushContext(rw, h)
556 }
557
558 t.Run("RSA", func(t *testing.T) {
559 pk, err := rsa.GenerateKey(rand.Reader, 2048)
560 if err != nil {
561 t.Fatal(err)
562 }
563 rp := Public{
564 Type: AlgRSA,
565 NameAlg: AlgSHA1,
566 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
567 RSAParameters: &RSAParams{
568 Sign: &SigScheme{
569 Alg: AlgRSASSA,
570 Hash: AlgSHA1,
571 },
572 KeyBits: 2048,
573 ExponentRaw: uint32(pk.PublicKey.E),
574 ModulusRaw: pk.PublicKey.N.Bytes(),
575 },
576 }
577 private := Private{
578 Type: AlgRSA,
579 Sensitive: pk.Primes[0].Bytes(),
580 }
581 run(t, rp, private)
582 })
583 t.Run("ECC", func(t *testing.T) {
584 skipOnUnsupportedAlg(t, rw, AlgECC)
585 pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
586 if err != nil {
587 t.Fatal(err)
588 }
589 public := Public{
590 Type: AlgECC,
591 NameAlg: AlgSHA1,
592 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
593 ECCParameters: &ECCParams{
594 Sign: &SigScheme{
595 Alg: AlgECDSA,
596 Hash: AlgSHA1,
597 },
598 CurveID: CurveNISTP256,
599 Point: ECPoint{XRaw: pk.PublicKey.X.Bytes(), YRaw: pk.PublicKey.Y.Bytes()},
600 },
601 }
602 private := Private{
603 Type: AlgECC,
604 Sensitive: pk.D.Bytes(),
605 }
606 run(t, public, private)
607 })
608 }
609
610 func TestCertify(t *testing.T) {
611 rw := openTPM(t)
612 defer rw.Close()
613
614 params := Public{
615 Type: AlgRSA,
616 NameAlg: AlgSHA256,
617 Attributes: FlagSignerDefault,
618 RSAParameters: &RSAParams{
619 Sign: &SigScheme{
620 Alg: AlgRSASSA,
621 Hash: AlgSHA256,
622 },
623 KeyBits: 2048,
624 },
625 }
626 signerHandle, signerPub, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, params)
627 if err != nil {
628 t.Fatalf("CreatePrimary(signer) failed: %s", err)
629 }
630 defer FlushContext(rw, signerHandle)
631
632 subjectHandle, subjectPub, err := CreatePrimary(rw, HandlePlatform, pcrSelection7, emptyPassword, defaultPassword, params)
633 if err != nil {
634 t.Fatalf("CreatePrimary(subject) failed: %s", err)
635 }
636 defer FlushContext(rw, subjectHandle)
637
638 attest, sigRaw, err := Certify(rw, defaultPassword, defaultPassword, subjectHandle, signerHandle, nil)
639 if err != nil {
640 t.Errorf("Certify failed: %s", err)
641 return
642 }
643 sig, err := DecodeSignature(bytes.NewBuffer(sigRaw))
644 if err != nil {
645 t.Errorf("DecodeSignature failed: %s", err)
646 return
647 }
648
649 attestHash := sha256.Sum256(attest)
650 if err := rsa.VerifyPKCS1v15(signerPub.(*rsa.PublicKey), crypto.SHA256, attestHash[:], sig.RSA.Signature); err != nil {
651 t.Errorf("Signature verification failed: %v", err)
652 }
653
654 t.Run("DecodeAttestationData", func(t *testing.T) {
655 ad, err := DecodeAttestationData(attest)
656 if err != nil {
657 t.Fatal("DecodeAttestationData:", err)
658 }
659 params := Public{
660 Type: AlgRSA,
661 NameAlg: AlgSHA256,
662 Attributes: FlagSignerDefault,
663 RSAParameters: &RSAParams{
664 Sign: &SigScheme{
665 Alg: AlgRSASSA,
666 Hash: AlgSHA256,
667 },
668 KeyBits: 2048,
669 // Note: we don't include Exponent because CreatePrimary also
670 // returns Public without it.
671 ModulusRaw: subjectPub.(*rsa.PublicKey).N.Bytes(),
672 },
673 }
674 matches, err := ad.AttestedCertifyInfo.Name.MatchesPublic(params)
675 if err != nil {
676 t.Fatalf("AttestedCertifyInfo.Name.MatchesPublic error: %v", err)
677 }
678 if !matches {
679 t.Error("Name in AttestationData doesn't match Public structure of subject")
680 }
681 })
682 }
683
684 func TestCertifyEx(t *testing.T) {
685 rw := openTPM(t)
686 defer rw.Close()
687
688 restrictedKeySignerFlags := FlagSignerDefault
689 unrestrictedKeySignerFlags := FlagSign | FlagFixedTPM | FlagFixedParent | FlagSensitiveDataOrigin | FlagUserWithAuth
690 testCases := []struct {
691 description string
692 attributes KeyProp
693 keyScheme SigScheme
694 passedScheme SigScheme
695 shouldPass bool
696 }{
697 {"Null-SHA1", unrestrictedKeySignerFlags, SigScheme{Alg: AlgNull}, SigScheme{Alg: AlgRSASSA, Hash: AlgSHA1}, true},
698 {"Null-SHA256", unrestrictedKeySignerFlags, SigScheme{Alg: AlgNull}, SigScheme{Alg: AlgRSASSA, Hash: AlgSHA256}, true},
699 {"Null-Null", unrestrictedKeySignerFlags, SigScheme{Alg: AlgNull}, SigScheme{Alg: AlgNull}, false},
700 {"SHA256-Null", restrictedKeySignerFlags, SigScheme{Alg: AlgRSASSA, Hash: AlgSHA256}, SigScheme{Alg: AlgNull}, true},
701 {"SHA256-SHA256", restrictedKeySignerFlags, SigScheme{Alg: AlgRSASSA, Hash: AlgSHA256}, SigScheme{Alg: AlgRSASSA, Hash: AlgSHA256}, true},
702 {"SHA256-SHA1", restrictedKeySignerFlags, SigScheme{Alg: AlgRSASSA, Hash: AlgSHA256}, SigScheme{Alg: AlgRSASSA, Hash: AlgSHA1}, false},
703 }
704
705 for _, testCase := range testCases {
706 params := Public{
707 Type: AlgRSA,
708 NameAlg: AlgSHA256,
709 Attributes: testCase.attributes,
710 RSAParameters: &RSAParams{
711 Sign: &testCase.keyScheme,
712 KeyBits: 2048,
713 },
714 }
715
716 t.Run(testCase.description, func(t *testing.T) {
717 signerHandle, _, err := CreatePrimary(rw, HandleOwner, PCRSelection{}, emptyPassword, defaultPassword, params)
718 if err != nil {
719 t.Fatalf("CreatePrimary(signer) failed: %s", err)
720 }
721 defer FlushContext(rw, signerHandle)
722
723 subjectHandle, _, err := CreatePrimary(rw, HandlePlatform, PCRSelection{}, emptyPassword, defaultPassword, params)
724 if err != nil {
725 t.Fatalf("CreatePrimary(subject) failed: %s", err)
726 }
727 defer FlushContext(rw, subjectHandle)
728
729 _, _, err = CertifyEx(rw, defaultPassword, defaultPassword, subjectHandle, signerHandle, nil, testCase.passedScheme)
730 if err != nil && testCase.shouldPass {
731 t.Errorf("CertifyEx expected to succeed but failed: %s", err)
732 } else if err == nil && !testCase.shouldPass {
733 t.Errorf("CertifyEx expected to fail but succeeded")
734 }
735 })
736 }
737 }
738
739 func TestCertifyExternalKey(t *testing.T) {
740 rw := openTPM(t)
741 defer rw.Close()
742
743 params := Public{
744 Type: AlgRSA,
745 NameAlg: AlgSHA256,
746 Attributes: FlagSignerDefault,
747 RSAParameters: &RSAParams{
748 Sign: &SigScheme{
749 Alg: AlgRSASSA,
750 Hash: AlgSHA256,
751 },
752 KeyBits: 2048,
753 },
754 }
755 signerHandle, signerPub, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, params)
756 if err != nil {
757 t.Fatalf("CreatePrimary(signer) failed: %s", err)
758 }
759 defer FlushContext(rw, signerHandle)
760
761 run := func(t *testing.T, public Public, private Private) {
762 t.Helper()
763 subjectHandle, _, err := LoadExternal(rw, public, private, HandleNull)
764 if err != nil {
765 t.Fatalf("LoadExternal: %v", err)
766 }
767 defer FlushContext(rw, subjectHandle)
768
769 attest, sigRaw, err := Certify(rw, emptyPassword, defaultPassword, subjectHandle, signerHandle, nil)
770 if err != nil {
771 t.Errorf("Certify failed: %s", err)
772 return
773 }
774 sig, err := DecodeSignature(bytes.NewBuffer(sigRaw))
775 if err != nil {
776 t.Errorf("DecodeSignature failed: %s", err)
777 return
778 }
779
780 attestHash := sha256.Sum256(attest)
781 if err := rsa.VerifyPKCS1v15(signerPub.(*rsa.PublicKey), crypto.SHA256, attestHash[:], sig.RSA.Signature); err != nil {
782 t.Errorf("Signature verification failed: %v", err)
783 }
784 }
785 t.Run("RSA", func(t *testing.T) {
786 pk, err := rsa.GenerateKey(rand.Reader, 2048)
787 if err != nil {
788 t.Fatal(err)
789 }
790 public := Public{
791 Type: AlgRSA,
792 NameAlg: AlgSHA1,
793 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
794 RSAParameters: &RSAParams{
795 Sign: &SigScheme{
796 Alg: AlgRSASSA,
797 Hash: AlgSHA1,
798 },
799 KeyBits: 2048,
800 ExponentRaw: uint32(pk.PublicKey.E),
801 ModulusRaw: pk.PublicKey.N.Bytes(),
802 },
803 }
804 private := Private{
805 Type: AlgRSA,
806 Sensitive: pk.Primes[0].Bytes(),
807 }
808 run(t, public, private)
809 })
810 t.Run("ECC", func(t *testing.T) {
811 skipOnUnsupportedAlg(t, rw, AlgECC)
812 pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
813 if err != nil {
814 t.Fatal(err)
815 }
816 public := Public{
817 Type: AlgECC,
818 NameAlg: AlgSHA1,
819 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
820 ECCParameters: &ECCParams{
821 Sign: &SigScheme{
822 Alg: AlgECDSA,
823 Hash: AlgSHA1,
824 },
825 CurveID: CurveNISTP256,
826 Point: ECPoint{XRaw: pk.PublicKey.X.Bytes(), YRaw: pk.PublicKey.Y.Bytes()},
827 },
828 }
829 private := Private{
830 Type: AlgECC,
831 Sensitive: pk.D.Bytes(),
832 }
833 run(t, public, private)
834 })
835 }
836
837 func TestSign(t *testing.T) {
838 rw := openTPM(t)
839 defer rw.Close()
840
841 run := func(t *testing.T, pub Public) {
842 signerHandle, signerPub, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, pub)
843 if err != nil {
844 t.Fatalf("CreatePrimary failed: %s", err)
845 }
846 defer FlushContext(rw, signerHandle)
847
848 digest := sha256.Sum256([]byte("heyo"))
849
850 sig, err := Sign(rw, signerHandle, defaultPassword, digest[:], nil, nil)
851 if err != nil {
852 t.Fatalf("Sign failed: %s", err)
853 }
854 switch signerPub := signerPub.(type) {
855 case *rsa.PublicKey:
856 switch pub.RSAParameters.Sign.Alg {
857 case AlgRSASSA:
858 if err := rsa.VerifyPKCS1v15(signerPub, crypto.SHA256, digest[:], sig.RSA.Signature); err != nil {
859 t.Errorf("Signature verification failed: %v", err)
860 }
861 case AlgRSAPSS:
862 if err := rsa.VerifyPSS(signerPub, crypto.SHA256, digest[:], sig.RSA.Signature, nil); err != nil {
863 t.Errorf("Signature verification failed: %v", err)
864 }
865 default:
866 t.Errorf("unsupported signature algorithm 0x%x", pub.RSAParameters.Sign.Alg)
867 }
868 case *ecdsa.PublicKey:
869 if !ecdsa.Verify(signerPub, digest[:], sig.ECC.R, sig.ECC.S) {
870 t.Error("Signature verification failed")
871 }
872 }
873 }
874
875 t.Run("RSA SSA", func(t *testing.T) {
876 run(t, Public{
877 Type: AlgRSA,
878 NameAlg: AlgSHA256,
879 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
880 RSAParameters: &RSAParams{
881 Sign: &SigScheme{
882 Alg: AlgRSASSA,
883 Hash: AlgSHA256,
884 },
885 KeyBits: 2048,
886 },
887 })
888 })
889 t.Run("RSA PSS", func(t *testing.T) {
890 run(t, Public{
891 Type: AlgRSA,
892 NameAlg: AlgSHA256,
893 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
894 RSAParameters: &RSAParams{
895 Sign: &SigScheme{
896 Alg: AlgRSAPSS,
897 Hash: AlgSHA256,
898 },
899 KeyBits: 2048,
900 },
901 })
902 })
903 t.Run("ECC", func(t *testing.T) {
904 skipOnUnsupportedAlg(t, rw, AlgECC)
905 run(t, Public{
906 Type: AlgECC,
907 NameAlg: AlgSHA256,
908 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
909 ECCParameters: &ECCParams{
910 Sign: &SigScheme{
911 Alg: AlgECDSA,
912 Hash: AlgSHA256,
913 },
914 CurveID: CurveNISTP256,
915 },
916 })
917 })
918 }
919
920 func TestSignWithAttestationKey(t *testing.T) {
921 rw := openTPM(t)
922 defer rw.Close()
923
924 run := func(t *testing.T, data []byte, wantErr bool, pub Public) {
925 signerHandle, signerPub, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, pub)
926 if err != nil {
927 t.Fatalf("CreatePrimary failed: %v", err)
928 }
929 defer FlushContext(rw, signerHandle)
930
931 digest, validation, err := Hash(rw, AlgSHA256, data, HandleOwner)
932 if err != nil {
933 t.Fatalf("Hash failed unexpectedly: %v", err)
934 }
935
936 sig, err := Sign(rw, signerHandle, defaultPassword, digest, validation, nil)
937 if err != nil && !wantErr {
938 t.Fatalf("Sign failed unexpectedly: %v", err)
939 }
940 if err == nil && wantErr {
941 t.Fatalf("Sign succeeded unexpectedly: %v", sig)
942 }
943 if !wantErr {
944 switch signerPub := signerPub.(type) {
945 case *rsa.PublicKey:
946 switch pub.RSAParameters.Sign.Alg {
947 case AlgRSASSA:
948 if err := rsa.VerifyPKCS1v15(signerPub, crypto.SHA256, digest[:], sig.RSA.Signature); err != nil {
949 t.Errorf("Signature verification failed: %v", err)
950 }
951 case AlgRSAPSS:
952 if err := rsa.VerifyPSS(signerPub, crypto.SHA256, digest[:], sig.RSA.Signature, nil); err != nil {
953 t.Errorf("Signature verification failed: %v", err)
954 }
955 default:
956 t.Errorf("unsupported signature algorithm 0x%x", pub.RSAParameters.Sign.Alg)
957 }
958 case *ecdsa.PublicKey:
959 if !ecdsa.Verify(signerPub, digest[:], sig.ECC.R, sig.ECC.S) {
960 t.Error("Signature verification failed")
961 }
962 }
963 }
964 }
965
966 rsassa := Public{
967 Type: AlgRSA,
968 NameAlg: AlgSHA256,
969 Attributes: FlagSign | FlagRestricted | FlagSensitiveDataOrigin | FlagUserWithAuth,
970 RSAParameters: &RSAParams{
971 Sign: &SigScheme{
972 Alg: AlgRSASSA,
973 Hash: AlgSHA256,
974 },
975 KeyBits: 2048,
976 },
977 }
978 rsapss := Public{
979 Type: AlgRSA,
980 NameAlg: AlgSHA256,
981 Attributes: FlagSign | FlagRestricted | FlagSensitiveDataOrigin | FlagUserWithAuth,
982 RSAParameters: &RSAParams{
983 Sign: &SigScheme{
984 Alg: AlgRSAPSS,
985 Hash: AlgSHA256,
986 },
987 KeyBits: 2048,
988 },
989 }
990 ecdsa := Public{
991 Type: AlgECC,
992 NameAlg: AlgSHA256,
993 Attributes: FlagSign | FlagRestricted | FlagSensitiveDataOrigin | FlagUserWithAuth,
994 ECCParameters: &ECCParams{
995 Sign: &SigScheme{
996 Alg: AlgECDSA,
997 Hash: AlgSHA256,
998 },
999 CurveID: CurveNISTP256,
1000 },
1001 }
1002
1003 t.Run("RSA SSA", func(t *testing.T) {
1004 run(t, []byte("test123"), false, rsassa)
1005 })
1006 t.Run("RSA PSS", func(t *testing.T) {
1007 run(t, []byte("test123"), false, rsapss)
1008 })
1009 t.Run("ECC", func(t *testing.T) {
1010 skipOnUnsupportedAlg(t, rw, AlgECC)
1011 run(t, []byte("test123"), false, ecdsa)
1012 })
1013 t.Run("RSA SSA with TPM_GENERATED_VALUE", func(t *testing.T) {
1014 run(t, []byte("\xffTCG123"), true, rsassa)
1015 })
1016 t.Run("RSA PSS with TPM_GENERATED_VALUE", func(t *testing.T) {
1017 run(t, []byte("\xffTCG123"), true, rsapss)
1018 })
1019 t.Run("ECC with TPM_GENERATED_VALUE", func(t *testing.T) {
1020 skipOnUnsupportedAlg(t, rw, AlgECC)
1021 run(t, []byte("\xffTCG123"), true, ecdsa)
1022 })
1023 }
1024
1025 func TestPCREvent(t *testing.T) {
1026 rw := openTPM(t)
1027 defer rw.Close()
1028 debugPCR := uint32(16)
1029 arbitraryBytes := []byte{1}
1030 if err := PCREvent(rw, tpmutil.Handle(debugPCR), arbitraryBytes); err != nil {
1031 t.Fatal(err)
1032 }
1033 }
1034
1035 func TestPCRExtend(t *testing.T) {
1036 rw := openTPM(t)
1037 defer rw.Close()
1038
1039 tests := []struct {
1040 desc string
1041 hashAlg Algorithm
1042 hashSize int
1043 hashSum func([]byte) []byte
1044 }{
1045 {
1046 desc: "SHA1",
1047 hashAlg: AlgSHA1,
1048 hashSize: sha1.Size,
1049 hashSum: func(in []byte) []byte {
1050 s := sha1.Sum(in)
1051 return s[:]
1052 },
1053 },
1054 {
1055 desc: "SHA256",
1056 hashAlg: AlgSHA256,
1057 hashSize: sha256.Size,
1058 hashSum: func(in []byte) []byte {
1059 s := sha256.Sum256(in)
1060 return s[:]
1061 },
1062 },
1063 }
1064
1065 const pcr = int(16)
1066
1067 for _, tt := range tests {
1068 t.Run(tt.desc, func(t *testing.T) {
1069 pcrValue := bytes.Repeat([]byte{0xF}, tt.hashSize)
1070 oldPCRValue, err := ReadPCR(rw, pcr, tt.hashAlg)
1071 if err != nil {
1072 t.Fatalf("Can't read PCR %d from the TPM: %s", pcr, err)
1073 }
1074
1075 if err = PCRExtend(rw, tpmutil.Handle(pcr), tt.hashAlg, pcrValue, ""); err != nil {
1076 t.Fatalf("Failed to extend PCR %d: %s", pcr, err)
1077 }
1078
1079 newPCRValue, err := ReadPCR(rw, pcr, tt.hashAlg)
1080 if err != nil {
1081 t.Fatalf("Can't read PCR %d from the TPM: %s", pcr, err)
1082 }
1083
1084 finalPCR := tt.hashSum(append(oldPCRValue, pcrValue...))
1085
1086 if !bytes.Equal(finalPCR, newPCRValue) {
1087 t.Fatalf("PCRs not equal, got %x, want %x", finalPCR, newPCRValue)
1088 }
1089 })
1090 }
1091 }
1092
1093 func TestReadPCR(t *testing.T) {
1094 rw := openTPM(t)
1095 defer rw.Close()
1096 pcrVal, err := ReadPCR(rw, 16 /*pcr*/, AlgSHA256)
1097 if err != nil {
1098 t.Fatal(err)
1099 }
1100 if len(pcrVal) != 32 {
1101 t.Fatalf("Expected a 32 byte PCR value but got: %v", pcrVal)
1102 }
1103 }
1104
1105 func TestPCRReset(t *testing.T) {
1106 rw := openTPM(t)
1107 defer rw.Close()
1108 allZeroBytes := make([]byte, 32)
1109 debugPCR := 16
1110
1111 var fakeHashSum [32]byte
1112 err := PCRExtend(rw, tpmutil.Handle(debugPCR), AlgSHA256, fakeHashSum[:], "")
1113 if err != nil {
1114 t.Fatal(err)
1115 }
1116
1117 pcrVal, err := ReadPCR(rw, debugPCR, AlgSHA256)
1118 if err != nil {
1119 t.Fatal(err)
1120 }
1121 if bytes.Equal(allZeroBytes, pcrVal) {
1122 t.Fatal("PCR shouldn't be all zeros after PCRExtend")
1123 }
1124
1125 err = PCRReset(rw, tpmutil.Handle(debugPCR))
1126 if err != nil {
1127 t.Fatal(err)
1128 }
1129 pcrVal, err = ReadPCR(rw, debugPCR, AlgSHA256)
1130 if err != nil {
1131 t.Fatal(err)
1132 }
1133 if !bytes.Equal(allZeroBytes, pcrVal) {
1134 t.Fatal("PCR should be all zeros after PCRReset")
1135 }
1136 }
1137
1138 func TestPCRAllocate(t *testing.T) {
1139 rw := openTPM(t)
1140 defer rw.Close()
1141
1142 pcrSelectionRemoveSHA1 := []PCRSelection{
1143 {Hash: AlgSHA1, PCRs: []int{}},
1144 {Hash: AlgSHA256, PCRs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}},
1145 }
1146
1147 err := PCRAllocate(rw, HandlePlatform, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession}, pcrSelectionRemoveSHA1)
1148 if err != nil {
1149 t.Fatalf("PCRAllocate failed: %v", err)
1150 }
1151 }
1152
1153 func makeAttestationData() AttestationData {
1154 signer := tpmutil.Handle(100)
1155 return AttestationData{
1156 Magic: 0xff544347,
1157 QualifiedSigner: Name{
1158 Handle: &signer,
1159 },
1160 ExtraData: []byte("foo"),
1161 ClockInfo: ClockInfo{
1162 Clock: 3,
1163 ResetCount: 4,
1164 RestartCount: 5,
1165 Safe: 6,
1166 },
1167 FirmwareVersion: 7,
1168 }
1169 }
1170
1171 func TestEncodeDecodeCertifyAttestationData(t *testing.T) {
1172 ciQualifiedName := tpmutil.Handle(101)
1173 ad := makeAttestationData()
1174 ad.Type = TagAttestCertify
1175 ad.AttestedCertifyInfo = &CertifyInfo{
1176 Name: Name{
1177 Digest: &HashValue{
1178 Alg: AlgSHA1,
1179 Value: make([]byte, crypto.SHA1.Size()),
1180 },
1181 },
1182 QualifiedName: Name{
1183 Handle: &ciQualifiedName,
1184 },
1185 }
1186
1187 encoded, err := ad.Encode()
1188 if err != nil {
1189 t.Fatalf("error encoding AttestationData: %v", err)
1190 }
1191 decoded, err := DecodeAttestationData(encoded)
1192 if err != nil {
1193 t.Fatalf("error decoding AttestationData: %v", err)
1194 }
1195
1196 if !reflect.DeepEqual(*decoded, ad) {
1197 t.Errorf("got decoded value:\n%v\nwant:\n%v", decoded, ad)
1198 }
1199 }
1200
1201 func TestEncodeDecodeCreationAttestationData(t *testing.T) {
1202 ad := makeAttestationData()
1203 ad.Type = TagAttestCreation
1204 ad.AttestedCreationInfo = &CreationInfo{
1205 Name: Name{
1206 Digest: &HashValue{
1207 Alg: AlgSHA1,
1208 Value: make([]byte, crypto.SHA1.Size()),
1209 },
1210 },
1211 OpaqueDigest: []byte{7, 8, 9},
1212 }
1213
1214 encoded, err := ad.Encode()
1215 if err != nil {
1216 t.Fatalf("error encoding AttestationData: %v", err)
1217 }
1218 decoded, err := DecodeAttestationData(encoded)
1219 if err != nil {
1220 t.Fatalf("error decoding AttestationData: %v", err)
1221 }
1222
1223 if !reflect.DeepEqual(*decoded, ad) {
1224 t.Errorf("got decoded value:\n%v\nwant:\n%v", decoded, ad)
1225 }
1226 }
1227
1228 func TestEncodeDecodePublicDefaultRSAExponent(t *testing.T) {
1229 p := Public{
1230 Type: AlgRSA,
1231 NameAlg: AlgSHA1,
1232 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
1233 RSAParameters: &RSAParams{
1234 Sign: &SigScheme{
1235 Alg: AlgRSASSA,
1236 Hash: AlgSHA1,
1237 },
1238 KeyBits: 2048,
1239 ExponentRaw: 1<<16 + 1,
1240 ModulusRaw: []byte{1, 2, 3, 4, 7, 8, 9, 9},
1241 },
1242 }
1243
1244 e, err := p.Encode()
1245 if err != nil {
1246 t.Fatalf("Public{%+v}.Encode() returned error: %v", p, err)
1247 }
1248 d, err := DecodePublic(e)
1249 if err != nil {
1250 t.Fatalf("DecodePublic(%v) returned error: %v", e, err)
1251 }
1252 if !reflect.DeepEqual(p, d) {
1253 t.Errorf("RSA TPMT_PUBLIC with default exponent changed after being encoded+decoded")
1254 t.Logf("\tGot: %+v", d)
1255 t.Logf("\tWant: %+v", p)
1256 }
1257 }
1258
1259 func TestEncodeDecodeSignature(t *testing.T) {
1260 randRSASig := func() []byte {
1261 // Key size 2048 bits
1262 var size uint16 = 256
1263 sizeU16 := make([]byte, 2)
1264 binary.BigEndian.PutUint16(sizeU16, size)
1265 key := make([]byte, size)
1266 rand.Read(key)
1267 return append(sizeU16, key...)
1268 }
1269
1270 run := func(t *testing.T, s Signature) {
1271 e, err := s.Encode()
1272 if err != nil {
1273 t.Fatalf("Signature{%+v}.Encode() returned error: %v", s, err)
1274 }
1275 d, err := DecodeSignature(bytes.NewBuffer(e))
1276 if err != nil {
1277 t.Fatalf("DecodeSignature{%v} returned error: %v", e, err)
1278 }
1279 if !reflect.DeepEqual(s, *d) {
1280 t.Errorf("got decoded value:\n%v\nwant:\n%v", d, s)
1281 }
1282 }
1283 t.Run("RSASSA", func(t *testing.T) {
1284 run(t, Signature{
1285 Alg: AlgRSASSA,
1286 RSA: &SignatureRSA{
1287 HashAlg: AlgSHA256,
1288 Signature: randRSASig(),
1289 },
1290 })
1291 })
1292 t.Run("RSAPSS", func(t *testing.T) {
1293 run(t, Signature{
1294 Alg: AlgRSAPSS,
1295 RSA: &SignatureRSA{
1296 HashAlg: AlgSHA256,
1297 Signature: randRSASig(),
1298 },
1299 })
1300 })
1301 t.Run("ECDSA", func(t *testing.T) {
1302 // Key size 256 bits
1303 size := 32
1304 randBytes := make([]byte, size)
1305 rand.Read(randBytes)
1306 r := big.NewInt(0).SetBytes(randBytes)
1307
1308 rand.Read(randBytes)
1309 s := big.NewInt(0).SetBytes(randBytes)
1310
1311 run(t, Signature{
1312 Alg: AlgECDSA,
1313 ECC: &SignatureECC{
1314 HashAlg: AlgSHA256,
1315 R: r,
1316 S: s,
1317 },
1318 })
1319 })
1320 }
1321
1322 func TestCreateKeyWithSensitive(t *testing.T) {
1323 rw := openTPM(t)
1324 defer rw.Close()
1325 parentHandle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, Public{
1326 Type: AlgRSA,
1327 NameAlg: AlgSHA256,
1328 Attributes: FlagRestricted | FlagDecrypt | FlagUserWithAuth | FlagFixedParent | FlagFixedTPM | FlagSensitiveDataOrigin,
1329 RSAParameters: &RSAParams{
1330 Symmetric: &SymScheme{
1331 Alg: AlgAES,
1332 KeyBits: 128,
1333 Mode: AlgCFB,
1334 },
1335 KeyBits: 2048,
1336 },
1337 })
1338 if err != nil {
1339 t.Fatalf("CreatePrimary failed: %s", err)
1340 }
1341 defer FlushContext(rw, parentHandle)
1342
1343 _, _, _, _, _, err = CreateKeyWithSensitive(rw, parentHandle, pcrSelection7, defaultPassword, defaultPassword, Public{
1344 Type: AlgKeyedHash,
1345 NameAlg: AlgSHA256,
1346 Attributes: FlagFixedTPM | FlagFixedParent,
1347 AuthPolicy: nil,
1348 }, []byte("test_secret"))
1349 if err != nil {
1350 t.Errorf("CreateKeyWithSensitive failed: %s", err)
1351 }
1352 }
1353
1354 func TestCreateAndCertifyCreation(t *testing.T) {
1355 rw := openTPM(t)
1356 defer rw.Close()
1357 params := Public{
1358 Type: AlgRSA,
1359 NameAlg: AlgSHA256,
1360 Attributes: FlagSignerDefault | FlagNoDA,
1361 RSAParameters: &RSAParams{
1362 Sign: &SigScheme{
1363 Alg: AlgRSASSA,
1364 Hash: AlgSHA256,
1365 },
1366 KeyBits: 2048,
1367 },
1368 }
1369 keyHandle, pub, _, creationHash, tix, _, err := CreatePrimaryEx(rw, HandleEndorsement, pcrSelection7, emptyPassword, emptyPassword, params)
1370 if err != nil {
1371 t.Fatalf("CreatePrimaryEx failed: %s", err)
1372 }
1373 defer FlushContext(rw, keyHandle)
1374
1375 scheme := SigScheme{Alg: AlgRSASSA, Hash: AlgSHA256, Count: 0}
1376 attestation, sigRaw, err := CertifyCreation(rw, emptyPassword, keyHandle, keyHandle, nil, creationHash, scheme, tix)
1377 if err != nil {
1378 t.Fatalf("CertifyCreation failed: %s", err)
1379 }
1380 att, err := DecodeAttestationData(attestation)
1381 if err != nil {
1382 t.Fatalf("DecodeAttestationData(%v) failed: %v", attestation, err)
1383 }
1384 signature, err := DecodeSignature(bytes.NewBuffer(sigRaw))
1385 if err != nil {
1386 t.Errorf("DecodeSignature failed: %s", err)
1387 return
1388 }
1389 if att.Type != TagAttestCreation {
1390 t.Errorf("Got att.Type = %v, want TagAttestCreation", att.Type)
1391 }
1392 p, err := DecodePublic(pub)
1393 if err != nil {
1394 t.Fatalf("DecodePublic failed: %v", err)
1395 }
1396 match, err := att.AttestedCreationInfo.Name.MatchesPublic(p)
1397 if err != nil {
1398 t.Fatalf("MatchesPublic failed: %v", err)
1399 }
1400 if !match {
1401 t.Error("Attested name does not match returned public key.")
1402 t.Logf("Name: %v", att.AttestedCreationInfo.Name)
1403 t.Logf("Public: %v", p)
1404 }
1405 rsaPub := rsa.PublicKey{E: int(p.RSAParameters.Exponent()), N: p.RSAParameters.Modulus()}
1406 hsh := crypto.SHA256.New()
1407 hsh.Write(attestation)
1408 if err := rsa.VerifyPKCS1v15(&rsaPub, crypto.SHA256, hsh.Sum(nil), signature.RSA.Signature); err != nil {
1409 t.Errorf("VerifyPKCS1v15 failed: %v", err)
1410 }
1411 }
1412
1413 func TestCreateAndCertifyCreationECC(t *testing.T) {
1414 rw := openTPM(t)
1415 defer rw.Close()
1416 params := Public{
1417 Type: AlgECC,
1418 NameAlg: AlgSHA256,
1419 Attributes: FlagSignerDefault,
1420 ECCParameters: &ECCParams{
1421 Sign: &SigScheme{
1422 Alg: AlgECDSA,
1423 Hash: AlgSHA256,
1424 },
1425 CurveID: CurveNISTP256,
1426 },
1427 }
1428 keyHandle, pub, _, creationHash, tix, _, err := CreatePrimaryEx(rw, HandleEndorsement, pcrSelection7, emptyPassword, emptyPassword, params)
1429 if err != nil {
1430 t.Fatalf("CreatePrimaryEx failed: %s", err)
1431 }
1432 defer FlushContext(rw, keyHandle)
1433
1434 scheme := SigScheme{Alg: AlgECDSA, Hash: AlgSHA256, Count: 0}
1435 attestation, sigRaw, err := CertifyCreation(rw, emptyPassword, keyHandle, keyHandle, nil, creationHash, scheme, tix)
1436 if err != nil {
1437 t.Fatalf("CertifyCreation failed: %s", err)
1438 }
1439
1440 att, err := DecodeAttestationData(attestation)
1441 if err != nil {
1442 t.Fatalf("DecodeAttestationData(%v) failed: %v", attestation, err)
1443 }
1444 signature, err := DecodeSignature(bytes.NewBuffer(sigRaw))
1445 if err != nil {
1446 t.Errorf("DecodeSignature failed: %s", err)
1447 return
1448 }
1449 if att.Type != TagAttestCreation {
1450 t.Errorf("Got att.Type = %v, want TagAttestCreation", att.Type)
1451 }
1452 p, err := DecodePublic(pub)
1453 if err != nil {
1454 t.Fatalf("DecodePublic failed: %v", err)
1455 }
1456 match, err := att.AttestedCreationInfo.Name.MatchesPublic(p)
1457 if err != nil {
1458 t.Fatalf("MatchesPublic failed: %v", err)
1459 }
1460 if !match {
1461 t.Error("Attested name does not match returned public key.")
1462 t.Logf("Name: %v", att.AttestedCreationInfo.Name)
1463 t.Logf("Public: %v", p)
1464 }
1465
1466 var pkEcdsa ecdsa.PublicKey
1467 var hsh hash.Hash
1468 pkEcdsa = ecdsa.PublicKey{Curve: elliptic.P256(), X: p.ECCParameters.Point.X(), Y: p.ECCParameters.Point.Y()}
1469 signHash, err := p.ECCParameters.Sign.Hash.Hash()
1470 if err != nil {
1471 t.Fatalf("Hash failed: %v", err)
1472 }
1473 hsh = signHash.New()
1474 hsh.Write(attestation)
1475
1476 if !ecdsa.Verify(&pkEcdsa, hsh.Sum(nil), signature.ECC.R, signature.ECC.S) {
1477 t.Fatalf("Verify failed")
1478 }
1479 }
1480
1481 func TestNVReadWriteAndLocks(t *testing.T) {
1482 rw := openTPM(t)
1483 defer rw.Close()
1484
1485 var (
1486 idx tpmutil.Handle = 0x1500000
1487 data = []byte("testdata")
1488 attr = AttrOwnerWrite | AttrOwnerRead | AttrWriteSTClear | AttrReadSTClear
1489 )
1490
1491 // Undefine the space, just in case the previous run of this test failed
1492 // to clean up.
1493 if err := NVUndefineSpace(rw, emptyPassword, HandleOwner, idx); err != nil {
1494 t.Logf("(not a failure) NVUndefineSpace at index 0x%x failed: %v", idx, err)
1495 }
1496
1497 // Define space in NV storage and clean up afterwards or subsequent runs will fail.
1498 if err := NVDefineSpace(rw,
1499 HandleOwner,
1500 idx,
1501 emptyPassword,
1502 emptyPassword,
1503 nil,
1504 attr,
1505 uint16(len(data)),
1506 ); err != nil {
1507 t.Fatalf("NVDefineSpace failed: %v", err)
1508 }
1509 defer NVUndefineSpace(rw, emptyPassword, HandleOwner, idx)
1510
1511 // Write the data
1512 if err := NVWrite(rw, HandleOwner, idx, emptyPassword, data, 0); err != nil {
1513 t.Fatalf("NVWrite failed: %v", err)
1514 }
1515
1516 // Enable write lock
1517 if err := NVWriteLock(rw, HandleOwner, idx, emptyPassword); err != nil {
1518 t.Fatalf("NVWriteLock failed: %v", err)
1519 }
1520
1521 // Write the data again. Should fail now because it's write-locked.
1522 err := NVWrite(rw, HandleOwner, idx, emptyPassword, data, 0)
1523 switch err := err.(type) {
1524 case nil:
1525 t.Fatal("NVWrite succeeded after NVWriteLock")
1526 case Error:
1527 if err.Code != RCNVLocked {
1528 t.Fatalf("NVWrite: unexpected error; want RCNVLocked, got %v", err)
1529 }
1530 default:
1531 t.Fatalf("NVWrite: unexpected error; want RCNVLocked, got %v", err)
1532 }
1533
1534 // Make sure the public area of the index can be read
1535 pub, err := NVReadPublic(rw, idx)
1536 if err != nil {
1537 t.Fatalf("NVReadPublic failed: %v", err)
1538 }
1539 if int(pub.DataSize) != len(data) {
1540 t.Fatalf("public NV data size mismatch, got %d, want %d, ", pub.DataSize, len(data))
1541 }
1542
1543 // Read all of the data with NVReadEx and compare to what was written
1544 outdata, err := NVReadEx(rw, idx, HandleOwner, emptyPassword, 0)
1545 if err != nil {
1546 t.Fatalf("NVReadEx failed: %v", err)
1547 }
1548 if !bytes.Equal(data, outdata) {
1549 t.Fatalf("data read from NV index does not match, got %x, want %x", outdata, data)
1550 }
1551
1552 // Enable read lock
1553 if err := NVReadLock(rw, HandleOwner, idx, emptyPassword); err != nil {
1554 t.Fatalf("NVReadLock failed: %v (%T)", err, err)
1555 }
1556
1557 // Read the data again. Should fail now because it's read-locked.
1558 if _, err := NVReadEx(rw, idx, HandleOwner, emptyPassword, 0); err == nil {
1559 t.Fatal("NVRead succeeded after NVReadLock")
1560 } else if !strings.HasSuffix(err.Error(), ": NV access locked") {
1561 t.Fatalf("NVRead: unexpected error; want RCNVLocked, got %v", err)
1562 }
1563 }
1564
1565 func TestPolicySecret(t *testing.T) {
1566 rw := openTPM(t)
1567 defer rw.Close()
1568
1569 expirations := []int32{math.MinInt32, math.MinInt32 + 1, -1, 0, 1, math.MaxInt32}
1570 for _, expiration := range expirations {
1571 t.Run(t.Name()+fmt.Sprint(expiration), func(t *testing.T) {
1572 _, tkt := testPolicySecret(t, rw, expiration)
1573 // Part 3: policyTicket is produced if the command succeeds and expiration in
1574 // the command was non-zero.
1575 // If expiration is non-negative, a NULL Ticket is returned.
1576 if expiration < 0 && len(tkt.Digest) == 0 {
1577 t.Fatalf("Got empty ticket digest, expected ticket with auth expiry")
1578 } else if expiration >= 0 && !reflect.DeepEqual(*tkt, nullTicketSecret) {
1579 t.Fatalf("Got ticket with non-empty digest, expected NULL ticket")
1580 }
1581 })
1582 }
1583 }
1584
1585 func testPolicySecret(t *testing.T, rw io.ReadWriter, expiration int32) ([]byte, *Ticket) {
1586 sessHandle, _, err := StartAuthSession(rw, HandleNull, HandleNull, make([]byte, 16), nil, SessionPolicy, AlgNull, AlgSHA256)
1587 if err != nil {
1588 t.Fatalf("StartAuthSession() failed: %v", err)
1589 }
1590 defer FlushContext(rw, sessHandle)
1591
1592 timeout, tkt, err := PolicySecret(rw, HandleEndorsement, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession}, sessHandle, nil, nil, nil, expiration)
1593 if err != nil {
1594 t.Fatalf("PolicySecret() failed: %v", err)
1595 }
1596 return timeout, tkt
1597 }
1598
1599 func TestPolicySigned(t *testing.T) {
1600 rw := openTPM(t)
1601 defer rw.Close()
1602
1603 signers := map[string]Public{
1604 "RSA": defaultRsaSignerParams,
1605 "ECC": defaultEccSignerParams,
1606 }
1607
1608 expirations := []int32{math.MinInt32, math.MinInt32 + 1, -1, 0, 1, math.MaxInt32}
1609 for _, expiration := range expirations {
1610 for signerType, params := range signers {
1611 t.Run(t.Name()+signerType+fmt.Sprint(expiration), func(t *testing.T) {
1612 _, tkt := testPolicySigned(t, rw, expiration, params)
1613 // Part 3: policyTicket is produced if the command succeeds and expiration in
1614 // the command was non-zero.
1615 // If expiration is non-negative, a NULL Ticket is returned.
1616 if expiration < 0 && len(tkt.Digest) == 0 {
1617 t.Fatalf("Got empty ticket digest, expected ticket with auth expiry")
1618 } else if expiration >= 0 && !reflect.DeepEqual(*tkt, nullTicketSigned) {
1619 t.Fatalf("Got ticket with non-empty digest, expected NULL ticket")
1620 }
1621 })
1622 }
1623 }
1624 }
1625
1626 func testPolicySigned(t *testing.T, rw io.ReadWriter, expiration int32, signerParams Public) ([]byte, *Ticket) {
1627 handle, _, err := CreatePrimary(rw, HandleOwner, PCRSelection{}, emptyPassword, emptyPassword, signerParams)
1628 if err != nil {
1629 t.Fatalf("CreatePrimary() failed: %s", err)
1630 }
1631 defer FlushContext(rw, handle)
1632
1633 sessHandle, nonce, err := StartAuthSession(rw, HandleNull, HandleNull, make([]byte, 16), nil, SessionPolicy, AlgNull, AlgSHA256)
1634 if err != nil {
1635 t.Fatalf("StartAuthSession() failed: %v", err)
1636 }
1637 defer FlushContext(rw, sessHandle)
1638
1639 // Sign the hash of the command parameters, as described in the TPM 2.0 spec, Part 3, Section 23.3.
1640 // We only use expiration here.
1641 expBytes := make([]byte, 4)
1642 binary.BigEndian.PutUint32(expBytes, uint32(expiration))
1643
1644 // TPM2.0 spec, Revision 1.38, Part 3 nonce must be present if expiration is non-zero.
1645 // aHash ≔ HauthAlg(nonceTPM || expiration || cpHashA || policyRef)
1646 toDigest := append(nonce, expBytes...)
1647
1648 digest := sha256.Sum256(toDigest)
1649
1650 sig, err := Sign(rw, handle, emptyPassword, digest[:], nil, nil)
1651 if err != nil {
1652 t.Fatalf("Sign failed: %s", err)
1653 }
1654
1655 signature, err := sig.Encode()
1656 if err != nil {
1657 t.Fatalf("Encode() failed: %v", err)
1658 }
1659
1660 timeout, tkt, err := PolicySigned(rw, handle, sessHandle, nonce, nil, nil, expiration, signature)
1661 if err != nil {
1662 t.Fatalf("PolicySigned() failed: %v", err)
1663 }
1664 return timeout, tkt
1665 }
1666
1667 func TestQuote(t *testing.T) {
1668 rw := openTPM(t)
1669 defer rw.Close()
1670 params := Public{
1671 Type: AlgRSA,
1672 NameAlg: AlgSHA256,
1673 Attributes: FlagSignerDefault | FlagNoDA,
1674 RSAParameters: &RSAParams{
1675 Sign: &SigScheme{
1676 Alg: AlgRSASSA,
1677 Hash: AlgSHA256,
1678 },
1679 KeyBits: 2048,
1680 },
1681 }
1682 keyHandle, pub, _, _, _, _, err := CreatePrimaryEx(rw, HandleEndorsement, pcrSelection7, emptyPassword, emptyPassword, params)
1683 if err != nil {
1684 t.Fatalf("CreatePrimaryEx failed: %s", err)
1685 }
1686 defer FlushContext(rw, keyHandle)
1687
1688 attestation, signature, err := Quote(rw, keyHandle, emptyPassword, emptyPassword, nil, pcrSelection7, AlgNull)
1689 if err != nil {
1690 t.Fatalf("Quote failed: %v", err)
1691 }
1692
1693 att, err := DecodeAttestationData(attestation)
1694 if err != nil {
1695 t.Fatalf("DecodeAttestationData(%v) failed: %v", attestation, err)
1696 }
1697 if att.Type != TagAttestQuote {
1698 t.Errorf("Got att.Type = %v, want TagAttestQuote", att.Type)
1699 }
1700 if att.AttestedQuoteInfo == nil {
1701 t.Error("AttestedQuoteInfo = nil, want non-nil")
1702 }
1703 p, err := DecodePublic(pub)
1704 if err != nil {
1705 t.Fatalf("DecodePublic failed: %v", err)
1706 }
1707 rsaPub := rsa.PublicKey{E: int(p.RSAParameters.Exponent()), N: p.RSAParameters.Modulus()}
1708 hsh := crypto.SHA256.New()
1709 hsh.Write(attestation)
1710 if err := rsa.VerifyPKCS1v15(&rsaPub, crypto.SHA256, hsh.Sum(nil), signature.RSA.Signature); err != nil {
1711 t.Errorf("VerifyPKCS1v15 failed: %v", err)
1712 }
1713 }
1714
1715 func TestReadPublicKey(t *testing.T) {
1716 rw := openTPM(t)
1717 defer rw.Close()
1718
1719 run := func(t *testing.T, public Public, private Private, pubKeyIn crypto.PublicKey) {
1720 t.Helper()
1721
1722 h, _, err := LoadExternal(rw, public, private, HandleNull)
1723 if err != nil {
1724 t.Fatal(err)
1725 }
1726 defer FlushContext(rw, h)
1727
1728 pub, _, _, err := ReadPublic(rw, h)
1729 if err != nil {
1730 t.Fatalf("ReadPublic failed: %s", err)
1731 }
1732
1733 pubKeyOut, err := pub.Key()
1734 if err != nil {
1735 t.Fatalf("Public.Key() failed: %s", err)
1736 }
1737
1738 if !reflect.DeepEqual(pubKeyIn, pubKeyOut) {
1739 t.Fatalf("Public.Key() = %#v; want %#v", pubKeyOut, pubKeyIn)
1740 }
1741 }
1742
1743 t.Run("RSA", func(t *testing.T) {
1744 pk, err := rsa.GenerateKey(rand.Reader, 2048)
1745 if err != nil {
1746 t.Fatal(err)
1747 }
1748 rp := Public{
1749 Type: AlgRSA,
1750 NameAlg: AlgSHA1,
1751 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
1752 RSAParameters: &RSAParams{
1753 Sign: &SigScheme{
1754 Alg: AlgRSASSA,
1755 Hash: AlgSHA1,
1756 },
1757 KeyBits: 2048,
1758 ExponentRaw: uint32(pk.PublicKey.E),
1759 ModulusRaw: pk.PublicKey.N.Bytes(),
1760 },
1761 }
1762 private := Private{
1763 Type: AlgRSA,
1764 Sensitive: pk.Primes[0].Bytes(),
1765 }
1766 run(t, rp, private, &pk.PublicKey)
1767 })
1768 t.Run("ECC", func(t *testing.T) {
1769 skipOnUnsupportedAlg(t, rw, AlgECC)
1770 pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
1771 if err != nil {
1772 t.Fatal(err)
1773 }
1774 public := Public{
1775 Type: AlgECC,
1776 NameAlg: AlgSHA1,
1777 Attributes: FlagSign | FlagSensitiveDataOrigin | FlagUserWithAuth,
1778 ECCParameters: &ECCParams{
1779 Sign: &SigScheme{
1780 Alg: AlgECDSA,
1781 Hash: AlgSHA1,
1782 },
1783 CurveID: CurveNISTP256,
1784 Point: ECPoint{XRaw: pk.PublicKey.X.Bytes(), YRaw: pk.PublicKey.Y.Bytes()},
1785 },
1786 }
1787 private := Private{
1788 Type: AlgECC,
1789 Sensitive: pk.D.Bytes(),
1790 }
1791 run(t, public, private, &pk.PublicKey)
1792 })
1793 }
1794
1795 func TestEncryptDecrypt(t *testing.T) {
1796 rw := openTPM(t)
1797 defer rw.Close()
1798
1799 parentHandle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, Public{
1800 Type: AlgRSA,
1801 NameAlg: AlgSHA256,
1802 Attributes: FlagRestricted | FlagDecrypt | FlagUserWithAuth | FlagFixedParent | FlagFixedTPM | FlagSensitiveDataOrigin,
1803 RSAParameters: &RSAParams{
1804 Symmetric: &SymScheme{
1805 Alg: AlgAES,
1806 KeyBits: 128,
1807 Mode: AlgCFB,
1808 },
1809 KeyBits: 2048,
1810 },
1811 })
1812 if err != nil {
1813 t.Fatalf("CreatePrimary failed: %s", err)
1814 }
1815 defer FlushContext(rw, parentHandle)
1816 privateBlob, publicBlob, _, _, _, err := CreateKey(rw, parentHandle, pcrSelection7, defaultPassword, defaultPassword, Public{
1817 Type: AlgSymCipher,
1818 NameAlg: AlgSHA256,
1819 Attributes: FlagDecrypt | FlagSign | FlagUserWithAuth | FlagFixedParent | FlagFixedTPM | FlagSensitiveDataOrigin,
1820 SymCipherParameters: &SymCipherParams{
1821 Symmetric: &SymScheme{
1822 Alg: AlgAES,
1823 KeyBits: 128,
1824 Mode: AlgCFB,
1825 },
1826 },
1827 })
1828 if err != nil {
1829 t.Fatalf("CreateKey failed: %s", err)
1830 }
1831 key, _, err := Load(rw, parentHandle, defaultPassword, publicBlob, privateBlob)
1832 if err != nil {
1833 t.Fatalf("Load failed: %s", err)
1834 }
1835 defer FlushContext(rw, key)
1836
1837 data := bytes.Repeat([]byte("a"), 1e4) // 10KB
1838 iv := make([]byte, 16)
1839
1840 encrypted, err := EncryptSymmetric(rw, defaultPassword, key, iv, data)
1841 if err != nil {
1842 t.Fatalf("EncryptSymmetric failed: %s", err)
1843 }
1844 if bytes.Equal(encrypted, data) {
1845 t.Error("encrypted blob matches unenecrypted data")
1846 }
1847 decrypted, err := DecryptSymmetric(rw, defaultPassword, key, iv, encrypted)
1848 if err != nil {
1849 t.Fatalf("DecryptSymmetric failed: %s", err)
1850 }
1851 if !bytes.Equal(decrypted, data) {
1852 t.Errorf("got decrypted data: %q, want: %q", decrypted, data)
1853 }
1854 }
1855
1856 func TestRSAEncryptDecrypt(t *testing.T) {
1857 rw := openTPM(t)
1858 defer rw.Close()
1859
1860 handle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, Public{
1861 Type: AlgRSA,
1862 NameAlg: AlgSHA256,
1863 Attributes: FlagDecrypt | FlagUserWithAuth | FlagFixedParent | FlagFixedTPM | FlagSensitiveDataOrigin,
1864 RSAParameters: &RSAParams{
1865 Sign: &SigScheme{
1866 Alg: AlgNull,
1867 Hash: AlgNull,
1868 },
1869 KeyBits: 2048,
1870 },
1871 })
1872 if err != nil {
1873 t.Fatalf("CreatePrimary failed: %s", err)
1874 }
1875 defer FlushContext(rw, handle)
1876
1877 tests := map[string]struct {
1878 scheme *AsymScheme
1879 data []byte
1880 label string
1881 }{
1882 "No padding": {
1883 scheme: &AsymScheme{Alg: AlgNull},
1884 data: bytes.Repeat([]byte("a"), 256),
1885 },
1886 "RSAES-PKCS1": {
1887 scheme: &AsymScheme{Alg: AlgRSAES},
1888 data: bytes.Repeat([]byte("a"), 245),
1889 },
1890 "RSAES-OAEP-SHA1": {
1891 scheme: &AsymScheme{Alg: AlgOAEP, Hash: AlgSHA1},
1892 data: bytes.Repeat([]byte("a"), 214),
1893 },
1894 "RSAES-OAEP-SHA256": {
1895 scheme: &AsymScheme{Alg: AlgOAEP, Hash: AlgSHA256},
1896 data: bytes.Repeat([]byte("a"), 190),
1897 },
1898 "RSAES-OAEP-SHA256 with label": {
1899 scheme: &AsymScheme{Alg: AlgOAEP, Hash: AlgSHA256},
1900 data: bytes.Repeat([]byte("a"), 190),
1901 label: "label",
1902 },
1903 }
1904
1905 for name, test := range tests {
1906 t.Run(name, func(t *testing.T) {
1907 encrypted, err := RSAEncrypt(rw, handle, test.data, test.scheme, test.label)
1908 if err != nil {
1909 t.Fatal("RSAEncrypt failed:", err)
1910 }
1911 decrypted, err := RSADecrypt(rw, handle, defaultPassword, encrypted, test.scheme, test.label)
1912 if err != nil {
1913 t.Fatal("RSADecrypt failed:", err)
1914 }
1915 if !bytes.Equal(decrypted, test.data) {
1916 t.Errorf("got decrypted data: %q, want: %q", decrypted, test.data)
1917 }
1918 })
1919 }
1920
1921 }
1922
1923 func TestECDHKeyGen(t *testing.T) {
1924 rw := openTPM(t)
1925 defer rw.Close()
1926
1927 // Generate my key and load the public point into the TPM.
1928 myPriv, myPubX, myPubY, err := elliptic.GenerateKey(elliptic.P256(), rand.Reader)
1929 if err != nil {
1930 t.Fatalf("GenerateKey failed: %v", err)
1931 }
1932 handle, _, err := LoadExternal(rw, Public{
1933 Type: AlgECC,
1934 NameAlg: AlgSHA256,
1935 Attributes: FlagDecrypt,
1936 ECCParameters: &ECCParams{
1937 CurveID: CurveNISTP256,
1938 Point: ECPoint{XRaw: myPubX.Bytes(), YRaw: myPubY.Bytes()},
1939 },
1940 }, Private{}, HandleOwner)
1941 if err != nil {
1942 t.Fatalf("LoadExternal failed: %v", err)
1943 }
1944 defer FlushContext(rw, handle)
1945
1946 // Ask the TPM to multiply an ephemeral priv by our pub.
1947 yourZ, yourPub, err := ECDHKeyGen(rw, handle)
1948 if err != nil {
1949 t.Fatalf("ECDHKeyGen failed: %v", err)
1950 }
1951
1952 // Same calculation on our side: multiply our priv by the TPM's ephemeral pub.
1953 myZX, myZY := elliptic.P256().ScalarMult(yourPub.X(), yourPub.Y(), myPriv)
1954
1955 if myZX.Cmp(yourZ.X()) != 0 || myZY.Cmp(yourZ.Y()) != 0 {
1956 t.Errorf("want (%x, %x) got (%x, %x)", myZX.Bytes(), myZY.Bytes(), yourZ.X().Bytes(), yourZ.Y().Bytes())
1957 }
1958 }
1959
1960 func TestECDHZGen(t *testing.T) {
1961 rw := openTPM(t)
1962 defer rw.Close()
1963
1964 // Generate our key.
1965 myPriv, myPubX, myPubY, err := elliptic.GenerateKey(elliptic.P256(), rand.Reader)
1966 if err != nil {
1967 t.Fatalf("GenerateKey failed: %v", err)
1968 }
1969
1970 // Generate a key in the TPM.
1971 handle, _, err := CreatePrimary(rw, HandleOwner, PCRSelection{}, emptyPassword, defaultPassword, Public{
1972 Type: AlgECC,
1973 NameAlg: AlgSHA256,
1974 Attributes: FlagDecrypt | FlagSensitiveDataOrigin | FlagUserWithAuth,
1975 ECCParameters: &ECCParams{
1976 CurveID: CurveNISTP256,
1977 },
1978 })
1979 if err != nil {
1980 t.Fatalf("CreatePrimary failed: %v", err)
1981 }
1982 defer FlushContext(rw, handle)
1983
1984 // Read the public key from the TPM.
1985 yourPub, _, _, err := ReadPublic(rw, handle)
1986 if err != nil {
1987 t.Fatalf("ReadPublic failed: %v", err)
1988 }
1989
1990 // Ask the TPM to multiply our public point by its private key.
1991 yourZ, err := ECDHZGen(rw, handle, defaultPassword, ECPoint{
1992 XRaw: myPubX.Bytes(),
1993 YRaw: myPubY.Bytes(),
1994 })
1995 if err != nil {
1996 t.Fatalf("ECDHZGen failed: %v", err)
1997 }
1998
1999 // Same calculation on our side: multiply our priv by the TPM's pub.
2000 myZX, myZY := elliptic.P256().ScalarMult(yourPub.ECCParameters.Point.X(), yourPub.ECCParameters.Point.Y(), myPriv)
2001
2002 if myZX.Cmp(yourZ.X()) != 0 || myZY.Cmp(yourZ.Y()) != 0 {
2003 t.Errorf("want (%x, %x) got (%x, %x)", myZX.Bytes(), myZY.Bytes(), yourZ.X().Bytes(), yourZ.Y().Bytes())
2004 }
2005 }
2006
2007 func TestCreatePrimaryRawTemplate(t *testing.T) {
2008 rw := openTPM(t)
2009 defer rw.Close()
2010
2011 pubRaw, err := defaultKeyParams.Encode()
2012 if err != nil {
2013 t.Fatal(err)
2014 }
2015 kh, pub, err := CreatePrimaryRawTemplate(rw, HandleEndorsement, PCRSelection{}, "", "", pubRaw)
2016 if err != nil {
2017 t.Fatalf("CreatePrimary failed: %v", err)
2018 }
2019 defer FlushContext(rw, kh)
2020
2021 pubRSA, ok := pub.(*rsa.PublicKey)
2022 if !ok {
2023 t.Fatalf("got public key type %T, want *rsa.PublicKey", pub)
2024 }
2025 gotKeySize, wantKeySize := pubRSA.Size(), int(defaultKeyParams.RSAParameters.KeyBits/8)
2026 if gotKeySize != wantKeySize {
2027 t.Errorf("got key size %v, want %v", gotKeySize, wantKeySize)
2028 }
2029 if pubRSA.E != int(defaultKeyParams.RSAParameters.Exponent()) {
2030 t.Errorf("got key exponent %v, want %v", pubRSA.E, defaultKeyParams.RSAParameters.Exponent())
2031 }
2032 }
2033
2034 func TestMatchesTemplate(t *testing.T) {
2035 tests := []struct {
2036 name string
2037 makePublic func() Public
2038 goodChange func(*Public)
2039 badChange func(*Public)
2040 }{
2041 {
2042 "RSA",
2043 func() Public {
2044 return Public{
2045 Type: AlgRSA,
2046 NameAlg: AlgSHA256,
2047 Attributes: FlagSignerDefault,
2048 RSAParameters: &RSAParams{
2049 Sign: &SigScheme{
2050 Alg: AlgRSASSA,
2051 Hash: AlgSHA256,
2052 },
2053 KeyBits: 2048,
2054 },
2055 }
2056 },
2057 func(pub *Public) { pub.RSAParameters.ModulusRaw = make([]byte, 256) },
2058 func(pub *Public) { pub.RSAParameters.KeyBits = 1024 },
2059 },
2060 {
2061 "ECC",
2062 func() Public {
2063 return Public{
2064 Type: AlgECC,
2065 NameAlg: AlgSHA256,
2066 Attributes: FlagSignerDefault,
2067 ECCParameters: &ECCParams{
2068 Sign: &SigScheme{
2069 Alg: AlgECDSA,
2070 Hash: AlgSHA256,
2071 },
2072 CurveID: CurveNISTP256,
2073 },
2074 }
2075 },
2076 func(pub *Public) { pub.ECCParameters.Point.XRaw = make([]byte, 32) },
2077 func(pub *Public) { pub.ECCParameters.CurveID = CurveNISTP384 },
2078 },
2079 {
2080 "SymCipher",
2081 func() Public {
2082 return Public{
2083 Type: AlgSymCipher,
2084 NameAlg: AlgSHA256,
2085 Attributes: FlagSignerDefault,
2086 SymCipherParameters: &SymCipherParams{
2087 Symmetric: &SymScheme{
2088 Alg: AlgAES,
2089 KeyBits: 128,
2090 Mode: AlgCFB,
2091 },
2092 },
2093 }
2094 },
2095 func(pub *Public) { pub.SymCipherParameters.Unique = make([]byte, 256) },
2096 func(pub *Public) { pub.SymCipherParameters.Symmetric.KeyBits = 256 },
2097 },
2098 {
2099 "KeyedHash",
2100 func() Public {
2101 return Public{
2102 Type: AlgKeyedHash,
2103 NameAlg: AlgSHA256,
2104 Attributes: FlagSignerDefault,
2105 KeyedHashParameters: &KeyedHashParams{
2106 Alg: AlgHMAC,
2107 Hash: AlgSHA256,
2108 },
2109 }
2110 },
2111 func(pub *Public) { pub.KeyedHashParameters.Unique = make([]byte, 256) },
2112 func(pub *Public) { pub.KeyedHashParameters.Hash = AlgSHA1 },
2113 },
2114 {
2115 "TypeMismatch",
2116 func() Public {
2117 return Public{
2118 Type: AlgKeyedHash,
2119 NameAlg: AlgSHA256,
2120 Attributes: FlagSignerDefault,
2121 KeyedHashParameters: &KeyedHashParams{Alg: AlgNull},
2122 }
2123 },
2124 func(pub *Public) { pub.KeyedHashParameters.Unique = make([]byte, 256) },
2125 func(pub *Public) { pub.Type = AlgRSA },
2126 },
2127 }
2128
2129 for _, test := range tests {
2130 t.Run(test.name, func(t *testing.T) {
2131 template := test.makePublic()
2132 pub := test.makePublic()
2133
2134 test.goodChange(&pub)
2135 if !pub.MatchesTemplate(template) {
2136 t.Error("Change should not cause template mismatch")
2137 }
2138
2139 encTmpl, err := template.Encode()
2140 if err != nil {
2141 t.Fatal(err)
2142 }
2143 decTmpl, err := DecodePublic(encTmpl)
2144 if err != nil {
2145 t.Fatal(err)
2146 }
2147 if !pub.MatchesTemplate(decTmpl) {
2148 t.Error("Encoding/Decoding should not cause template mismatch")
2149 }
2150
2151 test.badChange(&pub)
2152 if pub.MatchesTemplate(template) {
2153 t.Error("Change should cause template mismatch")
2154 }
2155 })
2156 }
2157 }
2158
2159 func TestPlainImport(t *testing.T) {
2160 // As this test imports a key without using an inner or outer wrapper, the
2161 // sensitive data is NOT encrypted. This setup should not actually be used.
2162 rw := openTPM(t)
2163 defer rw.Close()
2164
2165 // Create an EK that doesn't require authorization
2166 ekHandle, _, err := CreatePrimary(rw, HandleEndorsement, PCRSelection{}, "", "", defaultKeyParams)
2167 if err != nil {
2168 t.Fatalf("CreatePrimary failed: %s", err)
2169 }
2170 defer FlushContext(rw, ekHandle)
2171 emptyAuth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession}
2172
2173 inBuff := make([]byte, 18)
2174 io.ReadFull(rand.Reader, inBuff)
2175 // Create a private area containing the input
2176 private := Private{
2177 Type: AlgKeyedHash,
2178 AuthValue: nil,
2179 SeedValue: make([]byte, 32),
2180 Sensitive: inBuff,
2181 }
2182 io.ReadFull(rand.Reader, private.SeedValue)
2183
2184 privArea, err := private.Encode()
2185 if err != nil {
2186 t.Fatalf("Private encoding error: %s", err)
2187 }
2188 // We just use a plain Pack here, as there is no integrity checking.
2189 duplicate, err := tpmutil.Pack(tpmutil.U16Bytes(privArea))
2190 if err != nil {
2191 t.Fatalf("Duplicate encoding error: %s", err)
2192 }
2193
2194 // The corresponding Public area contains the hash of the Private area.
2195 privHash := crypto.SHA256.New()
2196 privHash.Write(private.SeedValue)
2197 privHash.Write(private.Sensitive)
2198 public := Public{
2199 Type: AlgKeyedHash,
2200 NameAlg: AlgSHA256,
2201 Attributes: FlagUserWithAuth,
2202 KeyedHashParameters: &KeyedHashParams{
2203 Alg: AlgNull,
2204 Unique: privHash.Sum(nil),
2205 },
2206 }
2207 pubArea, err := public.Encode()
2208 if err != nil {
2209 t.Fatalf("Public encoding error: %s", err)
2210 }
2211
2212 privInternal, err := Import(rw, ekHandle, emptyAuth, pubArea, duplicate, nil, nil, nil)
2213 if err != nil {
2214 t.Fatalf("Import failed: %s", err)
2215 }
2216 newHandle, _, err := Load(rw, ekHandle, "", pubArea, privInternal)
2217 if err != nil {
2218 t.Fatalf("Load failed: %s", err)
2219 }
2220 defer FlushContext(rw, newHandle)
2221
2222 outBuff, err := Unseal(rw, newHandle, "")
2223 if err != nil {
2224 t.Fatalf("Unseal failed: %s", err)
2225 }
2226 if !bytes.Equal(outBuff, inBuff) {
2227 t.Errorf("Got %X, expected %X", outBuff, inBuff)
2228 }
2229 }
2230
2231 func TestClear(t *testing.T) {
2232 if !*runClear {
2233 t.Skip("Missing flag: run-clear. Test skipped")
2234 }
2235
2236 rw := openTPM(t)
2237 defer rw.Close()
2238
2239 err := Clear(rw, HandleLockout, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession})
2240 if err != nil {
2241 t.Fatalf("Clear failed: %v", err)
2242 }
2243 }
2244
2245 func TestHierarchyChangeAuth(t *testing.T) {
2246 if !*runClear {
2247 t.Skip("Missing flag: run-clear. Test skipped")
2248 }
2249
2250 rw := openTPM(t)
2251 defer rw.Close()
2252
2253 err := Clear(rw, HandleLockout, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession})
2254 if err != nil {
2255 t.Fatalf("Clear failed: %v", err)
2256 }
2257
2258 err = HierarchyChangeAuth(rw, HandleOwner, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession}, "pass1")
2259 if err != nil {
2260 t.Fatalf("HierarchyChangeAuth failed: %v", err)
2261 }
2262
2263 // try to set password again, providing invalid auth
2264 err = HierarchyChangeAuth(rw, HandleOwner, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession}, "pass2")
2265 if err == nil {
2266 t.Fatal("Expected HierarchyChangeAuth to fail")
2267 }
2268
2269 // set password again, providing valid auth
2270 err = HierarchyChangeAuth(rw, HandleOwner, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte("pass1")}, "pass3")
2271 if err != nil {
2272 t.Fatalf("HierarchyChangeAuth failed: %v", err)
2273 }
2274
2275 err = Clear(rw, HandleLockout, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession})
2276 if err != nil {
2277 t.Fatalf("Clear failed: %v", err)
2278 }
2279
2280 }
2281
2282 func TestPolicyPCR(t *testing.T) {
2283 rw := openTPM(t)
2284 defer rw.Close()
2285
2286 sessHandle, _, err := StartAuthSession(rw, HandleNull, HandleNull, make([]byte, 16), nil, SessionPolicy, AlgNull, AlgSHA1)
2287 if err != nil {
2288 t.Fatalf("StartAuthSession failed: %v", err)
2289 }
2290 defer FlushContext(rw, sessHandle)
2291
2292 sel := PCRSelection{Hash: AlgSHA1, PCRs: []int{0, 1, 2, 3}}
2293 pcrs, err := ReadPCRs(rw, sel)
2294 if err != nil {
2295 t.Fatalf("ReadPCRs failed: %s", err)
2296 }
2297
2298 // From TPM 2.0 Part 1, Selecting Multiple PCR:
2299 // "The list of selectors is processed in order. The selected PCR are
2300 // concatenated, with the lowest numbered PCR in the first selector being
2301 // the first in the list and the highest numbered PCR in the last selector
2302 // being the last."
2303 //
2304 // Concatenate all selected PCR values before hashing. sel.PCRs is already
2305 // sorted in ascending order.
2306 var expectedVal []byte
2307 for _, pcr := range sel.PCRs {
2308 expectedVal = append(expectedVal, pcrs[pcr]...)
2309 }
2310 t.Logf("expectedVal=%x", expectedVal)
2311
2312 // Hash algorithm must match the one in StartAuthSession.
2313 expectedDigest := sha1.Sum(expectedVal)
2314 t.Logf("expectedDigest=%x", expectedDigest)
2315
2316 tests := []struct {
2317 desc string
2318 expectedDigest []byte
2319 wantErr bool
2320 }{
2321 // PolicyPCR expects a *digest* of the PCR value, not the value itself.
2322 // Make sure PolicyPCR with value actually fails.
2323 {desc: "success: digest passed in expectedDigest", expectedDigest: expectedDigest[:]},
2324 {desc: "fail: value passed in expectedDigest", expectedDigest: expectedVal, wantErr: true},
2325 {desc: "success: nil passed in expectedDigest", expectedDigest: nil},
2326 }
2327 for _, tt := range tests {
2328 t.Run(tt.desc, func(t *testing.T) {
2329 err := PolicyPCR(rw, sessHandle, tt.expectedDigest, sel)
2330 if (err != nil) != tt.wantErr {
2331 t.Fatalf("got error: %v, want error: %v", err != nil, tt.wantErr)
2332 }
2333 })
2334 }
2335 }
2336
2337 func TestDictionaryAttackParameters(t *testing.T) {
2338 rw := openTPM(t)
2339 defer rw.Close()
2340
2341 testCases := []struct {
2342 name string
2343 maxTries uint32
2344 recoveryTime uint32
2345 lockoutRecovery uint32
2346 }{
2347 {
2348 name: "0 0 0",
2349 maxTries: 0,
2350 recoveryTime: 0,
2351 lockoutRecovery: 0,
2352 },
2353 {
2354 name: "5 10 10",
2355 maxTries: 5,
2356 recoveryTime: 10,
2357 lockoutRecovery: 10,
2358 },
2359 }
2360
2361 auth := AuthCommand{
2362 Session: HandlePasswordSession,
2363 Attributes: AttrContinueSession,
2364 Auth: []byte(emptyPassword),
2365 }
2366 for _, tc := range testCases {
2367 t.Run(tc.name, func(t *testing.T) {
2368 if err := DictionaryAttackParameters(rw, auth, tc.maxTries, tc.recoveryTime, tc.lockoutRecovery); err != nil {
2369 t.Fatalf("DictionaryAttackParameters failed: %v", err)
2370 }
2371 caps, _, err := GetCapability(rw, CapabilityTPMProperties, 3, uint32(MaxAuthFail))
2372 if err != nil {
2373 t.Fatalf("GetCapability failed: %v", err)
2374 }
2375 if caps[0].(TaggedProperty).Value != tc.maxTries {
2376 t.Fatalf("got %d, expected %d", caps[0].(TaggedProperty).Value, tc.maxTries)
2377 }
2378 if caps[1].(TaggedProperty).Value != tc.recoveryTime {
2379 t.Fatalf("got %d, expected %d", caps[1].(TaggedProperty).Value, tc.recoveryTime)
2380 }
2381 if caps[2].(TaggedProperty).Value != tc.lockoutRecovery {
2382 t.Fatalf("got %d, expected %d", caps[2].(TaggedProperty).Value, tc.lockoutRecovery)
2383 }
2384 })
2385 }
2386 }
2387
2388 func TestDictionaryAttackLockReset(t *testing.T) {
2389 rw := openTPM(t)
2390 defer rw.Close()
2391
2392 auth := AuthCommand{
2393 Session: HandlePasswordSession,
2394 Attributes: AttrContinueSession,
2395 Auth: []byte(emptyPassword),
2396 }
2397 err := DictionaryAttackParameters(rw, auth, 5, 60, 60)
2398 if err != nil {
2399 t.Fatalf("DictionaryAttackParameters failed: %v", err)
2400 }
2401
2402 handle, _, err := CreatePrimary(rw, HandleOwner, pcrSelection7, emptyPassword, defaultPassword, Public{
2403 Type: AlgRSA,
2404 NameAlg: AlgSHA256,
2405 Attributes: FlagDecrypt | FlagUserWithAuth | FlagFixedParent | FlagFixedTPM | FlagSensitiveDataOrigin,
2406 RSAParameters: &RSAParams{
2407 Sign: &SigScheme{
2408 Alg: AlgNull,
2409 Hash: AlgNull,
2410 },
2411 KeyBits: 2048,
2412 },
2413 })
2414 if err != nil {
2415 t.Fatalf("CreatePrimary failed: %s", err)
2416 }
2417 defer FlushContext(rw, handle)
2418
2419 scheme := &AsymScheme{Alg: AlgOAEP, Hash: AlgSHA256}
2420 label := "label"
2421 encrypted, err := RSAEncrypt(rw, handle, bytes.Repeat([]byte("a"), 190), scheme, label)
2422 if err != nil {
2423 t.Fatalf("RSAEncrypt failed: %v", err)
2424 }
2425 // try RSADecrypt with bad password
2426 if _, err = RSADecrypt(rw, handle, "bad password", encrypted, scheme, label); err != nil {
2427 if serr, ok := err.(SessionError); !ok || serr.Code != RCAuthFail {
2428 t.Fatalf("RSADecrypt fails with unexpected error: %v", err)
2429 }
2430 }
2431
2432 caps, _, err := GetCapability(rw, CapabilityTPMProperties, 1, uint32(LockoutCounter))
2433 if err != nil {
2434 t.Fatalf("GetCapability failed: %v", err)
2435 }
2436 if caps[0].(TaggedProperty).Value != 1 {
2437 t.Fatalf("got %d, expected 1", caps[0].(TaggedProperty).Value)
2438 }
2439
2440 if err = DictionaryAttackLockReset(rw, auth); err != nil {
2441 t.Fatalf("DictionaryAttackLockReset failed: %v", err)
2442 }
2443
2444 caps, _, err = GetCapability(rw, CapabilityTPMProperties, 1, uint32(LockoutCounter))
2445 if err != nil {
2446 t.Fatalf("GetCapability failed: %v", err)
2447 }
2448 if caps[0].(TaggedProperty).Value != 0 {
2449 t.Fatalf("got %d, expected 0", caps[0].(TaggedProperty).Value)
2450 }
2451 }
2452
2453 func TestPolicyOr(t *testing.T) {
2454 rw := openTPM(t)
2455 defer rw.Close()
2456 hashAlg, err := AlgSHA256.Hash()
2457 if err != nil {
2458 t.Errorf("looking up hash algo with error: %v", err)
2459 }
2460 zeroHash := make([]byte, hashAlg.Size())
2461 customHash := make([]byte, hashAlg.Size())
2462
2463 _, err = rand.Read(customHash)
2464 if err != nil {
2465 t.Errorf("random read into byte slice with error: %v", err)
2466 }
2467
2468 tpml := TPMLDigest{Digests: []tpmutil.U16Bytes{
2469 zeroHash, customHash},
2470 }
2471
2472 sessHandle, _, err := StartAuthSession(rw, HandleNull, HandleNull, make([]byte, 16), nil, SessionPolicy, AlgNull, AlgSHA256)
2473 defer FlushContext(rw, sessHandle)
2474
2475 if err != nil {
2476 t.Errorf("StartAuthSession failed: %v", err)
2477 }
2478 err = PolicyOr(rw, sessHandle, tpml)
2479 if err != nil {
2480 t.Errorf("PolicyOr with error: %v", err)
2481 }
2482 }
2483
2484 func TestNVUndefineSpaceSpecial(t *testing.T) {
2485 rw := openTPM(t)
2486 defer rw.Close()
2487
2488 // Set up trial policy session for creation of PolicyCommandCode policy. The policy will be bound as 'delete policy' to the nv index.
2489 sess, _, err := StartAuthSession(rw, HandleNull, HandleNull, make([]byte, 16), nil, SessionTrial, AlgNull, AlgSHA256)
2490 if err != nil {
2491 t.Errorf("StartAuthSession() for policy generation failed: %v", err)
2492 }
2493 err = PolicyCommandCode(rw, sess, CmdNVUndefineSpaceSpecial)
2494 if err != nil {
2495 t.Errorf("PolicyCommandCode() failed: %v", err)
2496 }
2497 pol, err := PolicyGetDigest(rw, sess)
2498 if err != nil {
2499 t.Errorf("PolicyGetDigest() failed: %v", err)
2500 }
2501 if err := FlushContext(rw, sess); err != nil {
2502 t.Errorf("FlushContext() failed: %v", err)
2503 }
2504
2505 // Test index with
2506 pubIndex := NVPublic{
2507 NVIndex: 0x1500000,
2508 NameAlg: AlgSHA256,
2509 Attributes: AttrPlatformCreate | AttrPolicyDelete | AttrPolicyWrite | AttrNoDA | AttrAuthRead,
2510 AuthPolicy: pol,
2511 DataSize: 10,
2512 }
2513 // AuthCommand for platform hierarchy
2514 platformAuthCmd := AuthCommand{
2515 Session: HandlePasswordSession,
2516 Attributes: AttrContinueSession,
2517 Auth: EmptyAuth,
2518 }
2519
2520 // Create the index
2521 err = NVDefineSpaceEx(rw, HandlePlatform, "", pubIndex, platformAuthCmd)
2522 if err != nil {
2523 t.Errorf("NVDefineSpaceEx() failed: %v", err)
2524 }
2525
2526 // Start new auth session for authentication of nv index access
2527 sess, _, err = StartAuthSession(rw, HandleNull, HandleNull, make([]byte, 16), nil, SessionPolicy, AlgNull, AlgSHA256)
2528 if err != nil {
2529 t.Errorf("StartAuthSession() for nv index auth failed: %v", err)
2530 }
2531
2532 // Authorize UndefineSpaceSpecial by policy since it can't be authorized by auth value due to the attribute POLICY_DELETE on the index
2533 err = PolicyCommandCode(rw, sess, CmdNVUndefineSpaceSpecial)
2534 if err != nil {
2535 t.Errorf("PolicyCommandCode() or nv index auth failed: %v", err)
2536 }
2537
2538 indexAuthCmd := AuthCommand{
2539 Session: sess,
2540 Attributes: AttrContinueSession,
2541 Auth: EmptyAuth,
2542 }
2543 // Delete the index
2544 err = NVUndefineSpaceSpecial(rw, pubIndex.NVIndex, indexAuthCmd, platformAuthCmd)
2545 if err != nil {
2546 t.Errorf("NVUndefineSpaceSpecial() failed: %v", err)
2547 }
2548 }