You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@teaclave.apache.org by yu...@apache.org on 2025/08/29 11:25:49 UTC
(incubator-teaclave-trustzone-sdk) 01/01: example: add attestation-rs
This is an automated email from the ASF dual-hosted git repository.
yuanz pushed a commit to branch attestation
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave-trustzone-sdk.git
commit 18dcba7178779647ec555cee45e108ba389d7a17
Author: Yuan Zhuang <yu...@apache.org>
AuthorDate: Fri Aug 29 11:15:43 2025 +0000
example: add attestation-rs
---
examples/attestation-rs/app/Makefile | 39 ++
examples/attestation-rs/app/host/Cargo.toml | 42 ++
examples/attestation-rs/app/host/Makefile | 37 ++
.../app/host/demo_files/measurements.json | 8 +
examples/attestation-rs/app/host/src/cli.rs | 115 ++++
examples/attestation-rs/app/host/src/main.rs | 106 ++++
.../attestation-rs/app/host/src/measurements.rs | 158 ++++++
examples/attestation-rs/app/host/src/verifier.rs | 129 +++++
examples/attestation-rs/app/proto/Cargo.toml | 28 +
examples/attestation-rs/app/proto/src/lib.rs | 36 ++
examples/attestation-rs/app/ta/Cargo.toml | 41 ++
examples/attestation-rs/app/ta/Makefile | 48 ++
examples/attestation-rs/app/ta/Xargo.toml | 24 +
examples/attestation-rs/app/ta/build.rs | 25 +
examples/attestation-rs/app/ta/src/main.rs | 67 +++
examples/attestation-rs/app/uuid.txt | 1 +
examples/attestation-rs/attestation/Cargo.toml | 16 +
examples/attestation-rs/attestation/src/attest.rs | 91 ++++
examples/attestation-rs/attestation/src/common.rs | 595 +++++++++++++++++++++
examples/attestation-rs/attestation/src/endorse.rs | 101 ++++
examples/attestation-rs/attestation/src/lib.rs | 92 ++++
.../attestation/src/tests/attestation_flow.rs | 287 ++++++++++
examples/attestation-rs/attestation/src/verify.rs | 103 ++++
.../attestation_forwarder/Cargo.toml | 12 +
.../attestation_forwarder/src/client.rs | 118 ++++
.../attestation_forwarder/src/lib.rs | 21 +
....c43b8cf79b73c98c4474e952ecf9980e36bbda30.patch | 393 ++++++++++++++
examples/attestation-rs/sdk/quoting_ta/Cargo.toml | 53 ++
examples/attestation-rs/sdk/quoting_ta/Makefile | 53 ++
examples/attestation-rs/sdk/quoting_ta/Xargo.toml | 24 +
examples/attestation-rs/sdk/quoting_ta/build.rs | 25 +
.../attestation-rs/sdk/quoting_ta/src/attester.rs | 156 ++++++
.../sdk/quoting_ta/src/endorsement_store.rs | 86 +++
.../attestation-rs/sdk/quoting_ta/src/endorser.rs | 104 ++++
examples/attestation-rs/sdk/quoting_ta/src/main.rs | 140 +++++
.../sdk/quoting_ta/src/pta_command.rs | 37 ++
.../sdk/quoting_ta/test_keys/generate_test_keys.sh | 47 ++
.../attestation-rs/sdk/quoting_ta_proto/Cargo.toml | 28 +
.../attestation-rs/sdk/quoting_ta_proto/src/lib.rs | 39 ++
examples/attestation-rs/sdk/quoting_ta_uuid.txt | 1 +
40 files changed, 3526 insertions(+)
diff --git a/examples/attestation-rs/app/Makefile b/examples/attestation-rs/app/Makefile
new file mode 100644
index 0000000..a7a3dec
--- /dev/null
+++ b/examples/attestation-rs/app/Makefile
@@ -0,0 +1,39 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# If _HOST or _TA specific compiler/target are not specified, then use common
+# compiler/target for both
+CROSS_COMPILE_HOST ?= aarch64-linux-gnu-
+CROSS_COMPILE_TA ?= aarch64-linux-gnu-
+TARGET_HOST ?= aarch64-unknown-linux-gnu
+TARGET_TA ?= aarch64-unknown-linux-gnu
+
+.PHONY: host ta all clean
+
+all: host ta
+
+host:
+ $(q)make -C host TARGET=$(TARGET_HOST) \
+ CROSS_COMPILE=$(CROSS_COMPILE_HOST)
+
+ta:
+ $(q)make -C ta TARGET=$(TARGET_TA) \
+ CROSS_COMPILE=$(CROSS_COMPILE_TA)
+
+clean:
+ $(q)make -C host clean
+ $(q)make -C ta clean
diff --git a/examples/attestation-rs/app/host/Cargo.toml b/examples/attestation-rs/app/host/Cargo.toml
new file mode 100644
index 0000000..ec8ab9e
--- /dev/null
+++ b/examples/attestation-rs/app/host/Cargo.toml
@@ -0,0 +1,42 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+name = "attestation-rs"
+version = "0.1.0"
+authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
+license = "Apache-2.0"
+repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
+description = "An example of Rust OP-TEE TrustZone SDK."
+edition = "2018"
+
+[dependencies]
+attestation = { path = "../../attestation" }
+proto = { path = "../proto" }
+optee-teec = { path = "../../../../optee-teec" }
+
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+bincode = "1.0"
+anyhow = "1.0"
+clap = { version = "4", features = ["derive"] }
+hex = "0.4.3"
+ring = "=0.16.20"
+uuid = { version = "1.16.0", features = ["serde"] }
+
+[profile.release]
+lto = true
diff --git a/examples/attestation-rs/app/host/Makefile b/examples/attestation-rs/app/host/Makefile
new file mode 100644
index 0000000..cf02eef
--- /dev/null
+++ b/examples/attestation-rs/app/host/Makefile
@@ -0,0 +1,37 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+NAME := attestation-rs
+
+TARGET ?= aarch64-unknown-linux-gnu
+CROSS_COMPILE ?= aarch64-linux-gnu-
+OBJCOPY := $(CROSS_COMPILE)objcopy
+LINKER_CFG := target.$(TARGET).linker=\"$(CROSS_COMPILE)gcc\"
+
+OUT_DIR := $(CURDIR)/target/$(TARGET)/release
+
+
+all: host strip
+
+host:
+ @cargo build --target $(TARGET_HOST) --release --config $(LINKER_CFG)
+
+strip: host
+ @$(OBJCOPY) --strip-unneeded $(OUT_DIR)/$(NAME) $(OUT_DIR)/$(NAME)
+
+clean:
+ @cargo clean
diff --git a/examples/attestation-rs/app/host/demo_files/measurements.json b/examples/attestation-rs/app/host/demo_files/measurements.json
new file mode 100644
index 0000000..9caa550
--- /dev/null
+++ b/examples/attestation-rs/app/host/demo_files/measurements.json
@@ -0,0 +1,8 @@
+[
+ {
+ "ta_id": "653d34fb-f8e3-41fd-bd3d-215c8138ac03",
+ "mr_ta_binary": "8c30d2dee2ae667c87e7bffa5b2184864d7ae525c4680b346f7b5720414bcc7c",
+ "mr_ta_memory": "c320c11576dc685c68511b3c61b65d697ecf6c107cfa22abd02e5646672dd609",
+ "mr_os_memory": "3c407023703b2a00b23a171e0f4e66d47e31bb9aff2a7d12a1d0eaf537cffe3a"
+ }
+]
\ No newline at end of file
diff --git a/examples/attestation-rs/app/host/src/cli.rs b/examples/attestation-rs/app/host/src/cli.rs
new file mode 100644
index 0000000..5503ec5
--- /dev/null
+++ b/examples/attestation-rs/app/host/src/cli.rs
@@ -0,0 +1,115 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::measurements::MeasurementsRecorded;
+use anyhow::{anyhow, Context, Result};
+use attestation::{PlatformPubkey, Quote, UserData};
+use clap::{Parser, Subcommand};
+use std::{fs, path::PathBuf};
+
+/// Parse a hex string into Vec<u8>
+fn parse_user_data(hex: &str) -> Result<UserData> {
+ let hex = hex.strip_prefix("0x").unwrap_or(hex);
+
+ if hex.len() % 2 != 0 || hex.len() > 64 {
+ return Err(anyhow!(
+ "Nonce hex string must have even length and be at most 32 bytes"
+ ));
+ }
+ let mut data = [0u8; 32];
+ // hex decode
+ let decoded = hex::decode(hex).context("Failed to decode hex string")?;
+ data[..decoded.len()].copy_from_slice(&decoded);
+ Ok(UserData::new(data))
+}
+
+/// Parse a quote from a JSON file
+fn parse_quote(path: &str) -> Result<Box<Quote>> {
+ let data = fs::read(path).with_context(|| format!("Failed to read quote from {}", path))?;
+ let quote = serde_json::from_slice(&data)
+ .with_context(|| format!("Failed to parse quote from {}", path))?;
+ Ok(Box::new(quote))
+}
+
+/// Parse measurements from a JSON file
+fn parse_measurements(path: &str) -> Result<Box<MeasurementsRecorded>> {
+ let data =
+ fs::read(path).with_context(|| format!("Failed to read measurements from {}", path))?;
+ let json = String::from_utf8_lossy(&data);
+ let measurements = serde_json::from_str(&json)
+ .map_err(|e| anyhow!("Failed to parse measurements from {}: {}", path, e))?;
+ Ok(Box::new(measurements))
+}
+
+/// Parse a public key from hex string
+fn parse_pk(path: &str) -> Result<PlatformPubkey> {
+ let data =
+ fs::read(path).with_context(|| format!("Failed to read public key from {}", path))?;
+ let hex = String::from_utf8_lossy(&data);
+ // Remove "0x" prefix if present
+ let hex = hex.strip_prefix("0x").unwrap_or(&hex);
+ let decoded = hex::decode(hex).context("Failed to decode hex string")?;
+
+ PlatformPubkey::from_bytes(&decoded)
+}
+
+#[derive(Parser)]
+#[command(
+ name = "attestation-cli",
+ version,
+ about = "Attestation CLI Tool for quote generation and verification",
+ arg_required_else_help = true
+)]
+pub struct Cli {
+ #[command(subcommand)]
+ pub command: Command,
+}
+
+#[derive(Subcommand)]
+pub enum Command {
+ /// Get an attestation quote for the current TA
+ GetQuote {
+ /// User data in hex format (max 32 bytes)
+ #[arg(short, long, value_parser = parse_user_data)]
+ user_data: UserData,
+
+ /// Output path for the quote JSON file
+ #[arg(short, long, default_value = "quote.json")]
+ output: PathBuf,
+ },
+
+ /// Verify an attestation quote
+ VerifyQuote {
+ /// Path to the quote JSON file
+ /// We use Box<Quote> to reduce the total size of enum,
+ /// which is enforced by clippy: #[warn(clippy::large_enum_variant)]
+ #[arg(short, long, value_parser = parse_quote)]
+ quote: Box<Quote>,
+
+ /// Expected user data in hex format
+ #[arg(short, long, value_parser = parse_user_data)]
+ user_data: UserData,
+
+ /// Path to the endorsement public key file
+ #[arg(short, long, value_parser = parse_pk)]
+ endorse_pubkey: PlatformPubkey,
+
+ /// Path to the expected measurements JSON file
+ #[arg(short, long, value_parser = parse_measurements)]
+ measurements: Box<MeasurementsRecorded>,
+ },
+}
diff --git a/examples/attestation-rs/app/host/src/main.rs b/examples/attestation-rs/app/host/src/main.rs
new file mode 100644
index 0000000..80ce37b
--- /dev/null
+++ b/examples/attestation-rs/app/host/src/main.rs
@@ -0,0 +1,106 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+mod cli;
+mod measurements;
+mod verifier;
+
+use crate::measurements::MeasurementsRecorded;
+use crate::verifier::{EcdsaEndorsementVerifier, EcdsaReportVerifier};
+use attestation::{PlatformPubkey, Quote, QuoteVerifier, QuoteVerify, UserData};
+use clap::Parser;
+use optee_teec::{Context, Operation, ParamNone, ParamTmpRef, Uuid};
+use proto::{Command, MAX_OUTPUT_SIZE, UUID};
+use std::io::Write;
+
+fn main() -> optee_teec::Result<()> {
+ let cli = cli::Cli::parse();
+
+ match cli.command {
+ cli::Command::GetQuote { user_data, output } => {
+ let quote = get_quote(user_data)?;
+ println!("NW: Quote: {:?}", quote);
+ write_quote_to_file("e, &output).map_err(|e| {
+ println!("NW: Write quote to file failed: {:?}", e);
+ optee_teec::Error::new(optee_teec::ErrorKind::BadParameters)
+ })?;
+ println!("NW: Quote written to file: {:?}", output);
+ Ok(())
+ }
+ cli::Command::VerifyQuote {
+ quote,
+ user_data,
+ endorse_pubkey,
+ measurements,
+ } => verify_quote(*quote, user_data, endorse_pubkey, *measurements).map_err(|e| {
+ println!("NW: Verify quote failed: {:?}", e);
+ optee_teec::Error::new(optee_teec::ErrorKind::BadParameters)
+ }),
+ }
+}
+
+fn get_quote(user_data: UserData) -> optee_teec::Result<Quote> {
+ let mut ctx = Context::new()?;
+ let uuid = Uuid::parse_str(UUID).map_err(|e| {
+ println!("NW: Parse UUID failed: {:?}", e);
+ optee_teec::Error::new(optee_teec::ErrorKind::BadParameters)
+ })?;
+ let mut session = ctx.open_session(uuid)?;
+
+ let p0 = ParamTmpRef::new_input(user_data.as_bytes());
+ let mut output_quote = [0u8; MAX_OUTPUT_SIZE];
+ let p1 = ParamTmpRef::new_output(&mut output_quote);
+
+ let mut op = Operation::new(0, p0, p1, ParamNone, ParamNone);
+ session.invoke_command(Command::GetQuote as u32, &mut op)?;
+
+ let quote: Quote = bincode::deserialize(&output_quote).map_err(|e| {
+ println!("NW: Deserialize quote failed: {:?}", e);
+ optee_teec::Error::new(optee_teec::ErrorKind::BadParameters)
+ })?;
+ Ok(quote)
+}
+
+fn write_quote_to_file(quote: &Quote, path: &std::path::Path) -> anyhow::Result<()> {
+ let serialized_quote = serde_json::to_string(quote)?;
+ let mut file = std::fs::File::create(path)?;
+ file.write_all(serialized_quote.as_bytes())?;
+ Ok(())
+}
+
+fn verify_quote(
+ quote: Quote,
+ user_data: UserData,
+ platform_pk: PlatformPubkey,
+ measurements: MeasurementsRecorded,
+) -> anyhow::Result<()> {
+ // check: signature, user_data, measurements
+ let report_verifier = EcdsaReportVerifier {
+ user_data,
+ measurements,
+ };
+
+ // check: signature
+ let endorsement_verifier = EcdsaEndorsementVerifier;
+
+ // Create quote verifier
+ let verifier = QuoteVerifier::new(report_verifier, endorsement_verifier, platform_pk);
+
+ // Verify the quote
+ verifier.verify_quote("e)?;
+ Ok(())
+}
diff --git a/examples/attestation-rs/app/host/src/measurements.rs b/examples/attestation-rs/app/host/src/measurements.rs
new file mode 100644
index 0000000..907bd9a
--- /dev/null
+++ b/examples/attestation-rs/app/host/src/measurements.rs
@@ -0,0 +1,158 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use anyhow::{ensure, Result};
+use attestation::ReportBody;
+use serde::{
+ de::{self, MapAccess, Visitor},
+ Deserialize, Deserializer, Serialize,
+};
+use std::fmt;
+use uuid::Uuid;
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+#[serde(transparent)]
+pub struct MeasurementsRecorded(pub Vec<MeasurementRecord>);
+
+#[derive(Debug, Serialize, Clone)]
+pub struct MeasurementRecord {
+ pub ta_id: Uuid,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mr_ta_binary: Option<[u8; 32]>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mr_ta_memory: Option<[u8; 32]>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mr_os_memory: Option<[u8; 32]>,
+}
+
+impl<'de> Deserialize<'de> for MeasurementRecord {
+ fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct MeasurementRecordVisitor;
+
+ impl<'de> Visitor<'de> for MeasurementRecordVisitor {
+ type Value = MeasurementRecord;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("struct MeasurementRecord")
+ }
+
+ fn visit_map<V>(self, mut map: V) -> std::result::Result<MeasurementRecord, V::Error>
+ where
+ V: MapAccess<'de>,
+ {
+ let mut ta_id = None;
+ let mut mr_ta_binary = None;
+ let mut mr_ta_memory = None;
+ let mut mr_os_memory = None;
+
+ while let Some(key) = map.next_key::<String>()? {
+ match key.as_str() {
+ "ta_id" => {
+ ta_id = Some(map.next_value()?);
+ }
+ "mr_ta_binary" => {
+ let hex: Option<String> = map.next_value()?;
+ mr_ta_binary = hex.and_then(|h| parse_hex(&h).ok());
+ }
+ "mr_ta_memory" => {
+ let hex: Option<String> = map.next_value()?;
+ mr_ta_memory = hex.and_then(|h| parse_hex(&h).ok());
+ }
+ "mr_os_memory" => {
+ let hex: Option<String> = map.next_value()?;
+ mr_os_memory = hex.and_then(|h| parse_hex(&h).ok());
+ }
+ _ => {
+ let _ = map.next_value::<de::IgnoredAny>()?;
+ }
+ }
+ }
+
+ let ta_id = ta_id.ok_or_else(|| de::Error::missing_field("ta_id"))?;
+
+ Ok(MeasurementRecord {
+ ta_id,
+ mr_ta_binary,
+ mr_ta_memory,
+ mr_os_memory,
+ })
+ }
+ }
+
+ deserializer.deserialize_map(MeasurementRecordVisitor)
+ }
+}
+
+fn parse_hex(hex: &str) -> std::result::Result<[u8; 32], hex::FromHexError> {
+ let bytes = hex::decode(hex)?;
+ if bytes.len() != 32 {
+ return Err(hex::FromHexError::InvalidStringLength);
+ }
+ let mut array = [0u8; 32];
+ array.copy_from_slice(&bytes);
+ Ok(array)
+}
+
+impl MeasurementsRecorded {
+ /// Find a measurement record by TA ID
+ pub fn find_by_ta_id(&self, ta_id: &[u8; 16]) -> Option<&MeasurementRecord> {
+ self.0
+ .iter()
+ .find(|record| record.ta_id.as_bytes() == ta_id)
+ }
+}
+
+impl MeasurementRecord {
+ pub fn compare_to_report_body(&self, report_body: &ReportBody) -> Result<()> {
+ println!("[+] Verifying measurement record for TA ID {}", self.ta_id);
+
+ // check the measurements
+ if let Some(mr_ta_binary) = self.mr_ta_binary {
+ ensure!(
+ mr_ta_binary == report_body.mr_ta_binary,
+ "MR TA binary mismatch, expected: {:?}, got: {:?}",
+ mr_ta_binary,
+ report_body.mr_ta_binary
+ );
+ }
+ if let Some(mr_ta_memory) = self.mr_ta_memory {
+ ensure!(
+ mr_ta_memory == report_body.mr_ta_memory,
+ "MR TA memory mismatch, expected: {:?}, got: {:?}",
+ mr_ta_memory,
+ report_body.mr_ta_memory
+ );
+ }
+ if let Some(mr_os_memory) = self.mr_os_memory {
+ ensure!(
+ mr_os_memory == report_body.mr_os_memory,
+ "MR OS memory mismatch, expected: {:?}, got: {:?}",
+ mr_os_memory,
+ report_body.mr_os_memory
+ );
+ }
+
+ println!(
+ "[+] Measurement record for TA ID {} checked successfully",
+ self.ta_id
+ );
+ Ok(())
+ }
+}
diff --git a/examples/attestation-rs/app/host/src/verifier.rs b/examples/attestation-rs/app/host/src/verifier.rs
new file mode 100644
index 0000000..db88335
--- /dev/null
+++ b/examples/attestation-rs/app/host/src/verifier.rs
@@ -0,0 +1,129 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use anyhow::{ensure, Result};
+use attestation::{
+ AttestationKeyEndorsement, AttestationPubkey, AttestationReport, EndorsementVerification,
+ PlatformPubkey, ReportBody, ReportVerification, UserData,
+};
+use ring::signature;
+
+use crate::measurements::MeasurementsRecorded;
+
+/// ECDSA-based report verifier
+pub struct EcdsaReportVerifier {
+ pub user_data: UserData,
+ pub measurements: MeasurementsRecorded,
+}
+
+impl EcdsaReportVerifier {
+ pub fn check_report_body(&self, report: &ReportBody) -> Result<()> {
+ println!("[+] Checking report body");
+
+ // Find the measurement record for this specific TA ID
+ if let Some(measurement) = self.measurements.find_by_ta_id(&report.ta_id) {
+ measurement.compare_to_report_body(report)?;
+ } else {
+ println!(
+ "[!] No measurement record found for TA ID: {:?}",
+ report.ta_id
+ );
+ return Err(anyhow::anyhow!("No measurement record found for TA ID"));
+ }
+
+ println!("[+] Measurements checked successfully");
+
+ println!("[+] Report body checked successfully");
+ Ok(())
+ }
+
+ // Update the verifier with new measurements
+ pub fn _update_measurements(&mut self, measurements: MeasurementsRecorded) -> Result<()> {
+ println!("[+] Updating measurements");
+ self.measurements = measurements;
+ Ok(())
+ }
+
+ // Update the verifier with new user data
+ pub fn _update_user_data(&mut self, user_data: UserData) -> Result<()> {
+ println!("[+] Updating user data");
+ self.user_data = user_data;
+ Ok(())
+ }
+}
+
+impl ReportVerification for EcdsaReportVerifier {
+ fn verify_report(&self, ak_pub: &AttestationPubkey, report: &AttestationReport) -> Result<()> {
+ println!("[+] Verifying report signature with ECDSA");
+
+ let ak_pub = signature::UnparsedPublicKey::new(
+ &signature::ECDSA_P256_SHA256_ASN1,
+ ak_pub.as_bytes(),
+ );
+
+ let data = report.signing_data();
+ ak_pub
+ .verify(&data, report.signature().as_bytes())
+ .map_err(|e| anyhow::anyhow!("Failed to verify report signature: {:?}", e))?;
+
+ println!("[+] Report signature verified successfully");
+
+ // Check the user data
+ let user_data = report.user_data();
+ ensure!(
+ user_data == &self.user_data,
+ "User data does not match the expected value, expected: {:?}, got: {:?}",
+ self.user_data,
+ user_data
+ );
+ println!("[+] User data verified successfully");
+
+ // Check the report body
+ let report_body = report.report_body();
+ self.check_report_body(report_body)?;
+ println!("[+] Report body verified successfully");
+
+ Ok(())
+ }
+}
+
+/// ECDSA-based endorsement verifier
+pub struct EcdsaEndorsementVerifier;
+
+impl EndorsementVerification for EcdsaEndorsementVerifier {
+ fn verify_endorsement(
+ &self,
+ platform_pk: &PlatformPubkey,
+ endorsement: &AttestationKeyEndorsement,
+ ) -> Result<()> {
+ println!("[+] Verifying endorsement signature with ECDSA");
+
+ let platform_pub = signature::UnparsedPublicKey::new(
+ &signature::ECDSA_P256_SHA256_ASN1,
+ platform_pk.as_bytes(),
+ );
+
+ let hash = endorsement.signing_hash();
+
+ platform_pub
+ .verify(&hash, endorsement.signature().as_bytes())
+ .map_err(|e| anyhow::anyhow!("Failed to verify endorsement signature: {:?}", e))?;
+
+ println!("[+] Endorsement signature verified successfully");
+ Ok(())
+ }
+}
diff --git a/examples/attestation-rs/app/proto/Cargo.toml b/examples/attestation-rs/app/proto/Cargo.toml
new file mode 100644
index 0000000..e30aef8
--- /dev/null
+++ b/examples/attestation-rs/app/proto/Cargo.toml
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+name = "proto"
+version = "0.1.0"
+authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
+license = "Apache-2.0"
+repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
+description = "Data structures and functions shared by host and TA."
+edition = "2018"
+
+[dependencies]
+num_enum = { version = "0.7.3", default-features = false }
diff --git a/examples/attestation-rs/app/proto/src/lib.rs b/examples/attestation-rs/app/proto/src/lib.rs
new file mode 100644
index 0000000..bbf3943
--- /dev/null
+++ b/examples/attestation-rs/app/proto/src/lib.rs
@@ -0,0 +1,36 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![no_std]
+use num_enum::{FromPrimitive, IntoPrimitive};
+
+pub const MAX_OUTPUT_SIZE: usize = 4096;
+
+#[derive(FromPrimitive, IntoPrimitive)]
+#[repr(u32)]
+pub enum Command {
+ GetQuote,
+ // You can add other commands here:
+ // ...
+ #[default]
+ Unknown,
+}
+
+// If Uuid::parse_str() returns an InvalidLength error, there may be an extra
+// newline in your uuid.txt file. You can remove it by running
+// `truncate -s 36 uuid.txt`.
+pub const UUID: &str = &include_str!("../../uuid.txt");
diff --git a/examples/attestation-rs/app/ta/Cargo.toml b/examples/attestation-rs/app/ta/Cargo.toml
new file mode 100644
index 0000000..10a59d1
--- /dev/null
+++ b/examples/attestation-rs/app/ta/Cargo.toml
@@ -0,0 +1,41 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+name = "ta"
+version = "0.1.0"
+authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
+license = "Apache-2.0"
+repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
+description = "An example of Rust OP-TEE TrustZone SDK."
+edition = "2018"
+
+[dependencies]
+optee-utee-sys = { path = "../../../../optee-utee/optee-utee-sys" }
+optee-utee = { path = "../../../../optee-utee" }
+proto = { path = "../proto" }
+quoting_ta_proto = { path = "../../sdk/quoting_ta_proto"}
+attestation_forwarder = { path = "../../attestation_forwarder" }
+
+[build-dependencies]
+proto = { path = "../proto" }
+optee-utee-build = { path = "../../../../optee-utee-build" }
+
+[profile.release]
+panic = "abort"
+lto = true
+opt-level = 1
diff --git a/examples/attestation-rs/app/ta/Makefile b/examples/attestation-rs/app/ta/Makefile
new file mode 100644
index 0000000..5daf221
--- /dev/null
+++ b/examples/attestation-rs/app/ta/Makefile
@@ -0,0 +1,48 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+UUID ?= $(shell cat "../uuid.txt")
+
+TARGET ?= aarch64-unknown-linux-gnu
+CROSS_COMPILE ?= aarch64-linux-gnu-
+OBJCOPY := $(CROSS_COMPILE)objcopy
+# Configure the linker to use GCC, which works on both cross-compilation and ARM machines
+LINKER_CFG := target.$(TARGET).linker=\"$(CROSS_COMPILE)gcc\"
+
+TA_SIGN_KEY ?= $(TA_DEV_KIT_DIR)/keys/default_ta.pem
+SIGN := $(TA_DEV_KIT_DIR)/scripts/sign_encrypt.py
+OUT_DIR := $(CURDIR)/target/$(TARGET)/release
+
+BUILDER = $(if $(STD),xargo,cargo)
+
+all: ta strip sign
+
+ta:
+ @$(BUILDER) build --target $(TARGET) --release --config $(LINKER_CFG)
+
+strip: ta
+ @$(OBJCOPY) --strip-unneeded $(OUT_DIR)/ta $(OUT_DIR)/stripped_ta
+
+sign: strip
+ @$(SIGN) --uuid $(UUID) --key $(TA_SIGN_KEY) --in $(OUT_DIR)/stripped_ta --out $(OUT_DIR)/$(UUID).ta
+ @echo "SIGN => ${UUID}"
+
+clippy:
+ @$(BUILDER) clippy --target $(TARGET) --release --config $(LINKER_CFG) -- -D warnings
+
+clean:
+ @cargo clean
diff --git a/examples/attestation-rs/app/ta/Xargo.toml b/examples/attestation-rs/app/ta/Xargo.toml
new file mode 100644
index 0000000..251ee70
--- /dev/null
+++ b/examples/attestation-rs/app/ta/Xargo.toml
@@ -0,0 +1,24 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[dependencies.std]
+path = "../../../../rust/rust/library/std"
+
+[patch.crates-io]
+libc = { path = "../../../../rust/libc" }
+rustc-std-workspace-core = { path = "../../../../rust/rust/library/rustc-std-workspace-core" }
+rustc-std-workspace-alloc = { path = "../../../../rust/rust/library/rustc-std-workspace-alloc" }
diff --git a/examples/attestation-rs/app/ta/build.rs b/examples/attestation-rs/app/ta/build.rs
new file mode 100644
index 0000000..a9843e2
--- /dev/null
+++ b/examples/attestation-rs/app/ta/build.rs
@@ -0,0 +1,25 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use optee_utee_build::{Error, RustEdition, TaConfig};
+
+fn main() -> Result<(), Error> {
+ let ta_config = TaConfig::new_default_with_cargo_env(proto::UUID)?
+ .ta_stack_size(1024 * 1024)
+ .ta_data_size(1024 * 1024);
+ optee_utee_build::build(RustEdition::Before2024, ta_config)
+}
diff --git a/examples/attestation-rs/app/ta/src/main.rs b/examples/attestation-rs/app/ta/src/main.rs
new file mode 100644
index 0000000..2ef4a7f
--- /dev/null
+++ b/examples/attestation-rs/app/ta/src/main.rs
@@ -0,0 +1,67 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![no_std]
+#![no_main]
+extern crate alloc;
+
+use attestation_forwarder::QuotingTaClient;
+use optee_utee::{
+ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println,
+};
+use optee_utee::{Error, ErrorKind, Parameters, Result, Uuid};
+use proto::Command;
+use quoting_ta_proto::QUOTING_TA_UUID;
+
+#[ta_create]
+fn create() -> Result<()> {
+ trace_println!("[+] App TA create");
+ Ok(())
+}
+
+#[ta_open_session]
+fn open_session(_params: &mut Parameters) -> Result<()> {
+ trace_println!("[+] App TA open session");
+ Ok(())
+}
+
+#[ta_close_session]
+fn close_session() {
+ trace_println!("[+] App TA close session");
+}
+
+#[ta_destroy]
+fn destroy() {
+ trace_println!("[+] App TA destroy");
+}
+
+#[ta_invoke_command]
+fn invoke_command(cmd_id: u32, params: &mut Parameters) -> Result<()> {
+ trace_println!("[+] App TA invoke command");
+ match Command::from(cmd_id) {
+ Command::GetQuote => {
+ let quoting_ta_uuid =
+ Uuid::parse_str(QUOTING_TA_UUID).map_err(|_| Error::new(ErrorKind::BadState))?;
+
+ let service = QuotingTaClient::init(quoting_ta_uuid)?;
+ service.get_quote(params)
+ }
+ _ => Err(Error::new(ErrorKind::BadParameters)),
+ }
+}
+
+include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));
diff --git a/examples/attestation-rs/app/uuid.txt b/examples/attestation-rs/app/uuid.txt
new file mode 100644
index 0000000..b05020c
--- /dev/null
+++ b/examples/attestation-rs/app/uuid.txt
@@ -0,0 +1 @@
+653d34fb-f8e3-41fd-bd3d-215c8138ac03
\ No newline at end of file
diff --git a/examples/attestation-rs/attestation/Cargo.toml b/examples/attestation-rs/attestation/Cargo.toml
new file mode 100644
index 0000000..1ccbdd8
--- /dev/null
+++ b/examples/attestation-rs/attestation/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "attestation"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+anyhow = "1.0"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+sha2 = { version = "0.10.8", default-features = false }
+hex = "0.4"
+ring = { version = "0.16.20", optional = true }
+uuid = { version = "1.16.0", features = ["serde"] }
+
+[features]
+test = ["ring"]
\ No newline at end of file
diff --git a/examples/attestation-rs/attestation/src/attest.rs b/examples/attestation-rs/attestation/src/attest.rs
new file mode 100644
index 0000000..e158a9a
--- /dev/null
+++ b/examples/attestation-rs/attestation/src/attest.rs
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Attestation trait and related functionality
+
+use crate::common::{
+ AttestationPubkey, AttestationReport, AttestationSignature, Identity, ReportBody, UserData,
+};
+use anyhow::Result;
+
+/// Trait for components that can perform attestation
+///
+/// This trait abstracts over the attestation functionality provided by
+/// an attestation PTA (Pseudo Trusted Application) in OpTEE.
+pub trait Attesting {
+ /// Attest a target TA by its identity
+ ///
+ /// # Arguments
+ ///
+ /// * `target_ta` - The identity (UUID) of the target TA to attest
+ /// * `user_data` - Optional user data to include in the attestation
+ ///
+ /// # Returns
+ ///
+ /// An attestation report for the target TA
+ fn attest_ta(&self, target_ta: &Identity, user_data: UserData) -> Result<AttestationReport>;
+
+ /// Get the attestation public key
+ fn get_attestation_pubkey(&self) -> Result<AttestationPubkey>;
+}
+
+/// Trait for managing signing keys and operations
+pub trait AttestationKeyManagement {
+ /// Sign the given data with the attestation key
+ fn sign(&self, data: &[u8]) -> Result<AttestationSignature>;
+
+ /// Get the attestation public key
+ fn get_attestation_pubkey(&self) -> Result<AttestationPubkey>;
+}
+
+pub trait TaMeasurement {
+ fn measure_ta(&self, target_ta: &Identity) -> Result<ReportBody>;
+}
+
+pub struct Attester<K: AttestationKeyManagement, M: TaMeasurement> {
+ attestation_key_manager: K,
+ ta_measurer: M,
+}
+
+impl<K: AttestationKeyManagement, M: TaMeasurement> Attester<K, M> {
+ pub fn new(attestation_key_manager: K, ta_measurer: M) -> Self {
+ Self {
+ attestation_key_manager,
+ ta_measurer,
+ }
+ }
+}
+
+impl<K: AttestationKeyManagement, M: TaMeasurement> Attesting for Attester<K, M> {
+ fn attest_ta(&self, target_ta: &Identity, user_data: UserData) -> Result<AttestationReport> {
+ // Create report body
+ let body = self.ta_measurer.measure_ta(target_ta)?;
+
+ // Create signing data
+ let mut signing_data = body.signing_data();
+ signing_data.extend_from_slice(user_data.as_bytes());
+
+ // Sign the report
+ let signature = self.attestation_key_manager.sign(&signing_data)?;
+
+ Ok(AttestationReport::new(body, user_data, signature))
+ }
+
+ fn get_attestation_pubkey(&self) -> Result<AttestationPubkey> {
+ self.attestation_key_manager.get_attestation_pubkey()
+ }
+}
diff --git a/examples/attestation-rs/attestation/src/common.rs b/examples/attestation-rs/attestation/src/common.rs
new file mode 100644
index 0000000..9c952ff
--- /dev/null
+++ b/examples/attestation-rs/attestation/src/common.rs
@@ -0,0 +1,595 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Common types and structures for attestation
+
+use anyhow::{ensure, Result};
+use hex;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::convert::TryFrom;
+use std::fmt;
+
+/// Platform public key hash (SHA-256)
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PlatformPubkeyHash([u8; 32]);
+
+impl PlatformPubkeyHash {
+ pub fn from_pubkey(pubkey: &PlatformPubkey) -> Result<Self> {
+ let mut hasher = Sha256::new();
+ hasher.update(pubkey.as_bytes());
+ let hash = hasher.finalize();
+ let hash_bytes: [u8; 32] = hash
+ .as_slice()
+ .try_into()
+ .map_err(|_| anyhow::anyhow!("Failed to convert hash to array"))?;
+ Ok(Self(hash_bytes))
+ }
+
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+}
+
+impl fmt::Display for PlatformPubkeyHash {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", hex::encode(self.as_bytes()))
+ }
+}
+
+/// Platform public key (RSA 3072)
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PlatformPubkey(Vec<u8>);
+
+impl PlatformPubkey {
+ /// Create a new PlatformPubkey from raw bytes
+ pub fn new(bytes: Vec<u8>) -> Self {
+ PlatformPubkey(bytes)
+ }
+
+ /// Get the raw bytes
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+
+ /// Convert into raw bytes
+ pub fn into_bytes(self) -> Vec<u8> {
+ self.0
+ }
+
+ pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
+ ensure!(
+ bytes.len() > 4,
+ "Platform public key must be more than 4 bytes"
+ );
+ Ok(Self(bytes.to_vec()))
+ }
+}
+
+impl fmt::Display for PlatformPubkey {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", hex::encode(self.as_bytes()))
+ }
+}
+
+/// Attestation public key (supports various algorithms)
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct AttestationPubkey(Vec<u8>);
+
+impl AttestationPubkey {
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(bytes.to_vec())
+ }
+
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+
+ pub fn hash(&self) -> [u8; 32] {
+ let mut hasher = Sha256::new();
+ hasher.update(&self.0);
+ let hash = hasher.finalize();
+ let mut result = [0u8; 32];
+ result.copy_from_slice(&hash);
+ result
+ }
+}
+
+impl fmt::Display for AttestationPubkey {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", hex::encode(self.as_bytes()))
+ }
+}
+
+/// Attestation signature (supports various algorithms)
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct AttestationSignature(Vec<u8>);
+
+impl AttestationSignature {
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(bytes.to_vec())
+ }
+
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+}
+
+impl fmt::Display for AttestationSignature {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", hex::encode(self.as_bytes()))
+ }
+}
+
+/// Endorsement signature (RSA 3072)
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct EndorsementSignature(Vec<u8>); // RSA 3072 signature is 384 bytes
+
+impl EndorsementSignature {
+ pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
+ Ok(Self(bytes.to_vec()))
+ }
+
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+}
+
+impl fmt::Display for EndorsementSignature {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", hex::encode(self.as_bytes()))
+ }
+}
+
+/// Identity of a Trusted Application (UUID)
+#[derive(Debug, Clone)]
+pub struct Identity {
+ /// TA UUID
+ uuid: [u8; 16],
+}
+
+impl Identity {
+ pub fn new(uuid: [u8; 16]) -> Self {
+ Self { uuid }
+ }
+
+ pub fn as_uuid(&self) -> [u8; 16] {
+ self.uuid
+ }
+}
+
+impl fmt::Display for Identity {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ f,
+ "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
+ self.uuid[0], self.uuid[1], self.uuid[2], self.uuid[3],
+ self.uuid[4], self.uuid[5],
+ self.uuid[6], self.uuid[7],
+ self.uuid[8], self.uuid[9],
+ self.uuid[10], self.uuid[11], self.uuid[12], self.uuid[13], self.uuid[14], self.uuid[15]
+ )
+ }
+}
+
+impl TryFrom<String> for Identity {
+ type Error = anyhow::Error;
+ // format: "{:08x}-{:04x}-{:04x}-{}-{}"
+ fn try_from(value: String) -> Result<Self> {
+ let mut uuid = [0u8; 16];
+ let parts: Vec<&str> = value.split('-').collect();
+ ensure!(parts.len() == 5, "Invalid UUID format");
+
+ // Using big-endian order, follow the spec: https://www.ietf.org/rfc/rfc4122.txt
+ uuid[0..4].copy_from_slice(&u32::from_str_radix(parts[0], 16)?.to_be_bytes());
+ uuid[4..6].copy_from_slice(&u16::from_str_radix(parts[1], 16)?.to_be_bytes());
+ uuid[6..8].copy_from_slice(&u16::from_str_radix(parts[2], 16)?.to_be_bytes());
+ uuid[8..10].copy_from_slice(&hex::decode(parts[3])?);
+ uuid[10..].copy_from_slice(&hex::decode(parts[4])?);
+
+ Ok(Self { uuid })
+ }
+}
+
+/// Attestation report for a TA
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ReportBody {
+ /// TA UUID
+ pub ta_id: [u8; 16],
+ /// Measurement of TA binary
+ pub mr_ta_binary: [u8; 32],
+ /// Measurement of TA memory
+ pub mr_ta_memory: [u8; 32],
+ /// Measurement of OS memory
+ pub mr_os_memory: [u8; 32],
+}
+
+impl ReportBody {
+ pub fn signing_data(&self) -> Vec<u8> {
+ let mut vec = Vec::new();
+ vec.extend_from_slice(&self.ta_id);
+ vec.extend_from_slice(&self.mr_ta_binary);
+ vec.extend_from_slice(&self.mr_ta_memory);
+ vec.extend_from_slice(&self.mr_os_memory);
+ vec
+ }
+
+ pub fn decode_from_bytes(bytes: &[u8]) -> Result<Self> {
+ // ensure the length is size of report body
+ ensure!(
+ bytes.len() == core::mem::size_of::<ReportBody>(),
+ "Wrong length of report body: {}",
+ bytes.len()
+ );
+ let mut ta_id = [0u8; 16];
+ let mut mr_ta_binary = [0u8; 32];
+ let mut mr_ta_memory = [0u8; 32];
+ let mut mr_os_memory = [0u8; 32];
+
+ ta_id.copy_from_slice(&bytes[0..16]);
+ mr_ta_binary.copy_from_slice(&bytes[16..48]);
+ mr_ta_memory.copy_from_slice(&bytes[48..80]);
+ mr_os_memory.copy_from_slice(&bytes[80..112]);
+
+ Ok(Self {
+ ta_id,
+ mr_ta_binary,
+ mr_ta_memory,
+ mr_os_memory,
+ })
+ }
+}
+
+impl fmt::Display for ReportBody {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let indent = f.width().unwrap_or(0);
+ writeln!(f, "{{")?;
+ writeln!(
+ f,
+ "{:indent$} ta_id: {},",
+ "",
+ hex::encode(self.ta_id),
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} mr_ta_binary: {},",
+ "",
+ hex::encode(self.mr_ta_binary),
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} mr_ta_memory: {},",
+ "",
+ hex::encode(self.mr_ta_memory),
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} mr_os_memory: {},",
+ "",
+ hex::encode(self.mr_os_memory),
+ indent = indent
+ )?;
+ write!(f, "{:indent$}}}", "", indent = indent)
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct UserData {
+ data: [u8; 32],
+}
+
+impl UserData {
+ pub fn new(data: [u8; 32]) -> Self {
+ Self { data }
+ }
+
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.data
+ }
+
+ pub fn into_bytes(self) -> [u8; 32] {
+ self.data
+ }
+
+ pub fn from_fix_str(s: &str) -> Result<Self> {
+ ensure!(s.len() <= 32, "fix_str must be less than 32 bytes");
+ let mut data = [0u8; 32];
+ data[..s.len()].copy_from_slice(s.as_bytes());
+ Ok(Self { data })
+ }
+}
+
+impl TryFrom<Vec<u8>> for UserData {
+ type Error = anyhow::Error;
+
+ fn try_from(value: Vec<u8>) -> Result<Self> {
+ ensure!(value.len() <= 32, "User data must be less than 32 bytes");
+ let mut data = [0u8; 32];
+ data[..value.len()].copy_from_slice(&value);
+ Ok(Self { data })
+ }
+}
+
+impl fmt::Display for UserData {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", hex::encode(self.as_bytes()))
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AttestationReport {
+ /// Report body
+ body: ReportBody,
+ /// User data
+ user_data: UserData,
+ /// Signature over the report body
+ signature: AttestationSignature,
+}
+
+impl fmt::Display for AttestationReport {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let indent = f.width().unwrap_or(0);
+ writeln!(f, "{{")?;
+ writeln!(
+ f,
+ "{:indent$} body: {},",
+ "",
+ format!("{:width$}", self.body, width = indent + 2),
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} user_data: {},",
+ "",
+ self.user_data,
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} signature: {},",
+ "",
+ self.signature,
+ indent = indent
+ )?;
+ write!(f, "{:indent$}}}", "", indent = indent)
+ }
+}
+
+impl AttestationReport {
+ pub fn new(body: ReportBody, user_data: UserData, signature: AttestationSignature) -> Self {
+ Self {
+ body,
+ user_data,
+ signature,
+ }
+ }
+
+ pub fn signing_data(&self) -> Vec<u8> {
+ let mut vec = self.body.signing_data();
+ vec.extend_from_slice(self.user_data.as_bytes());
+ vec
+ }
+
+ pub fn to_vec(&self) -> Vec<u8> {
+ let mut vec = self.signing_data();
+ vec.extend_from_slice(self.signature.as_bytes());
+ vec
+ }
+
+ pub fn signature(&self) -> &AttestationSignature {
+ &self.signature
+ }
+
+ pub fn report_body(&self) -> &ReportBody {
+ &self.body
+ }
+
+ pub fn user_data(&self) -> &UserData {
+ &self.user_data
+ }
+}
+
+/// Attestation key endorsement
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EndorsementBody {
+ /// Attestation key public key
+ attestation_pubkey: AttestationPubkey,
+ /// Platform public key
+ platform_pubkey_hash: PlatformPubkeyHash,
+ /// Endorsement counter
+ counter: u32,
+ /// Quoter report
+ quoter_report: AttestationReport,
+}
+
+impl fmt::Display for EndorsementBody {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let indent = f.width().unwrap_or(0);
+ writeln!(f, "{{")?;
+ writeln!(
+ f,
+ "{:indent$} attestation_pubkey: {},",
+ "",
+ self.attestation_pubkey,
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} platform_pubkey_hash: {},",
+ "",
+ self.platform_pubkey_hash,
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} counter: {},",
+ "",
+ self.counter,
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} quoter_report: {},",
+ "",
+ format!("{:width$}", self.quoter_report, width = indent + 2),
+ indent = indent
+ )?;
+ write!(f, "{:indent$}}}", "", indent = indent)
+ }
+}
+
+impl EndorsementBody {
+ pub fn new(
+ attestation_pubkey: AttestationPubkey,
+ platform_pubkey_hash: PlatformPubkeyHash,
+ counter: u32,
+ quoter_report: AttestationReport,
+ ) -> Self {
+ Self {
+ attestation_pubkey,
+ platform_pubkey_hash,
+ counter,
+ quoter_report,
+ }
+ }
+
+ pub fn attestation_pubkey(&self) -> &AttestationPubkey {
+ &self.attestation_pubkey
+ }
+
+ pub fn platform_pubkey_hash(&self) -> &PlatformPubkeyHash {
+ &self.platform_pubkey_hash
+ }
+
+ pub fn counter(&self) -> u32 {
+ self.counter
+ }
+
+ pub fn quoter_report(&self) -> &AttestationReport {
+ &self.quoter_report
+ }
+}
+
+/// Attestation key endorsement
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AttestationKeyEndorsement {
+ body: EndorsementBody,
+ /// Endorsement signature
+ signature: EndorsementSignature,
+}
+
+impl fmt::Display for AttestationKeyEndorsement {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let indent = f.width().unwrap_or(0);
+ writeln!(f, "{{")?;
+ writeln!(
+ f,
+ "{:indent$} body: {},",
+ "",
+ format!("{:width$}", self.body, width = indent + 2),
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} signature: {},",
+ "",
+ self.signature,
+ indent = indent
+ )?;
+ write!(f, "{:indent$}}}", "", indent = indent)
+ }
+}
+
+impl AttestationKeyEndorsement {
+ pub fn new(body: EndorsementBody, signature: EndorsementSignature) -> Self {
+ Self { body, signature }
+ }
+
+ pub fn platform_pubkey_hash(&self) -> &PlatformPubkeyHash {
+ self.body.platform_pubkey_hash()
+ }
+
+ pub fn attestation_pubkey(&self) -> &AttestationPubkey {
+ self.body.attestation_pubkey()
+ }
+
+ pub fn counter(&self) -> u32 {
+ self.body.counter
+ }
+
+ pub fn quoter_report(&self) -> &AttestationReport {
+ self.body.quoter_report()
+ }
+
+ pub fn signature(&self) -> &EndorsementSignature {
+ &self.signature
+ }
+
+ pub fn signing_hash(&self) -> Vec<u8> {
+ self.body.signing_hash()
+ }
+}
+
+impl EndorsementBody {
+ pub fn signing_hash(&self) -> Vec<u8> {
+ let mut hasher = Sha256::new();
+ hasher.update(self.attestation_pubkey.as_bytes());
+ hasher.update(self.platform_pubkey_hash.as_bytes());
+ hasher.update(self.counter.to_be_bytes());
+ let body = self.quoter_report.to_vec();
+ hasher.update(&body);
+ hasher.finalize().to_vec()
+ }
+}
+
+/// Attestation quote
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Quote {
+ /// Attestation report for the target TA
+ pub report: AttestationReport,
+ /// Attestation key endorsement
+ pub attestation_key_endorsement: AttestationKeyEndorsement,
+}
+
+impl fmt::Display for Quote {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let indent = f.width().unwrap_or(0);
+ writeln!(f, "{{")?;
+ writeln!(
+ f,
+ "{:indent$} report: {},",
+ "",
+ format!("{:width$}", self.report, width = indent + 2),
+ indent = indent
+ )?;
+ writeln!(
+ f,
+ "{:indent$} attestation_key_endorsement: {},",
+ "",
+ format!(
+ "{:width$}",
+ self.attestation_key_endorsement,
+ width = indent + 2
+ ),
+ indent = indent
+ )?;
+ write!(f, "{:indent$}}}", "", indent = indent)
+ }
+}
diff --git a/examples/attestation-rs/attestation/src/endorse.rs b/examples/attestation-rs/attestation/src/endorse.rs
new file mode 100644
index 0000000..e6660f9
--- /dev/null
+++ b/examples/attestation-rs/attestation/src/endorse.rs
@@ -0,0 +1,101 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Endorsement trait and related functionality
+
+use crate::common::{
+ AttestationKeyEndorsement, AttestationPubkey, AttestationReport, EndorsementBody,
+ EndorsementSignature, PlatformPubkey, PlatformPubkeyHash,
+};
+use crate::verify::ReportVerification;
+use anyhow::{Context, Result};
+
+/// Trait for components that can endorse attestation keys
+///
+/// This trait abstracts over the manufacturing protection (MP) functionality
+/// provided by a MP PTA (Pseudo Trusted Application) in OpTEE.
+pub trait Endorsing {
+ /// Endorse an attestation key with the platform key
+ ///
+ /// # Arguments
+ ///
+ /// * `attestation_pubkey` - The attestation public key to endorse
+ /// * `quoter_report` - The TA report for the QuoteTA
+ ///
+ /// # Returns
+ ///
+ /// An endorsement with signature of the platform key
+ fn endorse_attestation_pubkey(
+ &self,
+ attestation_pubkey: AttestationPubkey,
+ quoter_report: AttestationReport,
+ ) -> Result<AttestationKeyEndorsement>;
+}
+
+pub trait PlatformKeyManagement {
+ /// Sign the given data with the endorsing key
+ fn sign(&self, data: &[u8]) -> Result<EndorsementSignature>;
+
+ /// Get the public endorsing key
+ fn get_platform_pubkey(&self) -> Result<PlatformPubkey>;
+
+ /// tick the endorsement counter to track the number of times the platform key has been used
+ fn tick_counter(&self) -> Result<u32>;
+}
+
+pub struct Endorser<K: PlatformKeyManagement, V: ReportVerification> {
+ platform_key_manager: K,
+ quote_verifier: V,
+}
+
+impl<K: PlatformKeyManagement, V: ReportVerification> Endorser<K, V> {
+ pub fn new(platform_key_manager: K, quote_verifier: V) -> Self {
+ Self {
+ platform_key_manager,
+ quote_verifier,
+ }
+ }
+}
+
+impl<K: PlatformKeyManagement, V: ReportVerification> Endorsing for Endorser<K, V> {
+ fn endorse_attestation_pubkey(
+ &self,
+ attestation_pubkey: AttestationPubkey,
+ quoter_report: AttestationReport,
+ ) -> Result<AttestationKeyEndorsement> {
+ self.quote_verifier
+ .verify_report(&attestation_pubkey, "er_report)
+ .context("Failed to verify quoter report")?;
+
+ let platform_pubkey = self.platform_key_manager.get_platform_pubkey()?;
+ let counter = self.platform_key_manager.tick_counter()?;
+
+ let platform_pubkey_hash = PlatformPubkeyHash::from_pubkey(&platform_pubkey)?;
+ let body = EndorsementBody::new(
+ attestation_pubkey,
+ platform_pubkey_hash,
+ counter,
+ quoter_report,
+ );
+
+ let hash = body.signing_hash();
+ let signature = self.platform_key_manager.sign(&hash)?;
+
+ let endorsement = AttestationKeyEndorsement::new(body, signature);
+ Ok(endorsement)
+ }
+}
diff --git a/examples/attestation-rs/attestation/src/lib.rs b/examples/attestation-rs/attestation/src/lib.rs
new file mode 100644
index 0000000..a862457
--- /dev/null
+++ b/examples/attestation-rs/attestation/src/lib.rs
@@ -0,0 +1,92 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use anyhow::Result;
+
+mod attest;
+mod common;
+mod endorse;
+mod verify;
+
+pub use attest::{AttestationKeyManagement, Attester, Attesting, TaMeasurement};
+pub use common::*;
+pub use endorse::{Endorser, Endorsing, PlatformKeyManagement};
+pub use verify::{EndorsementVerification, QuoteVerifier, QuoteVerify, ReportVerification};
+
+pub trait EndorsementStore {
+ /// Get an existing endorsement for the given attestation key
+ fn get_endorsement(
+ &self,
+ attestation_pubkey: &AttestationPubkey,
+ ) -> Option<AttestationKeyEndorsement>;
+
+ /// Store the endorsement
+ fn store_endorsement(&self, endorsement: AttestationKeyEndorsement) -> Result<()>;
+}
+
+pub struct Quoter<A: Attesting, E: Endorsing, S: EndorsementStore> {
+ identity: Identity,
+ attester: A,
+ endorser: E,
+ endorsement_store: S,
+}
+
+impl<A: Attesting, E: Endorsing, S: EndorsementStore> Quoter<A, E, S> {
+ pub fn new(identity: Identity, attester: A, endorser: E, endorsement_store: S) -> Self {
+ Self {
+ identity,
+ attester,
+ endorser,
+ endorsement_store,
+ }
+ }
+
+ fn endorsing_attestation_pubkey(
+ &self,
+ attestation_pubkey: AttestationPubkey,
+ ) -> Result<AttestationKeyEndorsement> {
+ let user_data = UserData::from_fix_str("QUOTER_SELF_ATTEST")?;
+ let quoter_report = self.attester.attest_ta(&self.identity, user_data)?;
+ self.endorser
+ .endorse_attestation_pubkey(attestation_pubkey, quoter_report)
+ }
+
+ pub fn get_quote(&self, target_ta: &Identity, user_data: UserData) -> Result<Quote> {
+ // First get the attestation key and endorsement (attest the quoter)
+ let attestation_pubkey = self.attester.get_attestation_pubkey()?;
+
+ let attestation_key_endorsement =
+ match self.endorsement_store.get_endorsement(&attestation_pubkey) {
+ Some(attestation_key_endorsement) => attestation_key_endorsement,
+ None => self.endorsing_attestation_pubkey(attestation_pubkey)?,
+ };
+
+ // Then get the attest the target TA
+ let ta_report = self.attester.attest_ta(target_ta, user_data)?;
+
+ // Return the complete quote
+ Ok(Quote {
+ report: ta_report,
+ attestation_key_endorsement,
+ })
+ }
+}
+
+#[cfg(all(test, feature = "test"))]
+mod tests {
+ pub mod attestation_flow;
+}
diff --git a/examples/attestation-rs/attestation/src/tests/attestation_flow.rs b/examples/attestation-rs/attestation/src/tests/attestation_flow.rs
new file mode 100644
index 0000000..80dc6d3
--- /dev/null
+++ b/examples/attestation-rs/attestation/src/tests/attestation_flow.rs
@@ -0,0 +1,287 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for the optee-attestation crate
+
+use crate::{
+ AttestationKeyEndorsement, AttestationKeyManagement, AttestationPubkey, AttestationSignature,
+ Attester, EndorsementSignature, EndorsementStore, EndorsementVerification, Endorser, Identity,
+ PlatformKeyManagement, PlatformPubkey, QuoteVerifier, QuoteVerify, Quoter, ReportBody,
+ ReportVerification, UserData,
+};
+use anyhow::Result;
+
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+use ring::{
+ rand,
+ signature::{
+ EcdsaKeyPair, KeyPair, UnparsedPublicKey, ECDSA_P256_SHA256_ASN1,
+ ECDSA_P256_SHA256_ASN1_SIGNING,
+ },
+};
+
+/// Algorithm Selection in Demonstration:
+/// 1. Design Flexibility:
+/// Our attestation system is algorithm-agnostic. Developers can implement any signing algorithm
+/// by implementing the required traits, allowing for different security and performance tradeoffs.
+///
+/// 2. We choose ECDSA for demonstration, the common choices are:
+/// - ECDSA_P256_SHA256_FIXED: Fixed-length signatures, optimized for IoT/embedded systems
+/// - ECDSA_P256_SHA256_ASN1_SIGNING: DER-encoded signatures, variable length, widely used in PKI/TLS
+///
+/// 3. Test Implementation Choice:
+/// We choose ECDSA_P256_SHA256_ASN1_SIGNING for this test because:
+/// - Compatible with common PKI tools and libraries (OpenSSL, Rustls, Webpki)
+/// - Easy to integrate with higher-level security protocols
+
+/// structs for Attester: This defines how does the attestation key managed
+struct MockAttestationKeyManager {
+ private_key: EcdsaKeyPair,
+}
+
+impl MockAttestationKeyManager {
+ fn new() -> Result<Self> {
+ // Generate a new key pair
+ let rng = rand::SystemRandom::new();
+ let pkcs8_bytes = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng)
+ .map_err(|e| anyhow::anyhow!("Failed to generate attestation key: {:?}", e))?;
+
+ let key_pair =
+ EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8_bytes.as_ref())
+ .map_err(|e| anyhow::anyhow!("Failed to generate attestation key: {:?}", e))?;
+ Ok(Self {
+ private_key: key_pair,
+ })
+ }
+}
+
+impl AttestationKeyManagement for MockAttestationKeyManager {
+ fn sign(&self, data: &[u8]) -> Result<AttestationSignature> {
+ let rng = rand::SystemRandom::new();
+ let signature = self
+ .private_key
+ .sign(&rng, data)
+ .map_err(|e| anyhow::anyhow!("Failed to sign attestation: {:?}", e))?;
+
+ Ok(AttestationSignature::from_bytes(signature.as_ref()))
+ }
+
+ fn get_attestation_pubkey(&self) -> Result<AttestationPubkey> {
+ Ok(AttestationPubkey::from_bytes(
+ &self.private_key.public_key().as_ref(),
+ ))
+ }
+}
+
+/// structs for Attester: This defines how to measure the TA
+struct MockTaMeasurer;
+
+impl crate::attest::TaMeasurement for MockTaMeasurer {
+ fn measure_ta(&self, target_ta: &Identity) -> Result<crate::common::ReportBody> {
+ Ok(ReportBody {
+ ta_id: target_ta.as_uuid(),
+ mr_ta_binary: [0xaa; 32],
+ mr_ta_memory: [0xbb; 32],
+ mr_os_memory: [0xcc; 32],
+ })
+ }
+}
+
+/// structs for Endorser: This defines how does the endorser manage the platform key
+struct MockPlatformKeyManager {
+ private_key: EcdsaKeyPair,
+ counter: Mutex<u32>,
+}
+
+impl MockPlatformKeyManager {
+ fn new() -> Result<Self> {
+ // Generate a new key pair for platform
+ let rng = rand::SystemRandom::new();
+ let pkcs8_bytes = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng)
+ .map_err(|e| anyhow::anyhow!("Failed to generate platform key: {:?}", e))?;
+
+ let key_pair =
+ EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8_bytes.as_ref())
+ .map_err(|e| anyhow::anyhow!("Failed to generate platform key: {:?}", e))?;
+
+ Ok(Self {
+ private_key: key_pair,
+ counter: Mutex::new(0),
+ })
+ }
+}
+
+impl PlatformKeyManagement for MockPlatformKeyManager {
+ fn sign(&self, data: &[u8]) -> Result<EndorsementSignature> {
+ let rng = rand::SystemRandom::new();
+ let signature = self
+ .private_key
+ .sign(&rng, data)
+ .map_err(|e| anyhow::anyhow!("Failed to sign endorsement: {:?}", e))?;
+ EndorsementSignature::from_bytes(signature.as_ref())
+ }
+
+ fn get_platform_pubkey(&self) -> Result<PlatformPubkey> {
+ Ok(PlatformPubkey::new(
+ self.private_key.public_key().as_ref().to_vec(),
+ ))
+ }
+
+ fn tick_counter(&self) -> Result<u32> {
+ let mut counter = self.counter.lock().unwrap();
+ *counter = counter.wrapping_add(1);
+ Ok(*counter)
+ }
+}
+
+/// structs for Endorser: This defines how does the endorser store the endorsements
+struct MockEndorsementStore {
+ endorsements: Mutex<HashMap<Vec<u8>, AttestationKeyEndorsement>>,
+}
+
+impl Default for MockEndorsementStore {
+ fn default() -> Self {
+ Self {
+ endorsements: Mutex::new(HashMap::new()),
+ }
+ }
+}
+
+impl EndorsementStore for MockEndorsementStore {
+ fn get_endorsement(
+ &self,
+ attestation_pubkey: &AttestationPubkey,
+ ) -> Option<AttestationKeyEndorsement> {
+ self.endorsements
+ .lock()
+ .unwrap()
+ .get(attestation_pubkey.as_bytes())
+ .cloned()
+ }
+
+ fn store_endorsement(&self, endorsement: AttestationKeyEndorsement) -> Result<()> {
+ self.endorsements.lock().unwrap().insert(
+ endorsement.attestation_pubkey().as_bytes().to_vec(),
+ endorsement,
+ );
+ Ok(())
+ }
+}
+
+/// structs for Endorser: This defines how does the endorser verify the quoter's report
+struct MockQuoterReportVerifier;
+
+impl ReportVerification for MockQuoterReportVerifier {
+ fn verify_report(
+ &self,
+ attestation_pubkey: &AttestationPubkey,
+ report: &crate::common::AttestationReport,
+ ) -> Result<()> {
+ let public_key =
+ UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, attestation_pubkey.as_bytes());
+
+ // verify the signature of the report
+ let signature = report.signature().as_bytes();
+ public_key
+ .verify(&report.signing_data(), signature)
+ .map_err(|e| anyhow::anyhow!("Failed to verify report signature: {:?}", e))
+ }
+}
+
+/// structs for ClientVerifier: This defines how does the client verify the App TA report
+struct MockReportVerifier;
+
+impl ReportVerification for MockReportVerifier {
+ fn verify_report(
+ &self,
+ attestation_pubkey: &AttestationPubkey,
+ report: &crate::common::AttestationReport,
+ ) -> Result<()> {
+ let public_key =
+ UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, attestation_pubkey.as_bytes());
+
+ // verify the signature of the report
+ let signature = report.signature().as_bytes();
+ public_key
+ .verify(&report.signing_data(), signature)
+ .map_err(|e| anyhow::anyhow!("Failed to verify report signature: {:?}", e))
+ }
+}
+
+/// structs for ClientVerifier: This defines how does the client verify the Attestation Key endorsement
+struct MockEndorsementVerifier;
+
+impl EndorsementVerification for MockEndorsementVerifier {
+ fn verify_endorsement(
+ &self,
+ platform_pubkey: &PlatformPubkey,
+ endorsement: &AttestationKeyEndorsement,
+ ) -> Result<()> {
+ let public_key =
+ UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, platform_pubkey.as_bytes());
+
+ // verify the signature of the endorsement
+ let signature = endorsement.signature().as_bytes();
+ public_key
+ .verify(&endorsement.signing_hash(), signature)
+ .map_err(|e| anyhow::anyhow!("Failed to verify endorsement signature: {:?}", e))
+ }
+}
+
+#[test]
+fn test_attestation_flow() -> Result<()> {
+ // get quote:
+ // Setup mock components
+ let attestation_key_manager = MockAttestationKeyManager::new()?;
+ let ta_measuring = MockTaMeasurer;
+ let platform_key_manager = MockPlatformKeyManager::new()?;
+ let endorsement_store = MockEndorsementStore::default();
+ let quoter_report_verifier = MockQuoterReportVerifier;
+
+ // Get the platform pubkey for verification
+ let platform_pubkey = platform_key_manager.get_platform_pubkey()?;
+
+ // Create attester and endorser
+ let attester = Attester::new(attestation_key_manager, ta_measuring);
+ let endorser = Endorser::new(platform_key_manager, quoter_report_verifier);
+
+ // Create quoter with this TA's identity
+ let quoter_identity = Identity::new([6; 16]);
+ let quoter = Quoter::new(quoter_identity, attester, endorser, endorsement_store);
+
+ // Test get_quote
+ let target_ta = Identity::new([7; 16]);
+ let user_data = UserData::new([8; 32]);
+ let quote = quoter.get_quote(&target_ta, user_data)?;
+ println!("quote: {}", quote);
+ println!("--------------------------------");
+ println!("report: {}", quote.report);
+ println!("--------------------------------");
+ println!("endorsement: {}", quote.attestation_key_endorsement);
+ println!("--------------------------------");
+
+ // verify quote:
+ // Test verify_quote
+ let report_verifier = MockReportVerifier;
+ let endorsement_verifier = MockEndorsementVerifier;
+ let verifier = QuoteVerifier::new(report_verifier, endorsement_verifier, platform_pubkey);
+ verifier.verify_quote("e)?;
+
+ Ok(())
+}
diff --git a/examples/attestation-rs/attestation/src/verify.rs b/examples/attestation-rs/attestation/src/verify.rs
new file mode 100644
index 0000000..aee2845
--- /dev/null
+++ b/examples/attestation-rs/attestation/src/verify.rs
@@ -0,0 +1,103 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Verification trait and related functionality
+
+use crate::common::{
+ AttestationKeyEndorsement, AttestationPubkey, AttestationReport, PlatformPubkey,
+ PlatformPubkeyHash, Quote,
+};
+use anyhow::{ensure, Result};
+
+/// Trait for verifying attestation reports
+pub trait ReportVerification {
+ fn verify_report(
+ &self,
+ attestation_pubkey: &AttestationPubkey,
+ report: &AttestationReport,
+ ) -> Result<()>;
+}
+
+/// Trait for verifying endorsements
+pub trait EndorsementVerification {
+ fn verify_endorsement(
+ &self,
+ platform_pubkey: &PlatformPubkey,
+ endorsement: &AttestationKeyEndorsement,
+ ) -> Result<()>;
+}
+
+/// Trait for components that can verify attestation quotes
+///
+/// This trait abstracts over the verification functionality for attestation quotes.
+pub trait QuoteVerify {
+ /// Verify an attestation quote
+ ///
+ /// # Arguments
+ ///
+ /// * `quote` - The attestation quote to verify
+ ///
+ /// # Returns
+ ///
+ /// Ok(()) if the quote is valid, Err otherwise
+ fn verify_quote(&self, quote: &Quote) -> Result<()>;
+}
+
+/// Quote verifier that uses separate verifiers for reports and endorsements
+pub struct QuoteVerifier<R: ReportVerification, E: EndorsementVerification> {
+ report_verifier: R,
+ endorsement_verifier: E,
+ platform_pubkey: PlatformPubkey,
+}
+
+impl<R: ReportVerification, E: EndorsementVerification> QuoteVerifier<R, E> {
+ pub fn new(
+ report_verifier: R,
+ endorsement_verifier: E,
+ platform_pubkey: PlatformPubkey,
+ ) -> Self {
+ Self {
+ report_verifier,
+ endorsement_verifier,
+ platform_pubkey,
+ }
+ }
+}
+
+impl<R: ReportVerification, E: EndorsementVerification> QuoteVerify for QuoteVerifier<R, E> {
+ fn verify_quote(&self, quote: &Quote) -> Result<()> {
+ let endorsement = "e.attestation_key_endorsement;
+ let report = "e.report;
+
+ // Verify platform key hash
+ ensure!(
+ endorsement.platform_pubkey_hash()
+ == &PlatformPubkeyHash::from_pubkey(&self.platform_pubkey)?,
+ "Platform public key hash mismatch"
+ );
+
+ // Verify endorsement
+ self.endorsement_verifier
+ .verify_endorsement(&self.platform_pubkey, endorsement)?;
+
+ // Verify report
+ self.report_verifier
+ .verify_report(endorsement.attestation_pubkey(), report)?;
+
+ Ok(())
+ }
+}
diff --git a/examples/attestation-rs/attestation_forwarder/Cargo.toml b/examples/attestation-rs/attestation_forwarder/Cargo.toml
new file mode 100644
index 0000000..726d2e4
--- /dev/null
+++ b/examples/attestation-rs/attestation_forwarder/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "attestation_forwarder"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+optee-utee-sys = { path = "../../../optee-utee/optee-utee-sys" }
+optee-utee = { path = "../../../optee-utee" }
+
+quoting_ta_proto = { path = "../sdk/quoting_ta_proto"}
+
+num_enum = { version = "0.7.3", default-features = false }
\ No newline at end of file
diff --git a/examples/attestation-rs/attestation_forwarder/src/client.rs b/examples/attestation-rs/attestation_forwarder/src/client.rs
new file mode 100644
index 0000000..93bf9fd
--- /dev/null
+++ b/examples/attestation-rs/attestation_forwarder/src/client.rs
@@ -0,0 +1,118 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+extern crate alloc;
+
+use alloc::vec::Vec;
+use optee_utee::{
+ trace_println, Error, ErrorKind, ParamIndex, Parameters, Result, TaSessionBuilder, TeeParams,
+ Uuid,
+};
+use quoting_ta_proto::{QuotingTaCommand, MAX_OUTPUT_SIZE};
+
+/// Service for handling attestation operations.
+/// Provides a clean interface for getting quotes from the Quoting TA.
+pub struct QuotingTaClient {
+ quoting_ta_uuid: Uuid,
+}
+
+impl QuotingTaClient {
+ /// Creates a new instance of QuotingTaClient
+ pub fn init(quoting_ta_uuid: Uuid) -> Result<Self> {
+ Ok(Self { quoting_ta_uuid })
+ }
+
+ /// Gets a quote from the Quoting TA.
+ ///
+ /// This is the main entry point for developers who want to get quotes for their TAs.
+ ///
+ /// # Arguments
+ /// * `params` - Parameters from the TA invocation. Expected format:
+ /// - params.0: Input buffer containing user data
+ /// - params.1: Output buffer where the quote will be written
+ ///
+ /// # Returns
+ /// * `Result<()>` - Ok if quote was successfully generated and written to output buffer
+ ///
+ /// # Example
+ /// ```no_run
+ /// fn ta_invoke_command(cmd_id: u32, params: &mut Parameters) -> Result<()> {
+ /// match cmd_id {
+ /// CMD_GET_QUOTE => {
+ /// let service = QuotingTaClient::init();
+ /// service.get_quote(params)
+ /// },
+ /// _ => Err(Error::new(ErrorKind::NotSupported)),
+ /// }
+ /// }
+ /// ```
+ pub fn get_quote(&self, params: &mut Parameters) -> Result<()> {
+ trace_println!("QuotingTaClient: get quote");
+ // Extract input and output buffers
+ let mut p0 = unsafe { params.0.as_memref().unwrap() };
+ let mut p1 = unsafe { params.1.as_memref().unwrap() };
+
+ // Get quote from Quoting TA
+ let quote = self.get_quote_from_ta(p0.buffer()).map_err(|e| {
+ trace_println!("[!] Failed to get quote: {:?}", e);
+ Error::new(ErrorKind::BadParameters)
+ })?;
+
+ // Write quote to output buffer
+ self.write_quote_to_buffer("e, p1.buffer())
+ .map_err(|e| {
+ trace_println!("[!] Failed to write quote: {:?}", e);
+ Error::new(ErrorKind::BadParameters)
+ })?;
+
+ trace_println!("[+] Quote successfully generated and written");
+ Ok(())
+ }
+
+ /// Internal function to get a quote from the Quoting TA
+ fn get_quote_from_ta(&self, user_data: &[u8]) -> Result<Vec<u8>> {
+ // Initialize session with Quoting TA
+ let mut session = TaSessionBuilder::new(self.quoting_ta_uuid).build()?;
+
+ // Prepare parameters for the quote request
+ let mut output_quote = [0u8; MAX_OUTPUT_SIZE];
+ let mut params = TeeParams::new()
+ .with_memref_in(ParamIndex::Arg0, user_data)
+ .with_memref_out(ParamIndex::Arg1, &mut output_quote);
+
+ // Get quote from Quoting TA
+ session.invoke_command(QuotingTaCommand::GetQuote as u32, &mut params)?;
+
+ // Extract quote from output buffer
+ let output = params[ParamIndex::Arg1]
+ .written_slice()
+ .map(|slice| slice.to_vec())
+ .ok_or_else(|| Error::new(ErrorKind::BadParameters))?;
+ Ok(output)
+ }
+
+ /// Internal function to write quote to output buffer
+ fn write_quote_to_buffer(&self, quote: &[u8], buffer: &mut [u8]) -> Result<()> {
+ if quote.len() > buffer.len() {
+ trace_println!("[!] Output buffer too small for quote");
+ return Err(Error::new(ErrorKind::BadParameters));
+ }
+
+ buffer[..quote.len()].copy_from_slice(quote);
+ Ok(())
+ }
+}
diff --git a/examples/attestation-rs/attestation_forwarder/src/lib.rs b/examples/attestation-rs/attestation_forwarder/src/lib.rs
new file mode 100644
index 0000000..d96e456
--- /dev/null
+++ b/examples/attestation-rs/attestation_forwarder/src/lib.rs
@@ -0,0 +1,21 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![no_std]
+
+mod client;
+pub use client::QuotingTaClient;
diff --git a/examples/attestation-rs/os/optee_os.c43b8cf79b73c98c4474e952ecf9980e36bbda30.patch b/examples/attestation-rs/os/optee_os.c43b8cf79b73c98c4474e952ecf9980e36bbda30.patch
new file mode 100644
index 0000000..533eff8
--- /dev/null
+++ b/examples/attestation-rs/os/optee_os.c43b8cf79b73c98c4474e952ecf9980e36bbda30.patch
@@ -0,0 +1,393 @@
+diff --git a/core/include/kernel/ts_manager.h b/core/include/kernel/ts_manager.h
+index ab1465491..48d4ec941 100644
+--- a/core/include/kernel/ts_manager.h
++++ b/core/include/kernel/ts_manager.h
+@@ -80,5 +80,6 @@ struct ts_session *ts_get_current_session_may_fail(void);
+ void ts_push_current_session(struct ts_session *sess);
+ struct ts_session *ts_pop_current_session(void);
+ struct ts_session *ts_get_calling_session(void);
++struct ts_session *ts_get_calling_calling_session(void);
+
+ #endif /*__KERNEL_TS_MANAGER_H*/
+diff --git a/core/kernel/ts_manager.c b/core/kernel/ts_manager.c
+index b27946343..ef8aa845d 100644
+--- a/core/kernel/ts_manager.c
++++ b/core/kernel/ts_manager.c
+@@ -60,6 +60,14 @@ struct ts_session *ts_get_calling_session(void)
+ return TAILQ_NEXT(ts_get_current_session(), link_tsd);
+ }
+
++struct ts_session *ts_get_calling_calling_session(void)
++{
++ struct ts_session *calling = TAILQ_NEXT(ts_get_current_session(), link_tsd);
++ if (!calling)
++ return NULL;
++ return TAILQ_NEXT(calling, link_tsd);
++}
++
+ struct ts_session *ts_get_current_session_may_fail(void)
+ {
+ return TAILQ_FIRST(&thread_get_tsd()->sess_stack);
+diff --git a/core/pta/attestation.c b/core/pta/attestation.c
+index d8a410758..9a797a318 100644
+--- a/core/pta/attestation.c
++++ b/core/pta/attestation.c
+@@ -760,6 +760,248 @@ out:
+ return res;
+ }
+
++static TEE_Result check_caller(TEE_UUID *uuid) {
++ struct ts_session *s = ts_get_calling_session();
++ if (!s) {
++ struct ts_session *ts = ts_get_current_session();
++ struct tee_ta_session *ta_session = to_ta_session(ts);
++
++ EMSG("Called from Normal World, client ID %pUl",
++ &ta_session->clnt_id);
++ return TEE_ERROR_ACCESS_DENIED;
++ }
++
++ if (!is_user_ta_ctx(s->ctx)) {
++ EMSG("Not called from a user TA, is_user_ta_ctx failed");
++ return TEE_ERROR_ACCESS_DENIED;
++ }
++
++ // print caller TA uuid
++ IMSG("Current caller TA uuid: %pUl", &s->ctx->uuid);
++
++ // check caller
++ if (memcmp(&s->ctx->uuid, uuid, sizeof(TEE_UUID)) != 0) {
++ EMSG("Not called from: %pUl", uuid);
++ return TEE_ERROR_ACCESS_DENIED;
++ }
++ IMSG("Called from: %pUl", uuid);
++ return TEE_SUCCESS;
++}
++
++static TEE_Result get_os_measurement(uint8_t *tee_memory_hash) {
++ TEE_Result res = TEE_ERROR_GENERIC;
++ void *ctx = NULL;
++
++ /////////////////////////////////////////////
++ // hash tee memory: copy from original command
++ res = crypto_hash_alloc_ctx(&ctx, TEE_ALG_SHA256);
++ if (res)
++ return res;
++ res = crypto_hash_init(ctx);
++ if (res)
++ goto out;
++ res = crypto_hash_update(ctx, __text_start,
++ __text_data_start - __text_start);
++ if (res)
++ goto out;
++ res = crypto_hash_update(ctx, __text_data_end,
++ __text_end - __text_data_end);
++ if (IS_ENABLED(CFG_WITH_PAGER)) {
++ res = crypto_hash_update(ctx, __text_init_start,
++ __text_init_end - __text_init_start);
++ if (res)
++ goto out;
++ res = crypto_hash_update(ctx, __text_pageable_start,
++ __text_pageable_end -
++ __text_pageable_start);
++ if (res)
++ goto out;
++ }
++ if (res)
++ goto out;
++ res = crypto_hash_update(ctx, __rodata_start,
++ __rodata_end - __rodata_start);
++ if (res)
++ goto out;
++ if (IS_ENABLED(CFG_WITH_PAGER)) {
++ res = crypto_hash_update(ctx, __rodata_init_start,
++ __rodata_init_end -
++ __rodata_init_start);
++ if (res)
++ goto out;
++ res = crypto_hash_update(ctx, __rodata_pageable_start,
++ __rodata_pageable_end -
++ __rodata_pageable_start);
++ if (res)
++ goto out;
++ }
++ res = crypto_hash_final(ctx, tee_memory_hash, TEE_SHA256_HASH_SIZE);
++ if (res)
++ goto out;
++ //////////////////////////////////////
++
++out:
++ crypto_hash_free_ctx(ctx);
++ return res;
++}
++
++static TEE_Result cmd_get_report(uint32_t param_types,
++ TEE_Param params[TEE_NUM_PARAMS])
++{
++ uint8_t *target_uuid_array = params[0].memref.buffer;
++ size_t target_uuid_sz = params[0].memref.size;
++ struct report_body *report = params[1].memref.buffer;
++ size_t report_sz = params[1].memref.size;
++ TEE_Result res = TEE_SUCCESS;
++
++ TEE_UUID quoting_ta_uuid = QUOTING_TA_UUID;
++ // parse big endian uuid to TEE_UUID structure
++ TEE_UUID target_uuid = {0};
++ tee_uuid_from_octets(&target_uuid, target_uuid_array);
++
++ if (param_types != TEE_PARAM_TYPES(TEE_PARAM_TYPE_MEMREF_INPUT,
++ TEE_PARAM_TYPE_MEMREF_OUTPUT,
++ TEE_PARAM_TYPE_NONE,
++ TEE_PARAM_TYPE_NONE))
++ return TEE_ERROR_BAD_PARAMETERS;
++
++ if (target_uuid_sz != sizeof(target_uuid)) {
++ EMSG("Target UUID size mismatch, input: %zu, expected: %zu", target_uuid_sz, sizeof(target_uuid));
++ return TEE_ERROR_BAD_PARAMETERS;
++ }
++
++ if (!report || report_sz < sizeof(*report)) {
++ EMSG("Report size mismatch, input: %zu, expected: %zu", report_sz, sizeof(*report));
++ return TEE_ERROR_BAD_PARAMETERS;
++ }
++
++ res = check_caller("ing_ta_uuid);
++ if (res) {
++ EMSG("Check caller TA failed, res: %x", res);
++ return res;
++ }
++
++ /* Copy target UUID array instead of target_uuid, because the target_uuid_array is in big endian format */
++ memcpy(&report->ta_id, target_uuid_array, sizeof(TEE_UUID));
++
++ /* Get measurements based on target UUID */
++ if (memcmp(&target_uuid, "ing_ta_uuid, sizeof(TEE_UUID)) == 0) {
++ /* Case 1: Target is Quoting TA itself */
++ struct ts_session *quoting_ta_session = ts_get_calling_session();
++ struct user_mode_ctx *quoting_ta_uctx = to_user_mode_ctx(quoting_ta_session->ctx);
++
++ if (!quoting_ta_uctx) {
++ EMSG("Failed to get quoting TA context");
++ return TEE_ERROR_BAD_STATE;
++ }
++
++ /* Get Quoting TA binary measurement */
++ res = hash_binary("ing_ta_uuid, report->mr_ta_binary);
++ if (res) {
++ EMSG("Failed to get quoting TA binary measurement");
++ return res;
++ }
++
++ /* Get Quoting TA memory measurement
++ hash_regions() read the virtual address so we need to switch to quoting TA context.
++
++ OS maintains the session queue:
++ App TA - Quoting TA - Current PTA (Queue Head)
++ Pop current session means switch to quoting TA context*/
++ struct ts_session *s = ts_pop_current_session();
++ res = hash_regions("ing_ta_uctx->vm_info, report->mr_ta_memory);
++ /* Push back the session*/
++ ts_push_current_session(s);
++ if (res) {
++ EMSG("Failed to get quoting TA memory measurement");
++ return res;
++ }
++ } else {
++ /* Case 2: Target is App TA
++ OS maintains the session queue:
++ App TA - Quoting TA - Current PTA (Queue Head)
++ So the target TA session is the calling session of Quoting TA,
++ which is the calling calling session of Current PTA
++ */
++ struct ts_session *target_ta_session = ts_get_calling_calling_session();
++
++ if (!target_ta_session) {
++ EMSG("Failed to get target TA session");
++ return TEE_ERROR_BAD_STATE;
++ }
++
++ /* Verify target TA UUID matches input UUID */
++ if (memcmp(&target_ta_session->ctx->uuid, &target_uuid, sizeof(TEE_UUID)) != 0) {
++ EMSG("Target TA UUID mismatch, input: %pUl, session ctx: %pUl", &target_uuid, &target_ta_session->ctx->uuid);
++ return TEE_ERROR_BAD_PARAMETERS;
++ }
++
++ struct user_mode_ctx *target_ta_uctx = to_user_mode_ctx(target_ta_session->ctx);
++ if (!target_ta_uctx) {
++ EMSG("Failed to get target TA context");
++ return TEE_ERROR_BAD_STATE;
++ }
++
++ /* Get target TA binary measurement */
++ res = hash_binary(&target_uuid, report->mr_ta_binary);
++ if (res) {
++ EMSG("Failed to get target TA binary measurement");
++ return res;
++ }
++
++ /* Get target TA memory measurement
++ hash_regions() read the virtual address so we need to switch to target TA context.
++
++ OS maintains the session queue:
++ App TA - Quoting TA - Current PTA (Queue Head)
++ So we need to pop 2 times to switch to App TA context
++ */
++ struct ts_session *s = ts_pop_current_session();
++ struct ts_session *s2 = ts_pop_current_session();
++
++ // Make a local copy of the hash buffer
++ uint8_t target_ta_mem_hash[TEE_SHA256_HASH_SIZE];
++
++ res = hash_regions(&target_ta_uctx->vm_info, target_ta_mem_hash);
++
++ // Debug: print the hash result
++ DMSG("Target TA memory hash result:");
++ DHEXDUMP(target_ta_mem_hash, TEE_SHA256_HASH_SIZE);
++
++ // Push back sessions in reverse order
++ ts_push_current_session(s2); // Push back Quoting TA first
++ ts_push_current_session(s); // Then push back PTA
++
++ if (res) {
++ EMSG("Failed to get target TA memory measurement");
++ return res;
++ }
++
++ // Copy the hash to the report after session management
++ memcpy(report->mr_ta_memory, target_ta_mem_hash, TEE_SHA256_HASH_SIZE);
++
++ // Debug: verify hash after copying
++ DMSG("Target TA memory hash after copying:");
++ DHEXDUMP(report->mr_ta_memory, TEE_SHA256_HASH_SIZE);
++ }
++
++ /* Get OS measurement */
++ res = get_os_measurement(report->mr_os_memory);
++ if (res) {
++ EMSG("Failed to get OS measurement");
++ return res;
++ }
++
++ /* Set output size */
++ params[1].memref.size = sizeof(*report);
++
++ // debug: print the report
++ DMSG("Report:");
++ DHEXDUMP(report, sizeof(*report));
++
++ return TEE_SUCCESS;
++}
++
+ static TEE_Result invoke_command(void *sess_ctx __unused, uint32_t cmd_id,
+ uint32_t param_types,
+ TEE_Param params[TEE_NUM_PARAMS])
+@@ -786,6 +1028,9 @@ static TEE_Result invoke_command(void *sess_ctx __unused, uint32_t cmd_id,
+ case PTA_ATTESTATION_HASH_TEE_MEMORY:
+ res = cmd_hash_tee_memory(param_types, eparams);
+ break;
++ case PTA_ATTESTATION_GET_REPORT:
++ res = cmd_get_report(param_types, eparams);
++ break;
+ default:
+ break;
+ }
+diff --git a/lib/libutee/include/pta_attestation.h b/lib/libutee/include/pta_attestation.h
+index 76a1d3a6b..93d022bde 100644
+--- a/lib/libutee/include/pta_attestation.h
++++ b/lib/libutee/include/pta_attestation.h
+@@ -99,4 +99,48 @@
+ */
+ #define PTA_ATTESTATION_HASH_TEE_MEMORY 0x3
+
++
++#include <stdint.h>
++#include <tee_api_types.h>
++
++/* Report Body structure */
++struct report_body {
++ /* TA UUID */
++ TEE_UUID ta_id;
++ /* Measurement of TA binary */
++ uint8_t mr_ta_binary[32];
++ /* Measurement of TA memory */
++ uint8_t mr_ta_memory[32];
++ /* Measurement of OS memory */
++ uint8_t mr_os_memory[32];
++};
++
++/*
++ * We hardcode the quoting TA UUID here
++ * In our design, the GET_REPORT command can only be called by the Quoting TA
++ */
++#define QUOTING_TA_UUID { 0x8479d039, 0x9bbc, 0x439c, \
++ { 0x98, 0x71, 0xd5, 0x10, 0x01, 0x32, 0x4c, 0x09 } }
++
++/*
++ * Generate an attestation report for a target TA. The report includes measurements
++ * of the TA binary, TA memory state, and OS memory state. This command can only
++ * be called by the Quoting TA.
++ *
++ * [in] memref[0] UUID of the target TA to generate report for
++ * [out] memref[1] Report body structure containing:
++ * - Target TA UUID (16 bytes)
++ * - TA binary measurement (SHA256, 32 bytes)
++ * - TA memory measurement (SHA256, 32 bytes)
++ * - OS memory measurement (SHA256, 32 bytes)
++ *
++ * Return codes:
++ * TEE_SUCCESS
++ * TEE_ERROR_ACCESS_DENIED - Caller is not the Quoting TA
++ * TEE_ERROR_BAD_PARAMETERS - Incorrect input param or buffer size
++ * TEE_ERROR_BAD_STATE - Failed to get required TA context
++ * TEE_ERROR_SECURITY - Target TA UUID doesn't match session UUID
++ */
++#define PTA_ATTESTATION_GET_REPORT 0x4
++
+ #endif /* __PTA_ATTESTATION_H */
+diff --git a/mk/config.mk b/mk/config.mk
+index 30bf37159..44c5edb98 100644
+--- a/mk/config.mk
++++ b/mk/config.mk
+@@ -73,13 +73,13 @@ CFG_TEE_CORE_DEBUG ?= y
+ # 2: error + info
+ # 3: error + info + debug
+ # 4: error + info + debug + flow
+-CFG_TEE_CORE_LOG_LEVEL ?= 2
++CFG_TEE_CORE_LOG_LEVEL ?= 4
+
+ # TA log level
+ # If user-mode library libutils.a is built with CFG_TEE_TA_LOG_LEVEL=0,
+ # TA tracing is disabled regardless of the value of CFG_TEE_TA_LOG_LEVEL
+ # when the TA is built.
+-CFG_TEE_TA_LOG_LEVEL ?= 1
++CFG_TEE_TA_LOG_LEVEL ?= 4
+
+ # TA enablement
+ # When defined to "y", TA traces are output according to
+@@ -303,7 +303,7 @@ CFG_BUILD_IN_TREE_TA ?= y
+ # When this flag is enabled, the ELF loader will introduce a random offset
+ # when mapping the application in user space. ASLR makes the exploitation of
+ # memory corruption vulnerabilities more difficult.
+-CFG_TA_ASLR ?= y
++CFG_TA_ASLR ?= n
+
+ # How much ASLR may shift the base address (in pages). The base address is
+ # randomly shifted by an integer number of pages comprised between these two
+@@ -317,7 +317,7 @@ CFG_TA_ASLR_MAX_OFFSET_PAGES ?= 128
+ # When this flag is enabled, the early init code will introduce a random
+ # offset when mapping TEE Core. ASLR makes the exploitation of memory
+ # corruption vulnerabilities more difficult.
+-CFG_CORE_ASLR ?= y
++CFG_CORE_ASLR ?= n
+
+ # Stack Protection for TEE Core
+ # This flag enables the compiler stack protection mechanisms -fstack-protector.
+@@ -677,7 +677,7 @@ CFG_DEVICE_ENUM_PTA ?= y
+
+ # The attestation pseudo TA provides an interface to request measurements of
+ # a TA or the TEE binary.
+-CFG_ATTESTATION_PTA ?= n
++CFG_ATTESTATION_PTA ?= y
+ $(eval $(call cfg-depends-all,CFG_ATTESTATION_PTA,_CFG_WITH_SECURE_STORAGE))
+
+ # RSA key size (in bits) for the attestation PTA. Must be at least 528 given
diff --git a/examples/attestation-rs/sdk/quoting_ta/Cargo.toml b/examples/attestation-rs/sdk/quoting_ta/Cargo.toml
new file mode 100644
index 0000000..8fb3c94
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/Cargo.toml
@@ -0,0 +1,53 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+name = "ta"
+version = "0.1.0"
+authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
+license = "Apache-2.0"
+repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
+description = "An example of Rust OP-TEE TrustZone SDK."
+edition = "2018"
+
+[dependencies]
+optee-utee = { path = "../../../../optee-utee" }
+optee-utee-sys = { path = "../../../../optee-utee/optee-utee-sys" }
+attestation = { path = "../../attestation" }
+secure_db = { path = "../../../../crates/secure_db" }
+quoting_ta_proto = { path = "../quoting_ta_proto" }
+
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+bincode = "1.0"
+anyhow = "1.0"
+base64ct = "=1.5.0"
+hex = "0.4"
+num_enum = { version = "0.7.3", default-features = false }
+ring = { git = "https://github.com/DemesneGH/ring-optee.git", branch = "0.16.20-optee", default-features = false }
+
+[build-dependencies]
+optee-utee-build = { path = "../../../../optee-utee-build" }
+quoting_ta_proto = { path = "../quoting_ta_proto" }
+
+[profile.release]
+panic = "abort"
+lto = false
+opt-level = 1
+
+[patch."https://github.com/apache/incubator-teaclave-trustzone-sdk.git"]
+optee-utee = { path = "../../../../optee-utee" }
\ No newline at end of file
diff --git a/examples/attestation-rs/sdk/quoting_ta/Makefile b/examples/attestation-rs/sdk/quoting_ta/Makefile
new file mode 100644
index 0000000..c43a978
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/Makefile
@@ -0,0 +1,53 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# STD-ONLY example
+
+UUID ?= $(shell cat "../quoting_ta_uuid.txt")
+
+TARGET ?= $(TARGET_TA)
+CROSS_COMPILE ?= $(CROSS_COMPILE_TA)
+OBJCOPY := $(CROSS_COMPILE)objcopy
+# Configure the linker to use GCC, which works on both cross-compilation and ARM machines
+LINKER_CFG := target.$(TARGET).linker=\"$(CROSS_COMPILE)gcc\"
+
+TA_SIGN_KEY ?= $(TA_DEV_KIT_DIR)/keys/default_ta.pem
+SIGN := $(TA_DEV_KIT_DIR)/scripts/sign_encrypt.py
+OUT_DIR := $(CURDIR)/target/$(TARGET)/release
+
+ifeq ($(STD),)
+all:
+ @echo "Please \`export STD=y\` then rerun \`source environment\` to build the STD version"
+else
+all: ta strip sign
+endif
+
+ta:
+ @xargo build --target $(TARGET) --release --config $(LINKER_CFG)
+
+strip: ta
+ @$(OBJCOPY) --strip-unneeded $(OUT_DIR)/ta $(OUT_DIR)/stripped_ta
+
+sign: strip
+ @$(SIGN) --uuid $(UUID) --key $(TA_SIGN_KEY) --in $(OUT_DIR)/stripped_ta --out $(OUT_DIR)/$(UUID).ta
+ @echo "SIGN => ${UUID}"
+
+clean:
+ @cargo clean
+
+clippy:
+ @xargo clippy --target $(TARGET) --release --config $(LINKER_CFG) -- -D warnings
diff --git a/examples/attestation-rs/sdk/quoting_ta/Xargo.toml b/examples/attestation-rs/sdk/quoting_ta/Xargo.toml
new file mode 100644
index 0000000..251ee70
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/Xargo.toml
@@ -0,0 +1,24 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[dependencies.std]
+path = "../../../../rust/rust/library/std"
+
+[patch.crates-io]
+libc = { path = "../../../../rust/libc" }
+rustc-std-workspace-core = { path = "../../../../rust/rust/library/rustc-std-workspace-core" }
+rustc-std-workspace-alloc = { path = "../../../../rust/rust/library/rustc-std-workspace-alloc" }
diff --git a/examples/attestation-rs/sdk/quoting_ta/build.rs b/examples/attestation-rs/sdk/quoting_ta/build.rs
new file mode 100644
index 0000000..b5f4e6d
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/build.rs
@@ -0,0 +1,25 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use optee_utee_build::{Error, RustEdition, TaConfig};
+
+fn main() -> Result<(), Error> {
+ let ta_config = TaConfig::new_default_with_cargo_env(quoting_ta_proto::QUOTING_TA_UUID)?
+ .ta_stack_size(1024 * 1024)
+ .ta_data_size(5 * 1024 * 1024);
+ optee_utee_build::build(RustEdition::Before2024, ta_config)
+}
diff --git a/examples/attestation-rs/sdk/quoting_ta/src/attester.rs b/examples/attestation-rs/sdk/quoting_ta/src/attester.rs
new file mode 100644
index 0000000..42c1b1c
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/src/attester.rs
@@ -0,0 +1,156 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use anyhow::Result;
+use attestation::{
+ AttestationKeyManagement, AttestationPubkey, AttestationSignature, Identity, ReportBody,
+ TaMeasurement,
+};
+use optee_utee::{trace_println, ParamIndex, TaSessionBuilder, TeeParams, Uuid};
+use ring::signature::KeyPair;
+use secure_db::{SecureStorageClient, Storable};
+use serde::{Deserialize, Serialize};
+
+use crate::pta_command::{AttestationPtaCommand, ATTESTATION_PTA_UUID, MAX_OUTPUT_SIZE};
+
+/// Implementation of TaMeasurement that gets measurements from PTA
+/// PTA is modified from OP-TEE original implementation
+/// Please refer to the OP-TEE OS patch in "os" for more details
+pub struct PtaAttester;
+
+impl TaMeasurement for PtaAttester {
+ fn measure_ta(&self, target_ta: &Identity) -> Result<ReportBody> {
+ let input = target_ta.as_uuid();
+ trace_println!("[+] Measuring TA: {:?}", input);
+ let mut output = vec![0u8; MAX_OUTPUT_SIZE];
+
+ let uuid = Uuid::parse_str(ATTESTATION_PTA_UUID)
+ .map_err(|e| anyhow::anyhow!("Failed to parse UUID: {:?}", e))?;
+ let mut session = TaSessionBuilder::new(uuid)
+ .build()
+ .map_err(|e| anyhow::anyhow!("Failed to create session: {:?}", e))?;
+
+ let mut params = TeeParams::new()
+ .with_memref_in(ParamIndex::Arg0, &input)
+ .with_memref_out(ParamIndex::Arg1, &mut output);
+
+ session
+ .invoke_command(AttestationPtaCommand::GetReport as u32, &mut params)
+ .map_err(|e| anyhow::anyhow!("Failed to invoke command: {:?}", e))?;
+
+ // Get the output buffer through written_slice()
+ let output = params[ParamIndex::Arg1]
+ .written_slice()
+ .ok_or(anyhow::anyhow!("Failed to get written slice"))?;
+
+ // Deserialize the output into ReportBody
+ let report_body = ReportBody::decode_from_bytes(output)?;
+ trace_println!("[+] attestation report body: {:?}", report_body);
+
+ Ok(report_body)
+ }
+}
+
+const AK_DB_NAME: &str = "ak_db";
+// Since we only have one ak pair, we can use a fixed key and overwrite the entry
+const AK_STORAGE_KEY: &str = "ak";
+
+// for storing the attestation key as a PKCS8 blob
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
+pub struct AttestationKeyBytes {
+ pkcs8_bytes: Vec<u8>,
+}
+
+impl Storable for AttestationKeyBytes {
+ type Key = String;
+
+ fn unique_id(&self) -> Self::Key {
+ // fix key
+ AK_STORAGE_KEY.to_string()
+ }
+}
+
+/// Implementation of AttestationKeyManagement that uses ECDSA for attestation key operations
+pub struct EcdsaAttestationKeyManager {
+ key_pair: ring::signature::EcdsaKeyPair,
+}
+
+impl EcdsaAttestationKeyManager {
+ pub fn init() -> Result<Self> {
+ trace_println!("[+] Initializing EcdsaAttestationKeyManager");
+
+ let db_client = SecureStorageClient::open(AK_DB_NAME)
+ .map_err(|e| anyhow::anyhow!("Failed to open secure storage: {:?}", e))?;
+ trace_println!("[+] Opened secure storage");
+
+ // check if the key pair exists in the db, if not, generate a new one
+ match db_client.get::<AttestationKeyBytes>(&AK_STORAGE_KEY.to_string()) {
+ Ok(ak) => {
+ trace_println!("[+] Found existing ECDSA key pair in secure storage");
+ let key_pair = ring::signature::EcdsaKeyPair::from_pkcs8(
+ &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING,
+ ak.pkcs8_bytes.as_ref(),
+ )
+ .map_err(|e| anyhow::anyhow!("Failed to create ECDSA key pair: {:?}", e))?;
+ Ok(Self { key_pair })
+ }
+ Err(e) => {
+ trace_println!(
+ "[-] Failed to get ECDSA key pair from secure storage: {:?}",
+ e
+ );
+ let rng = ring::rand::SystemRandom::new();
+ let pkcs8_bytes = ring::signature::EcdsaKeyPair::generate_pkcs8(
+ &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING,
+ &rng,
+ )
+ .map_err(|e| anyhow::anyhow!("Failed to generate ECDSA key pair: {:?}", e))?;
+ trace_println!("[+] Generated new ECDSA pkcs8 bytes");
+ let key_pair = ring::signature::EcdsaKeyPair::from_pkcs8(
+ &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING,
+ pkcs8_bytes.as_ref(),
+ )
+ .map_err(|e| anyhow::anyhow!("Failed to create ECDSA key pair: {:?}", e))?;
+ trace_println!("[+] Generated new ECDSA key pair");
+
+ let ak = AttestationKeyBytes {
+ pkcs8_bytes: pkcs8_bytes.as_ref().to_vec(),
+ };
+ db_client.put(&ak)?;
+ Ok(Self { key_pair })
+ }
+ }
+ }
+}
+
+impl AttestationKeyManagement for EcdsaAttestationKeyManager {
+ fn sign(&self, data: &[u8]) -> Result<AttestationSignature> {
+ let rng = ring::rand::SystemRandom::new();
+ let signature = self
+ .key_pair
+ .sign(&rng, data)
+ .map_err(|_| anyhow::anyhow!("Failed to sign data"))?;
+
+ Ok(AttestationSignature::from_bytes(signature.as_ref()))
+ }
+
+ fn get_attestation_pubkey(&self) -> Result<AttestationPubkey> {
+ Ok(AttestationPubkey::from_bytes(
+ self.key_pair.public_key().as_ref(),
+ ))
+ }
+}
diff --git a/examples/attestation-rs/sdk/quoting_ta/src/endorsement_store.rs b/examples/attestation-rs/sdk/quoting_ta/src/endorsement_store.rs
new file mode 100644
index 0000000..a0ca28d
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/src/endorsement_store.rs
@@ -0,0 +1,86 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use anyhow::{anyhow, Result};
+use attestation::{AttestationKeyEndorsement, AttestationPubkey, EndorsementStore};
+use optee_utee::trace_println;
+use secure_db::{SecureStorageClient, Storable};
+use serde::{Deserialize, Serialize};
+
+const ENDORSEMENT_DB_NAME: &str = "endorsement_db";
+
+// Define a new type wrapper for AttestationKeyEndorsement
+// Because Storable and AttestationKeyEndorsement are not from this crate,
+// we cannot derive Storable for AttestationKeyEndorsement directly.
+#[derive(Serialize, Deserialize)]
+pub struct StorableAttestationKeyEndorsement(pub AttestationKeyEndorsement);
+
+impl Storable for StorableAttestationKeyEndorsement {
+ type Key = String;
+
+ fn unique_id(&self) -> Self::Key {
+ // hash of AttestationPubkey
+ hex::encode(self.0.attestation_pubkey().hash())
+ }
+}
+
+/// Local implementation of EndorsementStore using secure storage
+pub struct LocalEndorsementStore {
+ db_client: SecureStorageClient,
+}
+
+impl LocalEndorsementStore {
+ pub fn init() -> Result<Self> {
+ trace_println!("[+] Initializing LocalEndorsementStore");
+ let db_client = SecureStorageClient::open(ENDORSEMENT_DB_NAME)
+ .map_err(|e| anyhow!("Failed to open secure storage: {:?}", e))?;
+
+ Ok(Self { db_client })
+ }
+}
+
+impl EndorsementStore for LocalEndorsementStore {
+ fn get_endorsement(
+ &self,
+ attestation_pubkey: &AttestationPubkey,
+ ) -> Option<AttestationKeyEndorsement> {
+ let attestation_pubkey_hash_as_storage_key = hex::encode(attestation_pubkey.hash());
+
+ match self
+ .db_client
+ .get::<StorableAttestationKeyEndorsement>(&attestation_pubkey_hash_as_storage_key)
+ {
+ Ok(endorsement) => {
+ trace_println!("[+] Found endorsement in store");
+ Some(endorsement.0)
+ }
+ Err(e) => {
+ trace_println!("[-] Failed to get endorsement: {:?}", e);
+ None
+ }
+ }
+ }
+
+ fn store_endorsement(&self, endorsement: AttestationKeyEndorsement) -> Result<()> {
+ self.db_client
+ .put(&StorableAttestationKeyEndorsement(endorsement))
+ .map_err(|e| anyhow!("Failed to store endorsement: {:?}", e))?;
+
+ trace_println!("[+] Successfully stored endorsement");
+ Ok(())
+ }
+}
diff --git a/examples/attestation-rs/sdk/quoting_ta/src/endorser.rs b/examples/attestation-rs/sdk/quoting_ta/src/endorser.rs
new file mode 100644
index 0000000..8a20162
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/src/endorser.rs
@@ -0,0 +1,104 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use anyhow::Result;
+use ring::rand;
+use ring::signature;
+use ring::signature::KeyPair;
+
+use attestation::{
+ AttestationPubkey, AttestationReport, EndorsementSignature, PlatformKeyManagement,
+ PlatformPubkey, ReportVerification,
+};
+use optee_utee::trace_println;
+use std::sync::atomic::{AtomicU32, Ordering};
+
+/// ECDSA platform key stored as DER-encoded PKCS#8 format
+/// For production use, this should be stored in secure hardware storage
+const PLATFORM_KEY_DER: &[u8] = include_bytes!("../test_keys/platform_key.der");
+
+/// Implementation of PlatformKeyManagement that uses ECDSA for platform key operations
+pub struct EcdsaPlatformKeyManager {
+ key_pair: signature::EcdsaKeyPair,
+ counter: AtomicU32,
+}
+
+impl EcdsaPlatformKeyManager {
+ pub fn init() -> Result<Self> {
+ let key_pair = signature::EcdsaKeyPair::from_pkcs8(
+ &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
+ PLATFORM_KEY_DER,
+ )
+ .map_err(|e| anyhow::anyhow!("Failed to load ECDSA key pair: {:?}", e))?;
+
+ Ok(Self {
+ key_pair,
+ counter: AtomicU32::new(0),
+ })
+ }
+}
+
+impl PlatformKeyManagement for EcdsaPlatformKeyManager {
+ fn sign(&self, data: &[u8]) -> Result<EndorsementSignature> {
+ let rng = rand::SystemRandom::new();
+ let signature = self
+ .key_pair
+ .sign(&rng, data)
+ .map_err(|_| anyhow::anyhow!("Failed to sign data"))?;
+
+ trace_println!("[+] Platform key signing data");
+ EndorsementSignature::from_bytes(signature.as_ref())
+ .map_err(|e| anyhow::anyhow!("Failed to create endorsement signature: {:?}", e))
+ }
+
+ fn get_platform_pubkey(&self) -> Result<PlatformPubkey> {
+ trace_println!("[+] Getting platform public key");
+ PlatformPubkey::from_bytes(self.key_pair.public_key().as_ref())
+ .map_err(|e| anyhow::anyhow!("Failed to create platform public key: {:?}", e))
+ }
+
+ fn tick_counter(&self) -> Result<u32> {
+ let new_value = self.counter.fetch_add(1, Ordering::SeqCst);
+ trace_println!("[+] Platform key counter ticked to: {}", new_value);
+ Ok(new_value)
+ }
+}
+
+/// Implementation of ReportVerification for the quoting TA
+/// This defines how does the endorser verify the quoter's report
+pub struct QuotingTaReportVerifier;
+
+impl ReportVerification for QuotingTaReportVerifier {
+ fn verify_report(&self, att_pk: &AttestationPubkey, report: &AttestationReport) -> Result<()> {
+ // Implement the verification logic specific to the quoting TA
+ // This might involve checking signatures, measurements, etc.
+ trace_println!("[+] Endorsement: verifying quoter's report");
+
+ // Verify the report signature
+ let signature = report.signature();
+ let data = report.signing_data();
+ let ak_pub = signature::UnparsedPublicKey::new(
+ &signature::ECDSA_P256_SHA256_ASN1,
+ att_pk.as_bytes(),
+ );
+ ak_pub
+ .verify(&data, signature.as_bytes())
+ .map_err(|e| anyhow::anyhow!("[+] Endorsement: failed to verify report: {:?}", e))?;
+ trace_println!("[+] Report verified successfully");
+ Ok(())
+ }
+}
diff --git a/examples/attestation-rs/sdk/quoting_ta/src/main.rs b/examples/attestation-rs/sdk/quoting_ta/src/main.rs
new file mode 100644
index 0000000..9ae9a3a
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/src/main.rs
@@ -0,0 +1,140 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![no_main]
+
+mod attester;
+mod endorsement_store;
+mod endorser;
+mod pta_command;
+
+use optee_utee::{
+ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println,
+};
+use optee_utee::property::{ClientIdentity, PropertyKey};
+use optee_utee::{Error, ErrorKind, Parameters, Result};
+
+use attestation::{Attester, Endorser, Identity, Quote, Quoter, UserData};
+use quoting_ta_proto::{QuotingTaCommand, QUOTING_TA_UUID};
+
+use std::convert::TryFrom;
+
+use crate::attester::{EcdsaAttestationKeyManager, PtaAttester};
+use crate::endorsement_store::LocalEndorsementStore;
+use crate::endorser::{EcdsaPlatformKeyManager, QuotingTaReportVerifier};
+
+fn get_quote(target_ta: &Identity, user_data: UserData) -> anyhow::Result<Quote> {
+ trace_println!("[+] Getting quote for target TA: {:?}", target_ta);
+ // Initialize components
+ let ak_manager = EcdsaAttestationKeyManager::init()?;
+ trace_println!("[+] AK manager initialized");
+ let ta_measuring = PtaAttester;
+ let platform_key_manager = EcdsaPlatformKeyManager::init()?;
+ trace_println!("[+] Platform key manager initialized");
+ let endorsement_store = LocalEndorsementStore::init()?;
+ trace_println!("[+] Endorsement store initialized");
+ let quoting_ta_report_verifier = QuotingTaReportVerifier;
+ trace_println!("[+] Components initialized");
+
+ // Create attester and endorser
+ let attester = Attester::new(ak_manager, ta_measuring);
+ let endorser = Endorser::new(platform_key_manager, quoting_ta_report_verifier);
+
+ // Create quoter with this TA's identity
+ let quoter_identity = Identity::try_from(QUOTING_TA_UUID.to_string())?;
+ let quoter = Quoter::new(quoter_identity, attester, endorser, endorsement_store);
+ trace_println!("[+] Quoter initialized");
+
+ // Get quote
+ let quote = quoter.get_quote(target_ta, user_data)?;
+ trace_println!("[+] Quote generated successfully");
+
+ Ok(quote)
+}
+
+#[ta_create]
+fn create() -> Result<()> {
+ trace_println!("[+] Quoting TA create");
+ Ok(())
+}
+
+#[ta_open_session]
+fn open_session(_params: &mut Parameters) -> Result<()> {
+ trace_println!("[+] Quoting TA open session");
+ Ok(())
+}
+
+#[ta_close_session]
+fn close_session() {
+ trace_println!("[+] Quoting TA close session");
+}
+
+#[ta_destroy]
+fn destroy() {
+ trace_println!("[+] Quoting TA destroy");
+}
+
+#[ta_invoke_command]
+fn invoke_command(cmd_id: u32, params: &mut Parameters) -> Result<()> {
+ trace_println!("[+] Quoting TA invoke command");
+ match QuotingTaCommand::from(cmd_id) {
+ QuotingTaCommand::GetQuote => {
+ trace_println!("[+] Get Quote command invoked");
+ // Get Quote command
+ let mut p0 = unsafe { params.0.as_memref().unwrap() };
+ let mut p1 = unsafe { params.1.as_memref().unwrap() };
+
+ // Get user data from input parameter
+ let user_data = UserData::try_from(p0.buffer().to_vec()).map_err(|e| {
+ trace_println!("[-] Failed to get user data: {:?}", e);
+ Error::new(ErrorKind::BadParameters)
+ })?;
+ trace_println!("[+] User data: {:?}", user_data);
+
+ // Get target TA identity (current client)
+ let target_ta_uuid = ClientIdentity.get()?.uuid().to_string();
+ trace_println!("[+] Target TA UUID: {:?}", target_ta_uuid);
+ // Convert UUID to Identity
+ let target_ta = Identity::try_from(target_ta_uuid).map_err(|e| {
+ trace_println!("[-] Failed to get target TA identity: {:?}", e);
+ Error::new(ErrorKind::BadParameters)
+ })?;
+ trace_println!("[+] Target TA identity: {:?}", target_ta);
+
+ // Get quote
+ let quote = get_quote(&target_ta, user_data).map_err(|e| {
+ trace_println!("[-] Failed to get quote: {:?}", e);
+ Error::new(ErrorKind::Generic)
+ })?;
+ trace_println!("[+] Quote generated: {:?}", quote);
+
+ // Serialize quote and write to output parameter
+ let serialized_quote = bincode::serialize("e).map_err(|e| {
+ trace_println!("[-] Failed to serialize quote: {:?}", e);
+ Error::new(ErrorKind::BadParameters)
+ })?;
+ trace_println!("[+] Serialized quote len: {:?}", serialized_quote.len());
+
+ p1.buffer()[..serialized_quote.len()].copy_from_slice(&serialized_quote);
+ trace_println!("[+] Quote written to output buffer");
+ Ok(())
+ }
+ _ => Err(Error::new(ErrorKind::NotSupported)),
+ }
+}
+
+include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));
diff --git a/examples/attestation-rs/sdk/quoting_ta/src/pta_command.rs b/examples/attestation-rs/sdk/quoting_ta/src/pta_command.rs
new file mode 100644
index 0000000..429893c
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/src/pta_command.rs
@@ -0,0 +1,37 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use num_enum::{FromPrimitive, IntoPrimitive};
+
+pub const MAX_OUTPUT_SIZE: usize = 4096;
+
+// AttestationPta (C): part of the OP-TEE OS
+// duplicated from attestation_pta.c and modify the following:
+// 1. get Identity(uuid, is_user_ta) of caller, caller should be Quoting TA
+// 2. get os_hash, target_ta_binary_hash and target_ta_mem_hash
+// 3. return ReportBody to Quoting TA
+#[derive(FromPrimitive, IntoPrimitive, Default)]
+#[repr(u32)]
+pub enum AttestationPtaCommand {
+ // param[0] memref_in: target_ta_uuid
+ // param[1] memref_out: encoded(ReportBody)
+ GetReport = 4,
+ #[default]
+ Unknown,
+}
+
+pub const ATTESTATION_PTA_UUID: &str = "39800861-182a-4720-9b67-2bcd622bc0b5";
diff --git a/examples/attestation-rs/sdk/quoting_ta/test_keys/generate_test_keys.sh b/examples/attestation-rs/sdk/quoting_ta/test_keys/generate_test_keys.sh
new file mode 100755
index 0000000..526fb67
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta/test_keys/generate_test_keys.sh
@@ -0,0 +1,47 @@
+#!/bin/bash
+
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# Script to generate test keys for the attestation example
+# This script generates a new ECDSA P-256 key pair for testing purposes
+
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+cd "$SCRIPT_DIR"
+
+echo "Generating test ECDSA P-256 key pair..."
+
+# Generate private key in PEM format
+openssl ecparam -genkey -name prime256v1 -noout -out platform_key.private
+
+# Convert private key to DER format (PKCS#8)
+openssl pkcs8 -topk8 -inform PEM -outform DER -in platform_key.private -out platform_key.der -nocrypt
+
+# Extract public key and convert to hex format
+openssl ec -in platform_key.private -pubout -outform DER | tail -c 65 | xxd -p -c 65 | tr -d '\n' > platform_key.pub
+
+echo "Test keys generated successfully:"
+echo " platform_key.private - Private key (PEM format) "
+echo " platform_key.der - Private key (DER format) "
+echo " platform_key.pub - Public key (hex format) - verifier reads this file through cli"
+echo ""
+echo "WARNING: These are test keys only. For production use, keys should be:"
+echo " - Generated in secure hardware (HSM/TPM)"
+echo " - Stored in secure storage"
+echo " - Never exposed in source code"
diff --git a/examples/attestation-rs/sdk/quoting_ta_proto/Cargo.toml b/examples/attestation-rs/sdk/quoting_ta_proto/Cargo.toml
new file mode 100644
index 0000000..c53b6ae
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta_proto/Cargo.toml
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+name = "quoting_ta_proto"
+version = "0.1.0"
+edition = "2021"
+authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
+license = "Apache-2.0"
+repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
+description = "Data structures and functions shared by host and TA."
+
+[dependencies]
+num_enum = { version = "0.7.3", default-features = false }
\ No newline at end of file
diff --git a/examples/attestation-rs/sdk/quoting_ta_proto/src/lib.rs b/examples/attestation-rs/sdk/quoting_ta_proto/src/lib.rs
new file mode 100644
index 0000000..897b101
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta_proto/src/lib.rs
@@ -0,0 +1,39 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![no_std]
+use num_enum::{FromPrimitive, IntoPrimitive};
+
+pub const MAX_OUTPUT_SIZE: usize = 4096;
+
+// Quoting TA (Rust): part of the SDK
+// Return the Quote to the App TA
+// 1. get Identity(uuid, is_user_ta) of caller TA (App TA)
+// 2. prepare attestation_pubkey, and sign it by endorser
+// 3. invoke Attestation PTA to get attestation report for caller TA
+// 4. concatenate the Quote and return to caller TA
+#[derive(FromPrimitive, IntoPrimitive, Default)]
+#[repr(u32)]
+pub enum QuotingTaCommand {
+ // param[0] memref_in: nonce
+ // param[1] memref_out: serialized(Quote)
+ GetQuote,
+ #[default]
+ Unknown,
+}
+
+pub const QUOTING_TA_UUID: &str = &include_str!("../../quoting_ta_uuid.txt");
diff --git a/examples/attestation-rs/sdk/quoting_ta_uuid.txt b/examples/attestation-rs/sdk/quoting_ta_uuid.txt
new file mode 100644
index 0000000..c6262d4
--- /dev/null
+++ b/examples/attestation-rs/sdk/quoting_ta_uuid.txt
@@ -0,0 +1 @@
+8479d039-9bbc-439c-9871-d51001324c09
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org