1use serde::{Deserialize, Serialize};
6use thiserror::Error;
7
8pub const SPDM_VERSION_1_0: u8 = 0x10;
9pub const SPDM_VERSION_1_1: u8 = 0x11;
10pub const SPDM_VERSION_1_2: u8 = 0x12;
11pub const SPDM_VERSION_1_3: u8 = 0x13;
12
13pub const CODE_GET_VERSION: u8 = 0x84;
14pub const CODE_VERSION: u8 = 0x04;
15pub const CODE_GET_CAPABILITIES: u8 = 0xE1;
16pub const CODE_CAPABILITIES: u8 = 0x61;
17pub const CODE_NEGOTIATE_ALGORITHMS: u8 = 0xE3;
18pub const CODE_ALGORITHMS: u8 = 0x63;
19pub const CODE_GET_DIGESTS: u8 = 0x81;
20pub const CODE_DIGESTS: u8 = 0x01;
21pub const CODE_GET_CERTIFICATE: u8 = 0x82;
22pub const CODE_CERTIFICATE: u8 = 0x02;
23pub const CODE_CHALLENGE: u8 = 0x83;
24pub const CODE_CHALLENGE_AUTH: u8 = 0x03;
25pub const CODE_GET_MEASUREMENTS: u8 = 0xE0;
26pub const CODE_MEASUREMENTS: u8 = 0x60;
27pub const CODE_ERROR: u8 = 0x7F;
28
29pub const HASH_ALG_SHA_256: u32 = 0x00000001;
30pub const HASH_ALG_SHA_384: u32 = 0x00000002;
31pub const HASH_ALG_SHA_512: u32 = 0x00000004;
32
33pub const ASYM_ALG_ECDSA_P256: u32 = 0x00000001;
34pub const ASYM_ALG_ECDSA_P384: u32 = 0x00000002;
35pub const ASYM_ALG_ED25519: u32 = 0x00000040;
36
37pub const DMTF_SPEC_MEASUREMENT: u8 = 0x01;
38
39pub const MEASUREMENT_TYPE_IMMUTABLE_ROM: u8 = 0x01;
40pub const MEASUREMENT_TYPE_MUTABLE_FIRMWARE: u8 = 0x02;
41pub const MEASUREMENT_TYPE_HARDWARE_CONFIG: u8 = 0x03;
42pub const MEASUREMENT_TYPE_FIRMWARE_CONFIG: u8 = 0x04;
43
44#[derive(Debug, Error)]
45pub enum ProtocolError {
46 #[error("Buffer too short: expected at least {expected} bytes, got {actual}")]
47 BufferTooShort { expected: usize, actual: usize },
48
49 #[error("Invalid SPDM header: version {version:#04x}, code {code:#04x}")]
50 InvalidHeader { version: u8, code: u8 },
51
52 #[error("Unsupported SPDM version: {0:#04x}")]
53 UnsupportedVersion(u8),
54
55 #[error("Unsupported hash algorithm: {0:#010x}")]
56 UnsupportedHashAlgorithm(u32),
57
58 #[error("Unsupported asymmetric algorithm: {0:#010x}")]
59 UnsupportedAsymAlgorithm(u32),
60
61 #[error("Malformed measurement block: {0}")]
62 MalformedMeasurementBlock(String),
63
64 #[error("Measurement record length mismatch: declared {declared}, parsed {parsed}")]
65 MeasurementLengthMismatch { declared: usize, parsed: usize },
66
67 #[error("Invalid signature length: {0}")]
68 InvalidSignatureLength(usize),
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
73pub struct SpdmHeader {
74 pub version: u8,
75 pub code: u8,
76 pub param1: u8,
77 pub param2: u8,
78}
79
80impl SpdmHeader {
81 pub const SIZE: usize = 4;
82
83 pub fn new(version: u8, code: u8, param1: u8, param2: u8) -> Self {
84 Self {
85 version,
86 code,
87 param1,
88 param2,
89 }
90 }
91
92 pub fn parse(buf: &[u8]) -> Result<Self, ProtocolError> {
93 if buf.len() < Self::SIZE {
94 return Err(ProtocolError::BufferTooShort {
95 expected: Self::SIZE,
96 actual: buf.len(),
97 });
98 }
99 Ok(Self {
100 version: buf[0],
101 code: buf[1],
102 param1: buf[2],
103 param2: buf[3],
104 })
105 }
106
107 pub fn write_to(&self, buf: &mut Vec<u8>) {
108 buf.push(self.version);
109 buf.push(self.code);
110 buf.push(self.param1);
111 buf.push(self.param2);
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct MeasurementBlock {
118 pub index: u8,
119 pub spec: u8,
120 pub value_type: u8,
121 pub value: Vec<u8>,
122}
123
124impl MeasurementBlock {
125 pub fn type_name(&self) -> &'static str {
126 match self.value_type & 0x7F {
127 MEASUREMENT_TYPE_IMMUTABLE_ROM => "Immutable Secure Boot ROM",
128 MEASUREMENT_TYPE_MUTABLE_FIRMWARE => "Mutable Firmware / Microcode",
129 MEASUREMENT_TYPE_HARDWARE_CONFIG => "Hardware Config / Security Registers",
130 MEASUREMENT_TYPE_FIRMWARE_CONFIG => "Firmware Config / VBIOS",
131 _ => "Unknown / Vendor-Defined",
132 }
133 }
134
135 pub fn is_raw_bitstream(&self) -> bool {
136 (self.value_type & 0x80) != 0
137 }
138
139 pub fn parse(buf: &[u8]) -> Result<(Self, usize), ProtocolError> {
140 if buf.len() < 4 {
141 return Err(ProtocolError::BufferTooShort {
142 expected: 4,
143 actual: buf.len(),
144 });
145 }
146 let index = buf[0];
147 let spec = buf[1];
148 let measurement_size = u16::from_le_bytes([buf[2], buf[3]]) as usize;
149
150 if buf.len() < 4 + measurement_size {
151 return Err(ProtocolError::BufferTooShort {
152 expected: 4 + measurement_size,
153 actual: buf.len(),
154 });
155 }
156
157 let inner = &buf[4..4 + measurement_size];
158 if spec == DMTF_SPEC_MEASUREMENT {
159 if inner.len() < 3 {
160 return Err(ProtocolError::MalformedMeasurementBlock(
161 "DMTF measurement payload too short".to_string(),
162 ));
163 }
164 let value_type = inner[0];
165 let val_size = u16::from_le_bytes([inner[1], inner[2]]) as usize;
166 if inner.len() < 3 + val_size {
167 return Err(ProtocolError::MalformedMeasurementBlock(
168 "DMTF measurement value length overflow".to_string(),
169 ));
170 }
171 let value = inner[3..3 + val_size].to_vec();
172 Ok((
173 Self {
174 index,
175 spec,
176 value_type,
177 value,
178 },
179 4 + measurement_size,
180 ))
181 } else {
182 Ok((
183 Self {
184 index,
185 spec,
186 value_type: 0,
187 value: inner.to_vec(),
188 },
189 4 + measurement_size,
190 ))
191 }
192 }
193
194 pub fn write_to(&self, buf: &mut Vec<u8>) {
195 buf.push(self.index);
196 buf.push(self.spec);
197
198 if self.spec == DMTF_SPEC_MEASUREMENT {
199 let inner_size = (3 + self.value.len()) as u16;
200 buf.extend_from_slice(&inner_size.to_le_bytes());
201 buf.push(self.value_type);
202 let val_size = self.value.len() as u16;
203 buf.extend_from_slice(&val_size.to_le_bytes());
204 buf.extend_from_slice(&self.value);
205 } else {
206 let inner_size = self.value.len() as u16;
207 buf.extend_from_slice(&inner_size.to_le_bytes());
208 buf.extend_from_slice(&self.value);
209 }
210 }
211}
212
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215pub struct MeasurementsResponse {
216 pub header: SpdmHeader,
217 pub number_of_blocks: u8,
218 pub blocks: Vec<MeasurementBlock>,
219 pub nonce: Option<[u8; 32]>,
220 pub opaque_data: Vec<u8>,
221 pub signature: Vec<u8>,
222}
223
224impl MeasurementsResponse {
225 pub fn parse(buf: &[u8], asym_algo: u32) -> Result<Self, ProtocolError> {
226 if buf.len() < 8 {
227 return Err(ProtocolError::BufferTooShort {
228 expected: 8,
229 actual: buf.len(),
230 });
231 }
232
233 let header = SpdmHeader::parse(buf)?;
234 if header.code != CODE_MEASUREMENTS {
235 return Err(ProtocolError::InvalidHeader {
236 version: header.version,
237 code: header.code,
238 });
239 }
240
241 let number_of_blocks = header.param1;
242 let sig_requested = (header.param2 & 0x01) != 0;
243
244 let record_len = (buf[4] as usize) | ((buf[5] as usize) << 8) | ((buf[6] as usize) << 16);
246 let mut offset = 8;
247
248 if buf.len() < offset + record_len {
249 return Err(ProtocolError::BufferTooShort {
250 expected: offset + record_len,
251 actual: buf.len(),
252 });
253 }
254
255 let record_end = offset + record_len;
256 let mut blocks = Vec::new();
257
258 while offset < record_end {
259 let (block, consumed) = MeasurementBlock::parse(&buf[offset..record_end])?;
260 blocks.push(block);
261 offset += consumed;
262 }
263
264 let mut nonce = None;
265 let mut opaque_data = Vec::new();
266 let mut signature = Vec::new();
267
268 if sig_requested {
269 if buf.len() < offset + 32 {
270 return Err(ProtocolError::BufferTooShort {
271 expected: offset + 32,
272 actual: buf.len(),
273 });
274 }
275 let mut n = [0u8; 32];
276 n.copy_from_slice(&buf[offset..offset + 32]);
277 nonce = Some(n);
278 offset += 32;
279
280 if buf.len() < offset + 2 {
281 return Err(ProtocolError::BufferTooShort {
282 expected: offset + 2,
283 actual: buf.len(),
284 });
285 }
286 let opaque_len = u16::from_le_bytes([buf[offset], buf[offset + 1]]) as usize;
287 offset += 2;
288
289 if buf.len() < offset + opaque_len {
290 return Err(ProtocolError::BufferTooShort {
291 expected: offset + opaque_len,
292 actual: buf.len(),
293 });
294 }
295 opaque_data = buf[offset..offset + opaque_len].to_vec();
296 offset += opaque_len;
297
298 let expected_sig_len = match asym_algo {
299 ASYM_ALG_ECDSA_P256 => 64,
300 ASYM_ALG_ECDSA_P384 => 96,
301 ASYM_ALG_ED25519 => 64,
302 _ => return Err(ProtocolError::UnsupportedAsymAlgorithm(asym_algo)),
303 };
304
305 if buf.len() < offset + expected_sig_len {
306 return Err(ProtocolError::BufferTooShort {
307 expected: offset + expected_sig_len,
308 actual: buf.len(),
309 });
310 }
311 signature = buf[offset..offset + expected_sig_len].to_vec();
312 }
313
314 Ok(Self {
315 header,
316 number_of_blocks,
317 blocks,
318 nonce,
319 opaque_data,
320 signature,
321 })
322 }
323
324 pub fn to_bytes(&self) -> Vec<u8> {
326 let mut buf = Vec::new();
327 let mut record_bytes = Vec::new();
328 for b in &self.blocks {
329 b.write_to(&mut record_bytes);
330 }
331
332 let record_len = record_bytes.len();
333 let mut header = self.header;
334 header.param1 = self.blocks.len() as u8;
335 if self.nonce.is_some() && !self.signature.is_empty() {
336 header.param2 |= 0x01;
337 }
338
339 header.write_to(&mut buf);
340 buf.push((record_len & 0xFF) as u8);
342 buf.push(((record_len >> 8) & 0xFF) as u8);
343 buf.push(((record_len >> 16) & 0xFF) as u8);
344 buf.push(0x00); buf.extend_from_slice(&record_bytes);
347
348 if let Some(nonce) = self.nonce {
349 buf.extend_from_slice(&nonce);
350 let opaque_len = self.opaque_data.len() as u16;
351 buf.extend_from_slice(&opaque_len.to_le_bytes());
352 buf.extend_from_slice(&self.opaque_data);
353 buf.extend_from_slice(&self.signature);
354 }
355
356 buf
357 }
358
359 pub fn signed_transcript(&self) -> Vec<u8> {
361 let full = self.to_bytes();
362 let sig_len = self.signature.len();
363 if full.len() >= sig_len {
364 full[..full.len() - sig_len].to_vec()
365 } else {
366 full
367 }
368 }
369}