/
resources.go
901 lines (779 loc) · 29.9 KB
/
resources.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
// Copyright 2019 Canonical Ltd.
// Licensed under the LGPLv3 with static-linking exception.
// See LICENCE file for details.
package tpm2
import (
"bytes"
"crypto"
_ "crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"reflect"
"github.com/canonical/go-tpm2/mu"
)
// HandleContext corresponds to an entity that resides on the TPM. Implementations of HandleContext
// maintain some host-side state in order to be able to participate in sessions. They are
// invalidated when used in a command that results in the entity being flushed or evicted from the
// TPM. Once invalidated, they can no longer be used.
type HandleContext interface {
// Handle returns the handle of the corresponding entity on the TPM. If Dispose has been called
// then this will return HandleUnassigned.
Handle() Handle
Name() Name // The name of the entity. This will be empty if there isn't one or Dispose has been called.
SerializeToBytes() []byte // Return a byte slice containing the serialized form of this HandleContext
SerializeToWriter(io.Writer) error // Write the serialized form of this HandleContext to the supplied io.Writer
Dispose() // Called when the corresponding resource has been flushed or evicted from the TPM
}
// SessionContextParams corresponds to the parameters of a session.
type SessionContextParams struct {
HashAlg HashAlgorithmId // The session's digest algorithm
IsBound bool // Whether the session is bound.
BoundEntity Name // The bound entity
Symmetric SymDef // The session's symmetric algorithm
SessionKey []byte // The session key
}
// SessionContextState corresponds to the state of a session.
type SessionContextState struct {
NonceTPM Nonce // The most recent TPM nonce value
IsAudit bool // Whether the session is currently an audit session
IsExclusive bool // Whether the session is currently an exclusive audit session
NeedsPassword bool // Whether a policy session includes the TPM2_PolicyPassword assertion
NeedsAuthValue bool // Whether a policy session includes the TPM2_PolicyAuthValue assertion
}
// SessionContext is a HandleContext that corresponds to a session on the TPM.
type SessionContext interface {
HandleContext
// Params returns a copy of the session parameters. This will return a default
// value (with HashAlg == HashAlgorithmNull) if the context was created via
// NewLimitedHandleContext or HandleContext.Dispose was called.
Params() SessionContextParams
// State provides access to read and modify the session state. This will return
// nil if the context was created via NewLimitedHandleContext or
// HandleContext.Dispose was called.
State() *SessionContextState
// Deprecated: Use Params
HashAlg() HashAlgorithmId
// Deprecated: Use State
NonceTPM() Nonce
// Deprecated: Use State
IsAudit() bool
// Deprecated: Use State
IsExclusive() bool
Attrs() SessionAttributes // The attributes associated with this session
SetAttrs(attrs SessionAttributes) // Set the attributes that will be used for this SessionContext
WithAttrs(attrs SessionAttributes) SessionContext // Return a duplicate of this SessionContext with the specified attributes
// IncludeAttrs returns a duplicate of this SessionContext and its attributes with the specified attributes included.
IncludeAttrs(attrs SessionAttributes) SessionContext
// ExcludeAttrs returns a duplicate of this SessionContext and its attributes with the specified attributes excluded.
ExcludeAttrs(attrs SessionAttributes) SessionContext
}
// ResourceContext is a HandleContext that corresponds to a non-session entity on the TPM.
type ResourceContext interface {
HandleContext
// AuthValue returns the authorization value previously set by SetAuthValue.
AuthValue() []byte
// SetAuthValue sets the authorization value that will be used in authorization roles where
// knowledge of the authorization value is required. Functions that create resources on the TPM
// and return a ResourceContext will set this automatically, else it will need to be set manually.
SetAuthValue([]byte)
}
// ObjectContext is a ResourceContext that corresponds to an object on the TPM.
type ObjectContext interface {
ResourceContext
// Public is the public area associated with the object. This will return nil
// if the context was created via NewLimitedHandleContext or
// NewLimitedResourceContext, or HandleContext.Dispose was called.
Public() *Public
}
// NVIndexContext is a ResourceContext that corresponds to a NV index.
type NVIndexContext interface {
ResourceContext
// Type returns the type of the index
Type() NVType
// SetAttr is called when an attribute is set so that the context
// can update its name.
SetAttr(a NVAttributes)
}
type sessionContextData struct {
Params SessionContextParams
State SessionContextState
}
type publicSized struct {
Data *Public `tpm2:"sized"`
}
type nvPublicSized struct {
Data *NVPublic `tpm2:"sized"`
}
type sessionContextDataSized struct {
Data *sessionContextData `tpm2:"sized"`
}
type handleContextU struct {
Object *publicSized
NV *nvPublicSized
Session *sessionContextDataSized
}
func (d *handleContextU) Select(selector reflect.Value) interface{} {
switch selector.Interface().(Handle).Type() {
case HandleTypePCR, HandleTypePermanent:
return mu.NilUnionValue
case HandleTypeTransient, HandleTypePersistent:
return &d.Object
case HandleTypeNVIndex:
return &d.NV
case HandleTypeHMACSession, HandleTypePolicySession:
return &d.Session
default:
return nil
}
}
type handleContext struct {
H Handle
N Name
Data *handleContextU
}
var _ HandleContext = (*handleContext)(nil)
func (h *handleContext) Handle() Handle {
return h.H
}
func (h *handleContext) Name() Name {
return h.N
}
func (h *handleContext) SerializeToBytes() []byte {
data := mu.MustMarshalToBytes(h)
hash := crypto.SHA256.New()
hash.Write(data)
return mu.MustMarshalToBytes(HashAlgorithmSHA256, hash.Sum(nil), data)
}
func (h *handleContext) SerializeToWriter(w io.Writer) error {
data := mu.MustMarshalToBytes(h)
hash := crypto.SHA256.New()
hash.Write(data)
_, err := mu.MarshalToWriter(w, HashAlgorithmSHA256, hash.Sum(nil), data)
return err
}
func (h *handleContext) Dispose() {
h.H = HandleUnassigned
h.N = nil
h.Data = new(handleContextU)
}
func (h *handleContext) checkValid() error {
switch h.H.Type() {
case HandleTypePCR, HandleTypeNVIndex, HandleTypePermanent, HandleTypeTransient, HandleTypePersistent:
return nil
case HandleTypeHMACSession, HandleTypePolicySession:
data := h.Data.Session.Data
if data == nil {
return nil
}
if !data.Params.HashAlg.Available() {
return errors.New("digest algorithm for session context is not available")
}
switch h.H.Type() {
case HandleTypeHMACSession:
if data.State.NeedsPassword || data.State.NeedsAuthValue {
return errors.New("invalid policy session HMAC type for HMAC session context")
}
case HandleTypePolicySession:
// ok
default:
panic("not reached")
}
return nil
default:
// shouldn't happen because it should have failed to unmarshal
panic("invalid context type")
}
}
func newLimitedHandleContext(handle Handle) HandleContext {
switch handle.Type() {
case HandleTypePCR, HandleTypePermanent:
return newPermanentContext(handle)
case HandleTypeNVIndex:
name := make(Name, binary.Size(Handle(0)))
binary.BigEndian.PutUint32(name, uint32(handle))
return newNVIndexContext(handle, name, nil)
case HandleTypeHMACSession, HandleTypePolicySession:
return newSessionContext(handle, nil)
case HandleTypeTransient, HandleTypePersistent:
name := make(Name, binary.Size(Handle(0)))
binary.BigEndian.PutUint32(name, uint32(handle))
return newObjectContext(handle, name, nil)
default:
panic("invalid handle type")
}
}
type resourceContext struct {
handleContext
authValue []byte
}
func newLimitedResourceContext(handle Handle, name Name) ResourceContext {
switch handle.Type() {
case HandleTypeNVIndex:
return newNVIndexContext(handle, name, nil)
case HandleTypeTransient, HandleTypePersistent:
return newObjectContext(handle, name, nil)
default:
panic("invalid handle type")
}
}
var _ ResourceContext = (*resourceContext)(nil)
func (r *resourceContext) SetAuthValue(authValue []byte) {
r.authValue = authValue
}
func (r *resourceContext) Dispose() {
r.authValue = nil
r.handleContext.Dispose()
}
func (r *resourceContext) AuthValue() []byte {
return bytes.TrimRight(r.authValue, "\x00")
}
type permanentContext struct {
resourceContext
}
func newPermanentContext(handle Handle) *permanentContext {
switch handle.Type() {
case HandleTypePCR, HandleTypePermanent:
// ok
default:
panic("invalid handle type")
}
name := make(Name, binary.Size(Handle(0)))
binary.BigEndian.PutUint32(name, uint32(handle))
return &permanentContext{
resourceContext: resourceContext{
handleContext: handleContext{
H: handle,
N: name}}}
}
var _ ResourceContext = (*permanentContext)(nil)
func (r *permanentContext) Dispose() {}
func nullResource() ResourceContext {
return newPermanentContext(HandleNull)
}
type objectContext struct {
resourceContext
}
func newObjectContext(handle Handle, name Name, public *Public) *objectContext {
switch handle.Type() {
case HandleTypeTransient, HandleTypePersistent:
// ok
default:
panic("invalid handle type")
}
return &objectContext{
resourceContext: resourceContext{
handleContext: handleContext{
H: handle,
N: name,
Data: &handleContextU{Object: &publicSized{Data: public}}}}}
}
func (t *TPMContext) newObjectContextFromTPM(context HandleContext, sessions ...SessionContext) (ResourceContext, error) {
pub, name, _, err := t.ReadPublic(context, sessions...)
if err != nil {
return nil, err
}
if pub.NameAlg.Available() && !pub.compareName(name) {
return nil, &InvalidResponseError{CommandReadPublic, errors.New("name and public area returned from TPM don't match")}
}
return newObjectContext(context.Handle(), name, pub), nil
}
var _ ObjectContext = (*objectContext)(nil)
func (r *objectContext) Public() *Public {
if r.Data.Object == nil {
// This context was disposed.
return nil
}
return r.Data.Object.Data
}
type nvIndexContext struct {
resourceContext
}
func newNVIndexContext(handle Handle, name Name, public *NVPublic) *nvIndexContext {
switch handle.Type() {
case HandleTypeNVIndex:
// ok
default:
panic("invalid handle type")
}
return &nvIndexContext{
resourceContext: resourceContext{
handleContext: handleContext{
H: handle,
N: name,
Data: &handleContextU{NV: &nvPublicSized{Data: public}}}}}
}
func (t *TPMContext) newNVIndexContextFromTPM(context HandleContext, sessions ...SessionContext) (ResourceContext, error) {
pub, name, err := t.NVReadPublic(context, sessions...)
if err != nil {
return nil, err
}
if pub.NameAlg.Available() && !pub.compareName(name) {
return nil, &InvalidResponseError{CommandNVReadPublic, errors.New("name and public area returned from TPM don't match")}
}
if pub.Index != context.Handle() {
return nil, &InvalidResponseError{CommandNVReadPublic, errors.New("unexpected index in public area")}
}
return newNVIndexContext(context.Handle(), name, pub), nil
}
var _ NVIndexContext = (*nvIndexContext)(nil)
func (r *nvIndexContext) Type() NVType {
if r.Data.NV == nil || r.Data.NV.Data == nil {
// This context was disposed or is limited
return 0
}
return r.Data.NV.Data.Attrs.Type()
}
func (r *nvIndexContext) SetAttr(a NVAttributes) {
if r.Data.NV == nil || r.Data.NV.Data == nil {
// This context was disposed or is limited
return
}
r.Data.NV.Data.Attrs |= a
r.N = r.Data.NV.Data.Name()
}
type sessionContext struct {
*handleContext
attrs SessionAttributes
}
func newSessionContext(handle Handle, data *sessionContextData) *sessionContext {
switch handle.Type() {
case HandleTypeHMACSession, HandleTypePolicySession:
// ok
default:
if handle != HandlePW {
panic("invalid handle type")
}
}
name := make(Name, binary.Size(Handle(0)))
binary.BigEndian.PutUint32(name, uint32(handle))
return &sessionContext{
handleContext: &handleContext{
H: handle,
N: name,
Data: &handleContextU{Session: &sessionContextDataSized{Data: data}}}}
}
var _ SessionContext = (*sessionContext)(nil)
func (r *sessionContext) Available() bool {
return r.Data() != nil
}
func (r *sessionContext) Params() SessionContextParams {
d := r.Data()
if d == nil {
return SessionContextParams{
HashAlg: HashAlgorithmNull,
Symmetric: SymDef{Algorithm: SymAlgorithmNull},
}
}
return d.Params
}
func (r *sessionContext) State() *SessionContextState {
d := r.Data()
if d == nil {
return nil
}
return &d.State
}
func (r *sessionContext) HashAlg() HashAlgorithmId {
return r.Params().HashAlg
}
func (r *sessionContext) NonceTPM() Nonce {
state := r.State()
if state == nil {
return nil
}
return state.NonceTPM
}
func (r *sessionContext) IsAudit() bool {
state := r.State()
if state == nil {
return false
}
return state.IsAudit
}
func (r *sessionContext) IsExclusive() bool {
state := r.State()
if state == nil {
return false
}
return state.IsExclusive
}
func (r *sessionContext) Attrs() SessionAttributes {
attrs := r.attrs
if attrs&AttrAuditExclusive > 0 {
attrs |= AttrAudit
}
if attrs&AttrAuditReset > 0 {
attrs |= AttrAudit
}
return attrs
}
func (r *sessionContext) SetAttrs(attrs SessionAttributes) {
r.attrs = attrs
}
func (r *sessionContext) WithAttrs(attrs SessionAttributes) SessionContext {
return &sessionContext{handleContext: r.handleContext, attrs: attrs}
}
func (r *sessionContext) IncludeAttrs(attrs SessionAttributes) SessionContext {
return &sessionContext{handleContext: r.handleContext, attrs: r.attrs | attrs}
}
func (r *sessionContext) ExcludeAttrs(attrs SessionAttributes) SessionContext {
return &sessionContext{handleContext: r.handleContext, attrs: r.attrs &^ attrs}
}
func (r *sessionContext) Data() *sessionContextData {
if r.handleContext.Data.Session == nil {
// This handle context was disposed.
return nil
}
return r.handleContext.Data.Session.Data
}
func pwSession() SessionContext {
return newSessionContext(HandlePW, &sessionContextData{
Params: SessionContextParams{
HashAlg: HashAlgorithmNull,
Symmetric: SymDef{Algorithm: SymAlgorithmNull},
},
}).WithAttrs(AttrContinueSession)
}
func (t *TPMContext) newResourceContextFromTPM(handle HandleContext, sessions ...SessionContext) (rc ResourceContext, err error) {
switch handle.Handle().Type() {
case HandleTypeNVIndex:
rc, err = t.newNVIndexContextFromTPM(handle, sessions...)
case HandleTypeTransient, HandleTypePersistent:
rc, err = t.newObjectContextFromTPM(handle, sessions...)
default:
panic("invalid handle type")
}
switch {
case IsTPMWarning(err, WarningReferenceH0, AnyCommandCode):
return nil, ResourceUnavailableError{handle.Handle()}
case IsTPMHandleError(err, ErrorHandle, AnyCommandCode, AnyHandleIndex):
return nil, ResourceUnavailableError{handle.Handle()}
case err != nil:
return nil, err
}
return rc, nil
}
// NewResourceContext creates and returns a new ResourceContext for the specified handle. It will
// execute a command to read the public area from the TPM in order to initialize state that
// is maintained on the host side. A [ResourceUnavailableError] error will be returned if the
// specified handle references a resource that doesn't exist.
//
// The public area and name returned from the TPM are checked for consistency as long as the
// corresponding name algorithm is linked into the current binary.
//
// If any sessions are supplied, the public area is read from the TPM twice. The second time uses
// the supplied sessions.
//
// This function will panic if handle doesn't correspond to a NV index, transient object or
// persistent object.
//
// If subsequent use of the returned ResourceContext requires knowledge of the authorization value
// of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
func (t *TPMContext) NewResourceContext(handle Handle, sessions ...SessionContext) (ResourceContext, error) {
rc, err := t.newResourceContextFromTPM(newLimitedHandleContext(handle))
if err != nil {
return nil, err
}
if len(sessions) == 0 {
return rc, nil
}
return t.newResourceContextFromTPM(rc, sessions...)
}
// CreateResourceContextFromTPM creates and returns a new ResourceContext for the specified handle.
// It will execute a command to read the public area from the TPM in order to initialize state that
// is maintained on the host side. A [ResourceUnavailableError] error will be returned if the
// specified handle references a resource that doesn't exist.
//
// The public area and name returned from the TPM are checked for consistency as long as the
// corresponding name algorithm is linked into the current binary.
//
// If any sessions are supplied, the public area is read from the TPM twice. The second time uses
// the supplied sessions.
//
// This function will panic if handle doesn't correspond to a NV index, transient object or
// persistent object.
//
// If subsequent use of the returned ResourceContext requires knowledge of the authorization value
// of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
//
// Deprecated: Use [TPMContext.NewResourceContext] instead.
func (t *TPMContext) CreateResourceContextFromTPM(handle Handle, sessions ...SessionContext) (ResourceContext, error) {
return t.NewResourceContext(handle, sessions...)
}
// NewLimitedHandleContext creates a new HandleContext for the specified handle. The returned
// HandleContext can not be used in any commands other than [TPMContext.FlushContext],
// [TPMContext.ReadPublic] or [TPMContext.NVReadPublic], and it cannot be used with any sessions.
//
// This function will panic if handle doesn't correspond to a session, transient or persistent
// object, or NV index.
func NewLimitedHandleContext(handle Handle) HandleContext {
switch handle.Type() {
case HandleTypeNVIndex, HandleTypeHMACSession, HandleTypePolicySession, HandleTypeTransient, HandleTypePersistent:
return newLimitedHandleContext(handle)
default:
panic("invalid handle type")
}
}
// CreatePartialHandleContext creates a new HandleContext for the specified handle. The returned
// HandleContext is partial and cannot be used in any command other than [TPMContext.FlushContext],
// [TPMContext.ReadPublic] or [TPMContext.NVReadPublic], and it cannot be used with any sessions.
//
// This function will panic if handle doesn't correspond to a session, transient or persistent
// object, or NV index.
//
// Deprecated: Use [NewLimitedHandleContext].
func CreatePartialHandleContext(handle Handle) HandleContext {
return NewLimitedHandleContext(handle)
}
// GetPermanentContext returns a ResourceContext for the specified permanent handle or PCR handle.
//
// This function will panic if handle does not correspond to a permanent or PCR handle.
//
// If subsequent use of the returned ResourceContext requires knowledge of the authorization value
// of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
func (t *TPMContext) GetPermanentContext(handle Handle) ResourceContext {
switch handle.Type() {
case HandleTypePermanent, HandleTypePCR:
if rc, exists := t.permanentResources[handle]; exists {
return rc
}
rc := newPermanentContext(handle)
t.permanentResources[handle] = rc
return rc
default:
panic("invalid handle type")
}
}
// OwnerHandleContext returns the ResouceContext corresponding to the owner hiearchy.
func (t *TPMContext) OwnerHandleContext() ResourceContext {
return t.GetPermanentContext(HandleOwner)
}
// NulHandleContext returns the ResourceContext corresponding to the null hiearchy.
func (t *TPMContext) NullHandleContext() ResourceContext {
return t.GetPermanentContext(HandleNull)
}
// LockoutHandleContext returns the ResourceContext corresponding to the lockout hiearchy.
func (t *TPMContext) LockoutHandleContext() ResourceContext {
return t.GetPermanentContext(HandleLockout)
}
// EndorsementHandleContext returns the ResourceContext corresponding to the endorsement hiearchy.
func (t *TPMContext) EndorsementHandleContext() ResourceContext {
return t.GetPermanentContext(HandleEndorsement)
}
// PlatformHandleContext returns the ResourceContext corresponding to the platform hiearchy.
func (t *TPMContext) PlatformHandleContext() ResourceContext {
return t.GetPermanentContext(HandlePlatform)
}
// PlatformNVHandleContext returns the ResourceContext corresponding to the platform hiearchy.
func (t *TPMContext) PlatformNVHandleContext() ResourceContext {
return t.GetPermanentContext(HandlePlatformNV)
}
// PCRHandleContext returns the ResourceContext corresponding to the PCR at the specified index.
// It will panic if pcr is not a valid PCR index.
func (t *TPMContext) PCRHandleContext(pcr int) ResourceContext {
h := Handle(pcr)
if h.Type() != HandleTypePCR {
panic("invalid PCR index")
}
return t.GetPermanentContext(h)
}
// NewHandleContextFromReader returns a new HandleContext created from the serialized data read
// from the supplied io.Reader. This should contain data that was previously created by
// [HandleContext].SerializeToBytes or [HandleContext].SerializeToWriter.
//
// If the supplied data corresponds to a session then a [SessionContext] will be returned, else a
// [ResourceContext] will be returned.
//
// If a ResourceContext is returned and subsequent use of it requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
func NewHandleContextFromReader(r io.Reader) (HandleContext, error) {
var integrityAlg HashAlgorithmId
var integrity []byte
var b []byte
if _, err := mu.UnmarshalFromReader(r, &integrityAlg, &integrity, &b); err != nil {
return nil, fmt.Errorf("cannot unpack context blob and checksum: %w", err)
}
if !integrityAlg.Available() {
return nil, errors.New("invalid checksum algorithm")
}
h := integrityAlg.NewHash()
h.Write(b)
if !bytes.Equal(h.Sum(nil), integrity) {
return nil, errors.New("invalid checksum")
}
var data *handleContext
n, err := mu.UnmarshalFromBytes(b, &data)
if err != nil {
return nil, fmt.Errorf("cannot unmarshal context data: %w", err)
}
if n < len(b) {
return nil, errors.New("context blob contains trailing bytes")
}
switch data.Handle().Type() {
case HandleTypePCR, HandleTypePermanent:
return nil, errors.New("cannot create a permanent context from serialized data")
}
if err := data.checkValid(); err != nil {
return nil, err
}
var hc HandleContext
switch data.Handle().Type() {
case HandleTypeNVIndex:
hc = &nvIndexContext{resourceContext: resourceContext{handleContext: *data}}
case HandleTypeHMACSession, HandleTypePolicySession:
if data.Data.Session.Data != nil {
data.Data.Session.Data.State.IsExclusive = false
}
hc = &sessionContext{handleContext: data}
case HandleTypeTransient, HandleTypePersistent:
hc = &objectContext{resourceContext: resourceContext{handleContext: *data}}
default:
panic("not reached")
}
return hc, nil
}
// CreateHandleContextFromReader returns a new HandleContext created from the serialized data read
// from the supplied io.Reader. This should contain data that was previously created by
// [HandleContext].SerializeToBytes or [HandleContext].SerializeToWriter.
//
// If the supplied data corresponds to a session then a [SessionContext] will be returned, else a
// [ResourceContext] will be returned.
//
// If a ResourceContext is returned and subsequent use of it requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
//
// Deprecated: Use [NewHandleContextFromReader].
func CreateHandleContextFromReader(r io.Reader) (HandleContext, error) {
return NewHandleContextFromReader(r)
}
// NewHandleContextFromBytes returns a new HandleContext created from the serialized data read
// from the supplied byte slice. This should contain data that was previously created by
// [HandleContext].SerializeToBytes or [HandleContext].SerializeToWriter.
//
// If the supplied data corresponds to a session then a [SessionContext] will be returned, else a
// [ResourceContext] will be returned.
//
// If a ResourceContext is returned and subsequent use of it requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
func NewHandleContextFromBytes(b []byte) (HandleContext, int, error) {
buf := bytes.NewReader(b)
rc, err := NewHandleContextFromReader(buf)
if err != nil {
return nil, 0, err
}
return rc, len(b) - buf.Len(), nil
}
// NewLimitedResourceContext creates a new ResourceContext with the specified handle and name. The
// returned ResourceContext has limited functionality - eg, it cannot be used in functions that
// require knowledge of the public area associated with the resource (such as
// [TPMContext.StartAuthSession] and some NV functions).
//
// This function will panic if handle doesn't correspond to a transient or persistent object, or an
// NV index.
func NewLimitedResourceContext(handle Handle, name Name) ResourceContext {
switch handle.Type() {
case HandleTypeNVIndex, HandleTypeTransient, HandleTypePersistent:
return newLimitedResourceContext(handle, name)
default:
panic("invalid handle type")
}
}
// CreateHandleContextFromBytes returns a new HandleContext created from the serialized data read
// from the supplied byte slice. This should contain data that was previously created by
// [HandleContext].SerializeToBytes or [HandleContext].SerializeToWriter.
//
// If the supplied data corresponds to a session then a [SessionContext] will be returned, else a
// [ResourceContext] will be returned.
//
// If a ResourceContext is returned and subsequent use of it requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
//
// Deprecated: Use [NewHandleContextFromBytes].
func CreateHandleContextFromBytes(b []byte) (HandleContext, int, error) {
return NewHandleContextFromBytes(b)
}
// NewNVIndexResourceContextFromPub returns a new ResourceContext created from the provided
// public area. If subsequent use of the returned ResourceContext requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
//
// This requires that the associated name algorithm is linked into the current binary.
func NewNVIndexResourceContextFromPub(pub *NVPublic) (ResourceContext, error) {
name, err := pub.ComputeName()
if err != nil {
return nil, fmt.Errorf("cannot compute name from public area: %v", err)
}
return newNVIndexContext(pub.Index, name, pub), nil
}
// NewNVIndexResourceContext returns a new ResourceContext created from the provided public area
// and associated name. This is useful for creating a ResourceContext for an object that uses a
// name algorithm that is not available. If subsequent use of the returned ResourceContext requires
// knowledge of the authorization value of the corresponding TPM resource, this should be provided
// by calling [ResourceContext].SetAuthValue.
func NewNVIndexResourceContext(pub *NVPublic, name Name) ResourceContext {
return newNVIndexContext(pub.Index, name, pub)
}
// CreateNVIndexResourceContextFromPublic returns a new ResourceContext created from the provided
// public area. If subsequent use of the returned ResourceContext requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
//
// This requires that the associated name algorithm is linked into the current binary.
//
// Deprecated: Use [NewNVIndexResourceContextFromPub].
func CreateNVIndexResourceContextFromPublic(pub *NVPublic) (ResourceContext, error) {
return NewNVIndexResourceContextFromPub(pub)
}
// NewObjectResourceContextFromPub returns a new ResourceContext created from the provided
// public area. If subsequent use of the returned ResourceContext requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
//
// This requires that the associated name algorithm is linked into the current binary.
func NewObjectResourceContextFromPub(handle Handle, pub *Public) (ResourceContext, error) {
switch handle.Type() {
case HandleTypeTransient, HandleTypePersistent:
name, err := pub.ComputeName()
if err != nil {
return nil, fmt.Errorf("cannot compute name from public area: %v", err)
}
return newObjectContext(handle, name, pub), nil
default:
return nil, errors.New("invalid handle type")
}
}
// NewObjectResourceContext returns a new ResourceContext created from the provided public area and
// associated name. This is useful for creating a ResourceContext for an object that uses a name
// algorithm that is not available. If subsequent use of the returned ResourceContext requires
// knowledge of the authorization value of the corresponding TPM resource, this should be provided
// by calling [ResourceContext].SetAuthValue.
//
// This will panic if the handle type is not [HandleTypeTransient] or [HandleTypePersistent].
func NewObjectResourceContext(handle Handle, pub *Public, name Name) ResourceContext {
switch handle.Type() {
case HandleTypeTransient, HandleTypePersistent:
return newObjectContext(handle, name, pub)
default:
panic("invalid handle type")
}
}
// CreateObjectResourceContextFromPublic returns a new ResourceContext created from the provided
// public area. If subsequent use of the returned ResourceContext requires knowledge of the
// authorization value of the corresponding TPM resource, this should be provided by calling
// [ResourceContext].SetAuthValue.
//
// This requires that the associated name algorithm is linked into the current binary.
//
// Deprecated: Use [NewObjectResourceContextFromPub].
func CreateObjectResourceContextFromPublic(handle Handle, pub *Public) (ResourceContext, error) {
return NewObjectResourceContextFromPub(handle, pub)
}