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