fix(macro): interpret responses dynamically
PATCH 1/1 fix(macro): interpret responses dynamically
Here's the failing case:
8001000000300000000002000000002000647915de6106c955b26456b8b8a3b10546fa446405d4eb2e1fb0247fb52080
What happens is that tpm_parse_response returns ParserUnderflow, and parsing fails (gracefully).
The root cause is incorrect interpretation of commands being applicable both with and without sessions. In the failing case the response is captured from a run of tpm2sh start-session.
It has hard to define the failing commit since this project barely has kicked off, and the recent history is encompassed of major overhauls in order to get where it is right now but most likely the failure was caused by when refactoring away from having tpm_response! in favor of universal tpm_struct!.
I highlight the parts of the diff that are relevant for addressing the issue:
First an analogous trait to TpmCommandBodyParse is defined for delivering the "discovered" tag in the different layers of the response parser:
pub(crate) trait TpmResponseBodyParse: Sized {
/// Parses the response body from a buffer, using the response tag to determine
/// the structure.
fn parse_body(tag: data::TpmSt, buf: &[u8]) -> TpmResult<(Self, &[u8])>;
}Then the trait call is patched to tpm_dispatch!:
- |buf| {
- <$rsp_ty>::parse(buf)
+ |tag, buf| {
+ <$rsp_ty as $crate::message::TpmResponseBodyParse>::parse_body(tag, buf)
The dispatcher generated is orchestrated from the "entry function" i.e, tpm_parse_response, so that's where the tag is originally supplied after doing a binary search to PARSE_RESPONSE_MAP:
- let (body, mut session_area) = (dispatch.2)(body_buf)?;
+ let (body, mut session_area) = (dispatch.2)(tag, body_buf)?;
Finally, tpm_struct! is mirgated to provide the trait implementation:
- fn parse(buf: &[u8]) -> $crate::TpmResult<(Self, &[u8])> {
+ fn parse_body(
+ tag: $crate::data::TpmSt,
+ buf: &[u8],
And that's how tag is delivered to the new response body parser for implementing the actual upgraded logic:
- if $with_sessions {
- let (size, buf_after_size) = u32::parse(cursor)?;
+ if $with_sessions && tag == $crate::data::TpmSt::Sessions {
This fixes the bug and as is proven against the failing case by test_response_start_auth_session_no_sessions_2.
However, this revealed a "symmetrical bug" in tpm_build_response() leading to a failure in the final comparison of the test case.
This led to the new TpmResponseBodyBuild, which matches the logic with already pre-existing TpmCommandBodyBuild, and fixes essentially fn len().
---
Took a quite many days to identify this, scope it into a test case, analyze it, and fixing. Given how the fix in the end reflects the overall architecture I'm now confident that this is right.
Thus, immediate merge, it's a show stopper bug.
I also cc'd this tpm2 as it's pretty good in describing some core ideas of this new TPM2 crate.
src/macro/mod.rs | 6 +-- src/macro/struct.rs | 50 +++++++++++---------- src/message/build.rs | 27 ++++++++--- src/message/mod.rs | 33 +++++++++++++- src/message/parse.rs | 2 +- tests/runner.rs | 104 ++++++++++++++++++------------------------- 6 files changed, 128 insertions(+), 94 deletions(-)
src/macro/mod.rs +3 -3
@@ -163,8 +163,8 @@ macro_rules! tpm_dispatch { ( <$rsp_tyas $crate::message::TpmHeader >::COMMAND , <$rsp_tyas $crate::message::TpmHeader >::WITH_SESSIONS , - |buf| { - <$rsp_ty>::parse (buf) + |tag, buf| { + <$rsp_tyas $crate::message::TpmResponseBodyParse >::parse_body (tag, buf) .map(|(r, rest)| (TpmResponseBody::$enum_variant(r), rest)) }, )
@@ -204,7 +204,7 @@ macro_rules! tpm_dispatch { }pub type TpmCommandParser =for <'a>fn (&'a [u8 ], &'a [u8 ]) -> $crate::TpmResult <(TpmCommandBody , &'a [u8 ])>; -pub type TpmResponseParser =for <'a>fn (&'a [u8 ]) -> $crate::TpmResult <(TpmResponseBody , &'a [u8 ])>; +pub type TpmResponseParser =for <'a>fn ($crate::data::TpmSt , &'a [u8 ]) -> $crate::TpmResult <(TpmResponseBody , &'a [u8 ])>;pub (crate )static PARSE_COMMAND_MAP : &[($crate::data::TpmCc ,bool ,bool ,usize ,TpmCommandParser )] = &[$(tpm_command_parser!($cmd, $variant),)*];
src/macro/struct.rs +26 -24
85 lines not on this page · raw message
src/message/build.rs +22 -5
@@ -4,7 +4,7 @@use crate ::{ data::{TpmRc ,TpmSt ,TpmsAuthCommand ,TpmsAuthResponse }, - message::{TpmCommandBuild ,TpmHeader ,TPM_HEADER_SIZE }, + message::{TpmCommandBuild ,TpmHeader ,TpmResponseBuild ,TPM_HEADER_SIZE },TpmBuild ,TpmErrorKind ,TpmResult ,TpmSized , };use core::mem::size_of;
@@ -90,7 +90,7 @@ pub fn tpm_build_response<R>( writer: &mut crate::TpmWriter, ) -> TpmResult<()>where -R :TpmHeader , +R :TpmHeader +TpmResponseBuild , { let tag = if !rc.is_error() && R::WITH_SESSIONS && !sessions.is_empty() { TpmSt::Sessions
@@ -105,9 +105,18 @@ wherereturn Ok (()); } -let body_len = response.len (); +let handle_area_size =R ::HANDLES *size_of ::<u32 >(); +let param_area_size = response.len () - handle_area_size;let sessions_len:usize = sessions.iter ().map (TpmSized ::len).sum (); -let total_body_len = body_len + sessions_len; + +let parameter_area_size_field_len =if tag ==TpmSt ::Sessions { +size_of ::<u32 >() + }else { +0 + }; + +let total_body_len = + handle_area_size + parameter_area_size_field_len + param_area_size + sessions_len;let response_size = u32::try_from (TPM_HEADER_SIZE + total_body_len).map_err (|_|TpmErrorKind ::BuildCapacity )?;
@@ -115,7 +124,15 @@ where response_size.build (writer)?; rc.value ().build (writer)?; - response.build (writer)?; + response.build_handles (writer)?; + +if tag ==TpmSt ::Sessions { +let params_len_u32 = + u32::try_from (param_area_size).map_err (|_|TpmErrorKind ::BuildCapacity )?; + params_len_u32.build (writer)?; + } + + response.build_parameters (writer)?;if tag ==TpmSt ::Sessions {for sin sessions {
src/message/mod.rs +32 -1
@@ -2,7 +2,7 @@// Copyright (c) 2025 Opinsys Oy // Copyright (c) 2024-2025 Jarkko Sakkinen -use crate ::{data, tpm_dispatch,TpmBuild ,TpmList ,TpmParse ,TpmResult ,TpmWriter }; +use crate ::{data, tpm_dispatch,TpmBuild ,TpmList ,TpmResult ,TpmWriter };use core::fmt::Debug ;mod asymmetric;
@@ -77,6 +77,24 @@ pub trait TpmCommandBuild {fn build_parameters (&self, writer: &mut TpmWriter ) ->TpmResult <()>; } +/// A trait for building response bodies in separate handle and parameter sections. +pub trait TpmResponseBuild { +/// Builds the handle area of the response. +/// +/// # Errors +/// +/// * `TpmErrorKind::BuildOverflow` if writer would run out of space. +fn build_handles (&self, writer: &mut TpmWriter ) ->TpmResult <()>; + +/// Builds the parameter area of the response. +/// +/// # Errors +/// +/// * `TpmErrorKind::BuildCapacity` if the object contains a value exceeding capacity limit. +/// * `TpmErrorKind::BuildOverflow` if writer would run out of space. +fn build_parameters (&self, writer: &mut TpmWriter ) ->TpmResult <()>; +} +/// Parses a command body from the slices point out to the handle area and /// parameter area of the original buffer. pub (crate )trait TpmCommandBodyParse :Sized {
@@ -89,6 +107,19 @@ pub(crate) trait TpmCommandBodyParse: Sized {fn parse_body <'a>(handles: &'a [u8 ], params: &'a [u8 ]) ->TpmResult <(Self , &'a [u8 ])>; } +/// Parses a response body using the response tag to handle structural variations. +pub trait TpmResponseBodyParse :Sized { +/// Parses the response body from a buffer, using the response tag dynamically +/// to determine the structure. +/// +/// # Errors +/// +/// This method can return parsing errors such as: +/// * `TpmErrorKind::ParseUnderflow` if the buffer is too small. +/// * `TpmErrorKind::TrailingData` if the buffer has unconsumed data after parsing. +fn parse_body (tag: data::TpmSt , buf: &[u8 ]) ->TpmResult <(Self , &[u8 ])>; +} +pub const TPM_HEADER_SIZE :usize =10 ;tpm_dispatch! {
src/message/parse.rs +1 -1
@@ -151,7 +151,7 @@ pub fn tpm_parse_response(cc: TpmCc, buf: &[u8]) -> TpmResult<TpmParseResult<'_> ) })?; -let (body,mut session_area) = (dispatch.2 )(body_buf)?; +let (body,mut session_area) = (dispatch.2 )(tag, body_buf)?;let mut auth_responses =TpmAuthResponses ::new ();if tag ==TpmSt ::Sessions {
tests/runner.rs +44 -60
146 lines not on this page · raw message
Signature · 1 line
2.39.5
Quoted 60 lines · Jarkko Sakkinen
Here's the failing case:
8001000000300000000002000000002000647915de6106c955b26456b8b8a3b10546fa446405d4eb2e1fb0247fb52080
What happens is that
tpm_parse_responsereturnsParserUnderflow, and parsing fails (gracefully).The root cause is incorrect interpretation of commands being applicable both with and without sessions. In the failing case the response is captured from a run of
tpm2sh start-session.It has hard to define the failing commit since this project barely has kicked off, and the recent history is encompassed of major overhauls in order to get where it is right now but most likely the failure was caused by when refactoring away from having
tpm_response!in favor of universaltpm_struct!.I highlight the parts of the diff that are relevant for addressing the issue:
First an analogous trait to
TpmCommandBodyParseis defined for delivering the "discovered" tag in the different layers of the response parser:pub(crate) trait TpmResponseBodyParse: Sized { /// Parses the response body from a buffer, using the response tag to determine /// the structure. fn parse_body(tag: data::TpmSt, buf: &[u8]) -> TpmResult<(Self, &[u8])>; }Then the trait call is patched to
tpm_dispatch!:src/macro/mod.rs +2
-2- |buf| { - <$rsp_ty>::parse (buf) + |tag, buf| { + <$rsp_tyas $crate::message::TpmResponseBodyParse >::parse_body (tag, buf)The dispatcher generated is orchestrated from the "entry function" i.e,
tpm_parse_response, so that's where the tag is originally supplied after doing a binary search toPARSE_RESPONSE_MAP:src/message/parse.rs +1
-1-let (body,mut session_area) = (dispatch.2 )(body_buf)?; +let (body,mut session_area) = (dispatch.2 )(tag, body_buf)?;Finally,
tpm_struct!is mirgated to provide the trait implementation:src/macro/struct.rs +3
-1-fn parse (buf: &[u8 ]) -> $crate::TpmResult <(Self , &[u8 ])> { +fn parse_body ( + tag: $crate::data::TpmSt , + buf: &[u8],And that's how tag is delivered to the new response body parser for implementing the actual upgraded logic:
src/macro/struct.rs +1
-2-if $with_sessions { -let (size, buf_after_size) = u32::parse (cursor)?; +if $with_sessions && tag == $crate::data::TpmSt ::Sessions {This fixes the bug and as is proven against the failing case by
test_response_start_auth_session_no_sessions_2.
Quoted 8 lines
However, this revealed a "symmetrical bug" in
tpm_build_response()leading to a failure in the final comparison of the test case.This led to the new
TpmResponseBodyBuild, which matches the logic with already pre-existingTpmCommandBodyBuild, and fixes essentiallyfn len().Signed-off-by Jarkko Sakkinen <[email protected]>
Since tpm2sh is a separate project I was a bit stressed whether the problem is fixed after releasing 0.10.21 of the stable 0.10.x branch but it clearly does:
❯ sudo RUST_TRACE=full RUST_LOG=trace target/debug/tpm2sh start-session
[sudo] password for jarkko:
[2025-09-02T17:05:31.895688Z TRACE cli::device] Command: 80010000003b0000017640000007400000070020c74f3cf4a9a62efe747457f8e8af8cd0bfb90a3725d62944a73002600617fd0e0000000010000b [2025-09-02T17:05:31.929485Z TRACE cli::device] Response: 800100000030000000000200000000208da38751c181fb84262d4e2dac59610fe5f14d5d177ecc3544afcb0ac8b47671 tpm://0x02000000
This also verifies that test_response_start_auth_session_no_sessions_2 is capturing the bug realistically, and it is factors less likely that the bug will retrigger.
BR, Jarkko