- 拆出 crates/mpc-hostd(axum/tokio/reqwest),mpc-tee 保持零 crates.io 依赖,保住 OP-TEE SDK 离线交叉编译 - mpc-hostd 提供 e2b 兼容 API + TeeRuntime + /attestation 四布尔分开报;站点侧 session_admit 产 TeeRequirement - 新增 mpc link plan|verdict|credential:EasyTier 三档中继策略,凭据由管理节点签发,框架不生成 - OP-TEE 补跨设备/跨重启验证编排与判据逻辑自测,真机验收延后 - 主门禁 11→13 条:新增 hostd 端到端(33 判据)与链路层桩自测(53 判据) - 同步 catalog 守卫测试、CLAUDE.md、INTEGRATION_ANALYSIS.md 与 OPTEE_VERIF_PLAN.md
672 lines
24 KiB
Rust
672 lines
24 KiB
Rust
//! TEE 抽象层(HAL)—— 只做控制平面,不做密文计算。
|
||
//!
|
||
//! # 为什么 HAL 里没有"加密计算"
|
||
//!
|
||
//! TEE 保护的是**内存不可被宿主读取**,不是**算得更快**。
|
||
//! MPC 的密文乘法本来就不需要保护(分片是随机的),
|
||
//! 把 O(样本×特征) 的 u64 矩阵塞进 enclave 只会被 EPC 换页拖死。
|
||
//!
|
||
//! TEE 在这里干四件"小、关键、必须可信"的事:
|
||
//!
|
||
//! 1. **持有密钥** —— 设备绑定 / 会话密钥,明文永不出安全世界;
|
||
//! 2. **密封存储** —— 落盘的东西只能在本设备/本 VM 解开;
|
||
//! 3. **输入承诺** —— 数据进 enclave 算 commitment 并签名,
|
||
//! 把"信任对方老实输入"换成"信任硬件";
|
||
//! 4. **出域策略签名** —— `check_fetch` 的判定结果由 enclave 签名,
|
||
//! 绕过 = 审计链对不上。
|
||
//!
|
||
//! # 四级可信度
|
||
//!
|
||
//! 现实里经常是一方有 TEE、一方没有,所以协议栈必须能降级。
|
||
//! 见 [`TrustPlan`]。
|
||
//!
|
||
//! | Level | 条件 | MPC 的角色 |
|
||
//! |---|---|---|
|
||
//! | L0 | 双方都无 TEE | 主力 |
|
||
//! | L1 | 单方有 TEE | 主力,TEE 保护那一方的明文与策略 |
|
||
//! | L2 | 双方有 TEE + attestation 互验 | **可退化为明文直算**,MPC 只留承诺与审计 |
|
||
//! | L3 | 双方有 TEE 但互不信任同一厂商 | MPC 保底,TEE 保输入 |
|
||
//!
|
||
//! L2 容易被忽略:如果双方都能验证对面跑的是同一份已签名代码,
|
||
//! "数据不出域"这个前提就已经满足,直接把明文合到一起算就是最优解,
|
||
//! MPC 的通信开销全部省掉。但这个选择必须由客户明示,不能默认。
|
||
|
||
#![cfg_attr(not(feature = "std"), no_std)]
|
||
|
||
extern crate alloc;
|
||
|
||
use alloc::format;
|
||
use alloc::string::{String, ToString};
|
||
use alloc::vec::Vec;
|
||
use core::fmt;
|
||
|
||
/// TEE 平台标识。
|
||
///
|
||
/// `tcb` 是可信计算基版本 —— L2 的 `min_tcb` 判定要用它拒绝有已知
|
||
/// 漏洞的固件版本(SNP 的 `reported_tcb`、TDX 的 `td_attributes` 同理)。
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub struct Platform {
|
||
/// 平台类型。
|
||
pub kind: PlatformKind,
|
||
/// TCB 版本号,语义由平台定义(SNP: bootloader+TEE+SNP+microcode 的组合版本)。
|
||
pub tcb: u32,
|
||
}
|
||
|
||
/// 支持的平台类型。
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum PlatformKind {
|
||
/// 无 TEE(纯软件,测试与 L0 用)。
|
||
None,
|
||
/// ARM OP-TEE(Zynq-7015 / QEMU arm32)—— 控制平面可验证实现。
|
||
Optee,
|
||
/// AMD SEV-SNP。
|
||
SevSnp,
|
||
/// Intel TDX。
|
||
Tdx,
|
||
/// 海光 CSV。
|
||
HygonCsv,
|
||
}
|
||
|
||
impl fmt::Display for PlatformKind {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
let s = match self {
|
||
Self::None => "none",
|
||
Self::Optee => "optee",
|
||
Self::SevSnp => "sev-snp",
|
||
Self::Tdx => "tdx",
|
||
Self::HygonCsv => "hygon-csv",
|
||
};
|
||
f.write_str(s)
|
||
}
|
||
}
|
||
|
||
/// 密封后的数据块:密文 + 绑定到平台的关联数据。
|
||
#[derive(Debug, Clone)]
|
||
pub struct SealedBlob {
|
||
/// 平台无关的封装格式版本,便于将来迁移。
|
||
pub version: u8,
|
||
/// 生成它的平台(解封时要校验一致,否则换个平台就能解开)。
|
||
pub platform: PlatformKind,
|
||
/// AEAD 的附加认证数据(含 AAD 哈希、nonce 等)。
|
||
pub aad: Vec<u8>,
|
||
/// 密文 + tag。
|
||
pub ciphertext: Vec<u8>,
|
||
}
|
||
|
||
/// 远程证明报告。
|
||
///
|
||
/// `user_data` 是 **64 字节定长** —— 这是按 SNP 的 `report_data` 字段定的。
|
||
/// 上层把"会话公钥哈希 + 代码度量哈希"塞进去,对端验证时比对这个值,
|
||
/// 就能确认"对面跑的确实是这份二进制,且密钥确实是它生成的"。
|
||
#[derive(Debug, Clone)]
|
||
pub struct Attestation {
|
||
/// 平台类型。
|
||
pub platform: PlatformKind,
|
||
/// 64 字节的调用方数据。
|
||
pub user_data: [u8; 64],
|
||
/// 平台签名的报告原文(格式随平台)。
|
||
pub report: Vec<u8>,
|
||
/// 证书链(SNP: VCEK ← ASK ← ARK;TDX: QE 报告链)。
|
||
pub cert_chain: Vec<Vec<u8>>,
|
||
}
|
||
|
||
/// 签名。
|
||
#[derive(Debug, Clone)]
|
||
pub struct Signature {
|
||
/// 算法标识(如 `ecdsa-p384-sha384`)。
|
||
pub alg: &'static str,
|
||
/// 签名字节。
|
||
pub bytes: Vec<u8>,
|
||
}
|
||
|
||
/// HAL 错误。
|
||
#[derive(Debug)]
|
||
pub enum TeeError {
|
||
/// 平台不支持该操作。
|
||
Unsupported(&'static str),
|
||
/// 解封失败(平台不符 / AAD 不匹配 / tag 校验失败)。
|
||
UnsealFailed,
|
||
/// 报告验证失败。
|
||
AttestFailed(String),
|
||
/// 输入本身不成立(自相矛盾的 TEE 声明、重复 site、少于两方等)。
|
||
BadInput(String),
|
||
/// 底层 IO / 驱动错误。
|
||
Io(String),
|
||
/// 节点准入被拒(设备 / 固件 / TCB / 镜像 pin / 会话绑定 / KBS 任一不达标)。
|
||
///
|
||
/// 与 `BadInput` 的区别:输入本身可能完全合法,是这台节点不够格。
|
||
/// 调度层一律 fail-closed,不存在"降级通过"的分支。
|
||
AdmissionDenied(String),
|
||
}
|
||
|
||
impl fmt::Display for TeeError {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
match self {
|
||
Self::Unsupported(what) => write!(f, "平台不支持: {what}"),
|
||
Self::UnsealFailed => f.write_str("解封失败(平台或 AAD 不匹配)"),
|
||
Self::AttestFailed(m) => write!(f, "证明验证失败: {m}"),
|
||
Self::BadInput(m) => write!(f, "输入不成立: {m}"),
|
||
Self::Io(m) => write!(f, "IO 错误: {m}"),
|
||
Self::AdmissionDenied(m) => write!(f, "{m}"),
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(feature = "std")]
|
||
impl std::error::Error for TeeError {}
|
||
|
||
/// TEE 能力的统一接口。
|
||
///
|
||
/// 四个方法,覆盖控制平面的全部需求。**不要往里加"执行计算"的方法** ——
|
||
/// 一旦开了这个口子,上层就会开始把矩阵乘塞进 enclave。
|
||
pub trait Tee {
|
||
/// 平台标识。
|
||
fn platform(&self) -> Platform;
|
||
|
||
/// 密封:输出绑定到当前平台的密文。
|
||
///
|
||
/// `aad` 会参与认证,解封时必须提供相同的值 —— 用来绑"这块数据属于哪个会话"。
|
||
fn seal(&self, plaintext: &[u8], aad: &[u8]) -> Result<SealedBlob, TeeError>;
|
||
|
||
/// 解封:只有同平台 + 同 AAD 才能成功。
|
||
fn unseal(&self, blob: &SealedBlob, aad: &[u8]) -> Result<Vec<u8>, TeeError>;
|
||
|
||
/// 生成远程证明报告,`user_data` 原样进报告。
|
||
fn attest(&self, user_data: &[u8; 64]) -> Result<Attestation, TeeError>;
|
||
|
||
/// 用设备密钥签名(策略判定、审计锚点)。
|
||
fn sign(&self, msg: &[u8]) -> Result<Signature, TeeError>;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 真平台实现(按阶段推进)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/// 纯软件 Mock。**没有任何安全性**,只保证接口语义与流程完整。
|
||
///
|
||
/// 密码学构造是真的(HKDF + AEAD),但密钥就在进程内存里,root 读得到
|
||
/// —— 所以它是"行为替身",不是"安全替身"。生产环境用它等于没上 TEE。
|
||
///
|
||
/// 只在 std 下编译:它读 `/dev/urandom`,TA 里没有也不该有。
|
||
#[cfg(feature = "std")]
|
||
pub mod mock;
|
||
|
||
/// OP-TEE 实现:core 逻辑(宿主可测)+ CA↔TA 协议 + TA/CA 源码。
|
||
///
|
||
/// 三层范式:core.rs 做密码学与格式(no_std),TA 薄壳做参数搬运 +
|
||
/// secure storage,CA 做 TEEC 调用。详见 `optee/mod.rs`。
|
||
pub mod optee;
|
||
|
||
// --- 直接调度 TEE(不经过容器编排层)-------------------------------------
|
||
//
|
||
// guest 内能力由 `Tee` 描述;下面三层负责「把这个 guest 直接跑起来」:
|
||
// platform 平台能力表(AMD SEV-SNP / 海光 CSV 的硬件与 qemu 参数)
|
||
// session 证明与 MPC 会话的绑定(user_data 64 字节)
|
||
// schedule 需求 / 节点能力 / fail-closed 准入 / 启动规格 LaunchSpec
|
||
// link 会话级链路策略(三档 relay 判定 / 凭据绑定 / link= 上报)
|
||
//
|
||
// 四者都是 no_std(只用 alloc),因为 TA 侧也要能算同一份绑定值。
|
||
/// 会话级链路策略:三档 relay 判定、凭据绑定与 `link=` 实际路径上报。
|
||
///
|
||
/// 放在本 crate 是为了让**站点侧与宿主侧共用同一份判据**;进程管理与
|
||
/// `easytier-cli` 调用在 `mpc-hostd::link`,本模块不碰任何外部二进制。
|
||
pub mod link;
|
||
#[cfg(feature = "std")]
|
||
pub mod guest;
|
||
/// KBS 资源下发的最小客户端(guest 内按会话取密钥)。
|
||
#[cfg(feature = "std")]
|
||
pub mod kbs;
|
||
// 宿主控制面(e2b 兼容 API + TeeRuntime)在独立 crate `mpc-hostd` 里。
|
||
//
|
||
// ★ 为什么不放在本 crate:build_optee.sh 会把整个 crates/mpc-tee 拷进
|
||
// OP-TEE SDK 的 workspace 做 armv7 离线交叉编译(TA 是 no_std + alloc)。
|
||
// hostd 要用 axum/tokio/reqwest,哪怕标成 optional,Cargo 解析阶段仍要
|
||
// 能拿到这些 crate —— 那会让 SDK 侧的构建在没网的机器上直接挂掉。
|
||
// 所以本 crate 保持零 crates.io 依赖,宿主控制面单独成 crate。
|
||
/// 证明包:guest 提交给 KBS 的结构化证据(报告 + 证书链 + 绑定值)。
|
||
#[cfg(feature = "std")]
|
||
pub mod bundle;
|
||
/// guest 内远程证明采集(CSV / SNP 芯片驱动)。
|
||
#[cfg(feature = "std")]
|
||
pub mod collect;
|
||
/// AMD SEV-SNP 报告采集(`/dev/sev-guest`,GHCB 扩展报告 + 证书链)。
|
||
#[cfg(feature = "std")]
|
||
pub mod snp_collect;
|
||
pub mod platform;
|
||
pub mod schedule;
|
||
/// 站点侧会话准入(两层控制面的第一段)—— 产出 `TeeRequirement`,不是 `LaunchSpec`。
|
||
pub mod site_admit;
|
||
pub mod session;
|
||
/// 证明报告结构校验与芯片验签委托(框架不自验签)。
|
||
#[cfg(feature = "std")]
|
||
pub mod verify;
|
||
|
||
// pub mod snp; // P6
|
||
// pub mod tdx; // P6
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 可信度方案(n 方)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/// 一方的 TEE 状况。
|
||
///
|
||
/// `platform == None` 表示这一方**没有** TEE —— 它的宿主机(也就是它自己)
|
||
/// 能读到自己的明文,任何"数据不出域"的承诺对它都不成立。
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub struct PartyTee {
|
||
/// 该方 site 名。
|
||
pub site: String,
|
||
/// TEE 平台 + TCB 版本;`None` 表示没有 TEE。
|
||
pub platform: Option<Platform>,
|
||
/// 是否已通过远端证明验证对方跑的确实是这份已签名代码。
|
||
///
|
||
/// 没有 TEE 时必须为 `false` —— [`TrustPlan::for_parties`] 会拒绝
|
||
/// `attested = true` 但 `platform = None` 这种自相矛盾的输入。
|
||
pub attested: bool,
|
||
}
|
||
|
||
impl PartyTee {
|
||
/// 有 TEE 的一方。
|
||
pub fn with_tee(
|
||
site: impl Into<String>,
|
||
kind: PlatformKind,
|
||
tcb: u32,
|
||
attested: bool,
|
||
) -> Self {
|
||
Self {
|
||
site: site.into(),
|
||
platform: Some(Platform { kind, tcb }),
|
||
attested,
|
||
}
|
||
}
|
||
|
||
/// 没有 TEE 的一方。
|
||
pub fn without_tee(site: impl Into<String>) -> Self {
|
||
Self {
|
||
site: site.into(),
|
||
platform: None,
|
||
attested: false,
|
||
}
|
||
}
|
||
|
||
/// 这一方有没有 TEE。
|
||
pub fn has_tee(&self) -> bool {
|
||
self.platform.is_some()
|
||
}
|
||
|
||
/// 在 `min_tcb` 门槛下,这一方的 enclave 是否可信。
|
||
///
|
||
/// TCB 太低的固件有已知漏洞(SNP 的 `reported_tcb` 就是干这个的),
|
||
/// 有 TEE 也不等于可信。
|
||
pub fn is_trusted(&self, min_tcb: u32) -> bool {
|
||
match &self.platform {
|
||
Some(p) => self.attested && p.tcb >= min_tcb,
|
||
None => false,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 客户必须明示的取舍。
|
||
///
|
||
/// 全部字段都不是默认安全的 —— `allow_plaintext_merge` 默认 `false`
|
||
/// 意味着"没说可以就不许把明文合到一起"。
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub struct TrustPolicy {
|
||
/// 可接受的最低 TCB 版本。
|
||
pub min_tcb: u32,
|
||
/// 是否承认"全体 attest 通过"足以省掉 MPC(即允许 L2 明文直算)。
|
||
///
|
||
/// 打开它等于说:我信任这些厂商的隔离性,MPC 那一层数学保障我不要了。
|
||
pub allow_plaintext_merge: bool,
|
||
}
|
||
|
||
impl Default for TrustPolicy {
|
||
fn default() -> Self {
|
||
Self {
|
||
min_tcb: 0,
|
||
allow_plaintext_merge: false,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 四级可信度。n 方时它是**整体**等级,取最弱环节。
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||
pub enum TrustGrade {
|
||
/// L0:全体无 TEE,只有 MPC 数学。
|
||
L0,
|
||
/// L1:部分方有 TEE,MPC 仍是主力。
|
||
L1,
|
||
/// L2:全体有 TEE 且互验通过,可明文直算。
|
||
L2,
|
||
/// L3:全体有 TEE 但不开明文直算(跨厂商 / 客户不允许)。
|
||
L3,
|
||
}
|
||
|
||
impl fmt::Display for TrustGrade {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
f.write_str(match self {
|
||
Self::L0 => "L0",
|
||
Self::L1 => "L1",
|
||
Self::L2 => "L2",
|
||
Self::L3 => "L3",
|
||
})
|
||
}
|
||
}
|
||
|
||
/// 可信度方案:协议栈据此决定"用不用 MPC、用多少"。
|
||
///
|
||
/// # n 方与两方的差别(这条不是措辞变化)
|
||
///
|
||
/// 两方时"一方无 TEE"看上去只是那一方少一层保护 —— 另一方仍然靠 MPC
|
||
/// 拿到数学保障。n 方时同一个问题变严重:**明文直算要把所有分片合到
|
||
/// 一处**,合出来的明文对**执行计算的那一方**完全可见。所以只要
|
||
/// **有一个**不受信方,全体数据就都在它眼前。
|
||
///
|
||
/// 因此 L2 的判据是「**每一方**都有 TEE 且被验证过」,而不是
|
||
/// 「有人在用 TEE」。两方时这两个说法等价,n 方时不等价 ——
|
||
/// 这是把成对枚举改成方案表之后唯一实质性的语义变化。
|
||
///
|
||
/// # MPC 侧的假设没有跟着变
|
||
///
|
||
/// 分片重建是 `n`-out-of-`n`(全方参与),这里**不需要**诚实多数假设,
|
||
/// 但也**不允许任何一方掉线**。TEE 帮不上这一条。
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub enum TrustPlan {
|
||
/// L0:全体无 TEE,只能靠 MPC 数学。
|
||
MpcOnly,
|
||
/// L1:部分方有 TEE(`tee_sides` 按字典序,保证各端算出的结果可比)。
|
||
TeeAssisted {
|
||
/// 拥有 TEE 的各方 site 名。
|
||
tee_sides: Vec<String>,
|
||
},
|
||
/// L2:全体有 TEE 且 attestation 互验通过 —— 可以明文直算。
|
||
///
|
||
/// `min_tcb` 用来拒绝有已知漏洞的固件版本。
|
||
MutualAttested {
|
||
/// 全体可接受的最低 TCB 版本。
|
||
min_tcb: u32,
|
||
},
|
||
/// L3:全体有 TEE 但不开明文直算,MPC 保底。
|
||
///
|
||
/// 两种情况落到这里:TCB 有方不达标 / 客户没明示允许合并。
|
||
TeePerParty,
|
||
}
|
||
|
||
impl TrustPlan {
|
||
/// 由各方 TEE 状况 + 客户策略算出方案。
|
||
///
|
||
/// # 拒绝的输入
|
||
///
|
||
/// - 少于两方(单方没有"协作计算"可言);
|
||
/// - `attested = true` 但 `platform = None`(自相矛盾,说明有人在撒谎或写错);
|
||
/// - site 名重复(重复会让分片按 site 查找时取到错的那一个)。
|
||
pub fn for_parties(parties: &[PartyTee], policy: TrustPolicy) -> Result<Self, TeeError> {
|
||
if parties.len() < 2 {
|
||
return Err(TeeError::BadInput(format!(
|
||
"可信度方案至少要两方,得到 {}",
|
||
parties.len()
|
||
)));
|
||
}
|
||
for p in parties {
|
||
if p.attested && p.platform.is_none() {
|
||
return Err(TeeError::BadInput(format!(
|
||
"site {} 声称已 attest 但没有 TEE 平台",
|
||
p.site
|
||
)));
|
||
}
|
||
}
|
||
for (i, a) in parties.iter().enumerate() {
|
||
if parties[..i].iter().any(|b| b.site == a.site) {
|
||
return Err(TeeError::BadInput(format!("site {} 重复", a.site)));
|
||
}
|
||
}
|
||
|
||
let mut tee_sides: Vec<String> = parties
|
||
.iter()
|
||
.filter(|p| p.has_tee())
|
||
.map(|p| p.site.clone())
|
||
.collect();
|
||
|
||
if tee_sides.is_empty() {
|
||
return Ok(Self::MpcOnly);
|
||
}
|
||
if tee_sides.len() < parties.len() {
|
||
tee_sides.sort();
|
||
return Ok(Self::TeeAssisted { tee_sides });
|
||
}
|
||
// 全体都有 TEE —— 剩下的问题只是"能不能省掉 MPC"
|
||
let all_trusted = parties.iter().all(|p| p.is_trusted(policy.min_tcb));
|
||
if all_trusted && policy.allow_plaintext_merge {
|
||
Ok(Self::MutualAttested {
|
||
min_tcb: policy.min_tcb,
|
||
})
|
||
} else {
|
||
Ok(Self::TeePerParty)
|
||
}
|
||
}
|
||
|
||
/// 这个方案下是否还需要 MPC 计算。
|
||
///
|
||
/// 只有 L2 返回 `false` —— 其他情况 MPC 都是必需的。
|
||
pub fn needs_mpc(&self) -> bool {
|
||
!matches!(self, Self::MutualAttested { .. })
|
||
}
|
||
|
||
/// 是否需要 TEE。
|
||
pub fn needs_tee(&self) -> bool {
|
||
!matches!(self, Self::MpcOnly)
|
||
}
|
||
|
||
/// 整体可信度(最弱环节)。
|
||
pub fn grade(&self) -> TrustGrade {
|
||
match self {
|
||
Self::MpcOnly => TrustGrade::L0,
|
||
Self::TeeAssisted { .. } => TrustGrade::L1,
|
||
Self::MutualAttested { .. } => TrustGrade::L2,
|
||
Self::TeePerParty => TrustGrade::L3,
|
||
}
|
||
}
|
||
|
||
/// 没有 TEE 的各方(`TeeAssisted` 时有值)。
|
||
///
|
||
/// n 方时可能是**多个** —— 这正是它取代 `tee_side: String` 的原因。
|
||
pub fn untrusted_sides<'a>(&'a self, parties: &'a [PartyTee]) -> Vec<&'a str> {
|
||
match self {
|
||
Self::MpcOnly => parties.iter().map(|p| p.site.as_str()).collect(),
|
||
Self::TeeAssisted { .. } => parties
|
||
.iter()
|
||
.filter(|p| !p.has_tee())
|
||
.map(|p| p.site.as_str())
|
||
.collect(),
|
||
_ => Vec::new(),
|
||
}
|
||
}
|
||
|
||
/// 是否允许把明文合到一处计算。
|
||
pub fn allows_plaintext_merge(&self) -> bool {
|
||
matches!(self, Self::MutualAttested { .. })
|
||
}
|
||
|
||
/// 一行人类可读的结论,给日志与 CLI 用。
|
||
pub fn summary(&self) -> String {
|
||
match self {
|
||
Self::MpcOnly => "L0 全体无 TEE:安全性完全由 MPC 数学承担".into(),
|
||
Self::TeeAssisted { tee_sides } => {
|
||
let mut s = String::from("L1 部分方有 TEE(");
|
||
s.push_str(&tee_sides.join(", "));
|
||
s.push_str("):MPC 为主力,TEE 只保护这几方的输入");
|
||
s
|
||
}
|
||
Self::MutualAttested { min_tcb } => {
|
||
let mut s = String::from("L2 全体 TEE 互验通过(min_tcb=");
|
||
s.push_str(&min_tcb.to_string());
|
||
s.push_str("):可明文直算,MPC 退化为审计链");
|
||
s
|
||
}
|
||
Self::TeePerParty => {
|
||
"L3 全体有 TEE 但不开明文直算:MPC 保底,TEE 保输入".into()
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
fn snp(site: &str, attested: bool) -> PartyTee {
|
||
PartyTee::with_tee(site, PlatformKind::SevSnp, 5, attested)
|
||
}
|
||
|
||
#[test]
|
||
fn only_l2_can_skip_mpc() {
|
||
assert!(TrustPlan::MpcOnly.needs_mpc());
|
||
assert!(!TrustPlan::MpcOnly.needs_tee());
|
||
assert!(TrustPlan::TeeAssisted {
|
||
tee_sides: vec!["alice".into()]
|
||
}
|
||
.needs_mpc());
|
||
assert!(!TrustPlan::MutualAttested { min_tcb: 3 }.needs_mpc());
|
||
assert!(TrustPlan::TeePerParty.needs_mpc());
|
||
}
|
||
|
||
#[test]
|
||
fn two_party_degenerates_to_old_semantics() {
|
||
// 两方全无 TEE → L0
|
||
let p = [
|
||
PartyTee::without_tee("alice"),
|
||
PartyTee::without_tee("bob"),
|
||
];
|
||
assert_eq!(TrustPlan::for_parties(&p, TrustPolicy::default()).unwrap(), TrustPlan::MpcOnly);
|
||
|
||
// 一方有 TEE → L1(就是原来的 TeeAssisted,只是名字从单数变复数)
|
||
let p = [snp("alice", true), PartyTee::without_tee("bob")];
|
||
assert_eq!(
|
||
TrustPlan::for_parties(&p, TrustPolicy::default()).unwrap(),
|
||
TrustPlan::TeeAssisted {
|
||
tee_sides: vec!["alice".into()]
|
||
}
|
||
);
|
||
|
||
// 两方全 attest 且客户允许合并 → L2
|
||
let p = [snp("alice", true), snp("bob", true)];
|
||
let policy = TrustPolicy {
|
||
min_tcb: 0,
|
||
allow_plaintext_merge: true,
|
||
};
|
||
assert_eq!(
|
||
TrustPlan::for_parties(&p, policy).unwrap(),
|
||
TrustPlan::MutualAttested { min_tcb: 0 }
|
||
);
|
||
|
||
// 两方全 attest 但客户不许合并 → L3
|
||
let p = [snp("alice", true), snp("bob", true)];
|
||
assert_eq!(
|
||
TrustPlan::for_parties(&p, TrustPolicy::default()).unwrap(),
|
||
TrustPlan::TeePerParty
|
||
);
|
||
}
|
||
|
||
/// n 方最关键的语义变化:三方里有**两方**有 TEE,仍然只是 L1,
|
||
/// 而且 `untrusted_sides` 必须报出那个没 TEE 的第三方。
|
||
#[test]
|
||
fn second_tee_party_does_not_upgrade_grade() {
|
||
let p = [
|
||
snp("alice", true),
|
||
snp("bob", true),
|
||
PartyTee::without_tee("carol"),
|
||
];
|
||
let policy = TrustPolicy {
|
||
min_tcb: 0,
|
||
allow_plaintext_merge: true,
|
||
};
|
||
let plan = TrustPlan::for_parties(&p, policy).unwrap();
|
||
assert_eq!(
|
||
plan,
|
||
TrustPlan::TeeAssisted {
|
||
tee_sides: vec!["alice".into(), "bob".into()]
|
||
},
|
||
"三方里两方有 TEE 不是 L2 —— 明文直算会让 carol 看到全体数据"
|
||
);
|
||
assert_eq!(plan.grade(), TrustGrade::L1);
|
||
assert_eq!(plan.untrusted_sides(&p), vec!["carol"]);
|
||
assert!(plan.needs_mpc());
|
||
assert!(!plan.allows_plaintext_merge());
|
||
}
|
||
|
||
#[test]
|
||
fn all_tee_but_one_unattested_is_l3() {
|
||
let p = [snp("alice", true), snp("bob", false)];
|
||
let policy = TrustPolicy {
|
||
min_tcb: 0,
|
||
allow_plaintext_merge: true,
|
||
};
|
||
assert_eq!(
|
||
TrustPlan::for_parties(&p, policy).unwrap(),
|
||
TrustPlan::TeePerParty,
|
||
"有一方没通过 attestation 就不能合并明文"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn low_tcb_blocks_plaintext_merge() {
|
||
// bob 的 TCB 是 2,门槛 5 —— 有 TEE 但固件版本有已知漏洞
|
||
let p = [
|
||
snp("alice", true),
|
||
PartyTee::with_tee("bob", PlatformKind::SevSnp, 2, true),
|
||
];
|
||
let policy = TrustPolicy {
|
||
min_tcb: 5,
|
||
allow_plaintext_merge: true,
|
||
};
|
||
assert_eq!(
|
||
TrustPlan::for_parties(&p, policy).unwrap(),
|
||
TrustPlan::TeePerParty,
|
||
"TCB 不达标不算互验通过"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn rejects_contradictory_and_duplicate_input() {
|
||
let p = [
|
||
PartyTee {
|
||
site: "alice".into(),
|
||
platform: None,
|
||
attested: true,
|
||
},
|
||
snp("bob", true),
|
||
];
|
||
assert!(matches!(
|
||
TrustPlan::for_parties(&p, TrustPolicy::default()),
|
||
Err(TeeError::BadInput(_))
|
||
));
|
||
|
||
let p = [snp("alice", true), snp("alice", true)];
|
||
assert!(matches!(
|
||
TrustPlan::for_parties(&p, TrustPolicy::default()),
|
||
Err(TeeError::BadInput(_))
|
||
));
|
||
|
||
let p = [snp("alice", true)];
|
||
assert!(
|
||
matches!(
|
||
TrustPlan::for_parties(&p, TrustPolicy::default()),
|
||
Err(TeeError::BadInput(_))
|
||
),
|
||
"单方没有协作计算可言"
|
||
);
|
||
}
|
||
|
||
/// 各方给出的 TEE 列表顺序不同,算出的方案必须一样 ——
|
||
/// 否则各端对"能不能合并明文"的判断会分叉。
|
||
#[test]
|
||
fn plan_is_order_independent() {
|
||
let a = snp("alice", true);
|
||
let b = PartyTee::without_tee("bob");
|
||
let c = snp("carol", true);
|
||
let forward = TrustPlan::for_parties(&[a.clone(), b.clone(), c.clone()], TrustPolicy::default()).unwrap();
|
||
let reverse = TrustPlan::for_parties(&[c, b, a], TrustPolicy::default()).unwrap();
|
||
assert_eq!(forward, reverse);
|
||
}
|
||
}
|