tpm2_protocol/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2025 Opinsys Oy
3// Copyright (c) 2024-2025 Jarkko Sakkinen
4
5//! # TPM 2.0 Protocol
6//!
7//! A library for marshaling and unmarshaling TCG TPM 2.0 protocol messages.
8//!
9//! ## Constraints
10//!
11//! * `alloc` is disallowed.
12//! * Dependencies are disallowed.
13//! * Developer dependencies are disallowed.
14//! * Panics are disallowed.
15//!
16//! ## Design Goals
17//!
18//! * The crate must compile with GNU make and rustc without any external
19//!   dependencies.
20
21#![cfg_attr(not(test), no_std)]
22#![deny(unsafe_code)]
23#![deny(clippy::all)]
24#![deny(clippy::pedantic)]
25#![recursion_limit = "256"]
26
27pub mod basic;
28pub mod constant;
29pub mod data;
30#[macro_use]
31pub mod r#macro;
32pub mod frame;
33
34/// A TPM handle, which is a 32-bit unsigned integer.
35#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
36#[repr(transparent)]
37pub struct TpmHandle(pub u32);
38
39impl core::convert::From<u32> for TpmHandle {
40    fn from(val: u32) -> Self {
41        Self(val)
42    }
43}
44
45impl core::convert::From<TpmHandle> for u32 {
46    fn from(val: TpmHandle) -> Self {
47        val.0
48    }
49}
50
51impl TpmMarshal for TpmHandle {
52    fn marshal(&self, writer: &mut TpmWriter) -> TpmResult<()> {
53        TpmMarshal::marshal(&self.0, writer)
54    }
55}
56
57impl TpmUnmarshal for TpmHandle {
58    fn unmarshal(buf: &[u8]) -> TpmResult<(Self, &[u8])> {
59        let (val, buf) = u32::unmarshal(buf)?;
60        Ok((Self(val), buf))
61    }
62}
63
64impl TpmSized for TpmHandle {
65    const SIZE: usize = size_of::<u32>();
66    fn len(&self) -> usize {
67        Self::SIZE
68    }
69}
70
71impl core::fmt::Display for TpmHandle {
72    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
73        core::fmt::Display::fmt(&self.0, f)
74    }
75}
76
77impl core::fmt::LowerHex for TpmHandle {
78    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
79        core::fmt::LowerHex::fmt(&self.0, f)
80    }
81}
82
83impl core::fmt::UpperHex for TpmHandle {
84    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
85        core::fmt::UpperHex::fmt(&self.0, f)
86    }
87}
88
89#[derive(Debug, PartialEq, Eq)]
90pub enum TpmDiscriminant {
91    Signed(i64),
92    Unsigned(u64),
93}
94
95impl core::fmt::LowerHex for TpmDiscriminant {
96    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
97        match self {
98            TpmDiscriminant::Signed(v) => write!(f, "{v:x}"),
99            TpmDiscriminant::Unsigned(v) => write!(f, "{v:x}"),
100        }
101    }
102}
103
104#[derive(Debug, PartialEq, Eq)]
105/// TPM protocol marshaling or unmarshaling error.
106pub enum TpmProtocolError {
107    /// An architectural limit (e.g., `MAX_SESSIONS`) was exceeded.
108    CapacityExceeded,
109    /// Data size exceeds the `u16` max for a TPM2B, or a writer's buffer is full.
110    BufferExceeded,
111    /// Item count exceeds the `u32` max for a TPML.
112    ListExceeded,
113    /// Unknown discriminant for an enum or tagged union.
114    InvalidDiscriminant(&'static str, TpmDiscriminant),
115    /// The frame or object is malformed.
116    MalformedValue,
117    /// Trailing data left after unmarshaling.
118    TrailingData,
119    /// Not enough bytes to unmarshal.
120    UnexpectedEof,
121}
122
123impl core::fmt::Display for TpmProtocolError {
124    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
125        match self {
126            Self::CapacityExceeded => write!(f, "capacity exceeded"),
127            Self::BufferExceeded => write!(f, "buffer exceeded"),
128            Self::ListExceeded => write!(f, "list exceeded"),
129            Self::InvalidDiscriminant(type_name, value) => {
130                write!(f, "invalid discriminant: {type_name}: 0x{value:x}")
131            }
132            Self::MalformedValue => write!(f, "malformed value"),
133            Self::TrailingData => write!(f, "trailing data"),
134            Self::UnexpectedEof => write!(f, "unexpected EOF"),
135        }
136    }
137}
138
139impl core::error::Error for TpmProtocolError {}
140
141pub type TpmResult<T> = Result<T, TpmProtocolError>;
142
143/// Writes into a mutable byte slice.
144pub struct TpmWriter<'a> {
145    buffer: &'a mut [u8],
146    cursor: usize,
147}
148
149impl<'a> TpmWriter<'a> {
150    /// Creates a new writer for the given buffer.
151    #[must_use]
152    pub fn new(buffer: &'a mut [u8]) -> Self {
153        Self { buffer, cursor: 0 }
154    }
155
156    /// Returns the number of bytes written so far.
157    #[must_use]
158    pub fn len(&self) -> usize {
159        self.cursor
160    }
161
162    /// Returns `true` if no bytes have been written.
163    #[must_use]
164    pub fn is_empty(&self) -> bool {
165        self.cursor == 0
166    }
167
168    /// Appends a slice of bytes to the writer.
169    ///
170    /// # Errors
171    ///
172    /// Returns `TpmProtocolError::BufferExceeded` if the writer does not have enough
173    /// capacity to hold the new bytes.
174    pub fn write_bytes(&mut self, bytes: &[u8]) -> TpmResult<()> {
175        let end = self.cursor + bytes.len();
176        if end > self.buffer.len() {
177            return Err(TpmProtocolError::BufferExceeded);
178        }
179        self.buffer[self.cursor..end].copy_from_slice(bytes);
180        self.cursor = end;
181        Ok(())
182    }
183}
184
185/// Provides two ways to determine the size of an object: a compile-time maximum
186/// and a runtime exact size.
187pub trait TpmSized {
188    /// The estimated size of the object in its serialized form evaluated at
189    /// compile-time (always larger than the realized length).
190    const SIZE: usize;
191
192    /// Returns the exact serialized size of the object.
193    fn len(&self) -> usize;
194
195    /// Returns `true` if the object has a serialized length of zero.
196    fn is_empty(&self) -> bool {
197        self.len() == 0
198    }
199}
200
201pub trait TpmMarshal: TpmSized {
202    /// Marshals the object into the given writer.
203    ///
204    /// # Errors
205    ///
206    /// Returns `Err(TpmProtocolError)` on a marshal failure.
207    fn marshal(&self, writer: &mut TpmWriter) -> TpmResult<()>;
208}
209
210pub trait TpmUnmarshal: Sized + TpmSized {
211    /// Unmarshals an object from the given buffer.
212    ///
213    /// Returns the unmarshald type and the remaining portion of the buffer.
214    ///
215    /// # Errors
216    ///
217    /// Returns `Err(TpmProtocolError)` on a unmarshal failure.
218    fn unmarshal(buf: &[u8]) -> TpmResult<(Self, &[u8])>;
219}
220
221/// Types that are composed of a tag and a value e.g., a union.
222pub trait TpmTagged {
223    /// The type of the tag/discriminant.
224    type Tag: TpmUnmarshal + TpmMarshal + Copy;
225    /// The type of the value/union.
226    type Value;
227}
228
229/// Unmarshals a tagged object from a buffer.
230pub trait TpmUnmarshalTagged: Sized {
231    /// Unmarshals a tagged object from the given buffer using the provided tag.
232    ///
233    /// # Errors
234    ///
235    /// This method can return any error of the underlying type's `TpmUnmarshal` implementation,
236    /// such as a `TpmProtocolError::UnexpectedEof` if the buffer is too small or an
237    /// `TpmProtocolError::MalformedValue` if the data is malformed.
238    fn unmarshal_tagged(tag: <Self as TpmTagged>::Tag, buf: &[u8]) -> TpmResult<(Self, &[u8])>
239    where
240        Self: TpmTagged,
241        <Self as TpmTagged>::Tag: TpmUnmarshal + TpmMarshal;
242}
243
244tpm_integer!(u8, Unsigned);
245tpm_integer!(i8, Signed);
246tpm_integer!(i32, Signed);
247tpm_integer!(u16, Unsigned);
248tpm_integer!(u32, Unsigned);
249tpm_integer!(u64, Unsigned);