Debian Codegraph @

legacy/tpm2/structures.go

raw
1 // Copyright (c) 2018, Google LLC All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of 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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package tpm2
16
17 import (
18 "bytes"
19 "crypto"
20 "crypto/ecdsa"
21 "crypto/rsa"
22 "encoding/binary"
23 "errors"
24 "fmt"
25 "math/big"
26 "reflect"
27
28 "github.com/google/go-tpm/tpmutil"
29 )
30
31 // NVPublic contains the public area of an NV index.
32 type NVPublic struct {
33 NVIndex tpmutil.Handle
34 NameAlg Algorithm
35 Attributes NVAttr
36 AuthPolicy tpmutil.U16Bytes
37 DataSize uint16
38 }
39
40 type tpmsSensitiveCreate struct {
41 UserAuth tpmutil.U16Bytes
42 Data tpmutil.U16Bytes
43 }
44
45 // PCRSelection contains a slice of PCR indexes and a hash algorithm used in
46 // them.
47 type PCRSelection struct {
48 Hash Algorithm
49 PCRs []int
50 }
51
52 type tpmsPCRSelection struct {
53 Hash Algorithm
54 Size byte
55 PCRs tpmutil.RawBytes
56 }
57
58 // Public contains the public area of an object.
59 type Public struct {
60 Type Algorithm
61 NameAlg Algorithm
62 Attributes KeyProp
63 AuthPolicy tpmutil.U16Bytes
64
65 // Exactly one of the following fields should be set
66 // When encoding/decoding, one will be picked based on Type.
67
68 // RSAParameters contains both [rsa]parameters and [rsa]unique.
69 RSAParameters *RSAParams
70 // ECCParameters contains both [ecc]parameters and [ecc]unique.
71 ECCParameters *ECCParams
72 // SymCipherParameters contains both [sym]parameters and [sym]unique.
73 SymCipherParameters *SymCipherParams
74 // KeyedHashParameters contains both [keyedHash]parameters and [keyedHash]unique.
75 KeyedHashParameters *KeyedHashParams
76 }
77
78 // Encode serializes a Public structure in TPM wire format.
79 func (p Public) Encode() ([]byte, error) {
80 head, err := tpmutil.Pack(p.Type, p.NameAlg, p.Attributes, p.AuthPolicy)
81 if err != nil {
82 return nil, fmt.Errorf("encoding Type, NameAlg, Attributes, AuthPolicy: %v", err)
83 }
84 var params []byte
85 switch p.Type {
86 case AlgRSA:
87 params, err = p.RSAParameters.encode()
88 case AlgKeyedHash:
89 params, err = p.KeyedHashParameters.encode()
90 case AlgECC:
91 params, err = p.ECCParameters.encode()
92 case AlgSymCipher:
93 params, err = p.SymCipherParameters.encode()
94 default:
95 err = fmt.Errorf("unsupported type in TPMT_PUBLIC: 0x%x", p.Type)
96 }
97 if err != nil {
98 return nil, fmt.Errorf("encoding RSAParameters, ECCParameters, SymCipherParameters or KeyedHash: %v", err)
99 }
100 return concat(head, params)
101 }
102
103 // Key returns the (public) key from the public area of an object.
104 func (p Public) Key() (crypto.PublicKey, error) {
105 var pubKey crypto.PublicKey
106 switch p.Type {
107 case AlgRSA:
108 // Endianness of big.Int.Bytes/SetBytes and modulus in the TPM is the same
109 // (big-endian).
110 pubKey = &rsa.PublicKey{N: p.RSAParameters.Modulus(), E: int(p.RSAParameters.Exponent())}
111 case AlgECC:
112 curve, ok := toGoCurve[p.ECCParameters.CurveID]
113 if !ok {
114 return nil, fmt.Errorf("can't map TPM EC curve ID 0x%x to Go elliptic.Curve value", p.ECCParameters.CurveID)
115 }
116 pubKey = &ecdsa.PublicKey{
117 X: p.ECCParameters.Point.X(),
118 Y: p.ECCParameters.Point.Y(),
119 Curve: curve,
120 }
121 default:
122 return nil, fmt.Errorf("unsupported public key type 0x%x", p.Type)
123 }
124 return pubKey, nil
125 }
126
127 // Name computes the Digest-based Name from the public area of an object.
128 func (p Public) Name() (Name, error) {
129 pubEncoded, err := p.Encode()
130 if err != nil {
131 return Name{}, err
132 }
133 hash, err := p.NameAlg.Hash()
134 if err != nil {
135 return Name{}, err
136 }
137 nameHash := hash.New()
138 nameHash.Write(pubEncoded)
139 return Name{
140 Digest: &HashValue{
141 Alg: p.NameAlg,
142 Value: nameHash.Sum(nil),
143 },
144 }, nil
145 }
146
147 // MatchesTemplate checks if the Public area has the same algorithms and
148 // parameters as the provided template. Note that this does not necessarily
149 // mean that the key was created from this template, as the Unique field is
150 // both provided in the template and overridden in the key creation process.
151 func (p Public) MatchesTemplate(template Public) bool {
152 if p.Type != template.Type ||
153 p.NameAlg != template.NameAlg ||
154 p.Attributes != template.Attributes ||
155 !bytes.Equal(p.AuthPolicy, template.AuthPolicy) {
156 return false
157 }
158 switch p.Type {
159 case AlgRSA:
160 return p.RSAParameters.matchesTemplate(template.RSAParameters)
161 case AlgECC:
162 return p.ECCParameters.matchesTemplate(template.ECCParameters)
163 case AlgSymCipher:
164 return p.SymCipherParameters.matchesTemplate(template.SymCipherParameters)
165 case AlgKeyedHash:
166 return p.KeyedHashParameters.matchesTemplate(template.KeyedHashParameters)
167 default:
168 return true
169 }
170 }
171
172 // DecodePublic decodes a TPMT_PUBLIC message. No error is returned if
173 // the input has extra trailing data.
174 func DecodePublic(buf []byte) (Public, error) {
175 in := bytes.NewBuffer(buf)
176 var pub Public
177 var err error
178 if err = tpmutil.UnpackBuf(in, &pub.Type, &pub.NameAlg, &pub.Attributes, &pub.AuthPolicy); err != nil {
179 return pub, fmt.Errorf("decoding TPMT_PUBLIC: %v", err)
180 }
181
182 switch pub.Type {
183 case AlgRSA:
184 pub.RSAParameters, err = decodeRSAParams(in)
185 case AlgECC:
186 pub.ECCParameters, err = decodeECCParams(in)
187 case AlgSymCipher:
188 pub.SymCipherParameters, err = decodeSymCipherParams(in)
189 case AlgKeyedHash:
190 pub.KeyedHashParameters, err = decodeKeyedHashParams(in)
191 default:
192 err = fmt.Errorf("unsupported type in TPMT_PUBLIC: 0x%x", pub.Type)
193 }
194 return pub, err
195 }
196
197 // RSAParams represents parameters of an RSA key pair:
198 // both the TPMS_RSA_PARMS and the TPM2B_PUBLIC_KEY_RSA.
199 //
200 // Symmetric and Sign may be nil, depending on key Attributes in Public.
201 //
202 // ExponentRaw and ModulusRaw are the actual data encoded in the template, which
203 // is useful for templates that differ in zero-padding, for example.
204 type RSAParams struct {
205 Symmetric *SymScheme
206 Sign *SigScheme
207 KeyBits uint16
208 ExponentRaw uint32
209 ModulusRaw tpmutil.U16Bytes
210 }
211
212 // Exponent returns the RSA exponent value represented by ExponentRaw, handling
213 // the fact that an exponent of 0 represents a value of 65537 (2^16 + 1).
214 func (p *RSAParams) Exponent() uint32 {
215 if p.ExponentRaw == 0 {
216 return defaultRSAExponent
217 }
218 return p.ExponentRaw
219 }
220
221 // Modulus returns the RSA modulus value represented by ModulusRaw, handling the
222 // fact that the same modulus value can have multiple different representations.
223 func (p *RSAParams) Modulus() *big.Int {
224 return new(big.Int).SetBytes(p.ModulusRaw)
225 }
226
227 func (p *RSAParams) matchesTemplate(t *RSAParams) bool {
228 return reflect.DeepEqual(p.Symmetric, t.Symmetric) &&
229 reflect.DeepEqual(p.Sign, t.Sign) &&
230 p.KeyBits == t.KeyBits && p.ExponentRaw == t.ExponentRaw
231 }
232
233 func (p *RSAParams) encode() ([]byte, error) {
234 if p == nil {
235 return nil, nil
236 }
237 sym, err := p.Symmetric.encode()
238 if err != nil {
239 return nil, fmt.Errorf("encoding Symmetric: %v", err)
240 }
241 sig, err := p.Sign.encode()
242 if err != nil {
243 return nil, fmt.Errorf("encoding Sign: %v", err)
244 }
245 rest, err := tpmutil.Pack(p.KeyBits, p.ExponentRaw, p.ModulusRaw)
246 if err != nil {
247 return nil, fmt.Errorf("encoding KeyBits, Exponent, Modulus: %v", err)
248 }
249 return concat(sym, sig, rest)
250 }
251
252 func decodeRSAParams(in *bytes.Buffer) (*RSAParams, error) {
253 var params RSAParams
254 var err error
255
256 if params.Symmetric, err = decodeSymScheme(in); err != nil {
257 return nil, fmt.Errorf("decoding Symmetric: %v", err)
258 }
259 if params.Sign, err = decodeSigScheme(in); err != nil {
260 return nil, fmt.Errorf("decoding Sign: %v", err)
261 }
262 if err := tpmutil.UnpackBuf(in, &params.KeyBits, &params.ExponentRaw, &params.ModulusRaw); err != nil {
263 return nil, fmt.Errorf("decoding KeyBits, Exponent, Modulus: %v", err)
264 }
265 return &params, nil
266 }
267
268 // ECCParams represents parameters of an ECC key pair:
269 // both the TPMS_ECC_PARMS and the TPMS_ECC_POINT.
270 //
271 // Symmetric, Sign and KDF may be nil, depending on key Attributes in Public.
272 type ECCParams struct {
273 Symmetric *SymScheme
274 Sign *SigScheme
275 CurveID EllipticCurve
276 KDF *KDFScheme
277 Point ECPoint
278 }
279
280 // ECPoint represents a ECC coordinates for a point using byte buffers.
281 type ECPoint struct {
282 XRaw, YRaw tpmutil.U16Bytes
283 }
284
285 // X returns the X Point value reprsented by XRaw.
286 func (p ECPoint) X() *big.Int {
287 return new(big.Int).SetBytes(p.XRaw)
288 }
289
290 // Y returns the Y Point value reprsented by YRaw.
291 func (p ECPoint) Y() *big.Int {
292 return new(big.Int).SetBytes(p.YRaw)
293 }
294
295 func (p *ECCParams) matchesTemplate(t *ECCParams) bool {
296 return reflect.DeepEqual(p.Symmetric, t.Symmetric) &&
297 reflect.DeepEqual(p.Sign, t.Sign) &&
298 p.CurveID == t.CurveID && reflect.DeepEqual(p.KDF, t.KDF)
299 }
300
301 func (p *ECCParams) encode() ([]byte, error) {
302 if p == nil {
303 return nil, nil
304 }
305 sym, err := p.Symmetric.encode()
306 if err != nil {
307 return nil, fmt.Errorf("encoding Symmetric: %v", err)
308 }
309 sig, err := p.Sign.encode()
310 if err != nil {
311 return nil, fmt.Errorf("encoding Sign: %v", err)
312 }
313 curve, err := tpmutil.Pack(p.CurveID)
314 if err != nil {
315 return nil, fmt.Errorf("encoding CurveID: %v", err)
316 }
317 kdf, err := p.KDF.encode()
318 if err != nil {
319 return nil, fmt.Errorf("encoding KDF: %v", err)
320 }
321 point, err := tpmutil.Pack(p.Point.XRaw, p.Point.YRaw)
322 if err != nil {
323 return nil, fmt.Errorf("encoding Point: %v", err)
324 }
325 return concat(sym, sig, curve, kdf, point)
326 }
327
328 func decodeECCParams(in *bytes.Buffer) (*ECCParams, error) {
329 var params ECCParams
330 var err error
331
332 if params.Symmetric, err = decodeSymScheme(in); err != nil {
333 return nil, fmt.Errorf("decoding Symmetric: %v", err)
334 }
335 if params.Sign, err = decodeSigScheme(in); err != nil {
336 return nil, fmt.Errorf("decoding Sign: %v", err)
337 }
338 if err := tpmutil.UnpackBuf(in, &params.CurveID); err != nil {
339 return nil, fmt.Errorf("decoding CurveID: %v", err)
340 }
341 if params.KDF, err = decodeKDFScheme(in); err != nil {
342 return nil, fmt.Errorf("decoding KDF: %v", err)
343 }
344 if err := tpmutil.UnpackBuf(in, &params.Point.XRaw, &params.Point.YRaw); err != nil {
345 return nil, fmt.Errorf("decoding Point: %v", err)
346 }
347 return &params, nil
348 }
349
350 // SymCipherParams represents parameters of a symmetric block cipher TPM object:
351 // both the TPMS_SYMCIPHER_PARMS and the TPM2B_DIGEST (hash of the key).
352 type SymCipherParams struct {
353 Symmetric *SymScheme
354 Unique tpmutil.U16Bytes
355 }
356
357 func (p *SymCipherParams) matchesTemplate(t *SymCipherParams) bool {
358 return reflect.DeepEqual(p.Symmetric, t.Symmetric)
359 }
360
361 func (p *SymCipherParams) encode() ([]byte, error) {
362 sym, err := p.Symmetric.encode()
363 if err != nil {
364 return nil, fmt.Errorf("encoding Symmetric: %v", err)
365 }
366 unique, err := tpmutil.Pack(p.Unique)
367 if err != nil {
368 return nil, fmt.Errorf("encoding Unique: %v", err)
369 }
370 return concat(sym, unique)
371 }
372
373 func decodeSymCipherParams(in *bytes.Buffer) (*SymCipherParams, error) {
374 var params SymCipherParams
375 var err error
376
377 if params.Symmetric, err = decodeSymScheme(in); err != nil {
378 return nil, fmt.Errorf("decoding Symmetric: %v", err)
379 }
380 if err := tpmutil.UnpackBuf(in, &params.Unique); err != nil {
381 return nil, fmt.Errorf("decoding Unique: %v", err)
382 }
383 return &params, nil
384 }
385
386 // KeyedHashParams represents parameters of a keyed hash TPM object:
387 // both the TPMS_KEYEDHASH_PARMS and the TPM2B_DIGEST (hash of the key).
388 type KeyedHashParams struct {
389 Alg Algorithm
390 Hash Algorithm
391 KDF Algorithm
392 Unique tpmutil.U16Bytes
393 }
394
395 func (p *KeyedHashParams) matchesTemplate(t *KeyedHashParams) bool {
396 if p.Alg != t.Alg {
397 return false
398 }
399 switch p.Alg {
400 case AlgHMAC:
401 return p.Hash == t.Hash
402 case AlgXOR:
403 return p.Hash == t.Hash && p.KDF == t.KDF
404 default:
405 return true
406 }
407 }
408
409 func (p *KeyedHashParams) encode() ([]byte, error) {
410 if p == nil {
411 return tpmutil.Pack(AlgNull, tpmutil.U16Bytes(nil))
412 }
413 var params []byte
414 var err error
415 switch p.Alg {
416 case AlgNull:
417 params, err = tpmutil.Pack(p.Alg)
418 case AlgHMAC:
419 params, err = tpmutil.Pack(p.Alg, p.Hash)
420 case AlgXOR:
421 params, err = tpmutil.Pack(p.Alg, p.Hash, p.KDF)
422 default:
423 err = fmt.Errorf("unsupported KeyedHash Algorithm: 0x%x", p.Alg)
424 }
425 if err != nil {
426 return nil, fmt.Errorf("encoding Alg Params: %v", err)
427 }
428 unique, err := tpmutil.Pack(p.Unique)
429 if err != nil {
430 return nil, fmt.Errorf("encoding Unique: %v", err)
431 }
432 return concat(params, unique)
433 }
434
435 func decodeKeyedHashParams(in *bytes.Buffer) (*KeyedHashParams, error) {
436 var p KeyedHashParams
437 var err error
438 if err = tpmutil.UnpackBuf(in, &p.Alg); err != nil {
439 return nil, fmt.Errorf("decoding Alg: %v", err)
440 }
441 switch p.Alg {
442 case AlgNull:
443 err = nil
444 case AlgHMAC:
445 err = tpmutil.UnpackBuf(in, &p.Hash)
446 case AlgXOR:
447 err = tpmutil.UnpackBuf(in, &p.Hash, &p.KDF)
448 default:
449 err = fmt.Errorf("unsupported KeyedHash Algorithm: 0x%x", p.Alg)
450 }
451 if err != nil {
452 return nil, fmt.Errorf("decoding Alg Params: %v", err)
453 }
454 if err = tpmutil.UnpackBuf(in, &p.Unique); err != nil {
455 return nil, fmt.Errorf("decoding Unique: %v", err)
456 }
457 return &p, nil
458 }
459
460 // SymScheme represents a symmetric encryption scheme.
461 // Known in the specification by TPMT_SYM_DEF_OBJECT.
462 type SymScheme struct {
463 Alg Algorithm
464 KeyBits uint16
465 Mode Algorithm
466 }
467
468 func (s *SymScheme) encode() ([]byte, error) {
469 if s == nil || s.Alg.IsNull() {
470 return tpmutil.Pack(AlgNull)
471 }
472 return tpmutil.Pack(s.Alg, s.KeyBits, s.Mode)
473 }
474
475 func decodeSymScheme(in *bytes.Buffer) (*SymScheme, error) {
476 var scheme SymScheme
477 if err := tpmutil.UnpackBuf(in, &scheme.Alg); err != nil {
478 return nil, fmt.Errorf("decoding Alg: %v", err)
479 }
480 if scheme.Alg == AlgNull {
481 return nil, nil
482 }
483 if err := tpmutil.UnpackBuf(in, &scheme.KeyBits, &scheme.Mode); err != nil {
484 return nil, fmt.Errorf("decoding KeyBits, Mode: %v", err)
485 }
486 return &scheme, nil
487 }
488
489 // AsymScheme represents am asymmetric encryption scheme.
490 type AsymScheme struct {
491 Alg Algorithm
492 Hash Algorithm
493 }
494
495 func (s *AsymScheme) encode() ([]byte, error) {
496 if s == nil || s.Alg.IsNull() {
497 return tpmutil.Pack(AlgNull)
498 }
499 if s.Alg.UsesHash() {
500 return tpmutil.Pack(s.Alg, s.Hash)
501 }
502 return tpmutil.Pack(s.Alg)
503 }
504
505 // SigScheme represents a signing scheme.
506 type SigScheme struct {
507 Alg Algorithm
508 Hash Algorithm
509 Count uint32
510 }
511
512 func (s *SigScheme) encode() ([]byte, error) {
513 if s == nil || s.Alg.IsNull() {
514 return tpmutil.Pack(AlgNull)
515 }
516 if s.Alg.UsesCount() {
517 return tpmutil.Pack(s.Alg, s.Hash, s.Count)
518 }
519 return tpmutil.Pack(s.Alg, s.Hash)
520 }
521
522 func decodeSigScheme(in *bytes.Buffer) (*SigScheme, error) {
523 var scheme SigScheme
524 if err := tpmutil.UnpackBuf(in, &scheme.Alg); err != nil {
525 return nil, fmt.Errorf("decoding Alg: %v", err)
526 }
527 if scheme.Alg == AlgNull {
528 return nil, nil
529 }
530 if err := tpmutil.UnpackBuf(in, &scheme.Hash); err != nil {
531 return nil, fmt.Errorf("decoding Hash: %v", err)
532 }
533 if scheme.Alg.UsesCount() {
534 if err := tpmutil.UnpackBuf(in, &scheme.Count); err != nil {
535 return nil, fmt.Errorf("decoding Count: %v", err)
536 }
537 }
538 return &scheme, nil
539 }
540
541 // KDFScheme represents a KDF (Key Derivation Function) scheme.
542 type KDFScheme struct {
543 Alg Algorithm
544 Hash Algorithm
545 }
546
547 func (s *KDFScheme) encode() ([]byte, error) {
548 if s == nil || s.Alg.IsNull() {
549 return tpmutil.Pack(AlgNull)
550 }
551 return tpmutil.Pack(s.Alg, s.Hash)
552 }
553
554 func decodeKDFScheme(in *bytes.Buffer) (*KDFScheme, error) {
555 var scheme KDFScheme
556 if err := tpmutil.UnpackBuf(in, &scheme.Alg); err != nil {
557 return nil, fmt.Errorf("decoding Alg: %v", err)
558 }
559 if scheme.Alg == AlgNull {
560 return nil, nil
561 }
562 if err := tpmutil.UnpackBuf(in, &scheme.Hash); err != nil {
563 return nil, fmt.Errorf("decoding Hash: %v", err)
564 }
565 return &scheme, nil
566 }
567
568 // Signature combines all possible signatures from RSA and ECC keys. Only one
569 // of RSA or ECC will be populated.
570 type Signature struct {
571 Alg Algorithm
572 RSA *SignatureRSA
573 ECC *SignatureECC
574 }
575
576 // Encode serializes a Signature structure in TPM wire format.
577 func (s Signature) Encode() ([]byte, error) {
578 head, err := tpmutil.Pack(s.Alg)
579 if err != nil {
580 return nil, fmt.Errorf("encoding Alg: %v", err)
581 }
582 var signature []byte
583 switch s.Alg {
584 case AlgRSASSA, AlgRSAPSS:
585 if signature, err = tpmutil.Pack(s.RSA); err != nil {
586 return nil, fmt.Errorf("encoding RSA: %v", err)
587 }
588 case AlgECDSA:
589 signature, err = tpmutil.Pack(s.ECC.HashAlg, tpmutil.U16Bytes(s.ECC.R.Bytes()), tpmutil.U16Bytes(s.ECC.S.Bytes()))
590 if err != nil {
591 return nil, fmt.Errorf("encoding ECC: %v", err)
592 }
593 }
594 return concat(head, signature)
595 }
596
597 // DecodeSignature decodes a serialized TPMT_SIGNATURE structure.
598 func DecodeSignature(in *bytes.Buffer) (*Signature, error) {
599 var sig Signature
600 if err := tpmutil.UnpackBuf(in, &sig.Alg); err != nil {
601 return nil, fmt.Errorf("decoding Alg: %v", err)
602 }
603 switch sig.Alg {
604 case AlgRSASSA, AlgRSAPSS:
605 sig.RSA = new(SignatureRSA)
606 if err := tpmutil.UnpackBuf(in, sig.RSA); err != nil {
607 return nil, fmt.Errorf("decoding RSA: %v", err)
608 }
609 case AlgECDSA:
610 sig.ECC = new(SignatureECC)
611 var r, s tpmutil.U16Bytes
612 if err := tpmutil.UnpackBuf(in, &sig.ECC.HashAlg, &r, &s); err != nil {
613 return nil, fmt.Errorf("decoding ECC: %v", err)
614 }
615 sig.ECC.R = big.NewInt(0).SetBytes(r)
616 sig.ECC.S = big.NewInt(0).SetBytes(s)
617 default:
618 return nil, fmt.Errorf("unsupported signature algorithm 0x%x", sig.Alg)
619 }
620 return &sig, nil
621 }
622
623 // SignatureRSA is an RSA-specific signature value.
624 type SignatureRSA struct {
625 HashAlg Algorithm
626 Signature tpmutil.U16Bytes
627 }
628
629 // SignatureECC is an ECC-specific signature value.
630 type SignatureECC struct {
631 HashAlg Algorithm
632 R *big.Int
633 S *big.Int
634 }
635
636 // Private contains private section of a TPM key.
637 type Private struct {
638 Type Algorithm
639 AuthValue tpmutil.U16Bytes
640 SeedValue tpmutil.U16Bytes
641 Sensitive tpmutil.U16Bytes
642 }
643
644 // Encode serializes a Private structure in TPM wire format.
645 func (p Private) Encode() ([]byte, error) {
646 if p.Type.IsNull() {
647 return nil, nil
648 }
649 return tpmutil.Pack(p)
650 }
651
652 // AttestationData contains data attested by TPM commands (like Certify).
653 type AttestationData struct {
654 Magic uint32
655 Type tpmutil.Tag
656 QualifiedSigner Name
657 ExtraData tpmutil.U16Bytes
658 ClockInfo ClockInfo
659 FirmwareVersion uint64
660 AttestedCertifyInfo *CertifyInfo
661 AttestedQuoteInfo *QuoteInfo
662 AttestedCreationInfo *CreationInfo
663 }
664
665 // DecodeAttestationData decode a TPMS_ATTEST message. No error is returned if
666 // the input has extra trailing data.
667 func DecodeAttestationData(in []byte) (*AttestationData, error) {
668 buf := bytes.NewBuffer(in)
669
670 var ad AttestationData
671 if err := tpmutil.UnpackBuf(buf, &ad.Magic, &ad.Type); err != nil {
672 return nil, fmt.Errorf("decoding Magic/Type: %v", err)
673 }
674 // All attestation structures have the magic prefix
675 // TPMS_GENERATED_VALUE to symbolize they were created by
676 // the TPM when signed with an AK.
677 if ad.Magic != 0xff544347 {
678 return nil, fmt.Errorf("incorrect magic value: %x", ad.Magic)
679 }
680
681 n, err := DecodeName(buf)
682 if err != nil {
683 return nil, fmt.Errorf("decoding QualifiedSigner: %v", err)
684 }
685 ad.QualifiedSigner = *n
686 if err := tpmutil.UnpackBuf(buf, &ad.ExtraData, &ad.ClockInfo, &ad.FirmwareVersion); err != nil {
687 return nil, fmt.Errorf("decoding ExtraData/ClockInfo/FirmwareVersion: %v", err)
688 }
689
690 // The spec specifies several other types of attestation data. We only need
691 // parsing of Certify & Creation attestation data for now. If you need
692 // support for other attestation types, add them here.
693 switch ad.Type {
694 case TagAttestCertify:
695 if ad.AttestedCertifyInfo, err = decodeCertifyInfo(buf); err != nil {
696 return nil, fmt.Errorf("decoding AttestedCertifyInfo: %v", err)
697 }
698 case TagAttestCreation:
699 if ad.AttestedCreationInfo, err = decodeCreationInfo(buf); err != nil {
700 return nil, fmt.Errorf("decoding AttestedCreationInfo: %v", err)
701 }
702 case TagAttestQuote:
703 if ad.AttestedQuoteInfo, err = decodeQuoteInfo(buf); err != nil {
704 return nil, fmt.Errorf("decoding AttestedQuoteInfo: %v", err)
705 }
706 default:
707 return nil, fmt.Errorf("only Quote, Certify & Creation attestation structures are supported, got type 0x%x", ad.Type)
708 }
709
710 return &ad, nil
711 }
712
713 // Encode serializes an AttestationData structure in TPM wire format.
714 func (ad AttestationData) Encode() ([]byte, error) {
715 head, err := tpmutil.Pack(ad.Magic, ad.Type)
716 if err != nil {
717 return nil, fmt.Errorf("encoding Magic, Type: %v", err)
718 }
719 signer, err := ad.QualifiedSigner.Encode()
720 if err != nil {
721 return nil, fmt.Errorf("encoding QualifiedSigner: %v", err)
722 }
723 tail, err := tpmutil.Pack(ad.ExtraData, ad.ClockInfo, ad.FirmwareVersion)
724 if err != nil {
725 return nil, fmt.Errorf("encoding ExtraData, ClockInfo, FirmwareVersion: %v", err)
726 }
727
728 var info []byte
729 switch ad.Type {
730 case TagAttestCertify:
731 if info, err = ad.AttestedCertifyInfo.encode(); err != nil {
732 return nil, fmt.Errorf("encoding AttestedCertifyInfo: %v", err)
733 }
734 case TagAttestCreation:
735 if info, err = ad.AttestedCreationInfo.encode(); err != nil {
736 return nil, fmt.Errorf("encoding AttestedCreationInfo: %v", err)
737 }
738 case TagAttestQuote:
739 if info, err = ad.AttestedQuoteInfo.encode(); err != nil {
740 return nil, fmt.Errorf("encoding AttestedQuoteInfo: %v", err)
741 }
742 default:
743 return nil, fmt.Errorf("only Quote, Certify & Creation attestation structures are supported, got type 0x%x", ad.Type)
744 }
745
746 return concat(head, signer, tail, info)
747 }
748
749 // CreationInfo contains Creation-specific data for TPMS_ATTEST.
750 type CreationInfo struct {
751 Name Name
752 // Most TPM2B_Digest structures contain a TPMU_HA structure
753 // and get parsed to HashValue. This is never the case for the
754 // digest in TPMS_CREATION_INFO.
755 OpaqueDigest tpmutil.U16Bytes
756 }
757
758 func decodeCreationInfo(in *bytes.Buffer) (*CreationInfo, error) {
759 var ci CreationInfo
760
761 n, err := DecodeName(in)
762 if err != nil {
763 return nil, fmt.Errorf("decoding Name: %v", err)
764 }
765 ci.Name = *n
766
767 if err := tpmutil.UnpackBuf(in, &ci.OpaqueDigest); err != nil {
768 return nil, fmt.Errorf("decoding Digest: %v", err)
769 }
770
771 return &ci, nil
772 }
773
774 func (ci CreationInfo) encode() ([]byte, error) {
775 n, err := ci.Name.Encode()
776 if err != nil {
777 return nil, fmt.Errorf("encoding Name: %v", err)
778 }
779
780 d, err := tpmutil.Pack(ci.OpaqueDigest)
781 if err != nil {
782 return nil, fmt.Errorf("encoding Digest: %v", err)
783 }
784
785 return concat(n, d)
786 }
787
788 // CertifyInfo contains Certify-specific data for TPMS_ATTEST.
789 type CertifyInfo struct {
790 Name Name
791 QualifiedName Name
792 }
793
794 func decodeCertifyInfo(in *bytes.Buffer) (*CertifyInfo, error) {
795 var ci CertifyInfo
796
797 n, err := DecodeName(in)
798 if err != nil {
799 return nil, fmt.Errorf("decoding Name: %v", err)
800 }
801 ci.Name = *n
802
803 n, err = DecodeName(in)
804 if err != nil {
805 return nil, fmt.Errorf("decoding QualifiedName: %v", err)
806 }
807 ci.QualifiedName = *n
808
809 return &ci, nil
810 }
811
812 func (ci CertifyInfo) encode() ([]byte, error) {
813 n, err := ci.Name.Encode()
814 if err != nil {
815 return nil, fmt.Errorf("encoding Name: %v", err)
816 }
817 qn, err := ci.QualifiedName.Encode()
818 if err != nil {
819 return nil, fmt.Errorf("encoding QualifiedName: %v", err)
820 }
821 return concat(n, qn)
822 }
823
824 // QuoteInfo represents a TPMS_QUOTE_INFO structure.
825 type QuoteInfo struct {
826 PCRSelection PCRSelection
827 PCRDigest tpmutil.U16Bytes
828 }
829
830 func decodeQuoteInfo(in *bytes.Buffer) (*QuoteInfo, error) {
831 var out QuoteInfo
832 sel, err := decodeOneTPMLPCRSelection(in)
833 if err != nil {
834 return nil, fmt.Errorf("decoding PCRSelection: %v", err)
835 }
836 out.PCRSelection = sel
837
838 if err := tpmutil.UnpackBuf(in, &out.PCRDigest); err != nil {
839 return nil, fmt.Errorf("decoding PCRDigest: %v", err)
840 }
841 return &out, nil
842 }
843
844 func (qi QuoteInfo) encode() ([]byte, error) {
845 sel, err := encodeTPMLPCRSelection(qi.PCRSelection)
846 if err != nil {
847 return nil, fmt.Errorf("encoding PCRSelection: %v", err)
848 }
849
850 digest, err := tpmutil.Pack(qi.PCRDigest)
851 if err != nil {
852 return nil, fmt.Errorf("encoding PCRDigest: %v", err)
853 }
854
855 return concat(sel, digest)
856 }
857
858 // IDObject represents an encrypted credential bound to a TPM object.
859 type IDObject struct {
860 IntegrityHMAC tpmutil.U16Bytes
861 // EncIdentity is packed raw, as the bytes representing the size
862 // of the credential value are present within the encrypted blob.
863 EncIdentity tpmutil.RawBytes
864 }
865
866 // CreationData describes the attributes and environment for an object created
867 // on the TPM. This structure encodes/decodes to/from TPMS_CREATION_DATA.
868 type CreationData struct {
869 PCRSelection PCRSelection
870 PCRDigest tpmutil.U16Bytes
871 Locality byte
872 ParentNameAlg Algorithm
873 ParentName Name
874 ParentQualifiedName Name
875 OutsideInfo tpmutil.U16Bytes
876 }
877
878 // EncodeCreationData encodes byte array to TPMS_CREATION_DATA message.
879 func (cd *CreationData) EncodeCreationData() ([]byte, error) {
880 sel, err := encodeTPMLPCRSelection(cd.PCRSelection)
881 if err != nil {
882 return nil, fmt.Errorf("encoding PCRSelection: %v", err)
883 }
884 d, err := tpmutil.Pack(cd.PCRDigest, cd.Locality, cd.ParentNameAlg)
885 if err != nil {
886 return nil, fmt.Errorf("encoding PCRDigest, Locality, ParentNameAlg: %v", err)
887 }
888 pn, err := cd.ParentName.Encode()
889 if err != nil {
890 return nil, fmt.Errorf("encoding ParentName: %v", err)
891 }
892 pqn, err := cd.ParentQualifiedName.Encode()
893 if err != nil {
894 return nil, fmt.Errorf("encoding ParentQualifiedName: %v", err)
895 }
896 o, err := tpmutil.Pack(cd.OutsideInfo)
897 if err != nil {
898 return nil, fmt.Errorf("encoding OutsideInfo: %v", err)
899 }
900 return concat(sel, d, pn, pqn, o)
901 }
902
903 // DecodeCreationData decodes a TPMS_CREATION_DATA message. No error is
904 // returned if the input has extra trailing data.
905 func DecodeCreationData(buf []byte) (*CreationData, error) {
906 in := bytes.NewBuffer(buf)
907 var out CreationData
908
909 sel, err := decodeOneTPMLPCRSelection(in)
910 if err != nil {
911 return nil, fmt.Errorf("decodeOneTPMLPCRSelection returned error %v", err)
912 }
913 out.PCRSelection = sel
914
915 if err := tpmutil.UnpackBuf(in, &out.PCRDigest, &out.Locality, &out.ParentNameAlg); err != nil {
916 return nil, fmt.Errorf("decoding PCRDigest, Locality, ParentNameAlg: %v", err)
917 }
918
919 n, err := DecodeName(in)
920 if err != nil {
921 return nil, fmt.Errorf("decoding ParentName: %v", err)
922 }
923 out.ParentName = *n
924 if n, err = DecodeName(in); err != nil {
925 return nil, fmt.Errorf("decoding ParentQualifiedName: %v", err)
926 }
927 out.ParentQualifiedName = *n
928
929 if err := tpmutil.UnpackBuf(in, &out.OutsideInfo); err != nil {
930 return nil, fmt.Errorf("decoding OutsideInfo: %v", err)
931 }
932
933 return &out, nil
934 }
935
936 // Name represents a TPM2B_NAME, a name for TPM entities. Only one of
937 // Handle or Digest should be set.
938 type Name struct {
939 Handle *tpmutil.Handle
940 Digest *HashValue
941 }
942
943 // DecodeName deserializes a Name hash from the TPM wire format.
944 func DecodeName(in *bytes.Buffer) (*Name, error) {
945 var nameBuf tpmutil.U16Bytes
946 if err := tpmutil.UnpackBuf(in, &nameBuf); err != nil {
947 return nil, err
948 }
949
950 name := new(Name)
951 switch len(nameBuf) {
952 case 0:
953 // No name is present.
954 case 4:
955 name.Handle = new(tpmutil.Handle)
956 if err := tpmutil.UnpackBuf(bytes.NewBuffer(nameBuf), name.Handle); err != nil {
957 return nil, fmt.Errorf("decoding Handle: %v", err)
958 }
959 default:
960 var err error
961 name.Digest, err = decodeHashValue(bytes.NewBuffer(nameBuf))
962 if err != nil {
963 return nil, fmt.Errorf("decoding Digest: %v", err)
964 }
965 }
966 return name, nil
967 }
968
969 // Encode serializes a Name hash into the TPM wire format.
970 func (n Name) Encode() ([]byte, error) {
971 var buf []byte
972 var err error
973 switch {
974 case n.Handle != nil:
975 if buf, err = tpmutil.Pack(*n.Handle); err != nil {
976 return nil, fmt.Errorf("encoding Handle: %v", err)
977 }
978 case n.Digest != nil:
979 if buf, err = n.Digest.Encode(); err != nil {
980 return nil, fmt.Errorf("encoding Digest: %v", err)
981 }
982 default:
983 // Name is empty, which is valid.
984 }
985 return tpmutil.Pack(tpmutil.U16Bytes(buf))
986 }
987
988 // MatchesPublic compares Digest in Name against given Public structure. Note:
989 // this only works for regular Names, not Qualified Names.
990 func (n Name) MatchesPublic(p Public) (bool, error) {
991 if n.Digest == nil {
992 return false, errors.New("Name doesn't have a Digest, can't compare to Public")
993 }
994 expected, err := p.Name()
995 if err != nil {
996 return false, err
997 }
998 // No secrets, so no constant-time comparison
999 return bytes.Equal(expected.Digest.Value, n.Digest.Value), nil
1000 }
1001
1002 // HashValue is an algorithm-specific hash value.
1003 type HashValue struct {
1004 Alg Algorithm
1005 Value tpmutil.U16Bytes
1006 }
1007
1008 func decodeHashValue(in *bytes.Buffer) (*HashValue, error) {
1009 var hv HashValue
1010 if err := tpmutil.UnpackBuf(in, &hv.Alg); err != nil {
1011 return nil, fmt.Errorf("decoding Alg: %v", err)
1012 }
1013 hfn, err := hv.Alg.Hash()
1014 if err != nil {
1015 return nil, err
1016 }
1017 hv.Value = make(tpmutil.U16Bytes, hfn.Size())
1018 if _, err := in.Read(hv.Value); err != nil {
1019 return nil, fmt.Errorf("decoding Value: %v", err)
1020 }
1021 return &hv, nil
1022 }
1023
1024 // Encode represents the given hash value as a TPMT_HA structure.
1025 func (hv HashValue) Encode() ([]byte, error) {
1026 return tpmutil.Pack(hv.Alg, tpmutil.RawBytes(hv.Value))
1027 }
1028
1029 // ClockInfo contains TPM state info included in AttestationData.
1030 type ClockInfo struct {
1031 Clock uint64
1032 ResetCount uint32
1033 RestartCount uint32
1034 Safe byte
1035 }
1036
1037 // AlgorithmAttributes represents a TPMA_ALGORITHM value.
1038 type AlgorithmAttributes uint32
1039
1040 // AlgorithmDescription represents a TPMS_ALGORITHM_DESCRIPTION structure.
1041 type AlgorithmDescription struct {
1042 ID Algorithm
1043 Attributes AlgorithmAttributes
1044 }
1045
1046 // TaggedProperty represents a TPMS_TAGGED_PROPERTY structure.
1047 type TaggedProperty struct {
1048 Tag TPMProp
1049 Value uint32
1050 }
1051
1052 // Ticket represents evidence the TPM previously processed
1053 // information.
1054 type Ticket struct {
1055 Type tpmutil.Tag
1056 Hierarchy tpmutil.Handle
1057 Digest tpmutil.U16Bytes
1058 }
1059
1060 // AuthCommand represents a TPMS_AUTH_COMMAND. This structure encapsulates parameters
1061 // which authorize the use of a given handle or parameter.
1062 type AuthCommand struct {
1063 Session tpmutil.Handle
1064 Nonce tpmutil.U16Bytes
1065 Attributes SessionAttributes
1066 Auth tpmutil.U16Bytes
1067 }
1068
1069 // TPMLDigest represents the TPML_Digest structure
1070 // It is used to convey a list of digest values.
1071 // This type is used in TPM2_PolicyOR() and in TPM2_PCR_Read()
1072 type TPMLDigest struct {
1073 Digests []tpmutil.U16Bytes
1074 }
1075
1076 // Encode converts the TPMLDigest structure into a byte slice
1077 func (list *TPMLDigest) Encode() ([]byte, error) {
1078 res, err := tpmutil.Pack(uint32(len(list.Digests)))
1079 if err != nil {
1080 return nil, err
1081 }
1082 for _, item := range list.Digests {
1083 b, err := tpmutil.Pack(item)
1084 if err != nil {
1085 return nil, err
1086 }
1087 res = append(res, b...)
1088
1089 }
1090 return res, nil
1091 }
1092
1093 // DecodeTPMLDigest decodes a TPML_Digest part of a message.
1094 func DecodeTPMLDigest(buf []byte) (*TPMLDigest, error) {
1095 in := bytes.NewBuffer(buf)
1096 var tpmld TPMLDigest
1097 var count uint32
1098 if err := binary.Read(in, binary.BigEndian, &count); err != nil {
1099 return nil, fmt.Errorf("decoding TPML_Digest: %v", err)
1100 }
1101 for in.Len() > 0 {
1102 var hash tpmutil.U16Bytes
1103 if err := hash.TPMUnmarshal(in); err != nil {
1104 return nil, err
1105 }
1106 tpmld.Digests = append(tpmld.Digests, hash)
1107 }
1108 if count != uint32(len(tpmld.Digests)) {
1109 return nil, fmt.Errorf("expected size and read size does not match")
1110 }
1111 return &tpmld, nil
1112 }