Debian Codegraph @

tpm2/reflect.go

raw
1 // Package tpm2 provides 1:1 mapping to TPM 2.0 APIs.
2 package tpm2
3
4 import (
5 "bytes"
6 "encoding/binary"
7 "fmt"
8 "math"
9 "reflect"
10 "strconv"
11 "strings"
12
13 "github.com/google/go-tpm/tpm2/transport"
14 )
15
16 const (
17 // Chosen based on MAX_DIGEST_BUFFER, the length of the longest
18 // reasonable list returned by the reference implementation.
19 // The maxListLength must be greater than MAX_CONTEXT_SIZE = 1344,
20 // in order to allow for the unmarshalling of Context.
21 maxListLength uint32 = 4096
22 )
23
24 // execute sends the provided command and returns the TPM's response.
25 func execute[R any](t transport.TPM, cmd Command[R, *R], rsp *R, extraSess ...Session) error {
26 cc := cmd.Command()
27 sess, err := cmdAuths(cmd)
28 if err != nil {
29 return err
30 }
31 sess = append(sess, extraSess...)
32 if len(sess) > 3 {
33 return fmt.Errorf("too many sessions: %v", len(sess))
34 }
35 hasSessions := len(sess) > 0
36 // Initialize the sessions, if needed
37 for i, s := range sess {
38 if err := s.Init(t); err != nil {
39 return fmt.Errorf("initializing session %d: %w", i, err)
40 }
41 if err := s.NewNonceCaller(); err != nil {
42 return err
43 }
44 }
45 handles, err := cmdHandles(cmd)
46 if err != nil {
47 return err
48 }
49 parms, err := cmdParameters(cmd, sess)
50 if err != nil {
51 return err
52 }
53 var names []TPM2BName
54 var sessions []byte
55 if hasSessions {
56 var err error
57 names, err = cmdNames(cmd)
58 if err != nil {
59 return err
60 }
61 sessions, err = cmdSessions(sess, cc, names, parms)
62 if err != nil {
63 return err
64 }
65 }
66 hdr := cmdHeader(hasSessions, 10 /* size of command header */ +len(handles)+len(sessions)+len(parms), cc)
67 command := append(hdr, handles...)
68 command = append(command, sessions...)
69 command = append(command, parms...)
70
71 // Send the command via the transport.
72 response, err := t.Send(command)
73 if err != nil {
74 return err
75 }
76
77 // Parse the command tpm2ly into the response structure.
78 rspBuf := bytes.NewBuffer(response)
79 err = rspHeader(rspBuf)
80 if err != nil {
81 var bonusErrs []string
82 // Emergency cleanup, then return.
83 for _, s := range sess {
84 if err := s.CleanupFailure(t); err != nil {
85 bonusErrs = append(bonusErrs, err.Error())
86 }
87 }
88 if len(bonusErrs) != 0 {
89 return fmt.Errorf("%w - additional errors encountered during cleanup: %v", err, strings.Join(bonusErrs, ", "))
90 }
91 return err
92 }
93 err = rspHandles(rspBuf, rsp)
94 if err != nil {
95 return err
96 }
97 rspParms, err := rspParametersArea(hasSessions, rspBuf)
98 if err != nil {
99 return err
100 }
101 if hasSessions {
102 // We don't need the TPM RC here because we would have errored
103 // out from rspHeader
104 // TODO: Authenticate the error code with sessions, if desired.
105 err = rspSessions(rspBuf, TPMRCSuccess, cc, names, rspParms, sess)
106 if err != nil {
107 return err
108 }
109 }
110 err = rspParameters(rspParms, sess, rsp)
111 if err != nil {
112 return err
113 }
114
115 return nil
116 }
117
118 func isMarshalledByReflection(v reflect.Value) bool {
119 var mbr marshallableByReflection
120 if v.Type().AssignableTo(reflect.TypeOf(&mbr).Elem()) {
121 return true
122 }
123 // basic types are also marshalled by reflection, as are empty structs
124 switch v.Kind() {
125 case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Array, reflect.Slice, reflect.Ptr:
126 return true
127 case reflect.Struct:
128 if v.NumField() == 0 {
129 return true
130 }
131 }
132 return false
133 }
134
135 // marshal will serialize the given value, appending onto the given buffer.
136 // Returns an error if the value is not marshallable.
137 func marshal(buf *bytes.Buffer, v reflect.Value) error {
138 // If the type is not marshalled by reflection, try to call the custom marshal method.
139 if !isMarshalledByReflection(v) {
140 u, ok := v.Interface().(Marshallable)
141 if ok {
142 u.marshal(buf)
143 return nil
144 }
145 if v.CanAddr() {
146 // Maybe we got an addressable value whose pointer implements Marshallable
147 pu, ok := v.Addr().Interface().(Marshallable)
148 if ok {
149 pu.marshal(buf)
150 return nil
151 }
152 }
153 return fmt.Errorf("can't marshal: type %v does not implement Marshallable or marshallableByReflection", v.Type().Name())
154 }
155
156 // Otherwise, use reflection.
157 switch v.Kind() {
158 case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
159 return marshalNumeric(buf, v)
160 case reflect.Array, reflect.Slice:
161 return marshalArray(buf, v)
162 case reflect.Struct:
163 return marshalStruct(buf, v)
164 case reflect.Ptr:
165 return marshal(buf, v.Elem())
166 case reflect.Interface:
167 // Special case: there are very few TPM types which, for TPM spec
168 // backwards-compatibility reasons, are implemented as Go interfaces
169 // so that callers can ergonomically satisfy cases where the TPM spec
170 // allows a parameter to literally be one of a couple of types.
171 // In a few of these cases, we want the caller to be able to sensibly
172 // omit the data, and fill in reasonable defaults.
173 // These cases are enumerated here.
174 if v.IsNil() {
175 switch v.Type().Name() {
176 case "TPMUSensitiveCreate":
177 return marshal(buf, reflect.ValueOf(TPM2BSensitiveData{}))
178 default:
179 return fmt.Errorf("missing required value for %v interface", v.Type().Name())
180 }
181 }
182 return marshal(buf, v.Elem())
183 default:
184 return fmt.Errorf("not marshallable: %#v", v)
185 }
186 }
187
188 // marshalOptional will serialize the given value, appending onto the given
189 // buffer.
190 // Special case: Part 3 specifies some input/output
191 // parameters as "optional", which means that they are
192 // sized fields that can be zero-length, even if the
193 // enclosed type has no legal empty serialization.
194 // When nil, marshal the zero size.
195 // Returns an error if the value is not marshallable.
196 func marshalOptional(buf *bytes.Buffer, v reflect.Value) error {
197 if v.Kind() == reflect.Ptr && v.IsNil() {
198 return marshalArray(buf, reflect.ValueOf([2]byte{}))
199 }
200 return marshal(buf, v)
201 }
202
203 func marshalNumeric(buf *bytes.Buffer, v reflect.Value) error {
204 return binary.Write(buf, binary.BigEndian, v.Interface())
205 }
206
207 func marshalArray(buf *bytes.Buffer, v reflect.Value) error {
208 for i := 0; i < v.Len(); i++ {
209 if err := marshal(buf, v.Index(i)); err != nil {
210 return fmt.Errorf("marshalling element %d of %v: %v", i, v.Type(), err)
211 }
212 }
213 return nil
214 }
215
216 // Marshals the members of the struct, handling sized and bitwise fields.
217 func marshalStruct(buf *bytes.Buffer, v reflect.Value) error {
218 // Check if this is a bitwise-defined structure. This requires all the
219 // members to be bitwise-defined.
220 numBitwise := 0
221 numChecked := 0
222 for i := 0; i < v.NumField(); i++ {
223 // Ignore embedded Bitfield hints.
224 if !v.Type().Field(i).IsExported() {
225 //if _, isBitfield := v.Field(i).Interface().(TPMABitfield); isBitfield {
226 continue
227 }
228 thisBitwise := hasTag(v.Type().Field(i), "bit")
229 if thisBitwise {
230 numBitwise++
231 if hasTag(v.Type().Field(i), "sized") || hasTag(v.Type().Field(i), "sized8") {
232 return fmt.Errorf("struct '%v' field '%v' is both bitwise and sized",
233 v.Type().Name(), v.Type().Field(i).Name)
234 }
235 if hasTag(v.Type().Field(i), "tag") {
236 return fmt.Errorf("struct '%v' field '%v' is both bitwise and a tagged union",
237 v.Type().Name(), v.Type().Field(i).Name)
238 }
239 }
240 numChecked++
241 }
242 if numBitwise != numChecked && numBitwise != 0 {
243 return fmt.Errorf("struct '%v' has mixture of bitwise and non-bitwise members", v.Type().Name())
244 }
245 if numBitwise > 0 {
246 return marshalBitwise(buf, v)
247 }
248 // Make a pass to create a map of tag values
249 // UInt64-valued fields with values greater than MaxInt64 cannot be
250 // selectors.
251 possibleSelectors := make(map[string]int64)
252 for i := 0; i < v.NumField(); i++ {
253 // Special case: Treat a zero-valued nullable field as
254 // TPMAlgNull for union selection.
255 // This allows callers to omit uninteresting scheme structures.
256 if v.Field(i).IsZero() && hasTag(v.Type().Field(i), "nullable") {
257 possibleSelectors[v.Type().Field(i).Name] = int64(TPMAlgNull)
258 continue
259 }
260 switch v.Field(i).Kind() {
261 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
262 possibleSelectors[v.Type().Field(i).Name] = v.Field(i).Int()
263 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
264 val := v.Field(i).Uint()
265 if val <= math.MaxInt64 {
266 possibleSelectors[v.Type().Field(i).Name] = int64(val)
267 }
268 }
269 }
270 for i := 0; i < v.NumField(); i++ {
271 if hasTag(v.Type().Field(i), "skip") {
272 continue
273 }
274 list := hasTag(v.Type().Field(i), "list")
275 sized := hasTag(v.Type().Field(i), "sized")
276 sized8 := hasTag(v.Type().Field(i), "sized8")
277 tag, _ := tag(v.Type().Field(i), "tag")
278 // Serialize to a temporary buffer, in case we need to size it
279 // (Better to simplify this complex reflection-based marshalling
280 // code than to save some unnecessary copying before talking to
281 // a low-speed device like a TPM)
282 var res bytes.Buffer
283 if list {
284 binary.Write(&res, binary.BigEndian, uint32(v.Field(i).Len()))
285 }
286 if tag != "" {
287 // Check that the tagged value was present (and numeric
288 // and smaller than MaxInt64)
289 tagValue, ok := possibleSelectors[tag]
290 // Don't marshal anything if the tag value was TPM_ALG_NULL
291 if tagValue == int64(TPMAlgNull) {
292 continue
293 }
294 if !ok {
295 return fmt.Errorf("union tag '%v' for member '%v' of struct '%v' did not reference "+
296 "a numeric field of int64-compatible value",
297 tag, v.Type().Field(i).Name, v.Type().Name())
298 }
299 if u, ok := v.Field(i).Interface().(marshallableWithHint); ok {
300 v, err := u.get(tagValue)
301 if err != nil {
302 return err
303 }
304 if err := marshal(buf, v); err != nil {
305 return err
306 }
307 }
308 } else if v.Field(i).IsZero() && v.Field(i).Kind() == reflect.Uint32 && hasTag(v.Type().Field(i), "nullable") {
309 // Special case: Anything with the same underlying type
310 // as TPMHandle's zero value is TPM_RH_NULL.
311 // This allows callers to omit uninteresting handles
312 // instead of specifying them as TPM_RH_NULL.
313 if err := binary.Write(&res, binary.BigEndian, uint32(TPMRHNull)); err != nil {
314 return err
315 }
316 } else if v.Field(i).IsZero() && v.Field(i).Kind() == reflect.Uint16 && hasTag(v.Type().Field(i), "nullable") {
317 // Special case: Anything with the same underlying type
318 // as TPMAlg's zero value is TPM_ALG_NULL.
319 // This allows callers to omit uninteresting
320 // algorithms/schemes instead of specifying them as
321 // TPM_ALG_NULL.
322 if err := binary.Write(&res, binary.BigEndian, uint16(TPMAlgNull)); err != nil {
323 return err
324 }
325 } else if hasTag(v.Type().Field(i), "optional") {
326 if err := marshalOptional(&res, v.Field(i)); err != nil {
327 return err
328 }
329 } else {
330 if err := marshal(&res, v.Field(i)); err != nil {
331 return err
332 }
333 }
334 if sized {
335 if err := binary.Write(buf, binary.BigEndian, uint16(res.Len())); err != nil {
336 return err
337 }
338 }
339 if sized8 {
340 if err := binary.Write(buf, binary.BigEndian, uint8(res.Len())); err != nil {
341 return err
342 }
343 }
344 buf.Write(res.Bytes())
345 }
346 return nil
347 }
348
349 // Marshals a bitwise-defined struct.
350 func marshalBitwise(buf *bytes.Buffer, v reflect.Value) error {
351 bg, ok := v.Interface().(BitGetter)
352 if !ok {
353 return fmt.Errorf("'%v' was not a BitGetter", v.Type().Name())
354 }
355 bitArray := make([]bool, bg.Length())
356 // Marshal the defined fields
357 for i := 0; i < v.NumField(); i++ {
358 if !v.Type().Field(i).IsExported() {
359 continue
360 }
361 high, low, _ := rangeTag(v.Type().Field(i), "bit")
362 var buf bytes.Buffer
363 if err := marshal(&buf, v.Field(i)); err != nil {
364 return err
365 }
366 b := buf.Bytes()
367 for i := 0; i <= (high - low); i++ {
368 bitArray[low+i] = ((b[len(b)-i/8-1] >> (i % 8)) & 1) == 1
369 }
370 }
371 // Also marshal the reserved values
372 for i := 0; i < len(bitArray); i++ {
373 if bg.GetReservedBit(i) {
374 bitArray[i] = true
375 }
376 }
377 result := make([]byte, len(bitArray)/8)
378 for i, bit := range bitArray {
379 if bit {
380 result[len(result)-(i/8)-1] |= (1 << (i % 8))
381 }
382 }
383 buf.Write(result)
384 return nil
385 }
386
387 // unmarshal will deserialize the given value from the given buffer.
388 // Returns an error if the buffer does not contain enough data to satisfy the
389 // type.
390 func unmarshal(buf *bytes.Buffer, v reflect.Value) error {
391 // If the type is not marshalled by reflection, try to call the custom unmarshal method.
392 if !isMarshalledByReflection(v) {
393 if u, ok := v.Addr().Interface().(Unmarshallable); ok {
394 return u.unmarshal(buf)
395 }
396 return fmt.Errorf("can't unmarshal: type %v does not implement Unmarshallable or marshallableByReflection", v.Type().Name())
397 }
398
399 switch v.Kind() {
400 case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
401 if err := unmarshalNumeric(buf, v); err != nil {
402 return err
403 }
404 case reflect.Slice:
405 var length uint32
406 // special case for byte slices: just read the entire
407 // rest of the buffer
408 if v.Type().Elem().Kind() == reflect.Uint8 {
409 length = uint32(buf.Len())
410 } else {
411 err := unmarshalNumeric(buf, reflect.ValueOf(&length).Elem())
412 if err != nil {
413 return fmt.Errorf("deserializing size for field of type '%v': %w", v.Type(), err)
414 }
415 }
416 if length > uint32(math.MaxInt32) || length > maxListLength {
417 return fmt.Errorf("could not deserialize slice of length %v", length)
418 }
419 // Go's reflect library doesn't allow increasing the
420 // capacity of an existing slice.
421 // Since we can't be sure that the capacity of the
422 // passed-in value was enough, allocate
423 // a new temporary one of the correct length, unmarshal
424 // to it, and swap it in.
425 tmp := reflect.MakeSlice(v.Type(), int(length), int(length))
426 if err := unmarshalArray(buf, tmp); err != nil {
427 return err
428 }
429 v.Set(tmp)
430 return nil
431 case reflect.Array:
432 return unmarshalArray(buf, v)
433 case reflect.Struct:
434 return unmarshalStruct(buf, v)
435 case reflect.Ptr:
436 return unmarshal(buf, v.Elem())
437 default:
438 return fmt.Errorf("not unmarshallable: %v", v.Type())
439 }
440 return nil
441 }
442
443 func unmarshalNumeric(buf *bytes.Buffer, v reflect.Value) error {
444 return binary.Read(buf, binary.BigEndian, v.Addr().Interface())
445 }
446
447 // For slices, the slice's length must already be set to the expected amount of
448 // data.
449 func unmarshalArray(buf *bytes.Buffer, v reflect.Value) error {
450 for i := 0; i < v.Len(); i++ {
451 if err := unmarshal(buf, v.Index(i)); err != nil {
452 return fmt.Errorf("deserializing slice/array index %v: %w", i, err)
453 }
454 }
455 return nil
456 }
457
458 // unmarshalStructField unmarshals a single field of a struct.
459 // Returns nil if successful or if the field was skipped (e.g., optional field with zero size).
460 func unmarshalStructField(buf *bytes.Buffer, v reflect.Value, i int) error {
461 fieldType := v.Type().Field(i)
462 fieldValue := v.Field(i)
463
464 if hasTag(fieldType, "skip") {
465 return nil
466 }
467
468 list := hasTag(fieldType, "list")
469 if list && (fieldValue.Kind() != reflect.Slice) {
470 return fmt.Errorf("field '%v' of struct '%v' had the 'list' tag but was not a slice",
471 fieldType.Name, v.Type().Name())
472 }
473 // Slices of anything but byte/uint8 must have the 'list' tag.
474 if !list && (fieldValue.Kind() == reflect.Slice) && (fieldType.Type.Elem().Kind() != reflect.Uint8) {
475 return fmt.Errorf("field '%v' of struct '%v' was a slice of non-byte but did not have the 'list' tag",
476 fieldType.Name, v.Type().Name())
477 }
478
479 if hasTag(fieldType, "optional") {
480 // Special case: Part 3 specifies some input/output
481 // parameters as "optional", which means that they are
482 // (2B-) sized fields that can be zero-length, even if the
483 // enclosed type has no legal empty serialization.
484 // When unmarshalling an optional field, test for zero size
485 // and skip if empty.
486 if buf.Len() >= 2 {
487 if binary.BigEndian.Uint16(buf.Bytes()) == 0 {
488 // Advance the buffer past the zero size and skip to the
489 // next field of the struct.
490 buf.Next(2)
491 return nil
492 }
493 // If non-zero size, proceed to unmarshal the contents below.
494 }
495 }
496
497 // Handle nullable fields (for command parameters)
498 if fieldValue.Kind() == reflect.Uint32 && hasTag(fieldType, "nullable") {
499 var val uint32
500 if err := binary.Read(buf, binary.BigEndian, &val); err != nil {
501 return fmt.Errorf("reading nullable uint32 parameter: %w", err)
502 }
503 fieldValue.SetUint(uint64(val))
504 return nil
505 } else if fieldValue.Kind() == reflect.Uint16 && hasTag(fieldType, "nullable") {
506 var val uint16
507 if err := binary.Read(buf, binary.BigEndian, &val); err != nil {
508 return fmt.Errorf("reading nullable uint16 parameter: %w", err)
509 }
510 fieldValue.SetUint(uint64(val))
511 return nil
512 }
513
514 sized := hasTag(fieldType, "sized")
515 sized8 := hasTag(fieldType, "sized8")
516 // If sized, unmarshal a size field first, then restrict
517 // unmarshalling to the given size
518 bufToReadFrom := buf
519 if sized {
520 var expectedSize uint16
521 binary.Read(buf, binary.BigEndian, &expectedSize)
522 sizedBufArray := make([]byte, int(expectedSize))
523 n, err := buf.Read(sizedBufArray)
524 if n != int(expectedSize) {
525 return fmt.Errorf("ran out of data reading sized parameter '%v' inside struct of type '%v'",
526 fieldType.Name, v.Type().Name())
527 }
528 if err != nil {
529 return fmt.Errorf("error reading data for parameter '%v' inside struct of type '%v'",
530 fieldType.Name, v.Type().Name())
531 }
532 bufToReadFrom = bytes.NewBuffer(sizedBufArray)
533 }
534 if sized8 {
535 var expectedSize uint8
536 binary.Read(buf, binary.BigEndian, &expectedSize)
537 sizedBufArray := make([]byte, int(expectedSize))
538 n, err := buf.Read(sizedBufArray)
539 if n != int(expectedSize) {
540 return fmt.Errorf("ran out of data reading sized parameter '%v' inside struct of type '%v'",
541 fieldType.Name, v.Type().Name())
542 }
543 if err != nil {
544 return fmt.Errorf("error reading data for parameter '%v' inside struct of type '%v'",
545 fieldType.Name, v.Type().Name())
546 }
547 bufToReadFrom = bytes.NewBuffer(sizedBufArray)
548 }
549
550 tagName, _ := tag(fieldType, "tag")
551 if tagName != "" {
552 // Make a pass to create a map of tag values
553 // UInt64-valued fields with values greater than
554 // MaxInt64 cannot be selectors.
555 possibleSelectors := make(map[string]int64)
556 for j := 0; j < v.NumField(); j++ {
557 switch v.Field(j).Kind() {
558 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
559 possibleSelectors[v.Type().Field(j).Name] = v.Field(j).Int()
560 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
561 val := v.Field(j).Uint()
562 if val <= math.MaxInt64 {
563 possibleSelectors[v.Type().Field(j).Name] = int64(val)
564 }
565 }
566 }
567 // Check that the tagged value was present (and numeric
568 // and smaller than MaxInt64)
569 tagValue, ok := possibleSelectors[tagName]
570 // Don't marshal anything if the tag value was TPM_ALG_NULL
571 if tagValue == int64(TPMAlgNull) {
572 return nil
573 }
574 if !ok {
575 return fmt.Errorf("union tag '%v' for member '%v' of struct '%v' did not reference "+
576 "a numeric field of in64-compatible value",
577 tagName, fieldType.Name, v.Type().Name())
578 }
579 var uwh unmarshallableWithHint
580 if fieldValue.CanAddr() && fieldValue.Addr().Type().AssignableTo(reflect.TypeOf(&uwh).Elem()) {
581 u := fieldValue.Addr().Interface().(unmarshallableWithHint)
582 contents, err := u.create(tagValue)
583 if err != nil {
584 return fmt.Errorf("unmarshalling field %v of struct of type '%v', %w", i, v.Type(), err)
585 }
586 err = unmarshal(buf, contents)
587 if err != nil {
588 return fmt.Errorf("unmarshalling field %v of struct of type '%v', %w", i, v.Type(), err)
589 }
590 } else if fieldValue.Type().AssignableTo(reflect.TypeOf(&uwh).Elem()) {
591 u := fieldValue.Interface().(unmarshallableWithHint)
592 contents, err := u.create(tagValue)
593 if err != nil {
594 return fmt.Errorf("unmarshalling field %v of struct of type '%v', %w", i, v.Type(), err)
595 }
596 err = unmarshal(buf, contents)
597 if err != nil {
598 return fmt.Errorf("unmarshalling field %v of struct of type '%v', %w", i, v.Type(), err)
599 }
600 }
601 } else {
602 if err := unmarshal(bufToReadFrom, fieldValue); err != nil {
603 return fmt.Errorf("unmarshalling field %v of struct of type '%v', %w", i, v.Type(), err)
604 }
605 }
606
607 if sized || sized8 {
608 if bufToReadFrom.Len() != 0 {
609 return fmt.Errorf("extra data at the end of sized parameter '%v' inside struct of type '%v'",
610 fieldType.Name, v.Type().Name())
611 }
612 }
613
614 return nil
615 }
616
617 func unmarshalStruct(buf *bytes.Buffer, v reflect.Value) error {
618 // Check if this is a bitwise-defined structure. This requires all the
619 // exported members to be bitwise-defined.
620 numBitwise := 0
621 numChecked := 0
622 for i := 0; i < v.NumField(); i++ {
623 // Ignore embedded Bitfield hints.
624 // Ignore embedded Bitfield hints.
625 if !v.Type().Field(i).IsExported() {
626 //if _, isBitfield := v.Field(i).Interface().(TPMABitfield); isBitfield {
627 continue
628 }
629 thisBitwise := hasTag(v.Type().Field(i), "bit")
630 if thisBitwise {
631 numBitwise++
632 if hasTag(v.Type().Field(i), "sized") {
633 return fmt.Errorf("struct '%v' field '%v' is both bitwise and sized",
634 v.Type().Name(), v.Type().Field(i).Name)
635 }
636 if hasTag(v.Type().Field(i), "tag") {
637 return fmt.Errorf("struct '%v' field '%v' is both bitwise and a tagged union",
638 v.Type().Name(), v.Type().Field(i).Name)
639 }
640 }
641 numChecked++
642 }
643 if numBitwise != numChecked && numBitwise != 0 {
644 return fmt.Errorf("struct '%v' has mixture of bitwise and non-bitwise members", v.Type().Name())
645 }
646 if numBitwise > 0 {
647 return unmarshalBitwise(buf, v)
648 }
649 for i := range v.NumField() {
650 if err := unmarshalStructField(buf, v, i); err != nil {
651 return err
652 }
653 }
654 return nil
655 }
656
657 // Unmarshals a bitwise-defined struct.
658 func unmarshalBitwise(buf *bytes.Buffer, v reflect.Value) error {
659 bs, ok := v.Addr().Interface().(BitSetter)
660 if !ok {
661 return fmt.Errorf("'%v' was not a BitSetter", v.Addr().Type())
662 }
663 bitArray := make([]bool, bs.Length())
664 // We will read big-endian, starting from the last byte and working our
665 // way down.
666 for i := len(bitArray)/8 - 1; i >= 0; i-- {
667 b, err := buf.ReadByte()
668 if err != nil {
669 return fmt.Errorf("error %d bits into field '%v' of struct '%v': %w",
670 i, v.Type().Field(i).Name, v.Type().Name(), err)
671 }
672 for j := 0; j < 8; j++ {
673 bitArray[8*i+j] = (((b >> j) & 1) == 1)
674 }
675 }
676 // Unmarshal the defined fields and clear the bits from the array as we
677 // read them.
678 for i := 0; i < v.NumField(); i++ {
679 if !v.Type().Field(i).IsExported() {
680 continue
681 }
682 high, low, _ := rangeTag(v.Type().Field(i), "bit")
683 var val uint64
684 for j := 0; j <= high-low; j++ {
685 if bitArray[low+j] {
686 val |= (1 << j)
687 }
688 bitArray[low+j] = false
689 }
690 if v.Field(i).Kind() == reflect.Bool {
691 v.Field(i).SetBool((val & 1) == 1)
692 } else {
693 v.Field(i).SetUint(val)
694 }
695 }
696 // Unmarshal the remaining uncleared bits as reserved bits.
697 for i := 0; i < len(bitArray); i++ {
698 bs.SetReservedBit(i, bitArray[i])
699 }
700 return nil
701 }
702
703 // Looks up the given gotpm tag on a field.
704 // Some tags are settable (with "="). For these, the value is the RHS.
705 // For all others, the value is the empty string.
706 func tag(t reflect.StructField, query string) (string, bool) {
707 allTags, ok := t.Tag.Lookup("gotpm")
708 if !ok {
709 return "", false
710 }
711 tags := strings.Split(allTags, ",")
712 for _, tag := range tags {
713 // Split on the equals sign for settable tags.
714 // If the split returns a slice of length 1, this is an
715 // un-settable tag or an empty tag (which we'll ignore).
716 // If the split returns a slice of length 2, this is a settable
717 // tag.
718 if tag == query {
719 return "", true
720 }
721 if strings.HasPrefix(tag, query+"=") {
722 assignment := strings.SplitN(tag, "=", 2)
723 return assignment[1], true
724 }
725 }
726 return "", false
727 }
728
729 // hasTag looks up to see if the type's gotpm-namespaced tag contains the
730 // given value.
731 // Returns false if there is no gotpm-namespaced tag on the type.
732 func hasTag(t reflect.StructField, query string) bool {
733 _, ok := tag(t, query)
734 return ok
735 }
736
737 // Returns the range on a tag like 4:3 or 4.
738 // If there is no colon, the low and high part of the range are equal.
739 func rangeTag(t reflect.StructField, query string) (int, int, bool) {
740 val, ok := tag(t, query)
741 if !ok {
742 return 0, 0, false
743 }
744 vals := strings.Split(val, ":")
745 high, err := strconv.Atoi(vals[0])
746 if err != nil {
747 return 0, 0, false
748 }
749 low := high
750 if len(vals) > 1 {
751 low, err = strconv.Atoi(vals[1])
752 if err != nil {
753 return 0, 0, false
754 }
755 }
756 if low > high {
757 low, high = high, low
758 }
759 return high, low, true
760 }
761
762 // taggedMembers will return a slice of all the members of the given
763 // structure that contain (or don't contain) the given tag in the "gotpm"
764 // namespace.
765 // Panics if v's Kind is not Struct.
766 func taggedMembers(v reflect.Value, tag string, invert bool) []reflect.Value {
767 var result []reflect.Value
768 t := v.Type()
769
770 for i := 0; i < t.NumField(); i++ {
771 // Add this one to the list if it has the tag and we're not
772 // inverting, or if it doesn't have the tag and we are
773 // inverting.
774 if hasTag(t.Field(i), tag) != invert {
775 result = append(result, v.Field(i))
776 }
777 }
778
779 return result
780 }
781
782 // cmdAuths returns the authorization sessions of the command.
783 func cmdAuths[R any](cmd Command[R, *R]) ([]Session, error) {
784 authHandles := taggedMembers(reflect.ValueOf(cmd), "auth", false)
785 var result []Session
786 for i, authHandle := range authHandles {
787 // TODO: A cleaner way to do this would be to have an interface method that
788 // returns a Session.
789 if h, ok := authHandle.Interface().(AuthHandle); ok {
790 if h.Auth == nil {
791 return nil, fmt.Errorf("missing auth for '%v' parameter",
792 reflect.ValueOf(cmd).Type().Field(i).Name)
793 }
794 result = append(result, h.Auth)
795 } else {
796 result = append(result, PasswordAuth(nil))
797 }
798 }
799
800 return result, nil
801 }
802
803 func asHandle(value reflect.Value) (handle, error) {
804 // Special case: `handle`-typed members.
805 // Since `handle` is an interface, the zero-value is nil.
806 // https://go.dev/ref/spec#Type_assertions in this case will return false.
807 // Similarly, reflect.AssignableTo() will panic.
808 // Workaround: treat any nil interface value annotated as a `handle` as TPMRHNull.
809 var h handle
810 if value.Kind() == reflect.Interface && value.IsNil() {
811 h = TPMRHNull
812 } else {
813 var ok bool
814 h, ok = value.Interface().(handle)
815 if !ok {
816 return nil, fmt.Errorf("value of type %q does not satisfy handle", value.Type())
817 }
818 }
819 return h, nil
820 }
821
822 // cmdHandles returns the handles area of the command.
823 func cmdHandles[R any](cmd Command[R, *R]) ([]byte, error) {
824 handles := taggedMembers(reflect.ValueOf(cmd), "handle", false)
825
826 // Initial capacity is enough to hold 3 handles
827 result := bytes.NewBuffer(make([]byte, 0, 12))
828
829 for _, maybeHandle := range handles {
830 h, err := asHandle(maybeHandle)
831 if err != nil {
832 return nil, fmt.Errorf("invalid 'handle'-tagged member of %q: %v",
833 reflect.TypeOf(cmd), err)
834 }
835 binary.Write(result, binary.BigEndian, h.HandleValue())
836 }
837
838 return result.Bytes(), nil
839 }
840
841 // cmdNames returns the names of the entities referenced by the handles of the command.
842 func cmdNames[R any](cmd Command[R, *R]) ([]TPM2BName, error) {
843 handles := taggedMembers(reflect.ValueOf(cmd), "handle", false)
844 var result []TPM2BName
845 for i, maybeHandle := range handles {
846 h, err := asHandle(maybeHandle)
847 if err != nil {
848 return nil, fmt.Errorf("invalid 'handle'-tagged member of %q: %v",
849 reflect.TypeOf(cmd), err)
850 }
851
852 // Special case: handles with an empty name buffer (anonymous:anon)
853 // See part 1: Architecture, section 32.4.5:
854 // The Name of a sequence object is an Empty Buffer (sized array with no
855 // data; indicated by a size field of zero followed by an array
856 // containing no elements)
857 if hasTag(reflect.ValueOf(cmd).Type().Field(i), "anon") {
858 continue
859 }
860
861 name := h.KnownName()
862 if name == nil {
863 return nil, fmt.Errorf("missing Name for '%v' parameter",
864 reflect.ValueOf(cmd).Type().Field(i).Name)
865 }
866 result = append(result, *name)
867 }
868
869 return result, nil
870 }
871
872 // TODO: Extract the logic of "marshal the Nth field of some struct after the handles"
873 // For now, we duplicate some logic from marshalStruct here.
874 func marshalParameter[R any](buf *bytes.Buffer, cmd Command[R, *R], i int) error {
875 numHandles := len(taggedMembers(reflect.ValueOf(cmd), "handle", false))
876 if numHandles+i >= reflect.TypeOf(cmd).NumField() {
877 return fmt.Errorf("invalid parameter index %v", i)
878 }
879 parm := reflect.ValueOf(cmd).Field(numHandles + i)
880 field := reflect.TypeOf(cmd).Field(numHandles + i)
881 if hasTag(field, "optional") {
882 return marshalOptional(buf, parm)
883 } else if parm.IsZero() && parm.Kind() == reflect.Uint32 && hasTag(field, "nullable") {
884 return marshal(buf, reflect.ValueOf(TPMRHNull))
885 } else if parm.IsZero() && parm.Kind() == reflect.Uint16 && hasTag(field, "nullable") {
886 return marshal(buf, reflect.ValueOf(TPMAlgNull))
887 }
888
889 return marshal(buf, parm)
890 }
891
892 // unmarshalParameter will deserialize the given parameter of the command from the buffer.
893 // Returns an error if the value is not unmarshallable or if there's insufficient data.
894 func unmarshalParameter[C Command[R, *R], R any](buf *bytes.Buffer, cmd *C, i int) error {
895 numHandles := len(taggedMembers(reflect.ValueOf(*cmd), "handle", false))
896 fieldIndex := numHandles + i
897 if fieldIndex >= reflect.TypeOf(*cmd).NumField() {
898 return fmt.Errorf("invalid parameter index %v", i)
899 }
900
901 // Use unmarshalStructField to handle this field with all its tags
902 cmdValue := reflect.ValueOf(cmd).Elem()
903 return unmarshalStructField(buf, cmdValue, fieldIndex)
904 }
905
906 // populateHandlesFromNames populates the handle fields of a command with handles
907 // created from the provided names.
908 //
909 // All handle fields are populated with [UnmarshalledHandle]
910 func populateHandlesFromNames[C Command[R, *R], R any](cmd *C, names []TPM2BName) error {
911 cmdValue := reflect.ValueOf(cmd).Elem()
912 cmdType := reflect.TypeOf(*cmd)
913
914 nameIdx := 0
915 for i := 0; i < cmdType.NumField(); i++ {
916 field := cmdType.Field(i)
917
918 if !hasTag(field, "handle") {
919 break
920 }
921
922 // Skip anonymous handles
923 if hasTag(field, "anon") {
924 continue
925 }
926
927 if nameIdx >= len(names) {
928 return fmt.Errorf("not enough names for handle field %d", i)
929 }
930
931 handleValue := UnmarshalledHandle{
932 Name: names[nameIdx],
933 }
934
935 cmdValue.Field(i).Set(reflect.ValueOf(handleValue))
936 nameIdx++
937 }
938
939 if nameIdx != len(names) {
940 return fmt.Errorf("name count mismatch: used %d names, got %d", nameIdx, len(names))
941 }
942 return nil
943 }
944
945 // unmarshalCmdParameters unmarshals the parameters area of the command from a buffer.
946 // This is the inverse operation of cmdParameters.
947 // The first parameter may be decrypted by one of the sessions if provided.
948 func unmarshalCmdParameters[C Command[R, *R], R any](buf *bytes.Buffer, cmd *C, sess []Session) error {
949 parms := taggedMembers(reflect.ValueOf(*cmd), "handle", true)
950 if len(parms) == 0 {
951 return nil
952 }
953
954 // Check if we need to decrypt the first parameter
955 decrypted := false
956 for i, s := range sess {
957 if s.IsDecryption() {
958 if decrypted {
959 return fmt.Errorf("too many decrypt sessions")
960 }
961 // Read the first parameter's size (2 bytes for TPM2B)
962 if buf.Len() < 2 {
963 return fmt.Errorf("insufficient data for first parameter size")
964 }
965
966 // Peek at the size to know how much to decrypt
967 var size uint16
968 tempBuf := *buf
969 if err := binary.Read(&tempBuf, binary.BigEndian, &size); err != nil {
970 return fmt.Errorf("reading first parameter size: %w", err)
971 }
972
973 // Read size + content
974 if buf.Len() < int(2+size) {
975 return fmt.Errorf("insufficient data for first parameter")
976 }
977
978 // Extract the parameter bytes (including size prefix)
979 paramBytes := make([]byte, 2+size)
980 if _, err := buf.Read(paramBytes); err != nil {
981 return fmt.Errorf("reading first parameter: %w", err)
982 }
983
984 // Decrypt the content (skip the 2-byte size prefix)
985 if err := s.Decrypt(paramBytes[2:]); err != nil {
986 return fmt.Errorf("decrypting with session %d: %w", i, err)
987 }
988
989 // Now unmarshal the decrypted parameter
990 paramBuf := bytes.NewBuffer(paramBytes)
991 if err := unmarshalParameter(paramBuf, cmd, 0); err != nil {
992 return fmt.Errorf("unmarshalling first parameter: %w", err)
993 }
994
995 decrypted = true
996 break
997 }
998 }
999
1000 // If we didn't decrypt, unmarshal the first parameter normally
1001 if !decrypted {
1002 if err := unmarshalParameter(buf, cmd, 0); err != nil {
1003 return fmt.Errorf("unmarshalling first parameter: %w", err)
1004 }
1005 }
1006
1007 // Unmarshal the rest of the parameters
1008 for i := 1; i < len(parms); i++ {
1009 if err := unmarshalParameter(buf, cmd, i); err != nil {
1010 return fmt.Errorf("unmarshalling parameter %d: %w", i, err)
1011 }
1012 }
1013
1014 return nil
1015 }
1016
1017 // cmdParameters returns the parameters area of the command.
1018 // The first parameter may be encrypted by one of the sessions.
1019 func cmdParameters[R any](cmd Command[R, *R], sess []Session) ([]byte, error) {
1020 parms := taggedMembers(reflect.ValueOf(cmd), "handle", true)
1021 if len(parms) == 0 {
1022 return nil, nil
1023 }
1024
1025 var firstParm bytes.Buffer
1026 if err := marshalParameter(&firstParm, cmd, 0); err != nil {
1027 return nil, err
1028 }
1029 firstParmBytes := firstParm.Bytes()
1030
1031 // Encrypt the first parameter if there are any decryption sessions.
1032 encrypted := false
1033 for i, s := range sess {
1034 if s.IsDecryption() {
1035 if encrypted {
1036 // Only one session may be used for decryption.
1037 return nil, fmt.Errorf("too many decrypt sessions")
1038 }
1039 if len(firstParmBytes) < 2 {
1040 return nil, fmt.Errorf("this command's first parameter is not a tpm2b")
1041 }
1042 err := s.Encrypt(firstParmBytes[2:])
1043 if err != nil {
1044 return nil, fmt.Errorf("encrypting with session %d: %w", i, err)
1045 }
1046 encrypted = true
1047 }
1048 }
1049
1050 var result bytes.Buffer
1051 result.Write(firstParmBytes)
1052 // Write the rest of the parameters normally.
1053 for i := 1; i < len(parms); i++ {
1054 if err := marshalParameter(&result, cmd, i); err != nil {
1055 return nil, err
1056 }
1057 }
1058 return result.Bytes(), nil
1059 }
1060
1061 // cmdSessions returns the authorization area of the command.
1062 func cmdSessions(sess []Session, cc TPMCC, names []TPM2BName, parms []byte) ([]byte, error) {
1063 // There is no authorization area if there are no sessions.
1064 if len(sess) == 0 {
1065 return nil, nil
1066 }
1067 // Find the non-first-session encryption and decryption session
1068 // nonceTPMs, if any.
1069 var encNonceTPM, decNonceTPM []byte
1070 if len(sess) > 0 {
1071 for i := 1; i < len(sess); i++ {
1072 s := sess[i]
1073 if s.IsEncryption() {
1074 if encNonceTPM != nil {
1075 // Only one encrypt session is permitted.
1076 return nil, fmt.Errorf("too many encrypt sessions")
1077 }
1078 encNonceTPM = s.NonceTPM().Buffer
1079 // A session used for both encryption and
1080 // decryption only needs its nonce counted once.
1081 continue
1082 }
1083 if s.IsDecryption() {
1084 if decNonceTPM != nil {
1085 // Only one decrypt session is permitted.
1086 return nil, fmt.Errorf("too many decrypt sessions")
1087 }
1088 decNonceTPM = s.NonceTPM().Buffer
1089 }
1090 }
1091 }
1092
1093 buf := bytes.NewBuffer(make([]byte, 0, 1024))
1094 // Skip space to write the size later
1095 buf.Write(make([]byte, 4))
1096 // Calculate the authorization HMAC for each session
1097 for i, s := range sess {
1098 var addNonces []byte
1099 // Special case: the HMAC on the first authorization session of
1100 // a command also includes any decryption and encryption
1101 // nonceTPMs, too.
1102 if i == 0 {
1103 addNonces = append(addNonces, decNonceTPM...)
1104 addNonces = append(addNonces, encNonceTPM...)
1105 }
1106 auth, err := s.Authorize(cc, parms, addNonces, names, i)
1107 if err != nil {
1108 return nil, fmt.Errorf("session %d: %w", i, err)
1109 }
1110 marshal(buf, reflect.ValueOf(auth).Elem())
1111 }
1112
1113 result := buf.Bytes()
1114 // Write the size
1115 binary.BigEndian.PutUint32(result[0:], uint32(buf.Len()-4))
1116
1117 return result, nil
1118 }
1119
1120 // cmdHeader returns the structured TPM command header.
1121 func cmdHeader(hasSessions bool, length int, cc TPMCC) []byte {
1122 tag := TPMSTNoSessions
1123 if hasSessions {
1124 tag = TPMSTSessions
1125 }
1126 hdr := TPMCmdHeader{
1127 Tag: tag,
1128 Length: uint32(length),
1129 CommandCode: cc,
1130 }
1131 buf := bytes.NewBuffer(make([]byte, 0, 8))
1132 marshal(buf, reflect.ValueOf(hdr))
1133 return buf.Bytes()
1134 }
1135
1136 // rspHeader parses the response header. If the TPM returned an error,
1137 // returns an error here.
1138 // rsp is updated to point to the rest of the response after the header.
1139 func rspHeader(rsp *bytes.Buffer) error {
1140 var hdr TPMRspHeader
1141 if err := unmarshal(rsp, reflect.ValueOf(&hdr).Elem()); err != nil {
1142 return fmt.Errorf("unmarshalling TPM response: %w", err)
1143 }
1144 if hdr.ResponseCode != TPMRCSuccess {
1145 return hdr.ResponseCode
1146 }
1147 return nil
1148 }
1149
1150 // rspHandles parses the response handles area into the response structure.
1151 // If there is a mismatch between the expected and actual amount of handles,
1152 // returns an error here.
1153 // rsp is updated to point to the rest of the response after the handles.
1154 func rspHandles(rsp *bytes.Buffer, rspStruct any) error {
1155 handles := taggedMembers(reflect.ValueOf(rspStruct).Elem(), "handle", false)
1156 for i, handle := range handles {
1157 if err := unmarshal(rsp, handle); err != nil {
1158 return fmt.Errorf("unmarshalling handle %v: %w", i, err)
1159 }
1160 }
1161 return nil
1162 }
1163
1164 // rspParametersArea fetches, but does not manipulate, the parameters area
1165 // from the response. If there is a mismatch between the response's
1166 // indicated parameters area size and the actual size, returns an error here.
1167 // rsp is updated to point to the rest of the response after the handles.
1168 func rspParametersArea(hasSessions bool, rsp *bytes.Buffer) ([]byte, error) {
1169 var length uint32
1170 if hasSessions {
1171 if err := binary.Read(rsp, binary.BigEndian, &length); err != nil {
1172 return nil, fmt.Errorf("reading length of parameter area: %w", err)
1173 }
1174 } else {
1175 // If there are no sessions, there is no length-of-parameters
1176 // field, because the whole rest of the response is the
1177 // parameters area.
1178 length = uint32(rsp.Len())
1179 }
1180 if length > uint32(rsp.Len()) {
1181 return nil, fmt.Errorf("response indicated %d bytes of parameters but there "+
1182 "were only %d more bytes of response", length, rsp.Len())
1183 }
1184 if length > math.MaxInt32 {
1185 return nil, fmt.Errorf("invalid length of parameter area: %d", length)
1186 }
1187 parms := make([]byte, int(length))
1188 if n, err := rsp.Read(parms); err != nil {
1189 return nil, fmt.Errorf("reading parameter area: %w", err)
1190 } else if n != len(parms) {
1191 return nil, fmt.Errorf("only read %d bytes of parameters, expected %d", n, len(parms))
1192 }
1193 return parms, nil
1194 }
1195
1196 // rspSessions fetches the sessions area of the response and updates all
1197 // the sessions with it. If there is a response validation error, returns
1198 // an error here.
1199 // rsp is updated to point to the rest of the response after the sessions.
1200 func rspSessions(rsp *bytes.Buffer, rc TPMRC, cc TPMCC, names []TPM2BName, parms []byte, sess []Session) error {
1201 for i, s := range sess {
1202 var auth TPMSAuthResponse
1203 if err := unmarshal(rsp, reflect.ValueOf(&auth).Elem()); err != nil {
1204 return fmt.Errorf("reading auth session %d: %w", i, err)
1205 }
1206 if err := s.Validate(rc, cc, parms, names, i, &auth); err != nil {
1207 return fmt.Errorf("validating auth session %d: %w", i, err)
1208 }
1209 }
1210 if rsp.Len() != 0 {
1211 return fmt.Errorf("%d unaccounted-for bytes at the end of the TPM response", rsp.Len())
1212 }
1213 return nil
1214 }
1215
1216 // marshalRspParameters marshals the parameters area of a response.
1217 func marshalRspParameters(rspStruct any, sess []Session) ([]byte, error) {
1218 parameters := taggedMembers(reflect.ValueOf(rspStruct).Elem(), "handle", true)
1219 if len(parameters) == 0 {
1220 return nil, nil
1221 }
1222
1223 var firstParm bytes.Buffer
1224 if err := marshal(&firstParm, parameters[0]); err != nil {
1225 return nil, fmt.Errorf("marshalling first parameter: %w", err)
1226 }
1227 firstParmBytes := firstParm.Bytes()
1228
1229 // Encrypt the first parameter if there are any encryption sessions.
1230 encrypted := false
1231 for i, s := range sess {
1232 if s.IsEncryption() {
1233 if encrypted {
1234 return nil, fmt.Errorf("too many encrypt sessions")
1235 }
1236 if len(firstParmBytes) < 2 {
1237 return nil, fmt.Errorf("first parameter is not a tpm2b")
1238 }
1239 err := s.Encrypt(firstParmBytes[2:])
1240 if err != nil {
1241 return nil, fmt.Errorf("encrypting with session %d: %w", i, err)
1242 }
1243 encrypted = true
1244 }
1245 }
1246
1247 var result bytes.Buffer
1248 result.Write(firstParmBytes)
1249 // Write the rest of the parameters normally.
1250 for i := 1; i < len(parameters); i++ {
1251 if err := marshal(&result, parameters[i]); err != nil {
1252 return nil, fmt.Errorf("marshalling parameter %d: %w", i, err)
1253 }
1254 }
1255 return result.Bytes(), nil
1256 }
1257
1258 // rspParameters decrypts (if needed) the parameters area of the response
1259 // into the response structure. If there is a mismatch between the expected
1260 // and actual response structure, returns an error here.
1261 func rspParameters(parms []byte, sess []Session, rspStruct any) error {
1262 numHandles := len(taggedMembers(reflect.ValueOf(rspStruct).Elem(), "handle", false))
1263
1264 // Use the heuristic of "does interpreting the first 2 bytes of response
1265 // as a length make any sense" to attempt encrypted parameter
1266 // decryption.
1267 // If the command supports parameter encryption, the first parameter is
1268 // a 2B.
1269 if len(parms) < 2 {
1270 return nil
1271 }
1272 length := binary.BigEndian.Uint16(parms[0:])
1273 // TODO: Make this nice using structure tagging.
1274 if int(length)+2 <= len(parms) {
1275 for i, s := range sess {
1276 if !s.IsEncryption() {
1277 continue
1278 }
1279 if err := s.Decrypt(parms[2 : 2+length]); err != nil {
1280 return fmt.Errorf("decrypting first parameter with session %d: %w", i, err)
1281 }
1282 }
1283 }
1284 buf := bytes.NewBuffer(parms)
1285 for i := numHandles; i < reflect.TypeOf(rspStruct).Elem().NumField(); i++ {
1286 parmsField := reflect.ValueOf(rspStruct).Elem().Field(i)
1287 if parmsField.Kind() == reflect.Ptr && hasTag(reflect.TypeOf(rspStruct).Elem().Field(i), "optional") {
1288 if binary.BigEndian.Uint16(buf.Bytes()) == 0 {
1289 // Advance the buffer past the zero size and skip to the
1290 // next field of the struct.
1291 buf.Next(2)
1292 continue
1293 }
1294 }
1295 if err := unmarshal(buf, parmsField); err != nil {
1296 return err
1297 }
1298 }
1299 return nil
1300 }