Debian Codegraph @

attest/attest.go

raw
1 // Copyright 2019 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 // Package attest abstracts TPM attestation operations.
16 package attest
17
18 import (
19 "crypto"
20 "crypto/x509"
21 "errors"
22 "fmt"
23 "io"
24 "strings"
25
26 "github.com/google/go-tpm/legacy/tpm2"
27 "github.com/google/go-tpm/tpmutil"
28 )
29
30 // TPMInterface indicates how the client communicates
31 // with the TPM.
32 type TPMInterface uint8
33
34 // TPM interfaces
35 const (
36 TPMInterfaceDirect TPMInterface = iota
37 TPMInterfaceKernelManaged
38 TPMInterfaceDaemonManaged
39 TPMInterfaceCommandChannel
40 )
41
42 // CommandChannelTPM20 represents a pipe along which TPM 2.0 commands
43 // can be issued, and measurement logs read.
44 type CommandChannelTPM20 interface {
45 io.ReadWriteCloser
46 MeasurementLog() ([]byte, error)
47 }
48
49 // OpenConfig encapsulates settings passed to OpenTPM().
50 type OpenConfig struct {
51 // CommandChannel provides a TPM 2.0 command channel, which can be
52 // used in-lieu of any TPM present on the platform.
53 CommandChannel CommandChannelTPM20
54 }
55
56 // keyEncoding indicates how an exported TPM key is represented.
57 type keyEncoding uint8
58
59 func (e keyEncoding) String() string {
60 switch e {
61 case keyEncodingInvalid:
62 return "invalid"
63 case keyEncodingOSManaged:
64 return "os-managed"
65 case keyEncodingEncrypted:
66 return "encrypted"
67 case keyEncodingParameterized:
68 return "parameterized"
69 default:
70 return fmt.Sprintf("keyEncoding<%d>", int(e))
71 }
72 }
73
74 // Key encodings
75 const (
76 keyEncodingInvalid keyEncoding = iota
77 // Managed by the OS but loadable by name.
78 keyEncodingOSManaged
79 // Key fully represented but in encrypted form.
80 keyEncodingEncrypted
81 // Parameters stored, but key must be regenerated before use.
82 keyEncodingParameterized
83 )
84
85 // ParentKeyConfig describes the Storage Root Key that is used
86 // as a parent for new keys.
87 type ParentKeyConfig struct {
88 Algorithm Algorithm
89 Handle tpmutil.Handle
90 }
91
92 var defaultParentConfig = ParentKeyConfig{
93 Algorithm: RSA,
94 Handle: 0x81000001,
95 }
96
97 type ak interface {
98 close(tpmBase) error
99 marshal() ([]byte, error)
100 activateCredential(tpm tpmBase, in EncryptedCredential, ek *EK) ([]byte, error)
101 quote(t tpmBase, nonce []byte, alg HashAlg, selectedPCRs []int) (*Quote, error)
102 attestationParameters() AttestationParameters
103 certify(tb tpmBase, handle any, opts CertifyOpts) (*CertificationParameters, error)
104 certifyWithDecryptionEk(tb tpmBase, ek *EK, challenge DecryptionEkChallenge) (*CertificationParameters, error)
105 signMsg(tb tpmBase, msg []byte, pub crypto.PublicKey, opts crypto.SignerOpts) ([]byte, error)
106 }
107
108 // AK represents a key which can be used for attestation.
109 type AK struct {
110 ak ak
111 pub crypto.PublicKey
112 }
113
114 // Public returns the public key for the AK. This is only supported for TPM 2.0
115 // on Linux currently.
116 func (k *AK) Public() crypto.PublicKey {
117 return k.pub
118 }
119
120 // Close unloads the AK from the system.
121 func (k *AK) Close(t *TPM) error {
122 return k.ak.close(t.tpm)
123 }
124
125 // Marshal encodes the AK in a format that can be reloaded with tpm.LoadAK().
126 // This method exists to allow consumers to store the key persistently and load
127 // it as a later time. Users SHOULD NOT attempt to interpret or extract values
128 // from this blob.
129 func (k *AK) Marshal() ([]byte, error) {
130 return k.ak.marshal()
131 }
132
133 // ActivateCredential decrypts the secret using the key to prove that the AK
134 // was generated on the same TPM as the EK. This method can be used with TPMs
135 // that have the default EK, i.e. RSA EK with handle 0x81010001.
136 //
137 // This operation is synonymous with TPM2_ActivateCredential.
138 func (k *AK) ActivateCredential(tpm *TPM, in EncryptedCredential) (secret []byte, err error) {
139 return k.ak.activateCredential(tpm.tpm, in, nil)
140 }
141
142 // ActivateCredentialWithEK decrypts the secret using the key to prove that the AK
143 // was generated on the same TPM as the EK. This method can be used with TPMs
144 // that have an ECC EK. The 'ek' argument must be one of EKs returned from
145 // TPM.EKs() or TPM.EKCertificates().
146 //
147 // This operation is synonymous with TPM2_ActivateCredential.
148 func (k *AK) ActivateCredentialWithEK(tpm *TPM, in EncryptedCredential, ek EK) (secret []byte, err error) {
149 return k.ak.activateCredential(tpm.tpm, in, &ek)
150 }
151
152 // Quote returns a quote over the platform state, signed by the AK.
153 //
154 // This is a low-level API. Consumers seeking to attest the state of the
155 // platform should use tpm.AttestPlatform() instead.
156 func (k *AK) Quote(tpm *TPM, nonce []byte, alg HashAlg) (*Quote, error) {
157 pcrs := make([]int, 24)
158 for pcr := range pcrs {
159 pcrs[pcr] = pcr
160 }
161 return k.ak.quote(tpm.tpm, nonce, alg, pcrs)
162 }
163
164 // QuotePCRs is like Quote() but allows the caller to select a subset of the PCRs.
165 func (k *AK) QuotePCRs(tpm *TPM, nonce []byte, alg HashAlg, pcrs []int) (*Quote, error) {
166 return k.ak.quote(tpm.tpm, nonce, alg, pcrs)
167 }
168
169 // AttestationParameters returns information about the AK, typically used to
170 // generate a credential activation challenge.
171 func (k *AK) AttestationParameters() AttestationParameters {
172 return k.ak.attestationParameters()
173 }
174
175 // Certify uses the attestation key to certify the key with `handle`. It returns
176 // certification parameters which allow to verify the properties of the attested
177 // key. Depending on the actual instantiation it can accept different handle
178 // types (e.g., tpmutil.Handle on Linux or uintptr on Windows).
179 func (k *AK) Certify(tpm *TPM, handle any) (*CertificationParameters, error) {
180 return k.ak.certify(tpm.tpm, handle, CertifyOpts{})
181 }
182
183 // CertifyWithDecryptionEk certifies the Attestation Key using the decryption
184 // capabilities of the Endorsement Key (EK) in response to a challenge.
185 // This follows the EK-Based Key Attestation protocol:
186 // https://trustedcomputinggroup.org/wp-content/uploads/EK-Based-Key-Attestation-with-TPM-Firmware-Version-Version-1_Pub.pdf
187 func (k *AK) CertifyWithDecryptionEk(tpm *TPM, ek *EK, challenge DecryptionEkChallenge) (*CertificationParameters, error) {
188 return k.ak.certifyWithDecryptionEk(tpm.tpm, ek, challenge)
189 }
190
191 // SignMsg signs the message (not the digest) with the AK. Note that AK is a
192 // restricted signing key, it cannot sign a digest directly.
193 func (k *AK) SignMsg(tpm *TPM, msg []byte, opts crypto.SignerOpts) ([]byte, error) {
194 return k.ak.signMsg(tpm.tpm, msg, k.pub, opts)
195 }
196
197 // AKConfig encapsulates parameters for minting keys.
198 type AKConfig struct {
199 // Optionally set unique name for AK on Windows.
200 Name string
201 // Parent describes the Storage Root Key that will be used as a parent.
202 // If nil, the default SRK (i.e. RSA with handle 0x81000001) is assumed.
203 // Supported only by TPM 2.0 on Linux.
204 Parent *ParentKeyConfig
205
206 // If not specified, the default algorithm (RSA) is assumed.
207 Algorithm Algorithm
208 }
209
210 // EncryptedCredential represents encrypted parameters which must be activated
211 // against a key.
212 type EncryptedCredential struct {
213 Credential []byte
214 Secret []byte
215 }
216
217 // DecryptionEkChallenge contains the parameters for the EK-based key attestation challenge.
218 type DecryptionEkChallenge struct {
219 ObjectPublic []byte
220 Duplicate []byte
221 InSymSeed []byte
222 }
223
224 // Quote encapsulates the results of a Quote operation against the TPM,
225 // using an attestation key.
226 type Quote struct {
227 Quote []byte
228 Signature []byte
229 }
230
231 // PCR encapsulates the value of a PCR at a point in time.
232 type PCR struct {
233 Index int
234 Digest []byte
235 DigestAlg crypto.Hash
236
237 // quoteVerified is true if the PCR was verified against a quote
238 // in a call to AKPublic.Verify or AKPublic.VerifyAll.
239 quoteVerified bool
240 }
241
242 // QuoteVerified returns true if the value of this PCR was previously
243 // verified against a Quote, in a call to AKPublic.Verify or AKPublic.VerifyAll.
244 func (p *PCR) QuoteVerified() bool {
245 return p.quoteVerified
246 }
247
248 // EK is a burned-in endorsement key bound to a TPM. This optionally contains
249 // a certificate that can chain to the TPM manufacturer.
250 type EK struct {
251 // Public key of the EK.
252 Public crypto.PublicKey
253
254 // Certificate is the EK certificate for TPMs that provide it.
255 Certificate *x509.Certificate
256
257 // For Intel TPMs, Intel hosts certificates at a public URL derived from the
258 // Public key. Clients or servers can perform an HTTP GET to this URL, and
259 // use ParseEKCertificate on the response body.
260 CertificateURL string
261
262 // The EK persistent handle.
263 handle tpmutil.Handle
264 }
265
266 // AttestationParameters describes information about a key which is necessary
267 // for verifying its properties remotely.
268 type AttestationParameters struct {
269 // Public represents the AK's canonical encoding. This blob includes the
270 // public key, as well as signing parameters such as the hash algorithm
271 // used to generate quotes.
272 //
273 // Use ParseAKPublic to access the key's data.
274 Public []byte
275 // For TPM 2.0 devices, Public is encoded as a TPMT_PUBLIC structure.
276 // For TPM 1.2 devices, Public is a TPM_PUBKEY structure, as defined in
277 // the TPM Part 2 Structures specification, available at
278 // https://trustedcomputinggroup.org/wp-content/uploads/TPM-Main-Part-2-TPM-Structures_v1.2_rev116_01032011.pdf
279
280 // UseTCSDActivationFormat is set when tcsd (trousers daemon) is operating
281 // as an intermediary between this library and the TPM. A value of true
282 // indicates that activation challenges should use the TCSD-specific format.
283 UseTCSDActivationFormat bool
284
285 // Subsequent fields are only populated for AKs generated on a TPM
286 // implementing version 2.0 of the specification. The specific structures
287 // referenced for each field are defined in the TPM Revision 2, Part 2 -
288 // Structures specification, available here:
289 // https://www.trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-2-Structures-01.38.pdf
290
291 // CreateData represents the properties of a TPM 2.0 key. It is encoded
292 // as a TPMS_CREATION_DATA structure.
293 CreateData []byte
294 // CreateAttestation represents an assertion as to the details of the key.
295 // It is encoded as a TPMS_ATTEST structure.
296 CreateAttestation []byte
297 // CreateSignature represents a signature of the CreateAttestation structure.
298 // It is encoded as a TPMT_SIGNATURE structure.
299 CreateSignature []byte
300 }
301
302 // AKPublic holds structured information about an AK's public key.
303 type AKPublic struct {
304 // Public is the public part of the AK. This can either be an *rsa.PublicKey or
305 // and *ecdsa.PublicKey.
306 Public crypto.PublicKey
307 // Hash is the hashing algorithm the AK will use when signing quotes.
308 Hash crypto.Hash
309 }
310
311 // ParseAKPublic parses the Public blob from the AttestationParameters,
312 // returning the public key and signing parameters for the key.
313 func ParseAKPublic(public []byte) (*AKPublic, error) {
314 pub, err := tpm2.DecodePublic(public)
315 if err != nil {
316 return nil, fmt.Errorf("parsing TPM public key structure: %v", err)
317 }
318 switch {
319 case pub.RSAParameters == nil && pub.ECCParameters == nil:
320 return nil, errors.New("parsing public key: missing asymmetric parameters")
321 case pub.RSAParameters != nil && pub.RSAParameters.Sign == nil:
322 return nil, errors.New("parsing public key: missing rsa signature scheme")
323 case pub.ECCParameters != nil && pub.ECCParameters.Sign == nil:
324 return nil, errors.New("parsing public key: missing ecc signature scheme")
325 }
326
327 pubKey, err := pub.Key()
328 if err != nil {
329 return nil, fmt.Errorf("parsing public key: %v", err)
330 }
331
332 var h crypto.Hash
333 switch pub.Type {
334 case tpm2.AlgRSA:
335 h, err = pub.RSAParameters.Sign.Hash.Hash()
336 case tpm2.AlgECC:
337 h, err = pub.ECCParameters.Sign.Hash.Hash()
338 default:
339 return nil, fmt.Errorf("unsupported public key type 0x%x", pub.Type)
340 }
341 if err != nil {
342 return nil, fmt.Errorf("invalid public key hash: %v", err)
343 }
344 return &AKPublic{Public: pubKey, Hash: h}, nil
345 }
346
347 // Verify is used to prove authenticity of the PCR measurements. It ensures that
348 // the quote was signed by the AK, and that its contents matches the PCR and
349 // nonce combination. An error is returned if a provided PCR index was not part
350 // of the quote. QuoteVerified() will return true on PCRs which were verified
351 // by a quote.
352 //
353 // Do NOT use this method if you have multiple quotes to verify: Use VerifyAll
354 // instead.
355 //
356 // The nonce is used to prevent replays of Quote and PCRs and is signed by the
357 // quote. Some TPMs don't support nonces longer than 20 bytes, and if the
358 // nonce is used to tie additional data to the quote, the additional data should be
359 // hashed to construct the nonce.
360 func (a *AKPublic) Verify(quote Quote, pcrs []PCR, nonce []byte) error {
361 return a.validateQuote(quote, pcrs, nonce)
362 }
363
364 // VerifyAll uses multiple quotes to verify the authenticity of all PCR
365 // measurements. See documentation on Verify() for semantics.
366 //
367 // An error is returned if any PCRs provided were not covered by a quote,
368 // or if no quote/nonce was provided.
369 func (a *AKPublic) VerifyAll(quotes []Quote, pcrs []PCR, nonce []byte) error {
370 if len(quotes) == 0 {
371 return errors.New("no quotes were provided")
372 }
373 if len(nonce) == 0 {
374 return errors.New("no nonce was provided")
375 }
376
377 for i, quote := range quotes {
378 if err := a.Verify(quote, pcrs, nonce); err != nil {
379 return fmt.Errorf("quote %d: %v", i, err)
380 }
381 }
382
383 var errPCRs []string
384 for _, p := range pcrs {
385 if !p.QuoteVerified() {
386 errPCRs = append(errPCRs, fmt.Sprintf("%d (%s)", p.Index, p.DigestAlg))
387 }
388 }
389 if len(errPCRs) > 0 {
390 return fmt.Errorf("some PCRs were not covered by a quote: %s", strings.Join(errPCRs, ", "))
391 }
392 return nil
393 }
394
395 // HashAlg identifies a hashing Algorithm.
396 type HashAlg uint8
397
398 // Known valid hash algorithms.
399 var (
400 HashSHA1 = HashAlg(tpm2.AlgSHA1)
401 HashSHA256 = HashAlg(tpm2.AlgSHA256)
402 HashSHA384 = HashAlg(tpm2.AlgSHA384)
403 HashSHA512 = HashAlg(tpm2.AlgSHA512)
404 )
405
406 func (a HashAlg) cryptoHash() (crypto.Hash, error) {
407 g := a.goTPMAlg()
408 h, err := g.Hash()
409 if err != nil {
410 return 0, fmt.Errorf("HashAlg %v (corresponding to TPM2.Algorithm %v) has no corresponding crypto.Hash", a, g)
411 }
412 return h, nil
413 }
414
415 func (a HashAlg) goTPMAlg() tpm2.Algorithm {
416 return tpm2.Algorithm(a)
417 }
418
419 // String returns a human-friendly representation of the hash algorithm.
420 func (a HashAlg) String() string {
421 return a.goTPMAlg().String()
422 }
423
424 // FromTPMAlg returns the HashAlg corresponding to the given tpm2.Algorithm.
425 func FromTPMAlg(h tpm2.Algorithm) (HashAlg, error) {
426 switch h {
427 case tpm2.AlgSHA1:
428 return HashSHA1, nil
429 case tpm2.AlgSHA256:
430 return HashSHA256, nil
431 case tpm2.AlgSHA384:
432 return HashSHA384, nil
433 case tpm2.AlgSHA512:
434 return HashSHA512, nil
435 default:
436 return 0, fmt.Errorf("tpm2.Algorithm %v has no corresponding HashAlg", h)
437 }
438 }
439
440 // FromCryptoHash returns the HashAlg corresponding to the given crypto.Hash.
441 func FromCryptoHash(h crypto.Hash) (HashAlg, error) {
442 switch h {
443 case crypto.SHA1:
444 return HashSHA1, nil
445 case crypto.SHA256:
446 return HashSHA256, nil
447 case crypto.SHA384:
448 return HashSHA384, nil
449 case crypto.SHA512:
450 return HashSHA512, nil
451 default:
452 return 0, fmt.Errorf("crypto.Hash %v has no corresponding HashAlg", h)
453 }
454 }
455
456 // PlatformParameters encapsulates the set of information necessary to attest
457 // the booted state of the machine the TPM is attached to.
458 //
459 // The digests contained in the event log can be considered authentic if:
460 // - The AK public corresponds to the known AK for that platform.
461 // - All quotes are verified with AKPublic.Verify(), and return no errors.
462 // - The event log parsed successfully using ParseEventLog(), and a call
463 // to EventLog.Verify() with the full set of PCRs returned no error.
464 type PlatformParameters struct {
465 // The public blob of the AK which endorsed the platform state. This can
466 // be decoded to verify the adjacent quotes using ParseAKPublic().
467 Public []byte
468 // The set of quotes which endorse the state of the PCRs.
469 Quotes []Quote
470 // The set of expected PCR values, which are used in replaying the event log
471 // to verify digests were not tampered with.
472 PCRs []PCR
473 // The raw event log provided by the platform. This can be processed with
474 // ParseEventLog().
475 EventLog []byte
476 }
477
478 var (
479 defaultOpenConfig = &OpenConfig{}
480
481 // ErrTPMNotAvailable is returned in response to OpenTPM() when
482 // either no TPM is available, or a TPM of the requested version
483 // is not available (if TPMVersion was set in the provided config).
484 ErrTPMNotAvailable = errors.New("TPM device not available")
485 )
486
487 // TPMInfo contains information about the version & interface
488 // of an open TPM.
489 type TPMInfo struct {
490 Interface TPMInterface
491 VendorInfo string
492 Manufacturer TCGVendorID
493
494 // FirmwareVersionMajor and FirmwareVersionMinor describe
495 // the firmware version of the TPM, but are only available
496 // for TPM 2.0 devices.
497 FirmwareVersionMajor int
498 FirmwareVersionMinor int
499 }
500
501 // OpenTPM initializes access to the TPM based on the
502 // config provided.
503 func OpenTPM(config *OpenConfig) (*TPM, error) {
504 if config == nil {
505 config = defaultOpenConfig
506 }
507 // As a special case, if the user provided us with a command channel,
508 // we should use that.
509 if config.CommandChannel != nil {
510 return &TPM{&wrappedTPM20{
511 interf: TPMInterfaceCommandChannel,
512 rwc: config.CommandChannel,
513 }}, nil
514 }
515
516 candidateTPMs, err := probeSystemTPMs()
517 if err != nil {
518 return nil, err
519 }
520
521 for _, tpm := range candidateTPMs {
522 return openTPM(tpm)
523 }
524
525 return nil, ErrTPMNotAvailable
526 }
527
528 // AvailableTPMs returns information about available TPMs matching
529 // the given config, without opening the devices.
530 func AvailableTPMs(config *OpenConfig) ([]TPMInfo, error) {
531 candidateTPMs, err := probeSystemTPMs()
532 if err != nil {
533 return nil, err
534 }
535
536 var out []TPMInfo
537
538 for _, tpm := range candidateTPMs {
539 t, err := openTPM(tpm)
540 if err != nil {
541 return nil, err
542 }
543 defer t.Close()
544 i, err := t.Info()
545 if err != nil {
546 return nil, err
547 }
548 out = append(out, *i)
549
550 }
551
552 return out, nil
553 }