| 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 tpmutil |
| 16 |
|
| 17 |
import ( |
| 18 |
"bytes" |
| 19 |
"encoding/binary" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
"reflect" |
| 24 |
) |
| 25 |
|
| 26 |
var ( |
| 27 |
selfMarshalerType = reflect.TypeOf((*SelfMarshaler)(nil)).Elem() |
| 28 |
handlesAreaType = reflect.TypeOf((*[]Handle)(nil)) |
| 29 |
) |
| 30 |
|
| 31 |
// packWithHeader takes a header and a sequence of elements that are either of |
| 32 |
// fixed length or slices of fixed-length types and packs them into a single |
| 33 |
// byte array using binary.Write. It updates the CommandHeader to have the right |
| 34 |
// length. |
| 35 |
func packWithHeader(ch commandHeader, cmd ...interface{}) ([]byte, error) { |
| 36 |
hdrSize := binary.Size(ch) |
| 37 |
body, err := Pack(cmd...) |
| 38 |
if err != nil { |
| 39 |
return nil, fmt.Errorf("couldn't pack message body: %v", err) |
| 40 |
} |
| 41 |
bodySize := len(body) |
| 42 |
ch.Size = uint32(hdrSize + bodySize) |
| 43 |
header, err := Pack(ch) |
| 44 |
if err != nil { |
| 45 |
return nil, fmt.Errorf("couldn't pack message header: %v", err) |
| 46 |
} |
| 47 |
return append(header, body...), nil |
| 48 |
} |
| 49 |
|
| 50 |
// Pack encodes a set of elements into a single byte array, using |
| 51 |
// encoding/binary. This means that all the elements must be encodeable |
| 52 |
// according to the rules of encoding/binary. |
| 53 |
// |
| 54 |
// It has one difference from encoding/binary: it encodes byte slices with a |
| 55 |
// prepended length, to match how the TPM encodes variable-length arrays. If |
| 56 |
// you wish to add a byte slice without length prefix, use RawBytes. |
| 57 |
func Pack(elts ...interface{}) ([]byte, error) { |
| 58 |
buf := new(bytes.Buffer) |
| 59 |
if err := packType(buf, elts...); err != nil { |
| 60 |
return nil, err |
| 61 |
} |
| 62 |
return buf.Bytes(), nil |
| 63 |
} |
| 64 |
|
| 65 |
// tryMarshal attempts to use a TPMMarshal() method defined on the type |
| 66 |
// to pack v into buf. True is returned if the method exists and the |
| 67 |
// marshal was attempted. |
| 68 |
func tryMarshal(buf io.Writer, v reflect.Value) (bool, error) { |
| 69 |
t := v.Type() |
| 70 |
if t.Implements(selfMarshalerType) { |
| 71 |
if v.Kind() == reflect.Ptr && v.IsNil() { |
| 72 |
return true, fmt.Errorf("cannot call TPMMarshal on a nil pointer of type %T", v) |
| 73 |
} |
| 74 |
return true, v.Interface().(SelfMarshaler).TPMMarshal(buf) |
| 75 |
} |
| 76 |
|
| 77 |
// We might have a non-pointer struct field, but we dont have a |
| 78 |
// pointer with which to implement the interface. |
| 79 |
// If the pointer of the type implements the interface, we should be |
| 80 |
// able to construct a value to call TPMMarshal() with. |
| 81 |
// TODO(awly): Try and avoid blowing away private data by using Addr() instead of Set() |
| 82 |
if reflect.PtrTo(t).Implements(selfMarshalerType) { |
| 83 |
tmp := reflect.New(t) |
| 84 |
tmp.Elem().Set(v) |
| 85 |
return true, tmp.Interface().(SelfMarshaler).TPMMarshal(buf) |
| 86 |
} |
| 87 |
|
| 88 |
return false, nil |
| 89 |
} |
| 90 |
|
| 91 |
func packValue(buf io.Writer, v reflect.Value) error { |
| 92 |
if v.Type() == handlesAreaType { |
| 93 |
v = v.Convert(reflect.TypeOf((*handleList)(nil))) |
| 94 |
} |
| 95 |
if canMarshal, err := tryMarshal(buf, v); canMarshal { |
| 96 |
return err |
| 97 |
} |
| 98 |
|
| 99 |
switch v.Kind() { |
| 100 |
case reflect.Ptr: |
| 101 |
if v.IsNil() { |
| 102 |
return fmt.Errorf("cannot pack nil %s", v.Type().String()) |
| 103 |
} |
| 104 |
return packValue(buf, v.Elem()) |
| 105 |
case reflect.Struct: |
| 106 |
for i := 0; i < v.NumField(); i++ { |
| 107 |
f := v.Field(i) |
| 108 |
if err := packValue(buf, f); err != nil { |
| 109 |
return err |
| 110 |
} |
| 111 |
} |
| 112 |
default: |
| 113 |
return binary.Write(buf, binary.BigEndian, v.Interface()) |
| 114 |
} |
| 115 |
return nil |
| 116 |
} |
| 117 |
|
| 118 |
func packType(buf io.Writer, elts ...interface{}) error { |
| 119 |
for _, e := range elts { |
| 120 |
if err := packValue(buf, reflect.ValueOf(e)); err != nil { |
| 121 |
return err |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
return nil |
| 126 |
} |
| 127 |
|
| 128 |
// tryUnmarshal attempts to use TPMUnmarshal() to perform the |
| 129 |
// unpack, if the given value implements SelfMarshaler. |
| 130 |
// True is returned if v implements SelfMarshaler & TPMUnmarshal |
| 131 |
// was called, along with an error returned from TPMUnmarshal. |
| 132 |
func tryUnmarshal(buf io.Reader, v reflect.Value) (bool, error) { |
| 133 |
t := v.Type() |
| 134 |
if t.Implements(selfMarshalerType) { |
| 135 |
if v.Kind() == reflect.Ptr && v.IsNil() { |
| 136 |
return true, fmt.Errorf("cannot call TPMUnmarshal on a nil pointer") |
| 137 |
} |
| 138 |
return true, v.Interface().(SelfMarshaler).TPMUnmarshal(buf) |
| 139 |
} |
| 140 |
|
| 141 |
// We might have a non-pointer struct field, which is addressable, |
| 142 |
// If the pointer of the type implements the interface, and the |
| 143 |
// value is addressable, we should be able to call TPMUnmarshal(). |
| 144 |
if v.CanAddr() && reflect.PtrTo(t).Implements(selfMarshalerType) { |
| 145 |
return true, v.Addr().Interface().(SelfMarshaler).TPMUnmarshal(buf) |
| 146 |
} |
| 147 |
|
| 148 |
return false, nil |
| 149 |
} |
| 150 |
|
| 151 |
// Unpack is a convenience wrapper around UnpackBuf. Unpack returns the number |
| 152 |
// of bytes read from b to fill elts and error, if any. |
| 153 |
func Unpack(b []byte, elts ...interface{}) (int, error) { |
| 154 |
buf := bytes.NewBuffer(b) |
| 155 |
err := UnpackBuf(buf, elts...) |
| 156 |
read := len(b) - buf.Len() |
| 157 |
return read, err |
| 158 |
} |
| 159 |
|
| 160 |
func unpackValue(buf io.Reader, v reflect.Value) error { |
| 161 |
if v.Type() == handlesAreaType { |
| 162 |
v = v.Convert(reflect.TypeOf((*handleList)(nil))) |
| 163 |
} |
| 164 |
if didUnmarshal, err := tryUnmarshal(buf, v); didUnmarshal { |
| 165 |
return err |
| 166 |
} |
| 167 |
|
| 168 |
switch v.Kind() { |
| 169 |
case reflect.Ptr: |
| 170 |
if v.IsNil() { |
| 171 |
return fmt.Errorf("cannot unpack nil %s", v.Type().String()) |
| 172 |
} |
| 173 |
return unpackValue(buf, v.Elem()) |
| 174 |
case reflect.Struct: |
| 175 |
for i := 0; i < v.NumField(); i++ { |
| 176 |
f := v.Field(i) |
| 177 |
if err := unpackValue(buf, f); err != nil { |
| 178 |
return err |
| 179 |
} |
| 180 |
} |
| 181 |
return nil |
| 182 |
default: |
| 183 |
// binary.Read can only set pointer values, so we need to take the address. |
| 184 |
if !v.CanAddr() { |
| 185 |
return fmt.Errorf("cannot unpack unaddressable leaf type %q", v.Type().String()) |
| 186 |
} |
| 187 |
return binary.Read(buf, binary.BigEndian, v.Addr().Interface()) |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
// UnpackBuf recursively unpacks types from a reader just as encoding/binary |
| 192 |
// does under binary.BigEndian, but with one difference: it unpacks a byte |
| 193 |
// slice by first reading an integer with lengthPrefixSize bytes, then reading |
| 194 |
// that many bytes. It assumes that incoming values are pointers to values so |
| 195 |
// that, e.g., underlying slices can be resized as needed. |
| 196 |
func UnpackBuf(buf io.Reader, elts ...interface{}) error { |
| 197 |
for _, e := range elts { |
| 198 |
v := reflect.ValueOf(e) |
| 199 |
if v.Kind() != reflect.Ptr { |
| 200 |
return fmt.Errorf("non-pointer value %q passed to UnpackBuf", v.Type().String()) |
| 201 |
} |
| 202 |
if v.IsNil() { |
| 203 |
return errors.New("nil pointer passed to UnpackBuf") |
| 204 |
} |
| 205 |
|
| 206 |
if err := unpackValue(buf, v); err != nil { |
| 207 |
return err |
| 208 |
} |
| 209 |
} |
| 210 |
return nil |
| 211 |
} |