| 1 |
package tpm2 |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/binary" |
| 6 |
"fmt" |
| 7 |
"reflect" |
| 8 |
) |
| 9 |
|
| 10 |
// Marshallable represents any TPM type that can be marshalled. |
| 11 |
type Marshallable interface { |
| 12 |
// marshal will serialize the given value, appending onto the given buffer. |
| 13 |
// Returns an error if the value is not marshallable. |
| 14 |
marshal(buf *bytes.Buffer) |
| 15 |
} |
| 16 |
|
| 17 |
// marshallableWithHint represents any TPM type that can be marshalled, |
| 18 |
// but that requires a selector ("hint") value when marshalling. Most TPMU_ are |
| 19 |
// an example of this. |
| 20 |
type marshallableWithHint interface { |
| 21 |
// get will return the corresponding union member by copy. If the union is |
| 22 |
// uninitialized, it will initialize a new zero-valued one. |
| 23 |
get(hint int64) (reflect.Value, error) |
| 24 |
} |
| 25 |
|
| 26 |
// Unmarshallable represents any TPM type that can be marshalled or unmarshalled. |
| 27 |
type Unmarshallable interface { |
| 28 |
Marshallable |
| 29 |
// marshal will deserialize the given value from the given buffer. |
| 30 |
// Returns an error if there was an unmarshalling error or if there was not |
| 31 |
// enough data in the buffer. |
| 32 |
unmarshal(buf *bytes.Buffer) error |
| 33 |
} |
| 34 |
|
| 35 |
// unmarshallableWithHint represents any TPM type that can be marshalled or unmarshalled, |
| 36 |
// but that requires a selector ("hint") value when unmarshalling. Most TPMU_ are |
| 37 |
// an example of this. |
| 38 |
type unmarshallableWithHint interface { |
| 39 |
marshallableWithHint |
| 40 |
// create will instantiate and return the corresponding union member. |
| 41 |
create(hint int64) (reflect.Value, error) |
| 42 |
} |
| 43 |
|
| 44 |
// Marshal will serialize the given values, returning them as a byte slice. |
| 45 |
func Marshal(v Marshallable) []byte { |
| 46 |
var buf bytes.Buffer |
| 47 |
if err := marshal(&buf, reflect.ValueOf(v)); err != nil { |
| 48 |
panic(fmt.Sprintf("unexpected error marshalling %v: %v", reflect.TypeOf(v).Name(), err)) |
| 49 |
} |
| 50 |
return buf.Bytes() |
| 51 |
} |
| 52 |
|
| 53 |
// Unmarshal unmarshals the given type from the byte array. |
| 54 |
// Returns an error if the buffer does not contain enough data to satisfy the |
| 55 |
// types, or if the types are not unmarshallable. |
| 56 |
func Unmarshal[T Marshallable, P interface { |
| 57 |
*T |
| 58 |
Unmarshallable |
| 59 |
}](data []byte) (*T, error) { |
| 60 |
buf := bytes.NewBuffer(data) |
| 61 |
var t T |
| 62 |
value := reflect.New(reflect.TypeOf(t)) |
| 63 |
if err := unmarshal(buf, value.Elem()); err != nil { |
| 64 |
return nil, err |
| 65 |
} |
| 66 |
return value.Interface().(*T), nil |
| 67 |
} |
| 68 |
|
| 69 |
// marshallableByReflection is a placeholder interface, to hint to the unmarshalling |
| 70 |
// library that it is supposed to use reflection. |
| 71 |
type marshallableByReflection interface { |
| 72 |
reflectionSafe() |
| 73 |
} |
| 74 |
|
| 75 |
// marshalByReflection is embedded into any type that can be marshalled by reflection, |
| 76 |
// needing no custom logic. |
| 77 |
type marshalByReflection struct{} |
| 78 |
|
| 79 |
func (marshalByReflection) reflectionSafe() {} |
| 80 |
|
| 81 |
// These placeholders are required because a type constraint cannot union another interface |
| 82 |
// that contains methods. |
| 83 |
// Otherwise, marshalByReflection would not implement Unmarshallable, and the Marshal/Unmarshal |
| 84 |
// functions would accept interface{ Marshallable | marshallableByReflection } instead. |
| 85 |
|
| 86 |
// Placeholder: because this type implements the defaultMarshallable interface, |
| 87 |
// the reflection library knows not to call this. |
| 88 |
func (marshalByReflection) marshal(_ *bytes.Buffer) { |
| 89 |
panic("not implemented") |
| 90 |
} |
| 91 |
|
| 92 |
// Placeholder: because this type implements the defaultMarshallable interface, |
| 93 |
// the reflection library knows not to call this. |
| 94 |
func (*marshalByReflection) unmarshal(_ *bytes.Buffer) error { |
| 95 |
panic("not implemented") |
| 96 |
} |
| 97 |
|
| 98 |
// boxed is a helper type for corner cases such as unions, where all members must be structs. |
| 99 |
type boxed[T any] struct { |
| 100 |
Contents *T |
| 101 |
} |
| 102 |
|
| 103 |
// box will put a value into a box. |
| 104 |
func box[T any](contents *T) boxed[T] { |
| 105 |
return boxed[T]{ |
| 106 |
Contents: contents, |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
// unbox will take a value out of a box. |
| 111 |
func (b *boxed[T]) unbox() *T { |
| 112 |
return b.Contents |
| 113 |
} |
| 114 |
|
| 115 |
// marshal implements the Marshallable interface. |
| 116 |
func (b *boxed[T]) marshal(buf *bytes.Buffer) { |
| 117 |
if b.Contents == nil { |
| 118 |
var contents T |
| 119 |
marshal(buf, reflect.ValueOf(&contents)) |
| 120 |
} else { |
| 121 |
marshal(buf, reflect.ValueOf(b.Contents)) |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
// unmarshal implements the Unmarshallable interface. |
| 126 |
func (b *boxed[T]) unmarshal(buf *bytes.Buffer) error { |
| 127 |
b.Contents = new(T) |
| 128 |
return unmarshal(buf, reflect.ValueOf(b.Contents)) |
| 129 |
} |
| 130 |
|
| 131 |
// MarshalCommand marshals a TPM command into its raw cpHash preimage format. |
| 132 |
// The returned bytes can be directly hashed to compute cpHash. |
| 133 |
// |
| 134 |
// Example: |
| 135 |
// |
| 136 |
// cmdData, _ := MarshalCommand(myCmd) |
| 137 |
// cpHash := sha256.Sum256(cmdData) |
| 138 |
// |
| 139 |
// Note: Encrypted command parameters (via sessions) are not currently supported. |
| 140 |
// The marshaled parameters are in their unencrypted form. |
| 141 |
func MarshalCommand[C Command[R, *R], R any](cmd C) ([]byte, error) { |
| 142 |
cc := cmd.Command() |
| 143 |
|
| 144 |
names, err := cmdNames(cmd) |
| 145 |
if err != nil { |
| 146 |
return nil, err |
| 147 |
} |
| 148 |
|
| 149 |
params, err := cmdParameters(cmd, nil) |
| 150 |
if err != nil { |
| 151 |
return nil, err |
| 152 |
} |
| 153 |
|
| 154 |
// Build raw cpHash preimage: CommandCode {∥ Name1 {∥ Name2 {∥ Name3 }}} {∥ Parameters } |
| 155 |
// See section 16.7 of TPM 2.0 specification, part 1. |
| 156 |
buf := new(bytes.Buffer) |
| 157 |
|
| 158 |
if err := binary.Write(buf, binary.BigEndian, cc); err != nil { |
| 159 |
return nil, fmt.Errorf("marshalling command code: %w", err) |
| 160 |
} |
| 161 |
|
| 162 |
for i, name := range names { |
| 163 |
if _, err := buf.Write(name.Buffer); err != nil { |
| 164 |
return nil, fmt.Errorf("marshalling name %d: %w", i, err) |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
if _, err := buf.Write(params); err != nil { |
| 169 |
return nil, fmt.Errorf("marshalling parameters: %w", err) |
| 170 |
} |
| 171 |
|
| 172 |
return buf.Bytes(), nil |
| 173 |
} |
| 174 |
|
| 175 |
// UnmarshalCommand unmarshals a raw cpHash preimage back into a TPM command. |
| 176 |
// The data should be the output from [MarshalCommand]. |
| 177 |
// |
| 178 |
// Example: |
| 179 |
// |
| 180 |
// cmdData, _ := MarshalCommand(myCmd) |
| 181 |
// cmd, _ := UnmarshalCommand[MyCommandType](cmdData) |
| 182 |
// |
| 183 |
// Notes: |
| 184 |
// - command produced from this function is not meant to be executed directly on a TPM, |
| 185 |
// instead it is expected to be used for purposes such as auditing or inspection. |
| 186 |
// - encrypted command parameters (via sessions) are not currently supported. |
| 187 |
func UnmarshalCommand[C Command[R, *R], R any](data []byte) (C, error) { |
| 188 |
var cmd C |
| 189 |
|
| 190 |
if data == nil { |
| 191 |
return cmd, fmt.Errorf("data cannot be nil") |
| 192 |
} |
| 193 |
|
| 194 |
buf := bytes.NewBuffer(data) |
| 195 |
|
| 196 |
var cc TPMCC |
| 197 |
if err := binary.Read(buf, binary.BigEndian, &cc); err != nil { |
| 198 |
return cmd, fmt.Errorf("unmarshalling command code: %w", err) |
| 199 |
} |
| 200 |
|
| 201 |
if cc != cmd.Command() { |
| 202 |
return cmd, fmt.Errorf("command code mismatch: expected %v, got %v", cmd.Command(), cc) |
| 203 |
} |
| 204 |
|
| 205 |
expectedNames, err := cmdNames(cmd) |
| 206 |
if err != nil { |
| 207 |
return cmd, fmt.Errorf("getting expected names count: %w", err) |
| 208 |
} |
| 209 |
numNames := len(expectedNames) |
| 210 |
|
| 211 |
names := make([]TPM2BName, numNames) |
| 212 |
for i := range numNames { |
| 213 |
remaining := buf.Bytes() |
| 214 |
if len(remaining) == 0 { |
| 215 |
return cmd, fmt.Errorf("unexpected end of data while parsing name %d", i) |
| 216 |
} |
| 217 |
|
| 218 |
nameSize, err := parseNameSize(remaining) |
| 219 |
if err != nil { |
| 220 |
return cmd, fmt.Errorf("parsing name %d size: %w", i, err) |
| 221 |
} |
| 222 |
|
| 223 |
if len(remaining) < nameSize { |
| 224 |
return cmd, fmt.Errorf("insufficient data for name %d: need %d bytes, have %d", i, nameSize, len(remaining)) |
| 225 |
} |
| 226 |
|
| 227 |
nameBytes := make([]byte, nameSize) |
| 228 |
if _, err := buf.Read(nameBytes); err != nil { |
| 229 |
return cmd, fmt.Errorf("reading name %d: %w", i, err) |
| 230 |
} |
| 231 |
|
| 232 |
names[i] = TPM2BName{Buffer: nameBytes} |
| 233 |
} |
| 234 |
|
| 235 |
// Populate the command's handle fields from the names |
| 236 |
if err := populateHandlesFromNames(&cmd, names); err != nil { |
| 237 |
return cmd, err |
| 238 |
} |
| 239 |
|
| 240 |
params := buf.Bytes() |
| 241 |
|
| 242 |
paramsBuf := bytes.NewBuffer(params) |
| 243 |
if err := unmarshalCmdParameters(paramsBuf, &cmd, nil); err != nil { |
| 244 |
return cmd, err |
| 245 |
} |
| 246 |
return cmd, nil |
| 247 |
} |
| 248 |
|
| 249 |
// parseNameSize determines the size of a TPM2BName by inspecting its first bytes. |
| 250 |
// Returns the total size in bytes for the name. |
| 251 |
// |
| 252 |
// Case 1: Handle-based names (4 bytes) |
| 253 |
// - 0x0000... → PCR |
| 254 |
// - 0x02... → HMAC Session |
| 255 |
// - 0x03... → Policy Session |
| 256 |
// - 0x40... → Permanent Values |
| 257 |
// |
| 258 |
// Case 2: Hash-based names (2 + hash_size bytes) - for all other entities |
| 259 |
// - Format: nameAlg (2 bytes) || H_nameAlg (hash digest) |
| 260 |
// |
| 261 |
// See section 14 of TPM 2.0 specification, part 1. |
| 262 |
func parseNameSize(buf []byte) (int, error) { |
| 263 |
if len(buf) < 2 { |
| 264 |
return 0, fmt.Errorf("buffer too short to parse name") |
| 265 |
} |
| 266 |
|
| 267 |
firstByte := TPMHT(buf[0]) |
| 268 |
firstTwoBytes := binary.BigEndian.Uint16(buf[0:2]) |
| 269 |
|
| 270 |
// Case 1: Handle-based names (4 bytes) |
| 271 |
switch { |
| 272 |
case firstTwoBytes == 0x0000: |
| 273 |
// PCR handles (pattern: 0x0000XXXX) |
| 274 |
// Must check both bytes to distinguish from hash algorithms |
| 275 |
// that also start with 0x00 (e.g., TPMAlgSHA256 = 0x000B) |
| 276 |
return 4, nil |
| 277 |
case firstByte == TPMHTHMACSession: // 0x02 |
| 278 |
return 4, nil |
| 279 |
case firstByte == TPMHTPolicySession: // 0x03 |
| 280 |
return 4, nil |
| 281 |
case firstByte == TPMHTPermanent: // 0x40 |
| 282 |
return 4, nil |
| 283 |
} |
| 284 |
|
| 285 |
// Case 2: Hash-based names (nameAlg || hash) |
| 286 |
// firstTwoBytes is the algorithm ID (0x0001 to 0x00B3) |
| 287 |
algID := TPMIAlgHash(firstTwoBytes) |
| 288 |
hashAlg, err := algID.Hash() |
| 289 |
if err != nil { |
| 290 |
return 0, fmt.Errorf("unsupported hash algorithm 0x%x in name: %w", firstTwoBytes, err) |
| 291 |
} |
| 292 |
|
| 293 |
// 2 bytes for algID + hash size |
| 294 |
return 2 + hashAlg.Size(), nil |
| 295 |
} |
| 296 |
|
| 297 |
// MarshalResponse marshals a TPM response into its raw rpHash preimage format. |
| 298 |
// The returned bytes can be directly hashed to compute rpHash. |
| 299 |
// |
| 300 |
// Example: |
| 301 |
// |
| 302 |
// rspData, _ := MarshalResponse(myCmd, myRsp) |
| 303 |
// rpHash := sha256.Sum256(rspData) |
| 304 |
// |
| 305 |
// Note: Encrypted response parameters (via sessions) are not currently supported. |
| 306 |
func MarshalResponse[C Command[R, *R], R any](cmd C, rsp *R) ([]byte, error) { |
| 307 |
cc := cmd.Command() |
| 308 |
|
| 309 |
params, err := marshalRspParameters(rsp, nil) |
| 310 |
if err != nil { |
| 311 |
return nil, err |
| 312 |
} |
| 313 |
|
| 314 |
// Build raw rpHash preimage: responseCode || commandCode || parameters |
| 315 |
buf := new(bytes.Buffer) |
| 316 |
|
| 317 |
// Write responseCode (4 bytes, always 0 for successful responses) |
| 318 |
if err := binary.Write(buf, binary.BigEndian, uint32(0)); err != nil { |
| 319 |
return nil, fmt.Errorf("marshalling response code: %w", err) |
| 320 |
} |
| 321 |
|
| 322 |
if err := binary.Write(buf, binary.BigEndian, cc); err != nil { |
| 323 |
return nil, fmt.Errorf("marshalling command code: %w", err) |
| 324 |
} |
| 325 |
|
| 326 |
if _, err := buf.Write(params); err != nil { |
| 327 |
return nil, fmt.Errorf("marshalling parameters: %w", err) |
| 328 |
} |
| 329 |
|
| 330 |
return buf.Bytes(), nil |
| 331 |
} |
| 332 |
|
| 333 |
// UnmarshalResponse unmarshals a raw rpHash preimage back into a TPM response. |
| 334 |
// The data should be the output from [MarshalResponse]. |
| 335 |
// |
| 336 |
// Example: |
| 337 |
// |
| 338 |
// rspData, _ := MarshalResponse(commandCode, myRsp) |
| 339 |
// rsp, _ := UnmarshalResponse[MyResponseType](rspData) |
| 340 |
// |
| 341 |
// Notes: |
| 342 |
// - the result from this function is expected to be used for purposes such as auditing or inspection. |
| 343 |
// - encrypted response parameters (via sessions) are not currently supported. |
| 344 |
func UnmarshalResponse[R any](data []byte) (*R, error) { |
| 345 |
var rsp R |
| 346 |
|
| 347 |
if data == nil { |
| 348 |
return nil, fmt.Errorf("data cannot be nil") |
| 349 |
} |
| 350 |
|
| 351 |
if len(data) < 8 { |
| 352 |
return nil, fmt.Errorf("data too short: need at least 8 bytes (responseCode + commandCode), got %d", len(data)) |
| 353 |
} |
| 354 |
|
| 355 |
buf := bytes.NewBuffer(data) |
| 356 |
|
| 357 |
var responseCode uint32 |
| 358 |
if err := binary.Read(buf, binary.BigEndian, &responseCode); err != nil { |
| 359 |
return nil, fmt.Errorf("unmarshalling response code: %w", err) |
| 360 |
} |
| 361 |
|
| 362 |
if responseCode != 0 { |
| 363 |
return nil, fmt.Errorf("invalid response code: expected 0, got 0x%x", responseCode) |
| 364 |
} |
| 365 |
|
| 366 |
var cc TPMCC |
| 367 |
if err := binary.Read(buf, binary.BigEndian, &cc); err != nil { |
| 368 |
return nil, fmt.Errorf("unmarshalling command code: %w", err) |
| 369 |
} |
| 370 |
|
| 371 |
params := buf.Bytes() |
| 372 |
|
| 373 |
if err := rspParameters(params, nil, &rsp); err != nil { |
| 374 |
return nil, err |
| 375 |
} |
| 376 |
return &rsp, nil |
| 377 |
} |