Skip to main content

tpm2_protocol/frame/
mod.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2025 Opinsys Oy
3// Copyright (c) 2024-2025 Jarkko Sakkinen
4
5use crate::{
6    TpmError, TpmMarshal, TpmResult, TpmSized, TpmUnmarshal, TpmWriter,
7    basic::{TpmHandle, TpmList},
8};
9use core::fmt::Debug;
10
11mod data;
12mod marshal;
13mod unmarshal;
14mod wire;
15
16pub use self::{data::*, marshal::*, wire::*};
17
18pub(crate) use self::unmarshal::TpmDispatch;
19
20use crate::constant::MAX_SESSIONS;
21
22const TPM_HEADER_SIZE: u32 = 10;
23
24/// A fixed-capacity list for command authorization sessions.
25pub type TpmAuthCommands = TpmList<crate::data::TpmsAuthCommand, MAX_SESSIONS>;
26
27/// A fixed-capacity list for response authorization sessions.
28pub type TpmAuthResponses = TpmList<crate::data::TpmsAuthResponse, MAX_SESSIONS>;
29
30/// A trait for TPM commands and responses that provides static header information.
31pub trait TpmHeader {
32    /// The Command Code (CC) for the command or response.
33    const CC: crate::data::TpmCc;
34    /// The number of handles in the handle area.
35    const HANDLES: usize;
36}
37
38/// A trait for TPM commands and responses that provides dynamic frame information.
39pub trait TpmFrame: TpmMarshal + TpmMarshalBody + Debug {
40    /// Returns the Command Code (CC) for the command or response.
41    fn cc(&self) -> crate::data::TpmCc;
42    /// Returns the number of handles in the handle area.
43    fn handles(&self) -> usize;
44}
45
46/// A trait for marshaling command/response bodies in separate handle and parameter sections.
47pub trait TpmMarshalBody: TpmSized {
48    /// Marshals the handle area.
49    ///
50    /// # Errors
51    ///
52    /// Returns `Err(TpmError)` on a marshal failure.
53    fn marshal_handles(&self, writer: &mut TpmWriter) -> TpmResult<()>;
54
55    /// Marshals the parameter area.
56    ///
57    /// # Errors
58    ///
59    /// Returns `Err(TpmError)` on a marshal failure.
60    fn marshal_parameters(&self, writer: &mut TpmWriter) -> TpmResult<()>;
61}
62
63/// Reconstructs an owned command/response body from separate handle and parameter areas.
64pub trait TpmUnmarshalBody: TpmHeader + Sized {
65    /// Reads the handle area and parameter area into an owned body.
66    ///
67    /// # Errors
68    ///
69    /// Returns `Err(TpmError)` when either area is malformed or contains trailing data.
70    fn unmarshal_body(handles: &[u8], parameters: &[u8]) -> TpmResult<Self>;
71}
72
73/// Reads exactly `N` handles and rejects leftover bytes.
74pub(crate) fn unmarshal_handle_area<const N: usize>(
75    mut buffer: &[u8],
76) -> TpmResult<[TpmHandle; N]> {
77    let mut handles = [TpmHandle::new(0); N];
78    for slot in &mut handles {
79        let (handle, tail) = TpmHandle::unmarshal(buffer)?;
80        *slot = handle;
81        buffer = tail;
82    }
83    ensure_consumed(buffer)?;
84    Ok(handles)
85}
86
87/// Rejects leftover bytes after an exact unmarshal.
88pub(crate) fn ensure_consumed(buffer: &[u8]) -> TpmResult<()> {
89    if buffer.is_empty() {
90        Ok(())
91    } else {
92        Err(TpmError::TrailingData {
93            offset: 0,
94            actual: buffer.len(),
95        })
96    }
97}
98
99tpm_dispatch! {
100    (TpmNvUndefineSpaceSpecialCommand, TpmNvUndefineSpaceSpecialResponse, NvUndefineSpaceSpecial),
101    (TpmEvictControlCommand, TpmEvictControlResponse, EvictControl),
102    (TpmHierarchyControlCommand, TpmHierarchyControlResponse, HierarchyControl),
103    (TpmNvUndefineSpaceCommand, TpmNvUndefineSpaceResponse, NvUndefineSpace),
104    (TpmChangeEpsCommand, TpmChangeEpsResponse, ChangeEps),
105    (TpmChangePpsCommand, TpmChangePpsResponse, ChangePps),
106    (TpmClearCommand, TpmClearResponse, Clear),
107    (TpmClearControlCommand, TpmClearControlResponse, ClearControl),
108    (TpmClockSetCommand, TpmClockSetResponse, ClockSet),
109    (TpmHierarchyChangeAuthCommand, TpmHierarchyChangeAuthResponse, HierarchyChangeAuth),
110    (TpmNvDefineSpaceCommand, TpmNvDefineSpaceResponse, NvDefineSpace),
111    (TpmPcrAllocateCommand, TpmPcrAllocateResponse, PcrAllocate),
112    (TpmPcrSetAuthPolicyCommand, TpmPcrSetAuthPolicyResponse, PcrSetAuthPolicy),
113    (TpmPpCommandsCommand, TpmPpCommandsResponse, PpCommands),
114    (TpmSetPrimaryPolicyCommand, TpmSetPrimaryPolicyResponse, SetPrimaryPolicy),
115    (TpmFieldUpgradeStartCommand, TpmFieldUpgradeStartResponse, FieldUpgradeStart),
116    (TpmClockRateAdjustCommand, TpmClockRateAdjustResponse, ClockRateAdjust),
117    (TpmCreatePrimaryCommand, TpmCreatePrimaryResponse, CreatePrimary),
118    (TpmNvGlobalWriteLockCommand, TpmNvGlobalWriteLockResponse, NvGlobalWriteLock),
119    (TpmGetCommandAuditDigestCommand, TpmGetCommandAuditDigestResponse, GetCommandAuditDigest),
120    (TpmNvIncrementCommand, TpmNvIncrementResponse, NvIncrement),
121    (TpmNvSetBitsCommand, TpmNvSetBitsResponse, NvSetBits),
122    (TpmNvExtendCommand, TpmNvExtendResponse, NvExtend),
123    (TpmNvWriteCommand, TpmNvWriteResponse, NvWrite),
124    (TpmNvWriteLockCommand, TpmNvWriteLockResponse, NvWriteLock),
125    (TpmDictionaryAttackLockResetCommand, TpmDictionaryAttackLockResetResponse, DictionaryAttackLockReset),
126    (TpmDictionaryAttackParametersCommand, TpmDictionaryAttackParametersResponse, DictionaryAttackParameters),
127    (TpmNvChangeAuthCommand, TpmNvChangeAuthResponse, NvChangeAuth),
128    (TpmPcrEventCommand, TpmPcrEventResponse, PcrEvent),
129    (TpmPcrResetCommand, TpmPcrResetResponse, PcrReset),
130    (TpmSequenceCompleteCommand, TpmSequenceCompleteResponse, SequenceComplete),
131    (TpmSetAlgorithmSetCommand, TpmSetAlgorithmSetResponse, SetAlgorithmSet),
132    (TpmSetCommandCodeAuditStatusCommand, TpmSetCommandCodeAuditStatusResponse, SetCommandCodeAuditStatus),
133    (TpmFieldUpgradeDataCommand, TpmFieldUpgradeDataResponse, FieldUpgradeData),
134    (TpmIncrementalSelfTestCommand, TpmIncrementalSelfTestResponse, IncrementalSelfTest),
135    (TpmSelfTestCommand, TpmSelfTestResponse, SelfTest),
136    (TpmStartupCommand, TpmStartupResponse, Startup),
137    (TpmShutdownCommand, TpmShutdownResponse, Shutdown),
138    (TpmStirRandomCommand, TpmStirRandomResponse, StirRandom),
139    (TpmActivateCredentialCommand, TpmActivateCredentialResponse, ActivateCredential),
140    (TpmCertifyCommand, TpmCertifyResponse, Certify),
141    (TpmPolicyNvCommand, TpmPolicyNvResponse, PolicyNv),
142    (TpmCertifyCreationCommand, TpmCertifyCreationResponse, CertifyCreation),
143    (TpmDuplicateCommand, TpmDuplicateResponse, Duplicate),
144    (TpmGetTimeCommand, TpmGetTimeResponse, GetTime),
145    (TpmGetSessionAuditDigestCommand, TpmGetSessionAuditDigestResponse, GetSessionAuditDigest),
146    (TpmNvReadCommand, TpmNvReadResponse, NvRead),
147    (TpmNvReadLockCommand, TpmNvReadLockResponse, NvReadLock),
148    (TpmObjectChangeAuthCommand, TpmObjectChangeAuthResponse, ObjectChangeAuth),
149    (TpmPolicySecretCommand, TpmPolicySecretResponse, PolicySecret),
150    (TpmRewrapCommand, TpmRewrapResponse, Rewrap),
151    (TpmCreateCommand, TpmCreateResponse, Create),
152    (TpmEcdhZGenCommand, TpmEcdhZGenResponse, EcdhZGen),
153    (TpmHmacCommand, TpmHmacResponse, Hmac),
154    (TpmImportCommand, TpmImportResponse, Import),
155    (TpmLoadCommand, TpmLoadResponse, Load),
156    (TpmQuoteCommand, TpmQuoteResponse, Quote),
157    (TpmRsaDecryptCommand, TpmRsaDecryptResponse, RsaDecrypt),
158    (TpmHmacStartCommand, TpmHmacStartResponse, HmacStart),
159    (TpmSequenceUpdateCommand, TpmSequenceUpdateResponse, SequenceUpdate),
160    (TpmSignCommand, TpmSignResponse, Sign),
161    (TpmUnsealCommand, TpmUnsealResponse, Unseal),
162    (TpmPolicySignedCommand, TpmPolicySignedResponse, PolicySigned),
163    (TpmContextLoadCommand, TpmContextLoadResponse, ContextLoad),
164    (TpmContextSaveCommand, TpmContextSaveResponse, ContextSave),
165    (TpmEcdhKeyGenCommand, TpmEcdhKeyGenResponse, EcdhKeyGen),
166    (TpmEncryptDecryptCommand, TpmEncryptDecryptResponse, EncryptDecrypt),
167    (TpmFlushContextCommand, TpmFlushContextResponse, FlushContext),
168    (TpmLoadExternalCommand, TpmLoadExternalResponse, LoadExternal),
169    (TpmMakeCredentialCommand, TpmMakeCredentialResponse, MakeCredential),
170    (TpmNvReadPublicCommand, TpmNvReadPublicResponse, NvReadPublic),
171    (TpmPolicyAuthorizeCommand, TpmPolicyAuthorizeResponse, PolicyAuthorize),
172    (TpmPolicyAuthValueCommand, TpmPolicyAuthValueResponse, PolicyAuthValue),
173    (TpmPolicyCommandCodeCommand, TpmPolicyCommandCodeResponse, PolicyCommandCode),
174    (TpmPolicyCounterTimerCommand, TpmPolicyCounterTimerResponse, PolicyCounterTimer),
175    (TpmPolicyCpHashCommand, TpmPolicyCpHashResponse, PolicyCpHash),
176    (TpmPolicyLocalityCommand, TpmPolicyLocalityResponse, PolicyLocality),
177    (TpmPolicyNameHashCommand, TpmPolicyNameHashResponse, PolicyNameHash),
178    (TpmPolicyOrCommand, TpmPolicyOrResponse, PolicyOr),
179    (TpmPolicyTicketCommand, TpmPolicyTicketResponse, PolicyTicket),
180    (TpmReadPublicCommand, TpmReadPublicResponse, ReadPublic),
181    (TpmRsaEncryptCommand, TpmRsaEncryptResponse, RsaEncrypt),
182    (TpmStartAuthSessionCommand, TpmStartAuthSessionResponse, StartAuthSession),
183    (TpmVerifySignatureCommand, TpmVerifySignatureResponse, VerifySignature),
184    (TpmEccParametersCommand, TpmEccParametersResponse, EccParameters),
185    (TpmFirmwareReadCommand, TpmFirmwareReadResponse, FirmwareRead),
186    (TpmGetCapabilityCommand, TpmGetCapabilityResponse, GetCapability),
187    (TpmGetRandomCommand, TpmGetRandomResponse, GetRandom),
188    (TpmGetTestResultCommand, TpmGetTestResultResponse, GetTestResult),
189    (TpmHashCommand, TpmHashResponse, Hash),
190    (TpmPcrReadCommand, TpmPcrReadResponse, PcrRead),
191    (TpmPolicyPcrCommand, TpmPolicyPcrResponse, PolicyPcr),
192    (TpmPolicyRestartCommand, TpmPolicyRestartResponse, PolicyRestart),
193    (TpmReadClockCommand, TpmReadClockResponse, ReadClock),
194    (TpmPcrExtendCommand, TpmPcrExtendResponse, PcrExtend),
195    (TpmPcrSetAuthValueCommand, TpmPcrSetAuthValueResponse, PcrSetAuthValue),
196    (TpmNvCertifyCommand, TpmNvCertifyResponse, NvCertify),
197    (TpmEventSequenceCompleteCommand, TpmEventSequenceCompleteResponse, EventSequenceComplete),
198    (TpmHashSequenceStartCommand, TpmHashSequenceStartResponse, HashSequenceStart),
199    (TpmPolicyPhysicalPresenceCommand, TpmPolicyPhysicalPresenceResponse, PolicyPhysicalPresence),
200    (TpmPolicyDuplicationSelectCommand, TpmPolicyDuplicationSelectResponse, PolicyDuplicationSelect),
201    (TpmPolicyGetDigestCommand, TpmPolicyGetDigestResponse, PolicyGetDigest),
202    (TpmTestParmsCommand, TpmTestParmsResponse, TestParms),
203    (TpmCommitCommand, TpmCommitResponse, Commit),
204    (TpmPolicyPasswordCommand, TpmPolicyPasswordResponse, PolicyPassword),
205    (TpmZGen2PhaseCommand, TpmZGen2PhaseResponse, ZGen2Phase),
206    (TpmEcEphemeralCommand, TpmEcEphemeralResponse, EcEphemeral),
207    (TpmPolicyNvWrittenCommand, TpmPolicyNvWrittenResponse, PolicyNvWritten),
208    (TpmPolicyTemplateCommand, TpmPolicyTemplateResponse, PolicyTemplate),
209    (TpmCreateLoadedCommand, TpmCreateLoadedResponse, CreateLoaded),
210    (TpmPolicyAuthorizeNvCommand, TpmPolicyAuthorizeNvResponse, PolicyAuthorizeNv),
211    (TpmEncryptDecrypt2Command, TpmEncryptDecrypt2Response, EncryptDecrypt2),
212    (TpmAcGetCapabilityCommand, TpmAcGetCapabilityResponse, AcGetCapability),
213    (TpmAcSendCommand, TpmAcSendResponse, AcSend),
214    (TpmPolicyAcSendSelectCommand, TpmPolicyAcSendSelectResponse, PolicyAcSendSelect),
215    (TpmActSetTimeoutCommand, TpmActSetTimeoutResponse, ActSetTimeout),
216    (TpmEccEncryptCommand, TpmEccEncryptResponse, EccEncrypt),
217    (TpmEccDecryptCommand, TpmEccDecryptResponse, EccDecrypt),
218    (TpmPolicyCapabilityCommand, TpmPolicyCapabilityResponse, PolicyCapability),
219    (TpmPolicyParametersCommand, TpmPolicyParametersResponse, PolicyParameters),
220    (TpmNvDefineSpace2Command, TpmNvDefineSpace2Response, NvDefineSpace2),
221    (TpmNvReadPublic2Command, TpmNvReadPublic2Response, NvReadPublic2),
222    (TpmSetCapabilityCommand, TpmSetCapabilityResponse, SetCapability),
223    (TpmReadOnlyControlCommand, TpmReadOnlyControlResponse, ReadOnlyControl),
224    (TpmPolicyTransportSpdmCommand, TpmPolicyTransportSpdmResponse, PolicyTransportSpdm),
225    (TpmVendorTcgTestCommand, TpmVendorTcgTestResponse, VendorTcgTest),
226}