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