tpm2-protocol 0.17.0

TPM 2.0 marshaler/unmarshaler
Documentation
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2025 Opinsys Oy
// Copyright (c) 2024-2025 Jarkko Sakkinen

//! # TPM 2.0 Protocol
//!
//! A library for marshaling and unmarshaling TCG TPM 2.0 protocol messages.
//!
//! ## Constraints
//!
//! * `alloc` is disallowed.
//! * Dependencies are disallowed.
//! * Developer dependencies are disallowed.
//! * Panics are disallowed.
//!
//! ## Design Goals
//!
//! * The crate must compile with GNU make and rustc without any external
//!   dependencies.

#![cfg_attr(not(test), no_std)]
#![deny(unsafe_op_in_unsafe_fn)]
#![deny(clippy::all)]
#![deny(clippy::undocumented_unsafe_blocks)]
#![deny(clippy::pedantic)]
#![recursion_limit = "256"]

pub mod basic;
pub mod constant;
pub mod data;
#[macro_use]
pub mod r#macro;
pub mod frame;

/// A byte-backed TPM wire view.
#[repr(transparent)]
pub struct TpmWire([u8]);

impl TpmWire {
    /// Casts a byte slice into a TPM wire view.
    #[must_use]
    pub fn cast(buf: &[u8]) -> &Self {
        // SAFETY: `TpmWire` accepts any byte slice as its backing storage.
        unsafe { Self::cast_unchecked(buf) }
    }

    /// Casts a byte slice into a TPM wire view without validation.
    ///
    /// # Safety
    ///
    /// `TpmWire` has no additional validity requirements beyond the validity
    /// of `buf`. Callers must still ensure any higher-level protocol
    /// invariants required by later typed accessors have been validated.
    #[must_use]
    pub unsafe fn cast_unchecked(buf: &[u8]) -> &Self {
        let ptr = core::ptr::from_ref(buf) as *const Self;

        // SAFETY: `TpmWire` is `repr(transparent)` over `[u8]`, so it has the
        // same layout, metadata, and alignment as the referenced slice.
        unsafe { &*ptr }
    }

    /// Casts a mutable byte slice into a mutable TPM wire view.
    #[must_use]
    pub fn cast_mut(buf: &mut [u8]) -> &mut Self {
        // SAFETY: `TpmWire` accepts any mutable byte slice as its backing
        // storage. The `&mut` input provides exclusive access.
        unsafe { Self::cast_mut_unchecked(buf) }
    }

    /// Casts a mutable byte slice into a mutable TPM wire view without validation.
    ///
    /// # Safety
    ///
    /// `TpmWire` has no additional validity requirements beyond the validity
    /// of `buf`. Callers must still ensure any higher-level protocol
    /// invariants required by later typed accessors have been validated. The
    /// returned reference inherits the exclusive access represented by `buf`.
    #[must_use]
    pub unsafe fn cast_mut_unchecked(buf: &mut [u8]) -> &mut Self {
        let ptr = core::ptr::from_mut(buf) as *mut Self;

        // SAFETY: `TpmWire` is `repr(transparent)` over `[u8]`, so it has the
        // same layout, metadata, and alignment as the referenced slice.
        unsafe { &mut *ptr }
    }

    /// Returns the backing bytes.
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Returns the mutable backing bytes.
    #[must_use]
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }

    /// Returns the number of backing bytes.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` when the backing byte slice is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl AsRef<[u8]> for TpmWire {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsMut<[u8]> for TpmWire {
    fn as_mut(&mut self) -> &mut [u8] {
        self.as_bytes_mut()
    }
}

/// A byte-backed TPM wire view with a fixed byte length.
#[repr(transparent)]
pub struct TpmWireBytes<const N: usize>([u8; N]);

impl<const N: usize> TpmWireBytes<N> {
    /// Casts a byte slice into a fixed-size TPM wire view.
    ///
    /// # Errors
    ///
    /// Returns [`UnexpectedEnd`](crate::TpmProtocolError::UnexpectedEnd) when
    /// `buf` is smaller than `N` bytes.
    /// Returns [`TrailingData`](crate::TpmProtocolError::TrailingData) when
    /// `buf` is larger than `N` bytes.
    pub fn cast(buf: &[u8]) -> TpmResult<&Self> {
        if buf.len() < N {
            return Err(TpmProtocolError::UnexpectedEnd);
        }

        if buf.len() > N {
            return Err(TpmProtocolError::TrailingData);
        }

        // SAFETY: The length check above guarantees that `buf` has exactly the
        // byte length required by `TpmWireBytes<N>`.
        Ok(unsafe { Self::cast_unchecked(buf) })
    }

    /// Casts a byte slice into a fixed-size TPM wire view without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `buf.len() == N`. Callers must also ensure
    /// any higher-level protocol invariants required by later typed accessors
    /// have been validated.
    #[must_use]
    pub unsafe fn cast_unchecked(buf: &[u8]) -> &Self {
        let ptr = buf.as_ptr().cast::<Self>();

        // SAFETY: `TpmWireBytes<N>` is `repr(transparent)` over `[u8; N]`, so it
        // has the same layout and alignment. The caller guarantees exact size.
        unsafe { &*ptr }
    }

    /// Casts a mutable byte slice into a fixed-size mutable TPM wire view.
    ///
    /// # Errors
    ///
    /// Returns [`UnexpectedEnd`](crate::TpmProtocolError::UnexpectedEnd) when
    /// `buf` is smaller than `N` bytes.
    /// Returns [`TrailingData`](crate::TpmProtocolError::TrailingData) when
    /// `buf` is larger than `N` bytes.
    pub fn cast_mut(buf: &mut [u8]) -> TpmResult<&mut Self> {
        if buf.len() < N {
            return Err(TpmProtocolError::UnexpectedEnd);
        }

        if buf.len() > N {
            return Err(TpmProtocolError::TrailingData);
        }

        // SAFETY: The length check above guarantees that `buf` has exactly the
        // byte length required by `TpmWireBytes<N>`. The `&mut` input provides
        // exclusive access.
        Ok(unsafe { Self::cast_mut_unchecked(buf) })
    }

    /// Casts a mutable byte slice into a fixed-size mutable TPM wire view without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `buf.len() == N`. Callers must also ensure
    /// any higher-level protocol invariants required by later typed accessors
    /// have been validated. The returned reference inherits the exclusive
    /// access represented by `buf`.
    #[must_use]
    pub unsafe fn cast_mut_unchecked(buf: &mut [u8]) -> &mut Self {
        let ptr = buf.as_mut_ptr().cast::<Self>();

        // SAFETY: `TpmWireBytes<N>` is `repr(transparent)` over `[u8; N]`, so it
        // has the same layout and alignment. The caller guarantees exact size.
        unsafe { &mut *ptr }
    }

    /// Returns the backing bytes.
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; N] {
        &self.0
    }

    /// Returns the mutable backing bytes.
    #[must_use]
    pub fn as_bytes_mut(&mut self) -> &mut [u8; N] {
        &mut self.0
    }

    /// Returns the number of backing bytes.
    #[must_use]
    pub const fn len(&self) -> usize {
        N
    }

    /// Returns `true` when the backing byte array is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        N == 0
    }
}

impl<const N: usize> AsRef<[u8]> for TpmWireBytes<N> {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<const N: usize> AsMut<[u8]> for TpmWireBytes<N> {
    fn as_mut(&mut self) -> &mut [u8] {
        self.as_bytes_mut()
    }
}

/// Casts caller-owned bytes into a TPM wire view.
pub trait TpmCast {
    /// Casts `buf` into `Self` after validating the wire-view invariants.
    ///
    /// # Errors
    ///
    /// Returns `Err(TpmProtocolError)` when `buf` does not satisfy the
    /// invariants for `Self`.
    fn cast(buf: &[u8]) -> TpmResult<&Self>;

    /// Casts `buf` into `Self` without validating the wire-view invariants.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `buf` satisfies the same invariants checked
    /// by [`TpmCast::cast`].
    unsafe fn cast_unchecked(buf: &[u8]) -> &Self;
}

/// Casts caller-owned mutable bytes into a mutable TPM wire view.
pub trait TpmCastMut: TpmCast {
    /// Casts `buf` into mutable `Self` after validating the wire-view invariants.
    ///
    /// # Errors
    ///
    /// Returns `Err(TpmProtocolError)` when `buf` does not satisfy the
    /// invariants for `Self`.
    fn cast_mut(buf: &mut [u8]) -> TpmResult<&mut Self>;

    /// Casts `buf` into mutable `Self` without validating the wire-view invariants.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `buf` satisfies the same invariants checked
    /// by [`TpmCastMut::cast_mut`]. The returned reference inherits the
    /// exclusive access represented by `buf`.
    unsafe fn cast_mut_unchecked(buf: &mut [u8]) -> &mut Self;
}

impl TpmCast for TpmWire {
    fn cast(buf: &[u8]) -> TpmResult<&Self> {
        Ok(Self::cast(buf))
    }

    unsafe fn cast_unchecked(buf: &[u8]) -> &Self {
        // SAFETY: The caller upholds the unchecked cast contract for `TpmWire`.
        unsafe { Self::cast_unchecked(buf) }
    }
}

impl TpmCastMut for TpmWire {
    fn cast_mut(buf: &mut [u8]) -> TpmResult<&mut Self> {
        Ok(Self::cast_mut(buf))
    }

    unsafe fn cast_mut_unchecked(buf: &mut [u8]) -> &mut Self {
        // SAFETY: The caller upholds the unchecked mutable cast contract for
        // `TpmWire`.
        unsafe { Self::cast_mut_unchecked(buf) }
    }
}

impl<const N: usize> TpmCast for TpmWireBytes<N> {
    fn cast(buf: &[u8]) -> TpmResult<&Self> {
        Self::cast(buf)
    }

    unsafe fn cast_unchecked(buf: &[u8]) -> &Self {
        // SAFETY: The caller upholds the unchecked cast contract for
        // `TpmWireBytes<N>`.
        unsafe { Self::cast_unchecked(buf) }
    }
}

impl<const N: usize> TpmCastMut for TpmWireBytes<N> {
    fn cast_mut(buf: &mut [u8]) -> TpmResult<&mut Self> {
        Self::cast_mut(buf)
    }

    unsafe fn cast_mut_unchecked(buf: &mut [u8]) -> &mut Self {
        // SAFETY: The caller upholds the unchecked mutable cast contract for
        // `TpmWireBytes<N>`.
        unsafe { Self::cast_mut_unchecked(buf) }
    }
}

/// TPM frame marshaling and unmarshaling error type containing variants
/// for all the possible error conditions.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum TpmProtocolError {
    /// Trying to marshal more bytes than buffer has space. This is unexpected
    /// situation, and should be considered possible bug in the crate itself.
    BufferOverflow,

    /// Integer overflow while converting to an integer of a different size.
    IntegerTooLarge,

    /// Boolean value was expected but the value is neither `0` nor `1`.
    InvalidBoolean,

    /// Non-existent command code encountered.
    InvalidCc,

    /// An [`TpmAttest`](crate::data::TpmAttest) instance contains an invalid
    /// magic value.
    InvalidMagicNumber,

    /// Tag is neither [`Sessions`](crate::data::TpmSt::Sessions) nor
    /// [`NoSessions`](crate::data::TpmSt::NoSessions).
    InvalidTag,

    /// Buffer contains more bytes than allowed by the TCG specifications.
    TooManyBytes,

    /// List contains more items than allowed by the TCG specifications.
    TooManyItems,

    /// Trailing data left after unmarshaling.
    TrailingData,

    /// Run out of bytes while unmarshaling.
    UnexpectedEnd,

    /// The variant accessed is not available.
    VariantNotAvailable,
}

impl core::fmt::Display for TpmProtocolError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::BufferOverflow => write!(f, "buffer overflow"),
            Self::InvalidBoolean => write!(f, "invalid boolean value"),
            Self::InvalidCc => write!(f, "invalid command code"),
            Self::InvalidMagicNumber => write!(f, "invalid magic number"),
            Self::InvalidTag => write!(f, "invalid tag"),
            Self::IntegerTooLarge => write!(f, "integer overflow"),
            Self::TooManyBytes => write!(f, "buffer capacity surpassed"),
            Self::TooManyItems => write!(f, "list capaacity surpassed"),
            Self::TrailingData => write!(f, "trailing data"),
            Self::UnexpectedEnd => write!(f, "unexpected end"),
            Self::VariantNotAvailable => write!(f, "enum variant is not available"),
        }
    }
}

impl core::error::Error for TpmProtocolError {}

pub type TpmResult<T> = Result<T, TpmProtocolError>;

/// Builds TPM wire bytes into a caller-provided mutable byte slice.
pub struct TpmWriter<'a> {
    buffer: &'a mut [u8],
    cursor: usize,
}

impl<'a> TpmWriter<'a> {
    /// Creates a new writer for the given buffer.
    #[must_use]
    pub fn new(buffer: &'a mut [u8]) -> Self {
        Self { buffer, cursor: 0 }
    }

    /// Returns the number of bytes written so far.
    #[must_use]
    pub fn len(&self) -> usize {
        self.cursor
    }

    /// Returns `true` if no bytes have been written.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cursor == 0
    }

    /// Returns the bytes written so far.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.buffer[..self.cursor]
    }

    /// Appends a slice of bytes to the writer.
    ///
    /// # Errors
    ///
    /// Returns [`OutOfMemory`](crate::TpmProtocolError::OutOfMemory)
    /// when the capacity of the buffer is exceeded.
    pub fn write_bytes(&mut self, bytes: &[u8]) -> TpmResult<()> {
        let end = self
            .cursor
            .checked_add(bytes.len())
            .ok_or(TpmProtocolError::BufferOverflow)?;

        if end > self.buffer.len() {
            return Err(TpmProtocolError::BufferOverflow);
        }
        self.buffer[self.cursor..end].copy_from_slice(bytes);
        self.cursor = end;
        Ok(())
    }
}

/// Provides two ways to determine the size of an oBject: a compile-time maximum
/// and a runtime exact size.
pub trait TpmSized {
    /// The estimated size of the object in its serialized form evaluated at
    /// compile-time (always larger than the realized length).
    const SIZE: usize;

    /// Returns the exact serialized size of the object.
    fn len(&self) -> usize;

    /// Returns `true` if the object has a serialized length of zero.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

pub trait TpmMarshal {
    /// Marshals the object into the given writer.
    ///
    /// # Errors
    ///
    /// Returns `Err(TpmProtocolError)` on a marshal failure.
    fn marshal(&self, writer: &mut TpmWriter) -> TpmResult<()>;
}

pub(crate) trait TpmUnmarshal: Sized + TpmSized {
    /// Unmarshals an object from the given buffer.
    ///
    /// Returns the unmarshald type and the remaining portion of the buffer.
    ///
    /// # Errors
    ///
    /// Returns `Err(TpmProtocolError)` on a unmarshal failure.
    fn unmarshal(buf: &[u8]) -> TpmResult<(Self, &[u8])>;
}

/// Types that are composed of a tag and a value e.g., a union.
pub(crate) trait TpmTagged {
    /// The type of the tag/discriminant.
    type Tag: TpmUnmarshal + TpmMarshal + Copy;
    /// The type of the value/union.
    type Value;
}

/// Unmarshals a tagged object from a buffer.
pub(crate) trait TpmUnmarshalTagged: Sized {
    /// Unmarshals a tagged object from the given buffer using the provided tag.
    ///
    /// # Errors
    ///
    /// This method can return any error of the underlying type's `TpmUnmarshal` implementation,
    /// such as a `TpmProtocolError::UnexpectedEnd` if the buffer is too small or an
    /// `TpmProtocolError::MalformedValue` if the data is malformed.
    fn unmarshal_tagged(tag: <Self as TpmTagged>::Tag, buf: &[u8]) -> TpmResult<(Self, &[u8])>
    where
        Self: TpmTagged,
        <Self as TpmTagged>::Tag: TpmUnmarshal + TpmMarshal;
}