tpm2-protocol 0.19.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
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2025 Opinsys Oy
// Copyright (c) 2024-2025 Jarkko Sakkinen

pub mod r#enum;
pub mod integer;
pub mod r#struct;

#[macro_export]
macro_rules! tpm_bitflags {
    (@impl $(#[$outer:meta])* $vis:vis struct $name:ident($wrapper:ty, $repr:ty) {
        $(
            $(#[$inner:meta])*
            const $field:ident = $value:expr, $string_name:literal;
        )*
    }) => {
        $(#[$outer])*
        $vis struct $name($repr);

        impl $name {
            $(
                $(#[$inner])*
                pub const $field: Self = Self($value);
            )*

            #[must_use]
            pub const fn bits(&self) -> $repr {
                self.0
            }

            #[must_use]
            pub const fn from_bits_truncate(bits: $repr) -> Self {
                Self(bits)
            }

            pub const fn set_bits(&mut self, bits: $repr) {
                self.0 = bits;
            }

            #[must_use]
            pub const fn empty() -> Self {
                Self(0)
            }

            #[must_use]
            pub const fn contains(&self, other: Self) -> bool {
                (self.0 & other.0) == other.0
            }
        }

        impl core::ops::BitOr for $name {
            type Output = Self;
            fn bitor(self, rhs: Self) -> Self::Output {
                Self(self.0 | rhs.0)
            }
        }

        impl core::ops::BitOrAssign for $name {
            fn bitor_assign(&mut self, rhs: Self) {
                self.0 |= rhs.0;
            }
        }

        impl core::ops::BitAnd for $name {
            type Output = Self;
            fn bitand(self, rhs: Self) -> Self::Output {
                Self(self.0 & rhs.0)
            }
        }

        impl core::ops::BitAndAssign for $name {
            fn bitand_assign(&mut self, rhs: Self) {
                self.0 &= rhs.0;
            }
        }

        impl core::ops::BitXor for $name {
            type Output = Self;
            fn bitxor(self, rhs: Self) -> Self::Output {
                Self(self.0 ^ rhs.0)
            }
        }

        impl core::ops::BitXorAssign for $name {
            fn bitxor_assign(&mut self, rhs: Self) {
                self.0 ^= rhs.0;
            }
        }

        impl core::ops::Not for $name {
            type Output = Self;
            fn not(self) -> Self::Output {
                Self(!self.0)
            }
        }

        impl $crate::TpmMarshal for $name {
            fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                let value = <$wrapper>::from(self.0);
                $crate::TpmMarshal::marshal(&value, writer)
            }
        }

        impl<'a> $crate::TpmField<'a> for $name {
            type View = Self;

            fn cast_prefix_field(buf: &'a [u8]) -> $crate::TpmResult<(Self::View, &'a [u8])> {
                let (value, buf) = <$wrapper as $crate::TpmCast>::cast_prefix(buf)?;

                Ok((Self(value.get()), buf))
            }
        }

        impl $crate::TpmSized for $name {
            const SIZE: usize = core::mem::size_of::<$repr>();
            fn len(&self) -> usize {
                Self::SIZE
            }
        }
    };

    ($(#[$meta:meta])* $vis:vis struct $name:ident(TpmUint8) { $($rest:tt)* }) => {
        tpm_bitflags!(@impl $(#[$meta])* $vis struct $name($crate::basic::TpmUint8, u8) { $($rest)* });
    };
    ($(#[$meta:meta])* $vis:vis struct $name:ident(TpmUint16) { $($rest:tt)* }) => {
        tpm_bitflags!(@impl $(#[$meta])* $vis struct $name($crate::basic::TpmUint16, u16) { $($rest)* });
    };
    ($(#[$meta:meta])* $vis:vis struct $name:ident(TpmUint32) { $($rest:tt)* }) => {
        tpm_bitflags!(@impl $(#[$meta])* $vis struct $name($crate::basic::TpmUint32, u32) { $($rest)* });
    };
    ($(#[$meta:meta])* $vis:vis struct $name:ident(TpmUint64) { $($rest:tt)* }) => {
        tpm_bitflags!(@impl $(#[$meta])* $vis struct $name($crate::basic::TpmUint64, u64) { $($rest)* });
    };
}

#[macro_export]
macro_rules! tpm_bool {
    (
        $(#[$outer:meta])*
        $vis:vis struct $name:ident(bool);
    ) => {
        $(#[$outer])*
        $vis struct $name(pub bool);

        impl From<bool> for $name {
            fn from(val: bool) -> Self {
                Self(val)
            }
        }

        impl From<$name> for bool {
            fn from(val: $name) -> Self {
                val.0
            }
        }

        impl $crate::TpmMarshal for $name {
            fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                let value = if self.0 { 1 } else { 0 };
                $crate::basic::TpmUint8::from(value).marshal(writer)
            }
        }

        impl<'a> $crate::TpmField<'a> for $name {
            type View = Self;

            fn cast_prefix_field(buf: &'a [u8]) -> $crate::TpmResult<(Self::View, &'a [u8])> {
                let (value, buf) = <$crate::basic::TpmUint8 as $crate::TpmCast>::cast_prefix(buf)?;
                match value.get() {
                    0 => Ok((Self(false), buf)),
                    1 => Ok((Self(true), buf)),
                    raw => Err($crate::TpmError::InvalidBoolean(
                        $crate::TpmErrorValue::new(0).value(u64::from(raw)),
                    )),
                }
            }
        }

        impl $crate::TpmSized for $name {
            const SIZE: usize = core::mem::size_of::<$crate::basic::TpmUint8>();
            fn len(&self) -> usize {
                Self::SIZE
            }
        }
    };
}

#[macro_export]
macro_rules! tpm_dispatch {
    (@const_check_sorted) => {};
    (@const_check_sorted $prev_cmd:ident, $( $rest_cmd:ident, )*) => {
        $crate::tpm_dispatch!(@const_check_sorted_impl $prev_cmd, $( $rest_cmd, )*);
    };
    (@const_check_sorted_impl $prev_cmd:ident,) => {};
    (@const_check_sorted_impl $prev_cmd:ident, $current_cmd:ident, $( $rest_cmd:ident, )* ) => {
        const _: () = assert!(
            <$crate::frame::data::$prev_cmd as $crate::frame::TpmHeader>::CC as u32 <= <$crate::frame::data::$current_cmd as $crate::frame::TpmHeader>::CC as u32,
            "TPM_DISPATCH_TABLE must be sorted by TpmCc."
        );
        $crate::tpm_dispatch!(@const_check_sorted_impl $current_cmd, $( $rest_cmd, )*);
    };

    ( $( ($cmd:ident, $resp:ident, $variant:ident) ),* $(,)? ) => {
        /// An owned TPM command body value.
        #[allow(clippy::large_enum_variant)]
        #[derive(Debug, PartialEq, Eq, Clone)]
        pub enum TpmCommandValue {
            $( $variant($crate::frame::data::$cmd), )*
        }

        impl $crate::TpmSized for TpmCommandValue {
            const SIZE: usize = $crate::constant::TPM_MAX_COMMAND_SIZE;
            fn len(&self) -> usize {
                match self {
                    $( Self::$variant(c) => $crate::TpmSized::len(c), )*
                }
            }
        }

        impl $crate::frame::TpmMarshalBody for TpmCommandValue {
             fn marshal_handles(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                 match self {
                     $( Self::$variant(c) => $crate::frame::TpmMarshalBody::marshal_handles(c, writer), )*
                 }
             }
             fn marshal_parameters(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                 match self {
                     $( Self::$variant(c) => $crate::frame::TpmMarshalBody::marshal_parameters(c, writer), )*
                 }
             }
        }

        impl $crate::TpmMarshal for TpmCommandValue {
             fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                 match self {
                     $( Self::$variant(c) => $crate::TpmMarshal::marshal(c, writer), )*
                 }
             }
        }

        impl $crate::frame::TpmFrame for TpmCommandValue {
            fn cc(&self) -> $crate::data::TpmCc {
                match self {
                    $( Self::$variant(c) => $crate::frame::TpmFrame::cc(c), )*
                }
            }
            fn handles(&self) -> usize {
                match self {
                    $( Self::$variant(c) => $crate::frame::TpmFrame::handles(c), )*
                }
            }
        }

        impl TpmCommandValue {
            /// Marshals a command body into a writer.
            ///
            /// # Errors
            ///
            /// Returns `Err(TpmError)` on a marshal failure.
            pub fn marshal_frame(
                &self,
                tag: $crate::data::TpmSt,
                sessions: &$crate::frame::TpmAuthCommands,
                writer: &mut $crate::TpmWriter,
            ) -> $crate::TpmResult<()> {
                match self {
                    $( Self::$variant(c) => $crate::frame::tpm_marshal_command(c, tag, sessions, writer), )*
                }
            }
        }

        /// A borrowed TPM command frame selected by command code.
        pub enum TpmCommandView<'a> {
            $( $variant(&'a $crate::frame::TpmCommand), )*
        }

        impl<'a> TpmCommandView<'a> {
            /// Casts bytes into a borrowed command dispatch value.
            ///
            /// # Errors
            ///
            /// Returns `Err(TpmError)` when the command frame is malformed or its
            /// command code has no dispatch entry.
            pub fn cast_frame(buf: &'a [u8]) -> $crate::TpmResult<Self> {
                let command = <$crate::frame::TpmCommand>::cast(buf)?;

                Self::cast(command)
            }

            /// Selects a borrowed command dispatch value from a command wire view.
            ///
            /// # Errors
            ///
            /// Returns `Err(TpmError)` when the command frame is malformed or its
            /// command code has no dispatch entry.
            pub fn cast(command: &'a $crate::frame::TpmCommand) -> $crate::TpmResult<Self> {
                command.validate()?;

                let cc = command.cc()?;
                match cc {
                    $( <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::CC => Ok(Self::$variant(command)), )*
                    _ => Err($crate::TpmError::InvalidCc(
                        $crate::TpmErrorValue::new(6).value(u64::from(cc.value())),
                    )),
                }
            }

            /// Returns the selected command frame.
            #[must_use]
            pub fn command(&self) -> &'a $crate::frame::TpmCommand {
                match self {
                    $( Self::$variant(command) => command, )*
                }
            }

            /// Returns the selected command code.
            #[must_use]
            pub fn cc(&self) -> $crate::data::TpmCc {
                match self {
                    $( Self::$variant(_) => <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::CC, )*
                }
            }
        }

        /// An owned TPM response body value.
        #[allow(clippy::large_enum_variant)]
        #[derive(Debug, PartialEq, Eq, Clone)]
        pub enum TpmResponseValue {
            $( $variant($crate::frame::data::$resp), )*
        }

        impl $crate::TpmSized for TpmResponseValue {
            const SIZE: usize = $crate::constant::TPM_MAX_COMMAND_SIZE;
            fn len(&self) -> usize {
                match self {
                    $( Self::$variant(r) => $crate::TpmSized::len(r), )*
                }
            }
        }

        impl $crate::frame::TpmMarshalBody for TpmResponseValue {
             fn marshal_handles(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                 match self {
                     $( Self::$variant(r) => $crate::frame::TpmMarshalBody::marshal_handles(r, writer), )*
                 }
             }
             fn marshal_parameters(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                 match self {
                     $( Self::$variant(r) => $crate::frame::TpmMarshalBody::marshal_parameters(r, writer), )*
                 }
             }
        }

        impl $crate::TpmMarshal for TpmResponseValue {
             fn marshal(&self, writer: &mut $crate::TpmWriter) -> $crate::TpmResult<()> {
                 match self {
                     $( Self::$variant(r) => $crate::TpmMarshal::marshal(r, writer), )*
                 }
             }
        }

        impl $crate::frame::TpmFrame for TpmResponseValue {
            fn cc(&self) -> $crate::data::TpmCc {
                match self {
                    $( Self::$variant(r) => $crate::frame::TpmFrame::cc(r), )*
                }
            }
            fn handles(&self) -> usize {
                match self {
                    $( Self::$variant(r) => $crate::frame::TpmFrame::handles(r), )*
                }
            }
        }

        impl TpmResponseValue {
            $(
                /// Attempts to convert the `TpmResponseValue` into a specific response type.
                ///
                /// # Errors
                ///
                /// Returns the original `TpmResponseValue` as an error if the enum variant does not match.
                #[allow(non_snake_case, clippy::result_large_err)]
                pub fn $variant(self) -> Result<$crate::frame::data::$resp, Self> {
                    if let Self::$variant(r) = self {
                        Ok(r)
                    } else {
                        Err(self)
                    }
                }
            )*

            /// Marshals a response body into a writer.
            ///
            /// # Errors
            ///
            /// Returns `Err(TpmError)` on a marshal failure.
            pub fn marshal_frame(
                &self,
                rc: $crate::data::TpmRc,
                sessions: &$crate::frame::TpmAuthResponses,
                writer: &mut $crate::TpmWriter,
            ) -> $crate::TpmResult<()> {
                match self {
                    $( Self::$variant(r) => $crate::frame::tpm_marshal_response(r, sessions, rc, writer), )*
                }
            }
        }

        /// A borrowed TPM response frame selected by command code.
        pub enum TpmResponseView<'a> {
            $( $variant(&'a $crate::frame::TpmResponse), )*
        }

        /// A borrowed response dispatch result or a TPM response code.
        pub type TpmResponseViewResult<'a> = Result<TpmResponseView<'a>, $crate::data::TpmRc>;

        impl<'a> TpmResponseView<'a> {
            /// Casts bytes into a borrowed response dispatch value.
            ///
            /// # Errors
            ///
            /// Returns `Err(TpmError)` when the response frame is malformed or `cc`
            /// has no dispatch entry.
            pub fn cast_frame(
                cc: $crate::data::TpmCc,
                buf: &'a [u8],
            ) -> $crate::TpmResult<TpmResponseViewResult<'a>> {
                let response = <$crate::frame::TpmResponse>::cast(buf)?;

                Self::cast(cc, response)
            }

            /// Selects a borrowed response dispatch value from a response wire view.
            ///
            /// # Errors
            ///
            /// Returns `Err(TpmError)` when the response frame is malformed or `cc`
            /// has no dispatch entry.
            pub fn cast(
                cc: $crate::data::TpmCc,
                response: &'a $crate::frame::TpmResponse,
            ) -> $crate::TpmResult<TpmResponseViewResult<'a>> {
                let rc = response.rc()?;
                if !matches!(rc, $crate::data::TpmRc::Fmt0($crate::data::TpmRcBase::Success)) {
                    return Ok(Err(rc));
                }

                response.validate(cc)?;

                match cc {
                    $( <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::CC => Ok(Ok(Self::$variant(response))), )*
                    _ => Err($crate::TpmError::InvalidCc(
                        $crate::TpmErrorValue::new(0).value(u64::from(cc.value())),
                    )),
                }
            }

            /// Returns the selected response frame.
            #[must_use]
            pub fn response(&self) -> &'a $crate::frame::TpmResponse {
                match self {
                    $( Self::$variant(response) => response, )*
                }
            }

            /// Returns the command code used for response dispatch.
            #[must_use]
            pub fn cc(&self) -> $crate::data::TpmCc {
                match self {
                    $( Self::$variant(_) => <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::CC, )*
                }
            }
        }

        pub(crate) static TPM_DISPATCH_TABLE: &[$crate::frame::TpmDispatch] = &[
            $(
                $crate::frame::TpmDispatch {
                    cc: <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::CC,
                    handles: <$crate::frame::data::$cmd as $crate::frame::TpmHeader>::HANDLES,
                    response_handles: <$crate::frame::data::$resp as $crate::frame::TpmHeader>::HANDLES,
                },
            )*
        ];

        $crate::tpm_dispatch!(@const_check_sorted $( $cmd, )*);
    };
}