tpm2_protocol/message/
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::{data, tpm_dispatch, TpmBuild, TpmList, TpmResult, TpmWriter};
6use core::fmt::Debug;
7
8mod asymmetric;
9mod attached;
10mod attestation;
11mod audit;
12mod build;
13mod capability;
14mod clocks_and_timers;
15mod context;
16mod dictionary_attack;
17mod duplication;
18mod enhanced_authorization;
19mod ephemeral;
20mod field_upgrade;
21mod hierarchy;
22mod integrity;
23mod miscellaneous_management;
24mod non_volatile;
25mod object;
26mod parse;
27mod random_number;
28mod sequence;
29mod session;
30mod signing;
31mod startup;
32mod symmetric;
33mod testing;
34mod vendor;
35
36pub use self::{
37    asymmetric::*, attached::*, attestation::*, audit::*, build::*, capability::*,
38    clocks_and_timers::*, context::*, dictionary_attack::*, duplication::*,
39    enhanced_authorization::*, ephemeral::*, field_upgrade::*, hierarchy::*, integrity::*,
40    miscellaneous_management::*, non_volatile::*, object::*, parse::*, random_number::*,
41    sequence::*, session::*, signing::*, startup::*, symmetric::*, testing::*, vendor::*,
42};
43
44/// The maximum number of handles a command can have.
45pub const MAX_HANDLES: usize = 8;
46/// The maximum number of sessions a command can have.
47pub const MAX_SESSIONS: usize = 8;
48/// A fixed-capacity list for TPM handles.
49pub type TpmHandles = TpmList<u32, MAX_HANDLES>;
50/// A fixed-capacity list for command authorization sessions.
51pub type TpmAuthCommands = TpmList<data::TpmsAuthCommand, MAX_SESSIONS>;
52/// A fixed-capacity list for response authorization sessions.
53pub type TpmAuthResponses = TpmList<data::TpmsAuthResponse, MAX_SESSIONS>;
54/// A trait for TPM commands and responses that provides header information.
55pub trait TpmHeader: TpmBuild + Debug {
56    const COMMAND: data::TpmCc;
57    const NO_SESSIONS: bool;
58    const WITH_SESSIONS: bool;
59    const HANDLES: usize;
60}
61
62/// A trait for building command bodies in separate handle and parameter sections.
63pub trait TpmCommandBuild {
64    /// Builds the handle area of the command.
65    ///
66    /// # Errors
67    ///
68    /// * `TpmErrorKind::BuildOverflow` if writer would run out of space.
69    fn build_handles(&self, writer: &mut TpmWriter) -> TpmResult<()>;
70
71    /// Builds the parameter area of the command.
72    ///
73    /// # Errors
74    ///
75    /// * `TpmErrorKind::BuildCapacity` if the object contains a value exceeding capacity limit.
76    /// * `TpmErrorKind::BuildOverflow` if writer would run out of space.
77    fn build_parameters(&self, writer: &mut TpmWriter) -> TpmResult<()>;
78}
79
80/// A trait for building response bodies in separate handle and parameter sections.
81pub trait TpmResponseBuild {
82    /// Builds the handle area of the response.
83    ///
84    /// # Errors
85    ///
86    /// * `TpmErrorKind::BuildOverflow` if writer would run out of space.
87    fn build_handles(&self, writer: &mut TpmWriter) -> TpmResult<()>;
88
89    /// Builds the parameter area of the response.
90    ///
91    /// # Errors
92    ///
93    /// * `TpmErrorKind::BuildCapacity` if the object contains a value exceeding capacity limit.
94    /// * `TpmErrorKind::BuildOverflow` if writer would run out of space.
95    fn build_parameters(&self, writer: &mut TpmWriter) -> TpmResult<()>;
96}
97
98/// Parses a command body from the slices point out to the handle area and
99/// parameter area of the original buffer.
100pub(crate) trait TpmCommandBodyParse: Sized {
101    /// Parses the command body from the handle and parameter area.
102    ///
103    /// # Errors
104    ///
105    /// * `TpmErrorKind::ParseCapacity` if the capacity limit is exceeded
106    /// * `TpmErrorKind::ParseUnderflow` if the parser runs out of bytes
107    fn parse_body<'a>(handles: &'a [u8], params: &'a [u8]) -> TpmResult<(Self, &'a [u8])>;
108}
109
110/// Parses a response body using the response tag to handle structural variations.
111pub trait TpmResponseBodyParse: Sized {
112    /// Parses the response body from a buffer, using the response tag dynamically
113    /// to determine the structure.
114    ///
115    /// # Errors
116    ///
117    /// This method can return parsing errors such as:
118    /// * `TpmErrorKind::ParseUnderflow` if the buffer is too small.
119    /// * `TpmErrorKind::TrailingData` if the buffer has unconsumed data after parsing.
120    fn parse_body(tag: data::TpmSt, buf: &[u8]) -> TpmResult<(Self, &[u8])>;
121}
122
123pub const TPM_HEADER_SIZE: usize = 10;
124
125tpm_dispatch! {
126    (TpmNvUndefineSpaceSpecialCommand, TpmNvUndefineSpaceSpecialResponse, NvUndefineSpaceSpecial),
127    (TpmEvictControlCommand, TpmEvictControlResponse, EvictControl),
128    (TpmHierarchyControlCommand, TpmHierarchyControlResponse, HierarchyControl),
129    (TpmNvUndefineSpaceCommand, TpmNvUndefineSpaceResponse, NvUndefineSpace),
130    (TpmChangeEpsCommand, TpmChangeEpsResponse, ChangeEps),
131    (TpmChangePpsCommand, TpmChangePpsResponse, ChangePps),
132    (TpmClearCommand, TpmClearResponse, Clear),
133    (TpmClearControlCommand, TpmClearControlResponse, ClearControl),
134    (TpmClockSetCommand, TpmClockSetResponse, ClockSet),
135    (TpmHierarchyChangeAuthCommand, TpmHierarchyChangeAuthResponse, HierarchyChangeAuth),
136    (TpmNvDefineSpaceCommand, TpmNvDefineSpaceResponse, NvDefineSpace),
137    (TpmPcrAllocateCommand, TpmPcrAllocateResponse, PcrAllocate),
138    (TpmPcrSetAuthPolicyCommand, TpmPcrSetAuthPolicyResponse, PcrSetAuthPolicy),
139    (TpmPpCommandsCommand, TpmPpCommandsResponse, PpCommands),
140    (TpmSetPrimaryPolicyCommand, TpmSetPrimaryPolicyResponse, SetPrimaryPolicy),
141    (TpmFieldUpgradeStartCommand, TpmFieldUpgradeStartResponse, FieldUpgradeStart),
142    (TpmClockRateAdjustCommand, TpmClockRateAdjustResponse, ClockRateAdjust),
143    (TpmCreatePrimaryCommand, TpmCreatePrimaryResponse, CreatePrimary),
144    (TpmNvGlobalWriteLockCommand, TpmNvGlobalWriteLockResponse, NvGlobalWriteLock),
145    (TpmGetCommandAuditDigestCommand, TpmGetCommandAuditDigestResponse, GetCommandAuditDigest),
146    (TpmNvIncrementCommand, TpmNvIncrementResponse, NvIncrement),
147    (TpmNvSetBitsCommand, TpmNvSetBitsResponse, NvSetBits),
148    (TpmNvExtendCommand, TpmNvExtendResponse, NvExtend),
149    (TpmNvWriteCommand, TpmNvWriteResponse, NvWrite),
150    (TpmNvWriteLockCommand, TpmNvWriteLockResponse, NvWriteLock),
151    (TpmDictionaryAttackLockResetCommand, TpmDictionaryAttackLockResetResponse, DictionaryAttackLockReset),
152    (TpmDictionaryAttackParametersCommand, TpmDictionaryAttackParametersResponse, DictionaryAttackParameters),
153    (TpmNvChangeAuthCommand, TpmNvChangeAuthResponse, NvChangeAuth),
154    (TpmPcrEventCommand, TpmPcrEventResponse, PcrEvent),
155    (TpmPcrResetCommand, TpmPcrResetResponse, PcrReset),
156    (TpmSequenceCompleteCommand, TpmSequenceCompleteResponse, SequenceComplete),
157    (TpmSetAlgorithmSetCommand, TpmSetAlgorithmSetResponse, SetAlgorithmSet),
158    (TpmSetCommandCodeAuditStatusCommand, TpmSetCommandCodeAuditStatusResponse, SetCommandCodeAuditStatus),
159    (TpmFieldUpgradeDataCommand, TpmFieldUpgradeDataResponse, FieldUpgradeData),
160    (TpmIncrementalSelfTestCommand, TpmIncrementalSelfTestResponse, IncrementalSelfTest),
161    (TpmSelfTestCommand, TpmSelfTestResponse, SelfTest),
162    (TpmStartupCommand, TpmStartupResponse, Startup),
163    (TpmShutdownCommand, TpmShutdownResponse, Shutdown),
164    (TpmStirRandomCommand, TpmStirRandomResponse, StirRandom),
165    (TpmActivateCredentialCommand, TpmActivateCredentialResponse, ActivateCredential),
166    (TpmCertifyCommand, TpmCertifyResponse, Certify),
167    (TpmPolicyNvCommand, TpmPolicyNvResponse, PolicyNv),
168    (TpmCertifyCreationCommand, TpmCertifyCreationResponse, CertifyCreation),
169    (TpmDuplicateCommand, TpmDuplicateResponse, Duplicate),
170    (TpmGetTimeCommand, TpmGetTimeResponse, GetTime),
171    (TpmGetSessionAuditDigestCommand, TpmGetSessionAuditDigestResponse, GetSessionAuditDigest),
172    (TpmNvReadCommand, TpmNvReadResponse, NvRead),
173    (TpmNvReadLockCommand, TpmNvReadLockResponse, NvReadLock),
174    (TpmObjectChangeAuthCommand, TpmObjectChangeAuthResponse, ObjectChangeAuth),
175    (TpmPolicySecretCommand, TpmPolicySecretResponse, PolicySecret),
176    (TpmRewrapCommand, TpmRewrapResponse, Rewrap),
177    (TpmCreateCommand, TpmCreateResponse, Create),
178    (TpmEcdhZGenCommand, TpmEcdhZGenResponse, EcdhZGen),
179    (TpmHmacCommand, TpmHmacResponse, Hmac),
180    (TpmImportCommand, TpmImportResponse, Import),
181    (TpmLoadCommand, TpmLoadResponse, Load),
182    (TpmQuoteCommand, TpmQuoteResponse, Quote),
183    (TpmRsaDecryptCommand, TpmRsaDecryptResponse, RsaDecrypt),
184    (TpmHmacStartCommand, TpmHmacStartResponse, HmacStart),
185    (TpmSequenceUpdateCommand, TpmSequenceUpdateResponse, SequenceUpdate),
186    (TpmSignCommand, TpmSignResponse, Sign),
187    (TpmUnsealCommand, TpmUnsealResponse, Unseal),
188    (TpmPolicySignedCommand, TpmPolicySignedResponse, PolicySigned),
189    (TpmContextLoadCommand, TpmContextLoadResponse, ContextLoad),
190    (TpmContextSaveCommand, TpmContextSaveResponse, ContextSave),
191    (TpmEcdhKeyGenCommand, TpmEcdhKeyGenResponse, EcdhKeyGen),
192    (TpmEncryptDecryptCommand, TpmEncryptDecryptResponse, EncryptDecrypt),
193    (TpmFlushContextCommand, TpmFlushContextResponse, FlushContext),
194    (TpmLoadExternalCommand, TpmLoadExternalResponse, LoadExternal),
195    (TpmMakeCredentialCommand, TpmMakeCredentialResponse, MakeCredential),
196    (TpmNvReadPublicCommand, TpmNvReadPublicResponse, NvReadPublic),
197    (TpmPolicyAuthorizeCommand, TpmPolicyAuthorizeResponse, PolicyAuthorize),
198    (TpmPolicyAuthValueCommand, TpmPolicyAuthValueResponse, PolicyAuthValue),
199    (TpmPolicyCommandCodeCommand, TpmPolicyCommandCodeResponse, PolicyCommandCode),
200    (TpmPolicyCounterTimerCommand, TpmPolicyCounterTimerResponse, PolicyCounterTimer),
201    (TpmPolicyCpHashCommand, TpmPolicyCpHashResponse, PolicyCpHash),
202    (TpmPolicyLocalityCommand, TpmPolicyLocalityResponse, PolicyLocality),
203    (TpmPolicyNameHashCommand, TpmPolicyNameHashResponse, PolicyNameHash),
204    (TpmPolicyOrCommand, TpmPolicyOrResponse, PolicyOr),
205    (TpmPolicyTicketCommand, TpmPolicyTicketResponse, PolicyTicket),
206    (TpmReadPublicCommand, TpmReadPublicResponse, ReadPublic),
207    (TpmRsaEncryptCommand, TpmRsaEncryptResponse, RsaEncrypt),
208    (TpmStartAuthSessionCommand, TpmStartAuthSessionResponse, StartAuthSession),
209    (TpmVerifySignatureCommand, TpmVerifySignatureResponse, VerifySignature),
210    (TpmEccParametersCommand, TpmEccParametersResponse, EccParameters),
211    (TpmFirmwareReadCommand, TpmFirmwareReadResponse, FirmwareRead),
212    (TpmGetCapabilityCommand, TpmGetCapabilityResponse, GetCapability),
213    (TpmGetRandomCommand, TpmGetRandomResponse, GetRandom),
214    (TpmGetTestResultCommand, TpmGetTestResultResponse, GetTestResult),
215    (TpmHashCommand, TpmHashResponse, Hash),
216    (TpmPcrReadCommand, TpmPcrReadResponse, PcrRead),
217    (TpmPolicyPcrCommand, TpmPolicyPcrResponse, PolicyPcr),
218    (TpmPolicyRestartCommand, TpmPolicyRestartResponse, PolicyRestart),
219    (TpmReadClockCommand, TpmReadClockResponse, ReadClock),
220    (TpmPcrExtendCommand, TpmPcrExtendResponse, PcrExtend),
221    (TpmPcrSetAuthValueCommand, TpmPcrSetAuthValueResponse, PcrSetAuthValue),
222    (TpmNvCertifyCommand, TpmNvCertifyResponse, NvCertify),
223    (TpmEventSequenceCompleteCommand, TpmEventSequenceCompleteResponse, EventSequenceComplete),
224    (TpmHashSequenceStartCommand, TpmHashSequenceStartResponse, HashSequenceStart),
225    (TpmPolicyPhysicalPresenceCommand, TpmPolicyPhysicalPresenceResponse, PolicyPhysicalPresence),
226    (TpmPolicyDuplicationSelectCommand, TpmPolicyDuplicationSelectResponse, PolicyDuplicationSelect),
227    (TpmPolicyGetDigestCommand, TpmPolicyGetDigestResponse, PolicyGetDigest),
228    (TpmTestParmsCommand, TpmTestParmsResponse, TestParms),
229    (TpmCommitCommand, TpmCommitResponse, Commit),
230    (TpmPolicyPasswordCommand, TpmPolicyPasswordResponse, PolicyPassword),
231    (TpmZGen2PhaseCommand, TpmZGen2PhaseResponse, ZGen2Phase),
232    (TpmEcEphemeralCommand, TpmEcEphemeralResponse, EcEphemeral),
233    (TpmPolicyNvWrittenCommand, TpmPolicyNvWrittenResponse, PolicyNvWritten),
234    (TpmPolicyTemplateCommand, TpmPolicyTemplateResponse, PolicyTemplate),
235    (TpmCreateLoadedCommand, TpmCreateLoadedResponse, CreateLoaded),
236    (TpmPolicyAuthorizeNvCommand, TpmPolicyAuthorizeNvResponse, PolicyAuthorizeNv),
237    (TpmEncryptDecrypt2Command, TpmEncryptDecrypt2Response, EncryptDecrypt2),
238    (TpmAcGetCapabilityCommand, TpmAcGetCapabilityResponse, AcGetCapability),
239    (TpmAcSendCommand, TpmAcSendResponse, AcSend),
240    (TpmPolicyAcSendSelectCommand, TpmPolicyAcSendSelectResponse, PolicyAcSendSelect),
241    (TpmActSetTimeoutCommand, TpmActSetTimeoutResponse, ActSetTimeout),
242    (TpmPolicyCapabilityCommand, TpmPolicyCapabilityResponse, PolicyCapability),
243    (TpmPolicyParametersCommand, TpmPolicyParametersResponse, PolicyParameters),
244    (TpmNvDefineSpace2Command, TpmNvDefineSpace2Response, NvDefineSpace2),
245    (TpmNvReadPublic2Command, TpmNvReadPublic2Response, NvReadPublic2),
246    (TpmReadOnlyControlCommand, TpmReadOnlyControlResponse, ReadOnlyControl),
247    (TpmPolicyTransportSpdmCommand, TpmPolicyTransportSpdmResponse, PolicyTransportSpdm),
248    (TpmVendorTcgTestCommand, TpmVendorTcgTestResponse, VendorTcgTest),
249}