Debian Codegraph @

attest/wrapped_tpm20.go

raw
1 // Copyright 2020 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 package attest
16
17 import (
18 "bytes"
19 "crypto"
20 "crypto/ecdsa"
21 "crypto/elliptic"
22 "crypto/rsa"
23 "crypto/x509"
24 "encoding/asn1"
25 "encoding/base64"
26 "errors"
27 "fmt"
28 "io"
29 "math/big"
30
31 "github.com/google/go-tpm/legacy/tpm2"
32 "github.com/google/go-tpm/tpmutil"
33 )
34
35 // The size of TPM2B_MAX_BUFFER is TPM-dependent. The value here is what all
36 // TPMs support. See TPM 2.0 spec, part 2, section 10.4.8 TPM2B_MAX_BUFFER.
37 const tpm2BMaxBufferSize = 1024
38
39 // wrappedTPM20 interfaces with a TPM 2.0 command channel.
40 type wrappedTPM20 struct {
41 interf TPMInterface
42 rwc CommandChannelTPM20
43 tpmRSAEkTemplate *tpm2.Public
44 tpmECCEkTemplate *tpm2.Public
45 }
46
47 // certifyingKey contains details of a TPM key that could certify other keys.
48 type certifyingKey struct {
49 handle tpmutil.Handle
50 alg Algorithm
51 }
52
53 func (t *wrappedTPM20) rsaEkTemplate() tpm2.Public {
54 if t.tpmRSAEkTemplate != nil {
55 return *t.tpmRSAEkTemplate
56 }
57
58 nonce, err := tpm2.NVReadEx(t.rwc, nvramRSAEkNonceIndex, tpm2.HandleOwner, "", 0)
59 if err != nil {
60 t.tpmRSAEkTemplate = &defaultRSAEKTemplate // No nonce, use the default template
61 } else {
62 template := defaultRSAEKTemplate
63 copy(template.RSAParameters.ModulusRaw, nonce)
64 t.tpmRSAEkTemplate = &template
65 }
66
67 return *t.tpmRSAEkTemplate
68 }
69
70 func (t *wrappedTPM20) eccEkTemplate() tpm2.Public {
71 if t.tpmECCEkTemplate != nil {
72 return *t.tpmECCEkTemplate
73 }
74
75 nonce, err := tpm2.NVReadEx(t.rwc, nvramECCEkNonceIndex, tpm2.HandleOwner, "", 0)
76 if err != nil {
77 t.tpmECCEkTemplate = &defaultECCEKTemplate // No nonce, use the default template
78 } else {
79 template := defaultECCEKTemplate
80 copy(template.ECCParameters.Point.XRaw, nonce)
81 t.tpmECCEkTemplate = &template
82 }
83
84 return *t.tpmECCEkTemplate
85 }
86
87 func (t *wrappedTPM20) close() error {
88 return t.rwc.Close()
89 }
90
91 // Info returns information about the TPM.
92 func (t *wrappedTPM20) info() (*TPMInfo, error) {
93 var (
94 tInfo = TPMInfo{
95 Interface: t.interf,
96 }
97 t2Info tpmInfo
98 err error
99 )
100
101 if t2Info, err = readVendorAttributes(t.rwc); err != nil {
102 return nil, err
103 }
104 tInfo.Manufacturer = t2Info.manufacturer
105 tInfo.VendorInfo = t2Info.vendor
106 tInfo.FirmwareVersionMajor = t2Info.fwMajor
107 tInfo.FirmwareVersionMinor = t2Info.fwMinor
108 return &tInfo, nil
109 }
110
111 // createEK creates a persistent EK given an ek template and a handle location
112 func (t *wrappedTPM20) createEK(ekTemplate tpm2.Public, targetEKHandle tpmutil.Handle, rerr error) error {
113 keyHnd, _, err := tpm2.CreatePrimary(t.rwc, tpm2.HandleEndorsement, tpm2.PCRSelection{}, "", "", ekTemplate)
114 if err != nil {
115 return fmt.Errorf("ReadPublic failed (%v), and then CreatePrimary failed: %v", rerr, err)
116 }
117 defer tpm2.FlushContext(t.rwc, keyHnd)
118
119 err = tpm2.EvictControl(t.rwc, "", tpm2.HandleOwner, keyHnd, targetEKHandle)
120 if err != nil {
121 return fmt.Errorf("EvictControl failed: %v", err)
122 }
123 return nil
124 }
125
126 // Return value: handle, whether we generated a new one, error.
127 func (t *wrappedTPM20) getEndorsementKeyHandle(ek *EK) (tpmutil.Handle, bool, error) {
128 var ekHandle tpmutil.Handle
129 var ekTemplate tpm2.Public
130
131 if ek == nil {
132 // The default is RSA for backward compatibility.
133 ekHandle = commonRSAEkEquivalentHandle
134 ekTemplate = t.rsaEkTemplate()
135 } else {
136 ekHandle = ek.handle
137 if ekHandle == 0 {
138 // Assume RSA EK handle if it was not provided.
139 ekHandle = commonRSAEkEquivalentHandle
140 }
141 switch pub := ek.Public.(type) {
142 case *rsa.PublicKey:
143 ekTemplate = t.rsaEkTemplate()
144 case *ecdsa.PublicKey:
145 ekTemplate = t.eccEkTemplate()
146 default:
147 return 0, false, fmt.Errorf("unsupported public key type %T", pub)
148 }
149 }
150
151 _, _, _, err := tpm2.ReadPublic(t.rwc, ekHandle)
152 if err == nil {
153 // Found the persistent handle, assume it's the key we want.
154 return ekHandle, false, nil
155 }
156 rerr := err // Preserve this failure for later logging, if needed
157
158 err = t.createEK(ekTemplate, ekHandle, rerr)
159 if err != nil {
160 return 0, false, err
161 }
162
163 return ekHandle, true, nil
164 }
165
166 // Return value: handle, whether we generated a new one, error
167 func (t *wrappedTPM20) getStorageRootKeyHandle(parent ParentKeyConfig) (tpmutil.Handle, bool, error) {
168 srkHandle := parent.Handle
169 _, _, _, err := tpm2.ReadPublic(t.rwc, srkHandle)
170 if err == nil {
171 // Found the persistent handle, assume it's the key we want.
172 return srkHandle, false, nil
173 }
174 rerr := err // Preserve this failure for later logging, if needed
175
176 var srkTemplate tpm2.Public
177 switch parent.Algorithm {
178 case RSA:
179 srkTemplate = defaultRSASRKTemplate
180 case ECDSA:
181 srkTemplate = defaultECCSRKTemplate
182 default:
183 return 0, false, fmt.Errorf("unsupported SRK algorithm: %v", parent.Algorithm)
184 }
185 err = t.createEK(srkTemplate, srkHandle, rerr)
186 if err != nil {
187 return 0, false, err
188 }
189 return srkHandle, true, nil
190 }
191
192 // returns the base64 encoding of the der encoding of a public key
193 func serializePublicKey(pub crypto.PublicKey) (string, error) {
194 derKey, err := x509.MarshalPKIXPublicKey(pub)
195 if err != nil {
196 return "", err
197 }
198 return base64.StdEncoding.EncodeToString(derKey), nil
199 }
200
201 // Unfortunatelly some TPMs have a non rsa2048 key in the commonRSAEkEquivalentHandle
202 // handle location. Thus we need an alternative handle to use for both creating
203 // and searching for the rsa2048 ek.
204 // The "Registry-of-Reserved-TPM-2.0-Handles-and-Localities-Version 1.2" section 2.3.1
205 // asserts that persistent EK handles should be in the range 0x8101000-0x810100FF
206 // Thus any value in this range is acceptable, so we arbitrarily chose
207 // a value inmediatelly after the ECC (p256) handle.
208 const altRSAEkEquivalentHandle = commonECCEkEquivalentHandle + 1
209
210 // creates a map of a base64 pkcs8 encoding of public keys to handles
211 func (t *wrappedTPM20) getKeyHandleKeyMap() (map[string]tpmutil.Handle, map[tpmutil.Handle]struct{}, error) {
212 key2Handle := make(map[string]tpmutil.Handle)
213 handleFound := make(map[tpmutil.Handle]struct{})
214 // The handles to searh today are the nvram locations where we expect to find keys
215 // we could augment this list int the future, by including the equivalent of
216 // "tpm2_getcap handles-persistent". However we want to limit the number of locations
217 // to probe as accessing the tpm is a relatively slow path.
218 knownHandlesToSearch := []tpmutil.Handle{
219 commonRSAEkEquivalentHandle,
220 commonECCEkEquivalentHandle,
221 altRSAEkEquivalentHandle,
222 }
223 for _, keyHandle := range knownHandlesToSearch {
224 pub, _, _, err := tpm2.ReadPublic(t.rwc, keyHandle)
225 if err != nil {
226 continue
227 }
228 if pub.RSAParameters != nil || pub.ECCParameters != nil {
229 key, err := pub.Key()
230 if err != nil {
231 return nil, nil, fmt.Errorf("failed to obtain public key for handle %x: %w", keyHandle, err)
232 }
233 serializedKey, err := serializePublicKey(key)
234 if err != nil {
235 return nil, nil, fmt.Errorf("failed to serialize public key for handle %x: %w", keyHandle, err)
236 }
237 key2Handle[serializedKey] = keyHandle
238 handleFound[keyHandle] = struct{}{}
239 }
240 }
241 return key2Handle, handleFound, nil
242 }
243
244 func (t *wrappedTPM20) create2048RSAEKInAvailableSlot(handleFoundMap map[tpmutil.Handle]struct{}) (tpmutil.Handle, error) {
245 rsakeyHandles := []tpmutil.Handle{
246 commonRSAEkEquivalentHandle,
247 altRSAEkEquivalentHandle,
248 }
249 for _, targetHandle := range rsakeyHandles {
250 _, handleInUse := handleFoundMap[targetHandle]
251 if handleInUse {
252 continue
253 }
254 ekTemplate := t.rsaEkTemplate()
255 err := t.createEK(ekTemplate, targetHandle, fmt.Errorf(""))
256 if err != nil {
257 return tpmutil.Handle(0), err
258 }
259 return targetHandle, nil
260 }
261 return tpmutil.Handle(0), fmt.Errorf("no available handles to create RSA 2048 key in persistent handle")
262 }
263
264 func (t *wrappedTPM20) ekCertificates() ([]EK, error) {
265 var res []EK
266 certIndexes := []int{nvramRSACertIndex, nvramECCCertIndex}
267 keyHandleMap, handleFoundMap, err := t.getKeyHandleKeyMap()
268 if err != nil {
269 return nil, err
270 }
271 for _, certIndex := range certIndexes {
272 if cert, err := readEKCertFromNVRAM20(t.rwc, tpmutil.Handle(certIndex)); err == nil {
273 serializedKey, err := serializePublicKey(cert.PublicKey)
274 if err != nil {
275 return nil, err
276 }
277
278 handleToUse, keyfound := keyHandleMap[serializedKey]
279 if !keyfound && certIndex == nvramRSACertIndex {
280 handleToUse, err = t.create2048RSAEKInAvailableSlot(handleFoundMap)
281 if err != nil {
282 return nil, err
283 }
284 keyfound = true
285 }
286 if !keyfound {
287 continue
288 }
289 res = append(res, EK{Public: crypto.PublicKey(cert.PublicKey), Certificate: cert, handle: handleToUse})
290 }
291 }
292 return res, nil
293 }
294
295 func (t *wrappedTPM20) eks() ([]EK, error) {
296 if cert, err := readEKCertFromNVRAM20(t.rwc, nvramRSACertIndex); err == nil {
297 return []EK{
298 {Public: crypto.PublicKey(cert.PublicKey), Certificate: cert, handle: commonRSAEkEquivalentHandle},
299 }, nil
300 }
301
302 // Attempt to create an EK.
303 ekHnd, _, err := tpm2.CreatePrimary(t.rwc, tpm2.HandleEndorsement, tpm2.PCRSelection{}, "", "", t.rsaEkTemplate())
304 if err != nil {
305 return nil, fmt.Errorf("EK CreatePrimary failed: %v", err)
306 }
307 defer tpm2.FlushContext(t.rwc, ekHnd)
308
309 pub, _, _, err := tpm2.ReadPublic(t.rwc, ekHnd)
310 if err != nil {
311 return nil, fmt.Errorf("EK ReadPublic failed: %v", err)
312 }
313 if pub.RSAParameters == nil {
314 return nil, errors.New("ECC EK not yet supported")
315 }
316
317 i, err := t.info()
318 if err != nil {
319 return nil, fmt.Errorf("retrieving TPM info failed: %v", err)
320 }
321 ekPub := &rsa.PublicKey{
322 E: int(pub.RSAParameters.Exponent()),
323 N: pub.RSAParameters.Modulus(),
324 }
325 certificateURL := ekCertURL(ekPub, i.Manufacturer.String())
326 return []EK{
327 {
328 Public: ekPub,
329 CertificateURL: certificateURL,
330 handle: commonRSAEkEquivalentHandle,
331 },
332 }, nil
333 }
334
335 func (t *wrappedTPM20) newAK(opts *AKConfig) (*AK, error) {
336 var parent ParentKeyConfig
337 if opts != nil && opts.Parent != nil {
338 parent = *opts.Parent
339 } else {
340 parent = defaultParentConfig
341 }
342 srk, _, err := t.getStorageRootKeyHandle(parent)
343 if err != nil {
344 return nil, fmt.Errorf("failed to get SRK handle: %v", err)
345 }
346
347 var akTemplate tpm2.Public
348 var sigScheme *tpm2.SigScheme
349 // The default is RSA.
350 if opts != nil && opts.Algorithm == ECDSA {
351 akTemplate = akTemplateECC
352 sigScheme = akTemplateECC.ECCParameters.Sign
353 } else {
354 akTemplate = akTemplateRSA
355 sigScheme = akTemplateRSA.RSAParameters.Sign
356 }
357 blob, pub, creationData, creationHash, tix, err := tpm2.CreateKey(t.rwc, srk, tpm2.PCRSelection{}, "", "", akTemplate)
358 if err != nil {
359 return nil, fmt.Errorf("CreateKeyEx() failed: %v", err)
360 }
361 keyHandle, _, err := tpm2.Load(t.rwc, srk, "", pub, blob)
362 if err != nil {
363 return nil, fmt.Errorf("Load() failed: %v", err)
364 }
365 // If any errors occur, free the AK's handle.
366 defer func() {
367 if err != nil {
368 tpm2.FlushContext(t.rwc, keyHandle)
369 }
370 }()
371
372 // We can only certify the creation immediately afterwards, so we cache the result.
373 attestation, sig, err := tpm2.CertifyCreation(t.rwc, "", keyHandle, keyHandle, nil, creationHash, *sigScheme, tix)
374 if err != nil {
375 return nil, fmt.Errorf("CertifyCreation failed: %v", err)
376 }
377
378 tpmPub, err := tpm2.DecodePublic(pub)
379 if err != nil {
380 return nil, fmt.Errorf("decode public key: %v", err)
381 }
382 pubKey, err := tpmPub.Key()
383 if err != nil {
384 return nil, fmt.Errorf("access public key: %v", err)
385 }
386
387 return &AK{
388 ak: newWrappedAK20(keyHandle, blob, pub, creationData, attestation, sig),
389 pub: pubKey,
390 }, nil
391 }
392
393 func (t *wrappedTPM20) newKey(ak *AK, opts *KeyConfig) (*Key, error) {
394 k, ok := ak.ak.(*wrappedKey20)
395 if !ok {
396 return nil, fmt.Errorf("expected *wrappedKey20, got: %T", k)
397 }
398
399 kAlg, err := k.algorithm()
400 if err != nil {
401 return nil, fmt.Errorf("get algorithm: %v", err)
402 }
403 ck := certifyingKey{handle: k.hnd, alg: kAlg}
404 return t.newKeyCertifiedByKey(ck, opts)
405 }
406
407 func (t *wrappedTPM20) newKeyCertifiedByKey(ck certifyingKey, opts *KeyConfig) (*Key, error) {
408 parent, blob, pub, creationData, err := createKey(t, opts)
409 if err != nil {
410 return nil, fmt.Errorf("cannot create key: %v", err)
411 }
412
413 keyHandle, _, err := tpm2.Load(t.rwc, parent, "", pub, blob)
414 if err != nil {
415 return nil, fmt.Errorf("Load() failed: %v", err)
416 }
417 // If any errors occur, free the handle.
418 defer func() {
419 if err != nil {
420 tpm2.FlushContext(t.rwc, keyHandle)
421 }
422 }()
423
424 // Certify application key by AK
425 certifyOpts := CertifyOpts{QualifyingData: opts.QualifyingData}
426 cp, err := certifyByKey(t, keyHandle, ck, certifyOpts)
427 if err != nil {
428 return nil, fmt.Errorf("certifyByKey() failed: %v", err)
429 }
430 if !bytes.Equal(pub, cp.Public) {
431 return nil, fmt.Errorf("certified incorrect key, expected: %v, certified: %v", pub, cp.Public)
432 }
433
434 // Pack the raw structure into a TPMU_SIGNATURE.
435 tpmPub, err := tpm2.DecodePublic(pub)
436 if err != nil {
437 return nil, fmt.Errorf("decode public key: %v", err)
438 }
439 pubKey, err := tpmPub.Key()
440 if err != nil {
441 return nil, fmt.Errorf("access public key: %v", err)
442 }
443 return &Key{key: newWrappedKey20(keyHandle, blob, pub, creationData, cp.CreateAttestation, cp.CreateSignature), pub: pubKey, tpm: t}, nil
444 }
445
446 func createKey(t *wrappedTPM20, opts *KeyConfig) (tpmutil.Handle, []byte, []byte, []byte, error) {
447 var parent ParentKeyConfig
448 if opts != nil && opts.Parent != nil {
449 parent = *opts.Parent
450 } else {
451 parent = defaultParentConfig
452 }
453 srk, _, err := t.getStorageRootKeyHandle(parent)
454 if err != nil {
455 return 0, nil, nil, nil, fmt.Errorf("failed to get SRK handle: %v", err)
456 }
457
458 tmpl, err := templateFromConfig(opts)
459 if err != nil {
460 return 0, nil, nil, nil, fmt.Errorf("incorrect key options: %v", err)
461 }
462
463 blob, pub, creationData, _, _, err := tpm2.CreateKey(t.rwc, srk, tpm2.PCRSelection{}, "", "", tmpl)
464 if err != nil {
465 return 0, nil, nil, nil, fmt.Errorf("CreateKey() failed: %v", err)
466 }
467
468 return srk, blob, pub, creationData, err
469 }
470
471 func templateFromConfig(opts *KeyConfig) (tpm2.Public, error) {
472 var tmpl tpm2.Public
473 switch opts.Algorithm {
474 case RSA:
475 tmpl = rsaKeyTemplate
476 if opts.Size < 0 || opts.Size > 65535 { // basic sanity check
477 return tmpl, fmt.Errorf("incorrect size parameter")
478 }
479 tmpl.RSAParameters.KeyBits = uint16(opts.Size)
480
481 case ECDSA:
482 tmpl = ecdsaKeyTemplate
483 switch opts.Size {
484 case 256:
485 tmpl.NameAlg = tpm2.AlgSHA256
486 tmpl.ECCParameters.Sign.Hash = tpm2.AlgSHA256
487 tmpl.ECCParameters.CurveID = tpm2.CurveNISTP256
488 case 384:
489 tmpl.NameAlg = tpm2.AlgSHA384
490 tmpl.ECCParameters.Sign.Hash = tpm2.AlgSHA384
491 tmpl.ECCParameters.CurveID = tpm2.CurveNISTP384
492 case 521:
493 tmpl.NameAlg = tpm2.AlgSHA512
494 tmpl.ECCParameters.Sign.Hash = tpm2.AlgSHA512
495 tmpl.ECCParameters.CurveID = tpm2.CurveNISTP521
496 default:
497 return tmpl, fmt.Errorf("unsupported key size: %v", opts.Size)
498 }
499 default:
500 return tmpl, fmt.Errorf("unsupported algorithm type: %q", opts.Algorithm)
501 }
502
503 return tmpl, nil
504 }
505
506 func (t *wrappedTPM20) deserializeAndLoad(opaqueBlob []byte, parent ParentKeyConfig) (tpmutil.Handle, *serializedKey, error) {
507 sKey, err := deserializeKey(opaqueBlob)
508 if err != nil {
509 return 0, nil, fmt.Errorf("deserializeKey() failed: %v", err)
510 }
511 if sKey.Encoding != keyEncodingEncrypted {
512 return 0, nil, fmt.Errorf("unsupported key encoding: %x", sKey.Encoding)
513 }
514
515 srk, _, err := t.getStorageRootKeyHandle(parent)
516 if err != nil {
517 return 0, nil, fmt.Errorf("failed to get SRK handle: %v", err)
518 }
519 var hnd tpmutil.Handle
520 if hnd, _, err = tpm2.Load(t.rwc, srk, "", sKey.Public, sKey.Blob); err != nil {
521 return 0, nil, fmt.Errorf("Load() failed: %v", err)
522 }
523 return hnd, sKey, nil
524 }
525
526 func (t *wrappedTPM20) loadAK(opaqueBlob []byte) (*AK, error) {
527 return t.loadAKWithParent(opaqueBlob, defaultParentConfig)
528 }
529
530 func (t *wrappedTPM20) loadAKWithParent(opaqueBlob []byte, parent ParentKeyConfig) (*AK, error) {
531 hnd, sKey, err := t.deserializeAndLoad(opaqueBlob, parent)
532 if err != nil {
533 return nil, fmt.Errorf("cannot load attestation key: %v", err)
534 }
535 return &AK{ak: newWrappedAK20(hnd, sKey.Blob, sKey.Public, sKey.CreateData, sKey.CreateAttestation, sKey.CreateSignature)}, nil
536 }
537
538 func (t *wrappedTPM20) loadKey(opaqueBlob []byte) (*Key, error) {
539 return t.loadKeyWithParent(opaqueBlob, defaultParentConfig)
540 }
541
542 func (t *wrappedTPM20) loadKeyWithParent(opaqueBlob []byte, parent ParentKeyConfig) (*Key, error) {
543 hnd, sKey, err := t.deserializeAndLoad(opaqueBlob, parent)
544 if err != nil {
545 return nil, fmt.Errorf("cannot load signing key: %v", err)
546 }
547 tpmPub, err := tpm2.DecodePublic(sKey.Public)
548 if err != nil {
549 return nil, fmt.Errorf("decode public blob: %v", err)
550 }
551 pub, err := tpmPub.Key()
552 if err != nil {
553 return nil, fmt.Errorf("access public key: %v", err)
554 }
555 return &Key{key: newWrappedKey20(hnd, sKey.Blob, sKey.Public, sKey.CreateData, sKey.CreateAttestation, sKey.CreateSignature), pub: pub, tpm: t}, nil
556 }
557
558 func (t *wrappedTPM20) pcrbanks() ([]HashAlg, error) {
559 return pcrbanks(t.rwc)
560 }
561
562 func (t *wrappedTPM20) pcrs(alg HashAlg) ([]PCR, error) {
563 PCRs, err := readAllPCRs(t.rwc, alg.goTPMAlg())
564 if err != nil {
565 return nil, fmt.Errorf("failed to read PCRs: %v", err)
566 }
567
568 out := make([]PCR, len(PCRs))
569 for index, digest := range PCRs {
570 digestAlg, err := alg.cryptoHash()
571 if err != nil {
572 return nil, fmt.Errorf("unknown algorithm ID %x: %v", alg, err)
573 }
574 out[int(index)] = PCR{
575 Index: int(index),
576 Digest: digest,
577 DigestAlg: digestAlg,
578 }
579 }
580
581 return out, nil
582 }
583
584 func (t *wrappedTPM20) measurementLog() ([]byte, error) {
585 return t.rwc.MeasurementLog()
586 }
587
588 func tpmHash(rwc CommandChannelTPM20, msg []byte, h crypto.Hash) ([]byte, *tpm2.Ticket, error) {
589 alg, err := tpm2.HashToAlgorithm(h)
590 if err != nil {
591 return nil, nil, fmt.Errorf("failed to convert hash algorithm: %v", err)
592 }
593
594 hnd, err := tpm2.HashSequenceStart(rwc, "", alg)
595 if err != nil {
596 return nil, nil, fmt.Errorf("failed to start hash sequence: %v", err)
597 }
598 flushHandle := true
599 defer func() {
600 if flushHandle {
601 tpm2.FlushContext(rwc, hnd)
602 }
603 }()
604
605 i := 0
606 // Handle all but the last chunk.
607 for {
608 end := i + tpm2BMaxBufferSize
609 if end >= len(msg) {
610 break
611 }
612 if err := tpm2.SequenceUpdate(rwc, "", hnd, msg[i:end]); err != nil {
613 return nil, nil, fmt.Errorf("failed to update hash sequence: %v", err)
614 }
615 i = end
616 }
617
618 // Handle the last chunk.
619 //
620 // Hardcoding tpm2.HandleOwner here should be fine --- "The hierarchy
621 // parameter is not related to the signing key hierarchy". See TPM 2.0
622 // spec, Part 3, Section 17.6 TPM2_SequenceComplete.
623 digest, validation, err := tpm2.SequenceComplete(rwc, "", hnd, tpm2.HandleOwner, msg[i:])
624 if err != nil {
625 return nil, nil, fmt.Errorf("failed to complete hash sequence: %v", err)
626 }
627 // "If this command completes successfully, the sequenceHandle object will
628 // be flushed." --- we don't need to flush it ourselves.
629 flushHandle = false
630
631 if validation.Hierarchy == tpm2.HandleNull {
632 return nil, nil, fmt.Errorf("validation ticket has a null hierarchy. msg might be too short or starts with TPM_GENERATED_VALUE")
633 }
634
635 return digest, validation, nil
636 }
637
638 // wrappedKey20 represents a key manipulated through a *wrappedTPM20.
639 type wrappedKey20 struct {
640 hnd tpmutil.Handle
641
642 blob []byte
643 public []byte // used by both TPM1.2 and 2.0
644 createData []byte
645 createAttestation []byte
646 createSignature []byte
647 }
648
649 func newWrappedAK20(hnd tpmutil.Handle, blob, public, createData, createAttestation, createSig []byte) ak {
650 return &wrappedKey20{
651 hnd: hnd,
652 blob: blob,
653 public: public,
654 createData: createData,
655 createAttestation: createAttestation,
656 createSignature: createSig,
657 }
658 }
659
660 func newWrappedKey20(hnd tpmutil.Handle, blob, public, createData, createAttestation, createSig []byte) key {
661 return &wrappedKey20{
662 hnd: hnd,
663 blob: blob,
664 public: public,
665 createData: createData,
666 createAttestation: createAttestation,
667 createSignature: createSig,
668 }
669 }
670
671 func (k *wrappedKey20) marshal() ([]byte, error) {
672 return (&serializedKey{
673 Encoding: keyEncodingEncrypted,
674 TPMVersion: 2,
675
676 Blob: k.blob,
677 Public: k.public,
678 CreateData: k.createData,
679 CreateAttestation: k.createAttestation,
680 CreateSignature: k.createSignature,
681 }).Serialize()
682 }
683
684 func (k *wrappedKey20) close(t tpmBase) error {
685 tpm, ok := t.(*wrappedTPM20)
686 if !ok {
687 return fmt.Errorf("expected *wrappedTPM20, got %T", t)
688 }
689 return tpm2.FlushContext(tpm.rwc, k.hnd)
690 }
691
692 func (k *wrappedKey20) activateCredential(tb tpmBase, in EncryptedCredential, ek *EK) ([]byte, error) {
693 t, ok := tb.(*wrappedTPM20)
694 if !ok {
695 return nil, fmt.Errorf("expected *wrappedTPM20, got %T", tb)
696 }
697
698 if len(in.Credential) < 2 {
699 return nil, fmt.Errorf("malformed credential blob")
700 }
701 credential := in.Credential[2:]
702 if len(in.Secret) < 2 {
703 return nil, fmt.Errorf("malformed encrypted secret")
704 }
705 secret := in.Secret[2:]
706
707 ekHnd, _, err := t.getEndorsementKeyHandle(ek)
708 if err != nil {
709 return nil, err
710 }
711
712 sessHandle, _, err := tpm2.StartAuthSession(
713 t.rwc,
714 tpm2.HandleNull, /*tpmKey*/
715 tpm2.HandleNull, /*bindKey*/
716 make([]byte, 16), /*nonceCaller*/
717 nil, /*secret*/
718 tpm2.SessionPolicy,
719 tpm2.AlgNull,
720 tpm2.AlgSHA256)
721 if err != nil {
722 return nil, fmt.Errorf("creating session: %v", err)
723 }
724 defer tpm2.FlushContext(t.rwc, sessHandle)
725
726 if _, _, err := tpm2.PolicySecret(t.rwc, tpm2.HandleEndorsement, tpm2.AuthCommand{Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession}, sessHandle, nil, nil, nil, 0); err != nil {
727 return nil, fmt.Errorf("tpm2.PolicySecret() failed: %v", err)
728 }
729
730 return tpm2.ActivateCredentialUsingAuth(t.rwc, []tpm2.AuthCommand{
731 {Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession},
732 {Session: sessHandle, Attributes: tpm2.AttrContinueSession},
733 }, k.hnd, ekHnd, credential, secret)
734 }
735
736 func sigSchemeFromAlgorithm(alg Algorithm) (tpm2.SigScheme, error) {
737 switch alg {
738 case RSA:
739 return tpm2.SigScheme{
740 Alg: tpm2.AlgRSASSA,
741 Hash: tpm2.AlgSHA256,
742 }, nil
743 case ECDSA:
744 return tpm2.SigScheme{
745 Alg: tpm2.AlgECDSA,
746 Hash: tpm2.AlgSHA256,
747 }, nil
748 default:
749 return tpm2.SigScheme{}, fmt.Errorf("algorithm %v not supported", alg)
750 }
751 }
752
753 func (k *wrappedKey20) certify(tb tpmBase, handle any, opts CertifyOpts) (*CertificationParameters, error) {
754 kAlg, err := k.algorithm()
755 if err != nil {
756 return nil, fmt.Errorf("unknown algorithm: %v", err)
757 }
758 ck := certifyingKey{
759 handle: k.hnd,
760 alg: kAlg,
761 }
762 return certifyByKey(tb, handle, ck, opts)
763 }
764
765 func certifyByKey(tb tpmBase, handle any, ck certifyingKey, opts CertifyOpts) (*CertificationParameters, error) {
766 t, ok := tb.(*wrappedTPM20)
767 if !ok {
768 return nil, fmt.Errorf("expected *wrappedTPM20, got %T", tb)
769 }
770 hnd, ok := handle.(tpmutil.Handle)
771 if !ok {
772 return nil, fmt.Errorf("expected tpmutil.Handle, got %T", handle)
773 }
774 scheme, err := sigSchemeFromAlgorithm(ck.alg)
775 if err != nil {
776 return nil, fmt.Errorf("get signature scheme: %v", err)
777 }
778 return certify(t.rwc, hnd, ck.handle, opts.QualifyingData, scheme)
779 }
780
781 func (k *wrappedKey20) quote(tb tpmBase, nonce []byte, alg HashAlg, selectedPCRs []int) (*Quote, error) {
782 t, ok := tb.(*wrappedTPM20)
783 if !ok {
784 return nil, fmt.Errorf("expected *wrappedTPM20, got %T", tb)
785 }
786 return quote20(t.rwc, k.hnd, tpm2.Algorithm(alg), nonce, selectedPCRs)
787 }
788
789 func (k *wrappedKey20) attestationParameters() AttestationParameters {
790 return AttestationParameters{
791 Public: k.public,
792 CreateData: k.createData,
793 CreateAttestation: k.createAttestation,
794 CreateSignature: k.createSignature,
795 }
796 }
797
798 func (k *wrappedKey20) certificationParameters() CertificationParameters {
799 return CertificationParameters{
800 Public: k.public,
801 CreateAttestation: k.createAttestation,
802 CreateSignature: k.createSignature,
803 }
804 }
805
806 func (k *wrappedKey20) signMsg(tb tpmBase, msg []byte, pub crypto.PublicKey, opts crypto.SignerOpts) ([]byte, error) {
807 t, ok := tb.(*wrappedTPM20)
808 if !ok {
809 return nil, fmt.Errorf("expected *wrappedTPM20, got %T", tb)
810 }
811 digest, validation, err := tpmHash(t.rwc, msg, opts.HashFunc())
812 if err != nil {
813 return nil, fmt.Errorf("failed to hash message: %v", err)
814 }
815
816 return k.signWithValidation(tb, digest, pub, opts, validation)
817 }
818
819 func (k *wrappedKey20) sign(tb tpmBase, digest []byte, pub crypto.PublicKey, opts crypto.SignerOpts) ([]byte, error) {
820 return k.signWithValidation(tb, digest, pub, opts, nil)
821 }
822
823 func (k *wrappedKey20) signWithValidation(tb tpmBase, digest []byte, pub crypto.PublicKey, opts crypto.SignerOpts, validation *tpm2.Ticket) ([]byte, error) {
824 t, ok := tb.(*wrappedTPM20)
825 if !ok {
826 return nil, fmt.Errorf("expected *wrappedTPM20, got %T", tb)
827 }
828 switch p := pub.(type) {
829 case *ecdsa.PublicKey:
830 return signECDSA(t.rwc, k.hnd, digest, p.Curve, opts, validation)
831 case *rsa.PublicKey:
832 return signRSA(t.rwc, k.hnd, digest, opts, validation)
833 }
834 return nil, fmt.Errorf("unsupported signing key type: %T", pub)
835 }
836
837 func signECDSA(rw io.ReadWriter, key tpmutil.Handle, digest []byte, curve elliptic.Curve, opts crypto.SignerOpts, validation *tpm2.Ticket) ([]byte, error) {
838 if _, ok := opts.(*rsa.PSSOptions); ok {
839 return nil, fmt.Errorf("cannot use rsa.PSSOptions with ECDSA key")
840 }
841 // https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/crypto/ecdsa/ecdsa.go;l=181
842 orderBits := curve.Params().N.BitLen()
843 orderBytes := (orderBits + 7) / 8
844 if len(digest) > orderBytes {
845 digest = digest[:orderBytes]
846 }
847 ret := new(big.Int).SetBytes(digest)
848 excess := len(digest)*8 - orderBits
849 if excess > 0 {
850 ret.Rsh(ret, uint(excess))
851 }
852 // call ret.FillBytes() here instead of ret.Bytes() to preserve leading zeroes
853 // that may have been dropped when converting the digest to an integer
854 digest = ret.FillBytes(digest)
855
856 sig, err := tpm2.Sign(rw, key, "", digest, validation, nil)
857 if err != nil {
858 return nil, fmt.Errorf("cannot sign: %v", err)
859 }
860 if sig.ECC == nil {
861 return nil, fmt.Errorf("expected ECDSA signature, got: %v", sig.Alg)
862 }
863 return asn1.Marshal(struct {
864 R *big.Int
865 S *big.Int
866 }{sig.ECC.R, sig.ECC.S})
867 }
868
869 func signRSA(rw io.ReadWriter, key tpmutil.Handle, digest []byte, opts crypto.SignerOpts, validation *tpm2.Ticket) ([]byte, error) {
870 h, err := tpm2.HashToAlgorithm(opts.HashFunc())
871 if err != nil {
872 return nil, fmt.Errorf("incorrect hash algorithm: %v", err)
873 }
874
875 scheme := &tpm2.SigScheme{
876 Alg: tpm2.AlgRSASSA,
877 Hash: h,
878 }
879
880 if pss, ok := opts.(*rsa.PSSOptions); ok {
881 if pss.SaltLength != rsa.PSSSaltLengthAuto && pss.SaltLength != rsa.PSSSaltLengthEqualsHash && pss.SaltLength != len(digest) {
882 return nil, fmt.Errorf("PSS salt length %d is incorrect, expected rsa.PSSSaltLengthAuto, rsa.PSSSaltLengthEqualsHash or %d", pss.SaltLength, len(digest))
883 }
884 scheme.Alg = tpm2.AlgRSAPSS
885 }
886
887 sig, err := tpm2.Sign(rw, key, "", digest, validation, scheme)
888 if err != nil {
889 return nil, fmt.Errorf("cannot sign: %v", err)
890 }
891 if sig.RSA == nil {
892 return nil, fmt.Errorf("expected RSA signature, got: %v", sig.Alg)
893 }
894 return sig.RSA.Signature, nil
895 }
896
897 func (k *wrappedKey20) decrypt(tb tpmBase, ctxt []byte) ([]byte, error) {
898 return nil, fmt.Errorf("not implemented")
899 }
900
901 func (k *wrappedKey20) blobs() ([]byte, []byte, error) {
902 return k.public, k.blob, nil
903 }
904
905 func (k *wrappedKey20) algorithm() (Algorithm, error) {
906 tpmPub, err := tpm2.DecodePublic(k.public)
907 if err != nil {
908 return "", fmt.Errorf("decode public key: %v", err)
909 }
910 switch tpmPub.Type {
911 case tpm2.AlgRSA:
912 return RSA, nil
913 case tpm2.AlgECC:
914 return ECDSA, nil
915 default:
916 return "", fmt.Errorf("unsupported key type: %v", tpmPub.Type)
917 }
918 }