Debian Codegraph @

client/keys.go

raw
1 // Package client contains some high-level TPM 2.0 functions.
2 package client
3
4 import (
5 "bytes"
6 "crypto"
7 "crypto/subtle"
8 "crypto/x509"
9 "errors"
10 "fmt"
11 "io"
12
13 "github.com/google/go-tpm-tools/internal"
14 pb "github.com/google/go-tpm-tools/proto/tpm"
15 "github.com/google/go-tpm/legacy/tpm2"
16 "github.com/google/go-tpm/tpmutil"
17 )
18
19 // Key wraps an active asymmetric TPM2 key. This can either be a signing key or
20 // an encryption key. Users of Key should be sure to call Close() when the Key
21 // is no longer needed, so that the underlying TPM handle can be freed.
22 // Concurrent accesses on Key are not safe, with the exception of the
23 // Sign method called on the crypto.Signer returned by Key.GetSigner.
24 type Key struct {
25 rw io.ReadWriter
26 handle tpmutil.Handle
27 pubArea tpm2.Public
28 pubKey crypto.PublicKey
29 name tpm2.Name
30 session Session
31 cert *x509.Certificate
32 }
33
34 // EndorsementKeyRSA generates and loads a key from DefaultEKTemplateRSA.
35 func EndorsementKeyRSA(rw io.ReadWriter) (*Key, error) {
36 ekRsa, err := NewCachedKey(rw, tpm2.HandleEndorsement, DefaultEKTemplateRSA(), EKReservedHandle)
37 if err != nil {
38 return nil, err
39 }
40 if err := ekRsa.trySetCertificateFromNvram(EKCertNVIndexRSA); err != nil {
41 ekRsa.Close()
42 return nil, err
43 }
44 return ekRsa, nil
45 }
46
47 // EndorsementKeyECC generates and loads a key from DefaultEKTemplateECC.
48 func EndorsementKeyECC(rw io.ReadWriter) (*Key, error) {
49 ekEcc, err := NewCachedKey(rw, tpm2.HandleEndorsement, DefaultEKTemplateECC(), EKECCReservedHandle)
50 if err != nil {
51 return nil, err
52 }
53 if err := ekEcc.trySetCertificateFromNvram(EKCertNVIndexECC); err != nil {
54 ekEcc.Close()
55 return nil, err
56 }
57 return ekEcc, nil
58 }
59
60 // StorageRootKeyRSA generates and loads a key from SRKTemplateRSA.
61 func StorageRootKeyRSA(rw io.ReadWriter) (*Key, error) {
62 return NewCachedKey(rw, tpm2.HandleOwner, SRKTemplateRSA(), SRKReservedHandle)
63 }
64
65 // StorageRootKeyECC generates and loads a key from SRKTemplateECC.
66 func StorageRootKeyECC(rw io.ReadWriter) (*Key, error) {
67 return NewCachedKey(rw, tpm2.HandleOwner, SRKTemplateECC(), SRKECCReservedHandle)
68 }
69
70 // AttestationKeyRSA generates and loads a key from AKTemplateRSA in the Owner hierarchy.
71 func AttestationKeyRSA(rw io.ReadWriter) (*Key, error) {
72 return NewCachedKey(rw, tpm2.HandleOwner, AKTemplateRSA(), DefaultAKRSAHandle)
73 }
74
75 // AttestationKeyECC generates and loads a key from AKTemplateECC in the Owner hierarchy.
76 func AttestationKeyECC(rw io.ReadWriter) (*Key, error) {
77 return NewCachedKey(rw, tpm2.HandleOwner, AKTemplateECC(), DefaultAKECCHandle)
78 }
79
80 // EndorsementKeyFromNvIndex generates and loads an endorsement key using the
81 // template stored at the provided nvdata index. This is useful for TPMs which
82 // have a preinstalled AK template.
83 func EndorsementKeyFromNvIndex(rw io.ReadWriter, idx uint32) (*Key, error) {
84 return KeyFromNvIndex(rw, tpm2.HandleEndorsement, idx)
85 }
86
87 // GceAttestationKeyRSA generates and loads the GCE RSA AK. Note that this
88 // function will only work on a GCE VM. Unlike AttestationKeyRSA, this key uses
89 // the Endorsement Hierarchy and its template loaded from GceAKTemplateNVIndexRSA.
90 func GceAttestationKeyRSA(rw io.ReadWriter) (*Key, error) {
91 akRsa, err := EndorsementKeyFromNvIndex(rw, GceAKTemplateNVIndexRSA)
92 if err != nil {
93 return nil, err
94 }
95 if err := akRsa.trySetCertificateFromNvram(GceAKCertNVIndexRSA); err != nil {
96 akRsa.Close()
97 return nil, err
98 }
99 return akRsa, nil
100 }
101
102 // GceAttestationKeyECC generates and loads the GCE ECC AK. Note that this
103 // function will only work on a GCE VM. Unlike AttestationKeyECC, this key uses
104 // the Endorsement Hierarchy and its template loaded from GceAKTemplateNVIndexECC.
105 func GceAttestationKeyECC(rw io.ReadWriter) (*Key, error) {
106 akEcc, err := EndorsementKeyFromNvIndex(rw, GceAKTemplateNVIndexECC)
107 if err != nil {
108 return nil, err
109 }
110 if err := akEcc.trySetCertificateFromNvram(GceAKCertNVIndexECC); err != nil {
111 akEcc.Close()
112 return nil, err
113 }
114 return akEcc, nil
115 }
116
117 // LoadCachedKey loads a key from cachedHandle.
118 // If the key is not found, an error is returned.
119 // This function will not overwrite an existing key, unlike NewCachedKey.
120 func LoadCachedKey(rw io.ReadWriter, cachedHandle tpmutil.Handle, keySession Session) (k *Key, err error) {
121 cachedPub, _, _, err := tpm2.ReadPublic(rw, cachedHandle)
122 if err != nil {
123 return nil, fmt.Errorf("failed to read public area of cached key: %w", err)
124 }
125
126 k = &Key{rw: rw, handle: cachedHandle, pubArea: cachedPub, session: keySession}
127 return k, k.finish()
128 }
129
130 // KeyFromNvIndex generates and loads a key under the provided parent
131 // (possibly a hierarchy root tpm2.Handle{Owner|Endorsement|Platform|Null})
132 // using the template stored at the provided nvdata index.
133 func KeyFromNvIndex(rw io.ReadWriter, parent tpmutil.Handle, idx uint32) (*Key, error) {
134 data, err := tpm2.NVReadEx(rw, tpmutil.Handle(idx), tpm2.HandleOwner, "", 0)
135 if err != nil {
136 return nil, fmt.Errorf("read error at index %d: %w", idx, err)
137 }
138 template, err := tpm2.DecodePublic(data)
139 if err != nil {
140 return nil, fmt.Errorf("index %d data was not a TPM key template: %w", idx, err)
141 }
142 return NewKey(rw, parent, template)
143 }
144
145 // NewCachedKey is almost identical to NewKey, except that it initially tries to
146 // see if the a key matching the provided template is at cachedHandle. If so,
147 // that key is returned. If not, the key is created as in NewKey, and that key
148 // is persisted to the cachedHandle, overwriting any existing key there.
149 func NewCachedKey(rw io.ReadWriter, parent tpmutil.Handle, template tpm2.Public, cachedHandle tpmutil.Handle) (k *Key, err error) {
150 owner := tpm2.HandleOwner
151 if parent == tpm2.HandlePlatform {
152 owner = tpm2.HandlePlatform
153 } else if parent == tpm2.HandleNull {
154 return nil, fmt.Errorf("cannot cache objects in the null hierarchy")
155 }
156
157 cachedPub, _, _, err := tpm2.ReadPublic(rw, cachedHandle)
158 if err == nil {
159 if cachedPub.MatchesTemplate(template) {
160 k = &Key{rw: rw, handle: cachedHandle, pubArea: cachedPub}
161 return k, k.finish()
162 }
163 // Kick out old cached key if it does not match
164 if err = tpm2.EvictControl(rw, "", owner, cachedHandle, cachedHandle); err != nil {
165 return nil, err
166 }
167 }
168
169 k, err = NewKey(rw, parent, template)
170 if err != nil {
171 return nil, err
172 }
173 defer tpm2.FlushContext(rw, k.handle)
174
175 if err = tpm2.EvictControl(rw, "", owner, k.handle, cachedHandle); err != nil {
176 return nil, err
177 }
178 k.handle = cachedHandle
179 return k, nil
180 }
181
182 // NewKey generates a key from the template and loads that key into the TPM
183 // under the specified parent. NewKey can call many different TPM commands:
184 // - If parent is tpm2.Handle{Owner|Endorsement|Platform|Null} a primary key
185 // is created in the specified hierarchy (using CreatePrimary).
186 // - If parent is a valid key handle, a normal key object is created under
187 // that parent (using Create and Load). NOTE: Not yet supported.
188 //
189 // This function also assumes that the desired key:
190 // - Does not have its usage locked to specific PCR values
191 // - Usable with empty authorization sessions (i.e. doesn't need a password)
192 func NewKey(rw io.ReadWriter, parent tpmutil.Handle, template tpm2.Public) (k *Key, err error) {
193 if !isHierarchy(parent) {
194 // TODO add support for normal objects with Create() and Load()
195 return nil, fmt.Errorf("unsupported parent handle: %x", parent)
196 }
197
198 handle, pubArea, _, _, _, _, err := tpm2.CreatePrimaryEx(rw, parent, tpm2.PCRSelection{}, "", "", template)
199 if err != nil {
200 return nil, err
201 }
202 defer func() {
203 if err != nil {
204 tpm2.FlushContext(rw, handle)
205 }
206 }()
207
208 k = &Key{rw: rw, handle: handle}
209 if k.pubArea, err = tpm2.DecodePublic(pubArea); err != nil {
210 return
211 }
212 return k, k.finish()
213 }
214
215 func (k *Key) finish() error {
216 var err error
217 if k.pubKey, err = k.pubArea.Key(); err != nil {
218 return err
219 }
220 if k.name, err = k.pubArea.Name(); err != nil {
221 return err
222 }
223 // We determine the right type of session based on the auth policy
224 if k.session == nil {
225 if bytes.Equal(k.pubArea.AuthPolicy, defaultEKAuthPolicy()) {
226 if k.session, err = NewEKSession(k.rw); err != nil {
227 return err
228 }
229 } else if len(k.pubArea.AuthPolicy) == 0 {
230 k.session = NullSession{}
231 } else {
232 return fmt.Errorf("unknown auth policy when creating key")
233 }
234 }
235 return nil
236 }
237
238 // Handle allows this key to be used directly with other go-tpm commands.
239 func (k *Key) Handle() tpmutil.Handle {
240 return k.handle
241 }
242
243 // Name is hash of this key's public area. Only the Digest field will ever be
244 // populated. It is useful for various TPM commands related to authorization.
245 // This is equivalent to k.PublicArea.Name(), except that is cannot fail.
246 func (k *Key) Name() tpm2.Name {
247 return k.name
248 }
249
250 // PublicArea exposes the key's entire public area. This is useful for
251 // determining additional properties of the underlying TPM key.
252 func (k *Key) PublicArea() tpm2.Public {
253 return k.pubArea
254 }
255
256 // PublicKey provides a go interface to the loaded key's public area.
257 func (k *Key) PublicKey() crypto.PublicKey {
258 return k.pubKey
259 }
260
261 // Close should be called when the key is no longer needed. This is important to
262 // do as most TPMs can only have a small number of key simultaneously loaded.
263 func (k *Key) Close() {
264 if k.session != nil {
265 k.session.Close()
266 }
267 tpm2.FlushContext(k.rw, k.handle)
268 }
269
270 // Seal seals the sensitive byte buffer to a key. This key must be an SRK (we
271 // currently do not support sealing to EKs). Optionally, the SealOpts struct can
272 // be modified to provide sealed-to PCRs. In this case, the sensitive data can
273 // only be unsealed if the seal-time PCRs are in the SealOpts-specified state.
274 // There must not be overlap in PCRs between SealOpts' Current and Target.
275 // During the sealing process, certification data will be created allowing
276 // Unseal() to validate the state of the TPM during the sealing process.
277 func (k *Key) Seal(sensitive []byte, opts SealOpts) (*pb.SealedBytes, error) {
278 var pcrs *pb.PCRs
279 var err error
280 var auth []byte
281
282 pcrs, err = mergePCRSelAndProto(k.rw, opts.Current, opts.Target)
283 if err != nil {
284 return nil, fmt.Errorf("invalid SealOpts: %v", err)
285 }
286 if len(pcrs.GetPcrs()) > 0 {
287 auth = internal.PCRSessionAuth(pcrs, SessionHashAlg)
288 }
289 certifySel := FullPcrSel(CertifyHashAlgTpm)
290 sb, err := sealHelper(k.rw, k.Handle(), auth, sensitive, certifySel)
291 if err != nil {
292 return nil, err
293 }
294
295 for pcrNum := range pcrs.GetPcrs() {
296 sb.Pcrs = append(sb.Pcrs, pcrNum)
297 }
298 sb.Hash = pcrs.GetHash()
299 sb.Srk = pb.ObjectType(k.pubArea.Type)
300 return sb, nil
301 }
302
303 func sealHelper(rw io.ReadWriter, parentHandle tpmutil.Handle, auth []byte, sensitive []byte, certifyPCRsSel tpm2.PCRSelection) (*pb.SealedBytes, error) {
304 inPublic := tpm2.Public{
305 Type: tpm2.AlgKeyedHash,
306 NameAlg: SessionHashAlgTpm,
307 Attributes: tpm2.FlagFixedTPM | tpm2.FlagFixedParent,
308 AuthPolicy: auth,
309 }
310 if auth == nil {
311 inPublic.Attributes |= tpm2.FlagUserWithAuth
312 } else {
313 inPublic.Attributes |= tpm2.FlagAdminWithPolicy
314 }
315
316 priv, pub, creationData, _, ticket, err := tpm2.CreateKeyWithSensitive(rw, parentHandle, certifyPCRsSel, "", "", inPublic, sensitive)
317 if err != nil {
318 return nil, fmt.Errorf("failed to create key: %w", err)
319 }
320 certifiedPcr, err := ReadPCRs(rw, certifyPCRsSel)
321 if err != nil {
322 return nil, fmt.Errorf("failed to read PCRs: %w", err)
323 }
324 computedDigest := internal.PCRDigest(certifiedPcr, SessionHashAlg)
325
326 decodedCreationData, err := tpm2.DecodeCreationData(creationData)
327 if err != nil {
328 return nil, fmt.Errorf("failed to decode creation data: %w", err)
329 }
330
331 // make sure PCRs haven't being altered after sealing
332 if subtle.ConstantTimeCompare(computedDigest, decodedCreationData.PCRDigest) == 0 {
333 return nil, fmt.Errorf("PCRs have been modified after sealing")
334 }
335
336 sb := &pb.SealedBytes{}
337 sb.CertifiedPcrs = certifiedPcr
338 sb.Priv = priv
339 sb.Pub = pub
340 sb.CreationData = creationData
341 if sb.Ticket, err = tpmutil.Pack(ticket); err != nil {
342 return nil, err
343 }
344 return sb, nil
345 }
346
347 // Unseal attempts to reverse the process of Seal(), using the PCRs, public, and
348 // private data in proto.SealedBytes. Optionally, the UnsealOpts parameter can
349 // be used to verify the state of the TPM when the data was sealed. The
350 // zero-value UnsealOpts can be passed to skip certification.
351 func (k *Key) Unseal(in *pb.SealedBytes, opts UnsealOpts) ([]byte, error) {
352 if in.Srk != pb.ObjectType(k.pubArea.Type) {
353 return nil, fmt.Errorf("expected key of type %v, got %v", in.Srk, k.pubArea.Type)
354 }
355 sealed, _, err := tpm2.Load(
356 k.rw,
357 k.Handle(),
358 /*parentPassword=*/ "",
359 in.GetPub(),
360 in.GetPriv())
361 if err != nil {
362 return nil, fmt.Errorf("failed to load sealed object: %w", err)
363 }
364 defer tpm2.FlushContext(k.rw, sealed)
365
366 pcrs, err := mergePCRSelAndProto(k.rw, opts.CertifyCurrent, opts.CertifyExpected)
367 if err != nil {
368 return nil, fmt.Errorf("invalid UnsealOpts: %v", err)
369 }
370 if len(pcrs.GetPcrs()) > 0 {
371 if err := internal.CheckSubset(pcrs, in.GetCertifiedPcrs()); err != nil {
372 return nil, fmt.Errorf("failed to certify PCRs: %w", err)
373 }
374
375 var ticket tpm2.Ticket
376 if _, err = tpmutil.Unpack(in.GetTicket(), &ticket); err != nil {
377 return nil, fmt.Errorf("ticket unpack failed: %w", err)
378 }
379 creationHash := SessionHashAlg.New()
380 creationHash.Write(in.GetCreationData())
381
382 _, _, certErr := tpm2.CertifyCreation(k.rw, "", sealed, tpm2.HandleNull, nil, creationHash.Sum(nil), tpm2.SigScheme{}, ticket)
383 // There is a bug in some older TPMs, where they are unable to
384 // CertifyCreation when using a Null signing handle (despite this
385 // being allowed by all versions of the TPM spec). To work around
386 // this bug, we use a temporary signing key and ignore the signed
387 // result. To reduce the cost of this workaround, we use a cached
388 // ECC signing key.
389 // We can detect this bug, as it triggers a RCInsufficient
390 // Unmarshaling error.
391 var (
392 paramError tpm2.ParameterError
393 handleError tpm2.HandleError
394 )
395 if (errors.As(certErr, &paramError) && paramError.Code == tpm2.RCInsufficient) ||
396 (errors.As(certErr, &handleError) && handleError.Code == tpm2.RCInsufficient) {
397 signer, err := AttestationKeyECC(k.rw)
398 if err != nil {
399 return nil, fmt.Errorf("failed to create fallback signing key: %w", err)
400 }
401 defer signer.Close()
402 _, _, certErr = tpm2.CertifyCreation(k.rw, "", sealed, signer.Handle(), nil, creationHash.Sum(nil), tpm2.SigScheme{}, ticket)
403 }
404 if certErr != nil {
405 return nil, fmt.Errorf("failed to certify creation: %w", certErr)
406 }
407
408 // verify certify PCRs haven't been modified
409 decodedCreationData, err := tpm2.DecodeCreationData(in.GetCreationData())
410 if err != nil {
411 return nil, fmt.Errorf("failed to decode creation data: %w", err)
412 }
413 if !internal.SamePCRSelection(in.GetCertifiedPcrs(), decodedCreationData.PCRSelection) {
414 return nil, fmt.Errorf("certify PCRs does not match the PCR selection in the creation data")
415 }
416 expectedDigest := internal.PCRDigest(in.GetCertifiedPcrs(), SessionHashAlg)
417 if subtle.ConstantTimeCompare(decodedCreationData.PCRDigest, expectedDigest) == 0 {
418 return nil, fmt.Errorf("certify PCRs digest does not match the digest in the creation data")
419 }
420 }
421
422 sel := tpm2.PCRSelection{Hash: tpm2.Algorithm(in.GetHash())}
423 for _, pcr := range in.GetPcrs() {
424 sel.PCRs = append(sel.PCRs, int(pcr))
425 }
426
427 session, err := NewPCRSession(k.rw, sel)
428 if err != nil {
429 return nil, fmt.Errorf("failed to create session: %w", err)
430 }
431 defer session.Close()
432
433 auth, err := session.Auth()
434 if err != nil {
435 return nil, err
436 }
437 return tpm2.UnsealWithSession(k.rw, auth.Session, sealed, "")
438 }
439
440 // Quote will tell TPM to compute a hash of a set of given PCR selection, together with
441 // some extra data (typically a nonce), sign it with the given signing key, and return
442 // the signature and the attestation data. This function will return an error if
443 // the key is not a restricted signing key.
444 func (k *Key) Quote(selpcr tpm2.PCRSelection, extraData []byte) (*pb.Quote, error) {
445 // Make sure that we have a valid signing key before trying quote
446 var err error
447 if _, err = internal.GetSigningHashAlg(k.pubArea); err != nil {
448 return nil, err
449 }
450 if !k.hasAttribute(tpm2.FlagRestricted) {
451 return nil, fmt.Errorf("unrestricted keys are insecure to use with Quote")
452 }
453
454 quote := &pb.Quote{}
455 quote.Quote, quote.RawSig, err = tpm2.QuoteRaw(k.rw, k.Handle(), "", "", extraData, selpcr, tpm2.AlgNull)
456 if err != nil {
457 return nil, fmt.Errorf("failed to quote: %w", err)
458 }
459 quote.Pcrs, err = ReadPCRs(k.rw, selpcr)
460 if err != nil {
461 return nil, fmt.Errorf("failed to read PCRs: %w", err)
462 }
463 // Verify the quote client-side to make sure we didn't mess things up.
464 // NOTE: the quote still must be verified server-side as well.
465 if err := internal.VerifyQuote(quote, k.PublicKey(), extraData); err != nil {
466 return nil, fmt.Errorf("failed to verify quote: %w", err)
467 }
468 return quote, nil
469 }
470
471 // Reseal is a shortcut to call Unseal() followed by Seal().
472 // CertifyOpt(nillable) will be used in Unseal(), and SealOpt(nillable)
473 // will be used in Seal()
474 func (k *Key) Reseal(in *pb.SealedBytes, uOpts UnsealOpts, sOpts SealOpts) (*pb.SealedBytes, error) {
475 sensitive, err := k.Unseal(in, uOpts)
476 if err != nil {
477 return nil, fmt.Errorf("failed to unseal: %w", err)
478 }
479 return k.Seal(sensitive, sOpts)
480 }
481
482 func (k *Key) hasAttribute(attr tpm2.KeyProp) bool {
483 return k.pubArea.Attributes&attr != 0
484 }
485
486 // Cert returns the parsed certificate (or nil) for the given key.
487 func (k *Key) Cert() *x509.Certificate {
488 return k.cert
489 }
490
491 // CertDERBytes provides the ASN.1 DER content of the key's certificate. If the
492 // key does not have a certficate, returns nil.
493 func (k *Key) CertDERBytes() []byte {
494 if k.cert == nil {
495 return nil
496 }
497 return k.cert.Raw
498 }
499
500 // SetCert assigns the provided certificate to the key after verifying it matches the key.
501 func (k *Key) SetCert(cert *x509.Certificate) error {
502 if cert == nil || cert.PublicKey == nil {
503 return errors.New("no certificate publickey provided")
504 }
505
506 certPubKey := cert.PublicKey.(crypto.PublicKey) // This cast cannot fail
507 if !internal.PubKeysEqual(certPubKey, k.pubKey) {
508 return errors.New("certificate does not match key")
509 }
510
511 k.cert = cert
512 return nil
513 }
514
515 // Attempt to fetch a key's certificate from NVRAM. If the certificate is simply
516 // missing, this function succeeds (and no certificate is set). This is to allow
517 // for AKs and EKs that simply don't have a certificate. However, if the
518 // certificate read from NVRAM is either malformed or does not match the key, we
519 // return an error.
520 func (k *Key) trySetCertificateFromNvram(index uint32) error {
521 certASN1, err := tpm2.NVReadEx(k.rw, tpmutil.Handle(index), tpm2.HandleOwner, "", 0)
522 if err != nil {
523 // Either the cert data is missing, or we are not allowed to read it
524 return nil
525 }
526 x509Cert, err := x509.ParseCertificate(certASN1)
527 if err != nil {
528 return fmt.Errorf("failed to parse certificate from NV memory: %w", err)
529 }
530 return k.SetCert(x509Cert)
531 }