diff --git a/target/veer/tests/spdm/BUILD.bazel b/target/veer/tests/spdm/BUILD.bazel new file mode 100644 index 000000000..0e889049c --- /dev/null +++ b/target/veer/tests/spdm/BUILD.bazel @@ -0,0 +1,123 @@ +# Licensed under the Apache-2.0 license +# SPDX-License-Identifier: Apache-2.0 + +load("@pigweed//pw_kernel/tooling:multi_process_app.bzl", "multi_process_app") +load("@pigweed//pw_kernel/tooling:rust_app.bzl", "rust_process") +load("@pigweed//pw_kernel/tooling:target_codegen.bzl", "target_codegen") +load("@pigweed//pw_kernel/tooling:target_linker_script.bzl", "target_linker_script") +load("@pigweed//pw_kernel/tooling/panic_detector:rust_binary_no_panics_test.bzl", "rust_binary_no_panics_test") +load("@rules_rust//rust:defs.bzl", "rust_binary") +load("//target/veer:defs.bzl", "TARGET_COMPATIBLE_WITH", "veer_system_config", "veer_system_image") +load("//target/veer/tooling:caliptra_runner.bzl", "caliptra_test") + +veer_system_config( + name = "system_config", + src = "system.json5.tmpl", +) + +target_codegen( + name = "codegen", + arch = "@pigweed//pw_kernel/arch/riscv:arch_riscv", + system_config = ":system_config", +) + +target_linker_script( + name = "linker_script", + system_config = ":system_config", + tags = ["kernel"], + template = "//target/veer:linker_script_template", +) + +rust_binary( + name = "target", + srcs = ["target.rs"], + edition = "2024", + tags = ["kernel"], + target_compatible_with = TARGET_COMPATIBLE_WITH, + deps = [ + ":codegen", + ":linker_script", + "//target/veer:config", + "//target/veer:entry", + "//target/veer/peripherals:wdt", + "@pigweed//pw_kernel/arch/riscv:arch_riscv", + "@pigweed//pw_kernel/kernel", + "@pigweed//pw_kernel/subsys/console:console_backend", + "@pigweed//pw_kernel/target:target_common", + "@pigweed//pw_kernel/userspace", + "@pigweed//pw_log/rust:pw_log", + ], +) + +# SPDM over MCTP over I3C. The I3C server, the MCTP server and the MCTP +# control responder are the processes of //target/veer/tests/mctp_i3c. +multi_process_app( + name = "spdm", + processes = [ + "//target/veer/tests/mctp_i3c:i3c_server", + "//target/veer/tests/mctp_i3c:mctp_server", + "//target/veer/tests/mctp_i3c:mctp_control", + ":spdm_responder", + ], + tags = ["kernel"], +) + +rust_process( + name = "spdm_responder", + srcs = [ + "platform.rs", + "spdm_responder.rs", + ], + codegen_crate_name = "spdm_responder_codegen", + crate_root = "spdm_responder.rs", + edition = "2024", + tags = ["kernel"], + deps = [ + "//hal/blocking", + "//services/mctp/api:mctp_api", + "//services/mctp/client-ipc:mctp_client_ipc", + "//services/spdm/responder:spdm_responder_lib", + "//services/spdm/transport-mctp:spdm_transport_mctp", + "//target/veer:config", + "//target/veer/peripherals:mailbox", + "//target/veer/peripherals:rng", + "//target/veer/peripherals:sha", + "@pigweed//pw_kernel/userspace", + "@pigweed//pw_log/rust:pw_log", + "@pigweed//pw_status/rust:pw_status", + "@rust_crates//:spdm-lib", + "@rust_crates//:zerocopy", + ], +) + +veer_system_image( + name = "spdm_image", + apps = [":spdm"], + kernel = ":target", + platform = "//target/veer", + system_config = ":system_config", + tags = ["kernel"], +) + +rust_binary_no_panics_test( + name = "no_panics_test", + binary = ":spdm_image", + tags = ["kernel"], +) + +# TODO: add an app_no_panics_test for this image. The test would fail: the +# app links panic paths from spdm-lib, //services/spdm/transport-mctp, the +# MCTP server process and heapless. + +# The host is the SPDM requester. It drives the firmware through +# caliptra_mcu_hw_model, as //target/veer/tests/mctp_i3c does. The +# caliptra_test rule generates spdm_test_emulator and spdm_test_fpga. +caliptra_test( + name = "spdm_test", + srcs = ["host_test.rs"], + mcu_image = ":spdm_image", + deps = [ + "//target/veer/tests/mctp_i3c:mctp_i3c_ids", + "//third_party/caliptra/caliptra-mcu-sw:mcu_testing_common", + ], +) diff --git a/target/veer/tests/spdm/host_test.rs b/target/veer/tests/spdm/host_test.rs new file mode 100644 index 000000000..8488a7ae1 --- /dev/null +++ b/target/veer/tests/spdm/host_test.rs @@ -0,0 +1,388 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! Host side of the VeeR SPDM test. The host is the SPDM requester: it boots +//! the firmware through `caliptra_mcu_hw_model` with an I3C socket, sends each +//! SPDM request as an MCTP message over I3C and reads the response. +//! +//! The test negotiates a connection (`GET_VERSION`, `GET_CAPABILITIES` and +//! `NEGOTIATE_ALGORITHMS`) and checks each response. It then sends a +//! `GET_DIGESTS` request, which the responder answers with an error because +//! it has no certificates, and checks that the responder still answers +//! `GET_VERSION`. +//! +//! The MCTP and I3C helpers are copies of those in the host test of +//! `//target/veer/tests/mctp_i3c`. +//! +//! TODO: build the requests and parse the responses with an SPDM requester +//! library. The test writes each request byte by byte and reads the response +//! fields at fixed offsets. +//! +//! The same binary runs on the emulator (x86_64) and on the VCK190, where the +//! model forwards the socket to the FPGA's I3C host controller. + +use caliptra_mcu_hw_model::McuHwModel; +use caliptra_mcu_testing_common::i3c_socket::BufferedStream; +use mctp_i3c_ids::{HOST_EID, OWN_EID}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::time::{Duration, Instant}; +use test_boot_files::BootFiles; + +const TARGET_EID: u8 = OWN_EID; + +/// The MCTP message type of SPDM (DSP0239). +const SPDM_MSG_TYPE: u8 = 5; + +/// The MCTP transport header is 4 bytes; the message body (type byte, payload) +/// follows it. +const MCTP_HEADER_LEN: usize = 4; + +/// Largest packet the host writes, header included: the MCTP baseline, a +/// 64-byte payload and the header. +const MAX_PACKET: usize = MCTP_HEADER_LEN + 64; + +/// Largest packet the target sends, header included. +const MAX_REPLY_PACKET: usize = 254; + +/// Logged by `spdm_responder.rs` once its listener is armed. +const READY: &str = "spdm responder: waiting for request"; + +const TIMEOUT_SECS: u64 = 120; + +/// Time to let the target drain one write before the next. +const WRITE_GAP: Duration = Duration::from_millis(50); + +/// The least the target's clock must advance during a gap. +const MIN_GAP_CYCLES: u64 = 150_000; + +/// SPDM version 1.0, which `GET_VERSION` and `VERSION` always use. +const SPDM_10: u8 = 0x10; + +/// SPDM version 1.2, the highest that the responder supports. +const SPDM_12: u8 = 0x12; + +// Request and response codes (DSP0274). +const GET_DIGESTS: u8 = 0x81; +const GET_VERSION: u8 = 0x84; +const GET_CAPABILITIES: u8 = 0xe1; +const NEGOTIATE_ALGORITHMS: u8 = 0xe3; +const VERSION: u8 = 0x04; +const CAPABILITIES: u8 = 0x61; +const ALGORITHMS: u8 = 0x63; +const ERROR: u8 = 0x7f; + +/// The SPDM error code `UnsupportedRequest`. +const UNSUPPORTED_REQUEST: u8 = 0x07; + +/// The largest SPDM message that the responder (`MAX_SPDM_MESSAGE` in +/// `spdm_responder.rs`) and this requester send or receive. +const MAX_SPDM_MESSAGE: u32 = 1024; + +/// `BaseAsymAlgo` bit for ECDSA with NIST P-384. +const ECDSA_P384: u32 = 1 << 7; + +/// `BaseHashAlgo` bit for SHA-384. +const SHA_384: u32 = 1 << 1; + +/// The MCTP packets of a message: the body (type byte, then payload) cut into +/// packets of at most `MAX_PACKET` bytes, each with a transport header (version 1, +/// `dest`, `src`, flags). Flags: SOM on the first, EOM on the last, a 2-bit packet +/// sequence number, the tag owner bit (set for a request, clear for a response), +/// and `tag`. +fn message_packets(body: &[u8], tag: u8, tag_owner: bool, dest: u8, src: u8) -> Vec> { + let chunks: Vec<&[u8]> = body.chunks(MAX_PACKET - MCTP_HEADER_LEN).collect(); + let last = chunks.len() - 1; + chunks + .iter() + .enumerate() + .map(|(i, chunk)| { + let mut flags = (tag & 0x07) | (((i & 0x03) as u8) << 4); + if tag_owner { + flags |= 0x08; + } + if i == 0 { + flags |= 0x80; + } + if i == last { + flags |= 0x40; + } + let mut packet = vec![0x01, dest, src, flags]; + packet.extend_from_slice(chunk); + packet + }) + .collect() +} + +/// Step the model until `term` appears in the MCU log, accumulated in `log`. +/// Panics on a fatal error or timeout. +fn wait_for_log(hw: &mut impl McuHwModel, log: &mut String, term: &str) { + let start = Instant::now(); + hw.step_until(|m| { + let out = m.output().take(usize::MAX); + if !out.is_empty() { + print!("{out}"); + log.push_str(&out); + } + log.contains(term) + || m.mci_fw_fatal_error().is_some() + || start.elapsed().as_secs() > TIMEOUT_SECS + }); + assert_eq!(hw.mci_fw_fatal_error(), None, "firmware hit a fatal error"); + assert!( + log.contains(term), + "timed out waiting for {term:?} in the MCU log" + ); +} + +/// Step the model for at least `gap` of wall-clock time and `MIN_GAP_CYCLES` cycles. +fn step_for(hw: &mut impl McuHwModel, log: &mut String, gap: Duration) { + let start = Instant::now(); + let c0 = hw.cycle_count(); + hw.step_until(|m| { + let out = m.output().take(usize::MAX); + if !out.is_empty() { + print!("{out}"); + log.push_str(&out); + } + (start.elapsed() >= gap && m.cycle_count() - c0 >= MIN_GAP_CYCLES) + || m.mci_fw_fatal_error().is_some() + }); + + assert_eq!(hw.mci_fw_fatal_error(), None, "firmware hit a fatal error"); +} + +/// Read one reply packet: wait for the target's IBI, then for the read it +/// triggers. Returns the packet with its PEC already checked and stripped. +fn read_packet( + hw: &mut impl McuHwModel, + stream: &mut BufferedStream, + log: &mut String, + target_addr: u8, +) -> Vec { + let mut packet: Option> = None; + let mut got_ibi = false; + let start = Instant::now(); + hw.step_until(|m| { + let out = m.output().take(usize::MAX); + if !out.is_empty() { + print!("{out}"); + log.push_str(&out); + } + if !got_ibi { + got_ibi = stream.receive_ibi(target_addr); + } else if let Some(data) = stream.receive_private_read(target_addr) { + packet = Some(data); + } + packet.is_some() + || m.mci_fw_fatal_error().is_some() + || start.elapsed().as_secs() > TIMEOUT_SECS + }); + assert_eq!(hw.mci_fw_fatal_error(), None, "firmware hit a fatal error"); + packet.unwrap_or_else(|| panic!("no reply packet read from the target (IBI seen: {got_ibi})")) +} + +/// Write each packet to the target, leaving it time to drain its receive FIFO +/// after each. +fn send_packets( + hw: &mut impl McuHwModel, + stream: &mut BufferedStream, + log: &mut String, + target_addr: u8, + packets: Vec>, +) { + for packet in packets { + assert!( + stream.send_private_write(target_addr, packet), + "I3C socket closed before the write" + ); + step_for(hw, log, WRITE_GAP); + } +} + +/// Read one message from the target and reassemble it. Returns the tag, the +/// tag owner bit and the body (the type byte, then the payload). +fn read_message( + hw: &mut impl McuHwModel, + stream: &mut BufferedStream, + log: &mut String, + target_addr: u8, +) -> (u8, bool, Vec) { + let mut body = Vec::new(); + loop { + let packet = read_packet(hw, stream, log, target_addr); + // [ver][dest = host][src = target][flags][body...] + assert!( + packet.len() > MCTP_HEADER_LEN, + "packet too short: {packet:02x?}" + ); + assert!( + packet.len() <= MAX_REPLY_PACKET, + "packet of {} bytes is over the MTU", + packet.len() + ); + let flags = packet[3]; + assert_eq!(packet[0] & 0x0f, 0x01, "MCTP header version"); + assert_eq!(packet[1], HOST_EID, "destination EID"); + assert_eq!(packet[2], TARGET_EID, "source EID"); + assert_eq!( + flags & 0x80 != 0, + body.is_empty(), + "SOM on the first packet only" + ); + body.extend_from_slice(&packet[MCTP_HEADER_LEN..]); + if flags & 0x40 != 0 { + return (flags & 0x07, flags & 0x08 != 0, body); + } + } +} + +/// The hardware model, its I3C socket and the MCU log of one run. +struct Requester { + hw: M, + stream: BufferedStream, + log: String, + target_addr: u8, + /// The MCTP tag of the next request. + tag: u8, +} + +impl Requester { + /// Send one SPDM request and return the SPDM response. + fn exchange(&mut self, request: &[u8]) -> Vec { + let tag = self.tag; + self.tag = (self.tag + 1) & 0x07; + let mut body = vec![SPDM_MSG_TYPE]; + body.extend_from_slice(request); + let packets = message_packets(&body, tag, true, TARGET_EID, HOST_EID); + send_packets( + &mut self.hw, + &mut self.stream, + &mut self.log, + self.target_addr, + packets, + ); + let (reply_tag, tag_owner, reply) = read_message( + &mut self.hw, + &mut self.stream, + &mut self.log, + self.target_addr, + ); + assert!(!tag_owner, "reply is a response (tag owner clear)"); + assert_eq!(reply_tag, tag, "reply tag"); + assert_eq!(reply[0] & 0x7f, SPDM_MSG_TYPE, "message type"); + println!( + "spdm host: request {:02x?} -> response {:02x?}", + request, + &reply[1..] + ); + reply[1..].to_vec() + } + + /// Send `GET_VERSION` and return the versions that the responder supports, + /// each as one byte (major in the high four bits, minor in the low four). + fn get_version(&mut self) -> Vec { + let response = self.exchange(&[SPDM_10, GET_VERSION, 0, 0]); + assert_eq!(&response[..2], [SPDM_10, VERSION], "VERSION header"); + // [version][code][param1][param2][reserved][count][entries...] + let count = usize::from(response[5]); + assert_eq!(response.len(), 6 + 2 * count, "VERSION length"); + // Each entry is 16 bits, little-endian. The high byte has the major + // version in its high four bits and the minor in its low four. + response[6..].chunks(2).map(|entry| entry[1]).collect() + } +} + +fn u32_at(bytes: &[u8], offset: usize) -> u32 { + u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) +} + +#[test] +fn spdm_negotiate_host_test() { + // A free port for the model's I3C socket. + let i3c_port = TcpListener::bind(("127.0.0.1", 0)) + .unwrap() + .local_addr() + .unwrap() + .port(); + + let files = BootFiles::from_env(); + let mut params = files.init_params(); + params.i3c_port = Some(i3c_port); + let mut hw = caliptra_mcu_hw_model::new(params).expect("hardware model failed to boot"); + + hw.start_i3c_controller(); + + let port = hw.i3c_port().unwrap(); + let target_addr = hw.i3c_address().unwrap(); + + let addr = SocketAddr::from(([127, 0, 0, 1], port)); + let stream = TcpStream::connect(addr).expect("failed to connect to the I3C socket"); + let mut requester = Requester { + hw, + stream: BufferedStream::new(stream), + log: String::new(), + target_addr, + tag: 0, + }; + + // The listener must be armed before the request arrives. + wait_for_log(&mut requester.hw, &mut requester.log, READY); + + let versions = requester.get_version(); + assert!(versions.contains(&0x11), "responder supports SPDM 1.1"); + assert!(versions.contains(&SPDM_12), "responder supports SPDM 1.2"); + + // GET_CAPABILITIES of SPDM 1.2: + // [version][code][param1][param2][reserved][CTExponent][reserved x2] + // [Flags x4][DataTransferSize x4][MaxSPDMmsgSize x4] + let mut request = vec![SPDM_12, GET_CAPABILITIES, 0, 0, 0, 0, 0, 0]; + request.extend_from_slice(&0u32.to_le_bytes()); + request.extend_from_slice(&MAX_SPDM_MESSAGE.to_le_bytes()); + request.extend_from_slice(&MAX_SPDM_MESSAGE.to_le_bytes()); + let response = requester.exchange(&request); + assert_eq!( + &response[..2], + [SPDM_12, CAPABILITIES], + "CAPABILITIES header" + ); + assert_eq!(response.len(), 20, "CAPABILITIES length"); + assert_eq!(u32_at(&response, 8), 0, "responder capability flags"); + assert_eq!(u32_at(&response, 12), MAX_SPDM_MESSAGE, "DataTransferSize"); + assert_eq!(u32_at(&response, 16), MAX_SPDM_MESSAGE, "MaxSPDMmsgSize"); + + // NEGOTIATE_ALGORITHMS of SPDM 1.2 with no algorithm structures: + // [version][code][param1 = structures][param2][Length x2] + // [MeasurementSpecification][OtherParamsSupport][BaseAsymAlgo x4] + // [BaseHashAlgo x4][reserved x12][ExtAsymCount][ExtHashCount][reserved x2] + let mut request = vec![SPDM_12, NEGOTIATE_ALGORITHMS, 0, 0, 32, 0, 0x01, 0]; + request.extend_from_slice(&ECDSA_P384.to_le_bytes()); + request.extend_from_slice(&SHA_384.to_le_bytes()); + request.extend_from_slice(&[0; 16]); + assert_eq!(request.len(), 32); + let response = requester.exchange(&request); + assert_eq!(&response[..2], [SPDM_12, ALGORITHMS], "ALGORITHMS header"); + // [version][code][param1][param2][Length x2][MeasurementSpecificationSel] + // [OtherParamsSelection][MeasurementHashAlgo x4][BaseAsymSel x4] + // [BaseHashSel x4]... + assert_eq!( + usize::from(u16::from_le_bytes([response[4], response[5]])), + response.len(), + "ALGORITHMS length" + ); + // The responder has no measurements, so it selects no measurement + // specification and no measurement hash. + assert_eq!(response[6], 0, "MeasurementSpecificationSel"); + assert_eq!(u32_at(&response, 8), 0, "MeasurementHashAlgo"); + assert_eq!(u32_at(&response, 12), ECDSA_P384, "BaseAsymSel"); + assert_eq!(u32_at(&response, 16), SHA_384, "BaseHashSel"); + + // The responder has no certificates, so it answers GET_DIGESTS with an + // error. + let response = requester.exchange(&[SPDM_12, GET_DIGESTS, 0, 0]); + assert_eq!(&response[..2], [SPDM_12, ERROR], "ERROR header"); + assert_eq!(response[2], UNSUPPORTED_REQUEST, "error code"); + + // The responder still answers after the error. + let versions = requester.get_version(); + assert!(versions.contains(&SPDM_12), "responder supports SPDM 1.2"); +} diff --git a/target/veer/tests/spdm/platform.rs b/target/veer/tests/spdm/platform.rs new file mode 100644 index 000000000..c79de8618 --- /dev/null +++ b/target/veer/tests/spdm/platform.rs @@ -0,0 +1,189 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! The platform of this test's SPDM responder. +//! +//! The hash and the random number generator use the Caliptra core through +//! its mailbox. The certificate store has no slots and the evidence source +//! has no evidence, so the responder does not advertise certificates, +//! challenges or measurements. +//! +//! `GET_VERSION`, `GET_CAPABILITIES` and `NEGOTIATE_ALGORITHMS` need no hash +//! and no random number, so this test does not call `CaliptraHash` or +//! `CaliptraRandom`. + +use openprot_hal_blocking::digest::owned::{DigestInit, DigestOp}; +use openprot_hal_blocking::digest::Sha2_384; +use openprot_hal_blocking::rng::CryptoRng; +use spdm_lib::cert_store::{CertStoreError, CertStoreResult, SpdmCertStore}; +use spdm_lib::platform::evidence::{SpdmEvidence, SpdmEvidenceError, SpdmEvidenceResult}; +use spdm_lib::platform::hash::{SpdmHash, SpdmHashAlgoType, SpdmHashError, SpdmHashResult}; +use spdm_lib::platform::rng::{SpdmRng, SpdmRngError, SpdmRngResult}; +use spdm_lib::protocol::algorithms::{AsymAlgo, ECC_P384_SIGNATURE_SIZE, SHA384_HASH_SIZE}; +use spdm_lib::protocol::certs::{CertificateInfo, KeyUsageMask}; +use veer_mailbox::Mailbox; +use veer_rng::CaliptraRng; +use veer_sha::{CaliptraSha, OwnedSha2Op}; + +/// SHA-384 that uses the Caliptra core. +pub struct CaliptraHash<'m> { + mailbox: &'m Mailbox, + /// The computation in progress. + op: Option>, +} + +impl<'m> CaliptraHash<'m> { + pub fn new(mailbox: &'m Mailbox) -> Self { + Self { mailbox, op: None } + } +} + +impl SpdmHash for CaliptraHash<'_> { + fn hash( + &mut self, + hash_algo: SpdmHashAlgoType, + data: &[u8], + hash: &mut [u8], + ) -> SpdmHashResult<()> { + self.init(hash_algo, Some(data))?; + self.finalize(hash) + } + + fn init(&mut self, hash_algo: SpdmHashAlgoType, data: Option<&[u8]>) -> SpdmHashResult<()> { + self.op = None; + if hash_algo != SpdmHashAlgoType::SHA384 { + return Err(SpdmHashError::InvalidAlgorithm); + } + let op = CaliptraSha::new(self.mailbox) + .init(Sha2_384) + .map_err(|_| SpdmHashError::PlatformError)?; + let op = match data { + Some(data) => op.update(data).map_err(|_| SpdmHashError::PlatformError)?, + None => op, + }; + self.op = Some(op); + Ok(()) + } + + fn update(&mut self, data: &[u8]) -> SpdmHashResult<()> { + let op = self.op.take().ok_or(SpdmHashError::PlatformError)?; + self.op = Some(op.update(data).map_err(|_| SpdmHashError::PlatformError)?); + Ok(()) + } + + fn finalize(&mut self, hash: &mut [u8]) -> SpdmHashResult<()> { + let op = self.op.take().ok_or(SpdmHashError::PlatformError)?; + let (digest, _) = op.finalize().map_err(|_| SpdmHashError::PlatformError)?; + let digest: [u8; SHA384_HASH_SIZE] = zerocopy::transmute!(digest.value); + let hash = hash + .get_mut(..SHA384_HASH_SIZE) + .ok_or(SpdmHashError::BufferTooSmall)?; + hash.iter_mut() + .zip(digest) + .for_each(|(to, from)| *to = from); + Ok(()) + } + + fn reset(&mut self) { + self.op = None; + } + + fn algo(&self) -> SpdmHashAlgoType { + SpdmHashAlgoType::SHA384 + } +} + +/// Random number generator that uses the Caliptra core. +pub struct CaliptraRandom<'m> { + rng: CaliptraRng<'m>, +} + +impl<'m> CaliptraRandom<'m> { + pub fn new(mailbox: &'m Mailbox) -> Self { + Self { + rng: CaliptraRng::new(mailbox), + } + } +} + +impl SpdmRng for CaliptraRandom<'_> { + fn get_random_bytes(&mut self, buf: &mut [u8]) -> SpdmRngResult<()> { + // `SpdmRngError` has no variant for a failure of the generator, so + // the failure is reported as `InvalidSize`. + self.rng.fill(buf).map_err(|_| SpdmRngError::InvalidSize) + } + + fn generate_random_number(&mut self, random_number: &mut [u8]) -> SpdmRngResult<()> { + self.get_random_bytes(random_number) + } +} + +/// Certificate store with no slots. +pub struct NoCertStore; + +impl SpdmCertStore for NoCertStore { + fn slot_count(&self) -> u8 { + 0 + } + + fn is_provisioned(&self, _slot_id: u8) -> bool { + false + } + + fn cert_chain_len(&mut self, _asym_algo: AsymAlgo, slot_id: u8) -> CertStoreResult { + Err(CertStoreError::InvalidSlotId(slot_id)) + } + + fn get_cert_chain( + &mut self, + slot_id: u8, + _asym_algo: AsymAlgo, + _offset: usize, + _cert_portion: &mut [u8], + ) -> CertStoreResult { + Err(CertStoreError::InvalidSlotId(slot_id)) + } + + fn root_cert_hash( + &mut self, + slot_id: u8, + _asym_algo: AsymAlgo, + _cert_hash: &mut [u8; SHA384_HASH_SIZE], + ) -> CertStoreResult<()> { + Err(CertStoreError::InvalidSlotId(slot_id)) + } + + fn sign_hash( + &self, + slot_id: u8, + _hash: &[u8; SHA384_HASH_SIZE], + _signature: &mut [u8; ECC_P384_SIGNATURE_SIZE], + ) -> CertStoreResult<()> { + Err(CertStoreError::InvalidSlotId(slot_id)) + } + + fn key_pair_id(&self, _slot_id: u8) -> Option { + None + } + + fn cert_info(&self, _slot_id: u8) -> Option { + None + } + + fn key_usage_mask(&self, _slot_id: u8) -> Option { + None + } +} + +/// Evidence source with no evidence. +pub struct NoEvidence; + +impl SpdmEvidence for NoEvidence { + fn pcr_quote(&self, _buffer: &mut [u8], _with_pqc_sig: bool) -> SpdmEvidenceResult { + Err(SpdmEvidenceError::UnsupportedEvidenceType) + } + + fn pcr_quote_size(&self, _with_pqc_sig: bool) -> SpdmEvidenceResult { + Err(SpdmEvidenceError::UnsupportedEvidenceType) + } +} diff --git a/target/veer/tests/spdm/spdm_responder.rs b/target/veer/tests/spdm/spdm_responder.rs new file mode 100644 index 000000000..41b345aa8 --- /dev/null +++ b/target/veer/tests/spdm/spdm_responder.rs @@ -0,0 +1,110 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! SPDM responder: answers SPDM requests as a client of the MCTP server. +//! +//! The responder runs the `//services/spdm/responder` service over MCTP. It +//! has no certificates and no measurements, so it supports only +//! `GET_VERSION`, `GET_CAPABILITIES` and `NEGOTIATE_ALGORITHMS`. +//! `platform.rs` has the hash, random number generator, certificate store +//! and evidence source that the service needs. + +#![no_main] +#![no_std] + +mod platform; + +use kernel_config::{MBOX_BASE, SOC_IFC_BASE}; +use openprot_mctp_api::Stack; +use openprot_mctp_client_ipc::IpcMctpClient; +use openprot_spdm_responder::{ResponderConfig, SpdmResponder}; +use openprot_spdm_transport_mctp::MctpSpdmTransport; +use platform::{CaliptraHash, CaliptraRandom, NoCertStore, NoEvidence}; +use spdm_lib::codec::MessageBuf; +use spdm_lib::error::SpdmError; +use spdm_lib::platform::transport::SpdmTransport as _; +use spdm_lib::protocol::CapabilityFlags; +use spdm_responder_codegen::handle; +use userspace::process_entry; +use userspace::syscall; +use veer_mailbox::Mailbox; + +/// Size in bytes of the buffer for one SPDM message. +const MESSAGE_BUF: usize = 2048; + +/// The largest SPDM message that the responder sends or receives, which +/// fits in the 1032 bytes that the MCTP server accepts. +const MAX_SPDM_MESSAGE: u32 = 1024; + +/// Logs `reason` and stops the test with a failure. +fn fail(reason: &'static str) -> ! { + pw_log::error!("SPDM responder failed: {}", reason as &str); + let _ = syscall::debug_shutdown(Err(pw_status::Error::Internal)); + #[expect(clippy::empty_loop)] + loop {} +} + +#[process_entry("spdm_responder")] +fn entry() { + // SAFETY: the system config maps the registers for this process, and + // this image has no other user of the mailbox. + let mailbox = unsafe { Mailbox::new(MBOX_BASE, SOC_IFC_BASE) }; + + let stack = Stack::new(IpcMctpClient::new(handle::MCTP)); + let mut transport = MctpSpdmTransport::new_responder(&stack); + if transport.init_sequence().is_err() { + fail("no MCTP listener"); + } + + let mut cert_store = NoCertStore; + let mut hash = CaliptraHash::new(&mailbox); + let mut m1_hash = CaliptraHash::new(&mailbox); + let mut l1_hash = CaliptraHash::new(&mailbox); + let mut rng = CaliptraRandom::new(&mailbox); + let evidence = NoEvidence; + + // The responder has no certificates and no measurements, so it + // advertises no capabilities. + let mut capabilities = ResponderConfig::default_capabilities(); + capabilities.flags = CapabilityFlags::default(); + capabilities.data_transfer_size = MAX_SPDM_MESSAGE; + capabilities.max_spdm_msg_size = MAX_SPDM_MESSAGE; + let config = ResponderConfig { + capabilities: Some(capabilities), + algorithms: None, + }; + + let mut responder = match SpdmResponder::new( + &mut transport, + &mut cert_store, + &mut hash, + &mut m1_hash, + &mut l1_hash, + &mut rng, + &evidence, + Some(config), + ) { + Ok(responder) => responder, + Err(_) => fail("no SPDM context"), + }; + + let mut buffer = [0u8; MESSAGE_BUF]; + let mut message = MessageBuf::new(&mut buffer); + + pw_log::info!("spdm responder: waiting for request"); + loop { + message.reset(); + match responder + .context_mut() + .responder_process_message(&mut message) + { + Ok(()) => {} + // The service did not accept the request. It has sent an SPDM + // error response if the request allows one. + Err(SpdmError::Command(_)) => { + pw_log::warn!("spdm responder: request not accepted") + } + Err(_) => fail("request not processed"), + } + } +} diff --git a/target/veer/tests/spdm/system.json5.tmpl b/target/veer/tests/spdm/system.json5.tmpl new file mode 100644 index 000000000..b42d187d0 --- /dev/null +++ b/target/veer/tests/spdm/system.json5.tmpl @@ -0,0 +1,143 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +// VeeR on-target test for an SPDM responder over MCTP over I3C. +// +// The app has four processes. The first three are the processes of +// tests/mctp_i3c: +// +// i3c_server -- owns the I3C peripheral and its interrupt. +// mctp_server -- runs the MCTP router over the i3c server and serves MCTP +// clients on the channel handlers "mctp" and +// "mctp_control". +// mctp_control -- answers MCTP control requests. +// spdm_responder -- an MCTP client (initiator "mctp" -> mctp_server "mctp") +// that answers SPDM requests. Its hash and random number +// generator use the Caliptra mailbox. +// +// Addresses are rendered per platform (emulator or FPGA) from upstream +// caliptra-mcu-sw's memory maps by `veer_system_config`: +// @KERNEL_FLASH_START@ MCU SRAM start (code + data execute here) +// @KERNEL_RAM_START@ app data, 0x40000 into MCU SRAM +// @I3C_BASE@ Active I3C core's register block (device-mapped into i3c_server) +// @I3C_IRQ@ PIC interrupt number of that core +// @MBOX_BASE@ Caliptra mailbox registers (device-mapped into spdm_responder) +// @SOC_IFC_BASE@ Caliptra SoC interface registers (device-mapped into spdm_responder) +{ + arch: { + type: "riscv", + }, + kernel: { + flash_start_address: @KERNEL_FLASH_START@, + flash_size_bytes: 0x12000, + ram_start_address: @KERNEL_RAM_START@, + ram_size_bytes: 0x8000, + }, + // A server has a higher priority than the processes that call it. + apps: [ + { + name: "spdm", + flash_size_bytes: 0x30000, + processes: [ + { + name: "i3c_server", + ram_size_bytes: 0x4000, + objects: [ + { name: "wg", type: "wait_group" }, + { + name: "i3c_irq", + type: "interrupt", + irqs: [{ name: "i3c", number: @I3C_IRQ@ }], + }, + { name: "channel", type: "channel_handler" }, + { + type: "thread", + name: "i3c_server_thread", + kernel_stack_size_bytes: 2048, + priority: "Level20", + }, + ], + memory_mappings: [ + { + name: "i3c_regs", + type: "device", + start_address: @I3C_BASE@, + size_bytes: 0x1000, + }, + ], + }, + { + name: "mctp_server", + ram_size_bytes: 0x10000, + objects: [ + { name: "wg", type: "wait_group" }, + { name: "mctp", type: "channel_handler" }, + { name: "mctp_control", type: "channel_handler" }, + { + name: "i3c", + type: "channel_initiator", + handler_process: "i3c_server", + handler_object_name: "channel", + }, + { + type: "thread", + name: "mctp_server_thread", + kernel_stack_size_bytes: 4096, + priority: "Level15", + }, + ], + }, + { + name: "spdm_responder", + ram_size_bytes: 0x8000, + objects: [ + { + name: "mctp", + type: "channel_initiator", + handler_process: "mctp_server", + handler_object_name: "mctp", + }, + { + type: "thread", + name: "spdm_responder_thread", + kernel_stack_size_bytes: 2048, + priority: "Level10", + }, + ], + memory_mappings: [ + { + name: "mbox", + type: "device", + start_address: @MBOX_BASE@, + size_bytes: 0x1000, + }, + { + name: "soc_ifc", + type: "device", + start_address: @SOC_IFC_BASE@, + size_bytes: 0x1000, + }, + ], + }, + { + name: "mctp_control", + ram_size_bytes: 0x4000, + objects: [ + { + name: "mctp", + type: "channel_initiator", + handler_process: "mctp_server", + handler_object_name: "mctp_control", + }, + { + type: "thread", + name: "mctp_control_thread", + kernel_stack_size_bytes: 2048, + priority: "Level10", + }, + ], + }, + ], + }, + ], +} diff --git a/target/veer/tests/spdm/target.rs b/target/veer/tests/spdm/target.rs new file mode 100644 index 000000000..c9405598a --- /dev/null +++ b/target/veer/tests/spdm/target.rs @@ -0,0 +1,49 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! Kernel image for the VeeR MCTP-over-I3C test. Boots and hands control to the +//! userspace app processes declared in system.json5 (i3c server, MCTP server, +//! and an MCTP echo app). + +#![no_std] +#![no_main] + +use arch_riscv::Arch; +use console_backend as _; +use entry::exit; +use target_common::{declare_target, TargetInterface}; +use veer_wdt::Wdt; + +pub struct Target {} + +impl TargetInterface for Target { + const NAME: &'static str = "Caliptra SPDM Test"; + + fn main() -> ! { + // The ROM leaves the MCU watchdog running with a period of 800 million + // clock cycles, and nothing here restarts it. A test that hangs would + // otherwise be reset mid-run, and the kernel's warm re-entry then trips + // a scheduler assertion that hides the real failure. + // + // SAFETY: this code runs in the kernel, which can access the MCI + // registers, and no other code in this image uses the watchdog. + unsafe { Wdt::new(kernel_config::MCI_BASE) }.stop(); + codegen::start(); + // The bootstrap thread has nothing left to do. Sleep rather than spin: a + // spinning thread at the same priority as the app threads takes a time + // slice at every scheduler tick and delays every wake-up behind it. + loop { + let _ = kernel::sleep_until(Arch, kernel::Instant::MAX); + } + } + + fn shutdown(code: u32) -> ! { + match code { + 0 => pw_log::info!("PASS"), + _ => pw_log::info!("FAIL: {}", code), + } + exit(code); + } +} + +declare_target!(Target);