diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..1c400b2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,119 @@ +# CLAUDE.md + +## 项目是什么 + +nax(**N**-arty **A**rithmetic e**X**ecution)的 Rust 重写:隐私计算框架,单二进制、低依赖、TEE 可编入。 +参考实现在 `refs/nax/`(Python/numpy/Ray,独立 git 仓库),**只读,不参与构建**,仅作行为基线与性能对照组。 + +## 三条铁律(优先级高于一切) + +1. **`nax-core` 必须能 no_std 编译**。CI 守:`cargo build -p nax-core --no-default-features`。 + 任何 `Vec` / `tokio` / `String` / `std::` 混进来就等于断了 TEE 那条路。 + 已知坑:`f64::round_ties_even` 是 std-only,已自实现。 + +2. **与 Python 参考实现逐位一致**。改任何确定性算子后必须重跑 + `.venv/bin/python tools/gen_golden.py && cargo test`。 + **不要为了让测试变绿去放宽断言** —— 先确认哪边对。 + 已知对齐点:`np.rint` 银行家舍入、uint64 回绕语义、算术右移有符号语义、`np.matmul` 整数也回绕。 + +3. **Ray 不进计算路径**。只用于部署期把 `nax-node` 钉到各方物理机 + (`resources={"_node": 1}`),计算走 nax 自己的帧协议。 + +## 快速验证 + +```bash +cargo test --workspace # 129 用例 +cargo build -p nax-core --no-default-features # no_std 守线 +cargo check --workspace --target armv7-unknown-linux-gnueabihf # 交叉编译守线 +cargo build --release -p nax-cli && ./target/release/nax selftest +``` + +## crate 分层 + +``` +nax-cli 单二进制入口(selftest / node / psi / lr 四个子命令) + ↓ +nax-node 一方一进程:TCP 会话、帧协议对接 + ↓ +nax-vault 协议编排:Beaver 乘 / 定点截断 / open / reveal(交互在这里,不在算子核) + ↓ +nax-core 算子核:Z_2^64 环算术、加性分享、Beaver 三元组、PRG、SHA-256、比较 + 零依赖 / no_std / 零分配(slice-in/slice-out) + 模块:ring / share / prg / hash / compare + ─────────── +nax-he 大数 Paillier + OLE + PIR + n 方 Beaver 三元组(无可信发牌方) + 手写 bigint(Montgomery CIOS 模幂 / Knuth D / Miller-Rabin) + 模块:bigint / paillier / ole / pir / triple + no_std + alloc,零外部依赖 + ─────────── +nax-psi X25519 ECDH-PSI(唯一允许外部密码学 crate 的地方:curve25519-dalek) + 模块:blind / reblind / match_points / resolve + ─────────── +nax-ml 纵向联邦 LR:sigmoid 多项式 + SGD,全程密文分片 + ─────────── +nax-tee TEE HAL:seal / unseal / attest / sign + 模块:mock(std-only)/ optee(core + proto + TA + CA) + TrustPlan 四级可信度:L0 纯 MPC / L1 单方 TEE / L2 双方互验 / L3 双方 TEE 互不信任 + ─────────── +nax-proto 帧协议:12 字节头 + 定长消息体,手写编解码(不引 protobuf/serde) +``` + +## 关键设计决策 + +- **公开值在分片重建里只能出现一次**。栽过两次:truncate 的 `cs`、sigmoid 的 `c₀`。 + 修法都是"只有 0 号持有公开值"。 +- **`MontCtx::modpow` 必须归约底数**。Montgomery 乘只读 `k` 个 limb, + 未归约的大底数被静默截断(decrypt 的 1024-bit 密文给 512-bit 模数上下文)。 +- **小指数走 1-bit 幂梯**,不要建 16 项窗口表(`mul_plain` 曾比 Python 还慢)。 +- **分片随机流每轮换 label**(递增 `share_round`),否则 `share₁ − share₂` 泄露差值。 +- **`reveal` 是双方同步 open**,测试里双方都必须走完 reveal,否则管道断/死锁。 + +## 性能基线(i5-5250U,2026-10-29 同机实测) + +| 算子 | Python | Rust | 倍数 | +|---|---|---|---| +| matmul 256³ u64 | 83.1 ms | 18.0 ms (AVX2) | 4.6× | +| 逐元素 mul 16M | 101 ms | 58.7 ms | 1.7× | +| Paillier 加密 n=1024 | 21.1 ms | 7.3 ms | 2.9× | +| Paillier 解密 n=1024 | 6.3 ms | 2.8 ms | 2.3× | +| OLE 全流程/元素 | ~48 ms | 15.8 ms | ~3× | + +**别再用旧的 "280×" 估计** —— 纯 Python 大数 pow 本来就走 C 循环,手写 Montgomery 只有 2–3.6×。 +HE 的真正收益是可用性(10 万元素预处理 80 分钟 → 16 分钟)+ 能编进 TEE。 + +## Zynq-7015 性能预算 + +A9 @667MHz 比 i5-5250U 慢 8–12×(不是 50×): +matmul 64³ ~2.5ms、纵向 LR ~150ms、PSI 1 万条 8–15s。 +**小规模场景完全可以在板上跑**。大矩阵密文训练横扩 x86 + SEV-SNP/TDX/海光 CSV。 + +## golden 向量 + +```bash +.venv/bin/python tools/gen_golden.py # → crates/nax-core/tests/golden_vectors.rs (215 条) + # → crates/nax-he/tests/golden_paillier.rs (50 条) +cargo test -p nax-core --test golden_vectors +cargo test -p nax-he --test golden_paillier +``` + +## QEMU OP-TEE 验证(P3) + +```bash +# 需要 cube-sandbox(16C/16G toolchain 模板) +xop --secret CUBE_API_KEY=llm_key -- python3 -u build/run_qemu.py < /dev/null +``` + +构建链:OP-TEE 4.11 + u-boot v2024.10 + ATF v2.11 + Linux 6.6 + rustup nightly-2026-08-05 ++ nax-tee TA/CA。判据:正常世界串口 `ALL OK`(provision → seal → unseal → 篡改被拒 → sign → attest)。 + +## 依赖 + +全项目**唯一**外部依赖:`curve25519-dalek`(在 `nax-psi`)。 +理由:X25519 必须恒定时间实现,手写会被时序侧信道攻击。 +`nax-he` 手写 bigint 零外部依赖。 + +## 文档 + +- `docs/ARCHITECTURE.md` — 分层、Ray 定位、TEE 定位(每条结论附"为什么不是另一种做法") +- `docs/ZYNQ.md` — Zynq-7015 性能预算、交叉编译、部署形态 +- `refs/nax/` — Python 参考实现(只读) diff --git a/build/build_optee.sh b/build/build_optee.sh new file mode 100755 index 0000000..0d45fbc --- /dev/null +++ b/build/build_optee.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# 构建 nax-tee TA + CA(armv7 / armhf),签名并校验。 +# +# 三层范式(op-tee-test 的 vault-core 模式): +# nax-tee/src/optee/core.rs 密码学与格式(no_std,宿主可测) +# crates/nax-tee/ta/ TA 薄壳(参数搬运 + RNG + secure storage) +# crates/nax-tee/ca/ CA 侧(OpteeTee 实现 Tee trait) +# +# 用法: +# # QEMU / 模拟设备 A +# NAX_SIM_DEV=nax-dev-A bash build/build_optee.sh +# +# # 模拟设备 B(拿到 A 的 blob 去解,应当失败) +# NAX_SIM_DEV=nax-dev-B OUT_PREFIX=nax-devB bash build/build_optee.sh +# +# # 真板:从 SLCR 读 DNA +# TA_FEATURES=board bash build/build_optee.sh +# +# 必需环境变量: +# OPTEE_OS optee_os 源码目录(已构建过,有 export-ta_arm32) +# SDK_DIR teaclave-trustzone-sdk 目录 +# OPTEE_CLIENT_EXPORT optee_client 的 out/export(不给就用 $OPTEE_OS/../optee_client/out/export) + +set -euo pipefail + +REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +OPTEE_OS="${OPTEE_OS:?需要指向 optee_os 源码目录}" +SDK_DIR="${SDK_DIR:?需要指向 teaclave-trustzone-sdk 目录}" +OPTEE_CLIENT_EXPORT="${OPTEE_CLIENT_EXPORT:-$(dirname "$OPTEE_OS")/optee_client/out/export}" + +UUID="a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" +TA_PKG="nax-tee-ta" +CA_PKG="nax-tee-ca" +TARGET="arm-unknown-linux-gnueabihf" +TA_FEATURES="${TA_FEATURES:-}" +OUT_PREFIX="${OUT_PREFIX:-nax-tee}" +OUT_DIR="${OUT_DIR:-$REPO/artifacts/optee}" +SIGN_KEY="${SIGN_KEY:-}" # 留空 = 开发密钥 default_ta.pem + +# ---- TA dev kit ---- +DK="" +for cand in "$OPTEE_OS/out/zynq7k/export-ta_arm32" "$OPTEE_OS/out/arm/export-ta_arm32" "$OPTEE_OS/out/qemu_virt/export-ta_arm32"; do + [ -d "$cand" ] && DK="$cand" && break +done +[ -n "$DK" ] || { echo "找不到 TA dev kit(先编 optee_os)" >&2; exit 1; } + +export TA_DEV_KIT_DIR="$DK" +export CROSS_COMPILE="${CROSS_COMPILE:-arm-linux-gnueabihf-}" +export CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER="${CROSS_COMPILE}gcc" +export CC_arm_unknown_linux_gnueabihf="${CROSS_COMPILE}gcc" +export RUSTUP_TOOLCHAIN="${RUSTUP_TOOLCHAIN:-nightly-2026-08-05}" + +# 模拟设备身份:编译期注入(换值要重编) +if [ -n "${NAX_SIM_DEV:-}" ]; then + export NAX_SIM_DEV + echo "== 模拟设备身份 NAX_SIM_DEV=$NAX_SIM_DEV(编译期常量)==" +fi + +echo "== 0. 把源码摆进 SDK 的 workspace ==" +# nax-core + nax-tee 都要拷(TA/CA 依赖 nax-tee,nax-tee 依赖 nax-core) +for ws in ta ca; do + rm -rf "$SDK_DIR/examples/$ws/nax-core" "$SDK_DIR/examples/$ws/nax-tee" + cp -a "$REPO/crates/nax-core" "$SDK_DIR/examples/$ws/nax-core" + cp -a "$REPO/crates/nax-tee" "$SDK_DIR/examples/$ws/nax-tee" + rm -rf "$SDK_DIR/examples/$ws/nax-core/target" "$SDK_DIR/examples/$ws/nax-tee/target" + rm -rf "$SDK_DIR/examples/$ws/nax-core/.git" "$SDK_DIR/examples/$ws/nax-tee/.git" + # nax-tee 的 Cargo.toml 里 nax-core 用 workspace 依赖,拷过去后要改成本地 path + sed -i.bak 's|nax-core = { workspace = true.*|nax-core = { path = "../nax-core" }|' \ + "$SDK_DIR/examples/$ws/nax-tee/Cargo.toml" 2>/dev/null || true +done + +rm -rf "$SDK_DIR/examples/ta/$TA_PKG" "$SDK_DIR/examples/ca/$CA_PKG" +cp -a "$REPO/crates/nax-tee/ta" "$SDK_DIR/examples/ta/$TA_PKG" +cp -a "$REPO/crates/nax-tee/ca" "$SDK_DIR/examples/ca/$CA_PKG" + +# TA/CA 的 Cargo.toml 里 nax-tee 用 path = "../..",拷过去后要改 +sed -i.bak 's|nax-tee = { path = "../..".*|nax-tee = { path = "../nax-tee" }|' \ + "$SDK_DIR/examples/ta/$TA_PKG/Cargo.toml" 2>/dev/null || true +sed -i.bak 's|nax-tee = { path = "../..".*|nax-tee = { path = "../nax-tee" }|' \ + "$SDK_DIR/examples/ca/$CA_PKG/Cargo.toml" 2>/dev/null || true + +# members 注入 +python3 - "$SDK_DIR/examples/ta/Cargo.toml" "nax-core" "nax-tee" "$TA_PKG" <<'PY' +import sys +path = sys.argv[1] +for name in sys.argv[2:]: + s = open(path).read() + if f'"{name}"' not in s and "members" in s: + s = s.replace("members = [", f'members = [ "{name}",', 1) + open(path, "w").write(s) +PY +python3 - "$SDK_DIR/examples/ca/Cargo.toml" "nax-core" "nax-tee" "$CA_PKG" <<'PY' +import sys +path = sys.argv[1] +for name in sys.argv[2:]: + s = open(path).read() + if f'"{name}"' not in s and "members" in s: + s = s.replace("members = [", f'members = [ "{name}",', 1) + open(path, "w").write(s) +PY + +echo "== 1. 编 TA ==" +cd "$SDK_DIR/examples/ta/$TA_PKG" +FEATURE_ARGS="" +[ -n "$TA_FEATURES" ] && FEATURE_ARGS="--features $TA_FEATURES" +cargo build --target "$TARGET" --release $FEATURE_ARGS 2>&1 | tail -5 + +TA_ELF="$SDK_DIR/examples/ta/$TA_PKG/target/$TARGET/release/$TA_PKG" +[ -f "$TA_ELF" ] || { echo "TA ELF 没找到: $TA_ELF" >&2; exit 1; } + +echo "== 2. 签名 TA ==" +mkdir -p "$OUT_DIR" +TA_OUT="$OUT_DIR/${OUT_PREFIX}.ta" +SIGN_ARGS="--uuid $UUID --in $TA_ELF --out $TA_OUT" +[ -n "$SIGN_KEY" ] && SIGN_ARGS="$SIGN_ARGS --key $SIGN_KEY" +python3 "$TA_DEV_KIT_DIR/sign_encrypt.py" sign-enc $SIGN_ARGS + +# 校验签名 +python3 "$TA_DEV_KIT_DIR/sign_encrypt.py" verify --uuid $UUID --in $TA_OUT ${SIGN_KEY:+--key $SIGN_KEY} && echo "TA 签名校验 OK" + +echo "== 3. 编 CA ==" +cd "$SDK_DIR/examples/ca/$CA_PKG" +cargo build --target "$TARGET" --release 2>&1 | tail -5 + +CA_ELF="$SDK_DIR/examples/ca/$CA_PKG/target/$TARGET/release/$CA_PKG" +[ -f "$CA_ELF" ] || { echo "CA ELF 没找到: $CA_ELF" >&2; exit 1; } +cp "$CA_ELF" "$OUT_DIR/${OUT_PREFIX}-ca" + +echo "== 产物 ==" +ls -lh "$OUT_DIR/" +echo "OK" diff --git a/build/p3_optee_qemu.sh b/build/p3_optee_qemu.sh new file mode 100755 index 0000000..4c2c202 --- /dev/null +++ b/build/p3_optee_qemu.sh @@ -0,0 +1,234 @@ +#!/bin/bash +# ============================================================================ +# OP-TEE 4.11 + nax-tee TA(设备绑定密钥 + 密封 + 签名)在 arm32 QEMU 上跑通 +# +# 与 op-tee-test/p1_vault_qemu.sh 同构,只把 vault 换成 nax-tee。 +# 成功判据:正常世界串口出现 `ALL OK` +# (provision → seal → 重开 session → unseal → 篡改被拒 → AAD 绑定 → sign → attest) +# +# 在 cube-sandbox 的 toolchain 模板里跑(16C/16G),约 15 分钟。 +# ============================================================================ +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +export PATH=/opt/cargo/bin:/usr/bin:/bin:/usr/sbin:/sbin +export PYTHON3=/usr/bin/python3 +export CROSS_COMPILE=arm-linux-gnueabihf- +export AARCH32_CROSS_COMPILE=arm-linux-gnueabihf- +export RUSTUP_HOME=/opt/rustup +export CARGO_HOME=/opt/cargo +export CARGO_NET_GIT_FETCH_WITH_CLI=true +export CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc +export CC_arm_unknown_linux_gnueabihf=arm-linux-gnueabihf-gcc +export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static +export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup + +NAX_UUID="a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" +W=/root +SRC=${SRC:-$W/src} +JOBS=$(nproc) +cd $W + +# ---------------- 1. 依赖 ---------------- +apt-get update -qq +apt-get install -y -qq --no-install-recommends \ + bc cpio device-tree-compiler xxd rsync gcc-arm-linux-gnueabihf \ + libc6-dev-armhf-cross qemu-system-arm qemu-system-data u-boot-tools \ + python3-cryptography python3-pyelftools libssl-dev uuid-dev libgnutls28-dev \ + swig python3-dev libncurses-dev kmod expect gawk + +# ---------------- 2. 源码 ---------------- +clone() { + git -c http.version=HTTP/1.1 clone -q --depth 1 ${3:+--branch $3} "$1" "$2" \ + || git -c http.version=HTTP/1.1 clone -q --depth 1 ${3:+--branch $3} "https://ghfast.top/$1" "$2" +} +[ -d optee_os ] || clone https://github.com/OP-TEE/optee_os.git optee_os 4.11.0 +[ -d optee_client ] || clone https://github.com/OP-TEE/optee_client.git optee_client 4.11.0 +[ -d optee-build ] || clone https://github.com/OP-TEE/build.git optee-build 4.11.0 +[ -d u-boot ] || clone https://github.com/u-boot/u-boot.git u-boot v2024.10 +[ -d trusted-firmware-a ] || clone https://github.com/ARM-software/arm-trusted-firmware.git trusted-firmware-a v2.11.0 +[ -d teaclave-sdk ] || clone https://github.com/apache/incubator-teaclave-trustzone-sdk.git teaclave-sdk "" +if [ ! -d linux ]; then + curl -sSL --max-time 900 -o linux.tar.xz https://mirrors.tuna.tsinghua.edu.cn/kernel/v6.x/linux-6.6.60.tar.xz + tar xf linux.tar.xz && mv linux-6.6.60 linux && rm -f linux.tar.xz +fi + +ln -sfn $W/optee-build $W/build +ln -sfn $W/trusted-firmware-a $W/arm-trusted-firmware + +F=$W/trusted-firmware-a/include/arch/aarch32/el3_common_macros.S +grep -q '^\s*\.fpu' "$F" || sed -i '0,/^#include/s//\t.fpu vfpv3\n#include/' "$F" + +# ---------------- 3. Rust 工具链 ---------------- +if [ ! -x /opt/cargo/bin/rustup ]; then + mkdir -p /opt/rustup + curl -sSL -o /tmp/rustup-init https://mirrors.ustc.edu.cn/rust-static/rustup/dist/x86_64-unknown-linux-gnu/rustup-init + chmod +x /tmp/rustup-init && /tmp/rustup-init -y --no-modify-path --default-toolchain none +fi +/opt/cargo/bin/rustup toolchain list | grep -q nightly-2026-08-05 \ + || /opt/cargo/bin/rustup toolchain install nightly-2026-08-05 --profile minimal \ + -c rust-src -t arm-unknown-linux-gnueabihf +export RUSTUP_TOOLCHAIN=nightly-2026-08-05 + +# ---------------- 4. optee_os + u-boot + ATF ---------------- +cd $W/optee-build +make -j"$JOBS" -f qemu.mk CFG_ARM64_core=n $PYTHON3 arm-tf +FW=$(find $W/trusted-firmware-a/build -name qemu_fw.rom | head -1) +DK=$(find $W/optee_os -maxdepth 4 -type d -name export-ta_arm32 | head -1) +echo "qemu_fw.rom = $FW"; echo "TA_DEV_KIT_DIR = $DK" + +# ---------------- 5. 内核 ---------------- +cd $W/linux +make ARCH=arm vexpress_defconfig >/dev/null +cat > /tmp/optee.frag <<'FRAG' +CONFIG_TEE=y +CONFIG_OPTEE=y +CONFIG_DEVTMPFS=y +CONFIG_DEVTMPFS_MOUNT=y +CONFIG_BLK_DEV_INITRD=y +CONFIG_RD_GZIP=y +CONFIG_SERIAL_AMBA_PL011=y +CONFIG_SERIAL_AMBA_PL011_CONSOLE=y +FRAG +scripts/kconfig/merge_config.sh -m .config /tmp/optee.frag >/dev/null +make ARCH=arm olddefconfig >/dev/null +grep -q '^CONFIG_OPTEE=y' .config || { echo "OPTEE 配置没生效"; exit 1; } +make ARCH=arm -j"$JOBS" zImage + +# ---------------- 6. optee_client ---------------- +cd $W/optee_client +make -j"$JOBS" CROSS_COMPILE=arm-linux-gnueabihf- || true +make -C tee-supplicant -j"$JOBS" CC=arm-linux-gnueabihf-gcc LD=arm-linux-gnueabihf-gcc \ + CROSS_COMPILE=arm-linux-gnueabihf- LDFLAGS="-L$W/optee_client/out/libteec" + +# ---------------- 7. Rust TA (nax-tee) + CA ---------------- +[ -d "$SRC/nax-core" ] || { echo "找不到 $SRC/nax-core"; exit 1; } +[ -d "$SRC/nax-tee" ] || { echo "找不到 $SRC/nax-tee"; exit 1; } + +# nax-core + nax-tee 是 TA 与 CA 共用的 no_std 逻辑 +for ws in ta ca; do + rm -rf $W/teaclave-sdk/examples/$ws/nax-core $W/teaclave-sdk/examples/$ws/nax-tee + cp -a "$SRC/nax-core" $W/teaclave-sdk/examples/$ws/nax-core + cp -a "$SRC/nax-tee" $W/teaclave-sdk/examples/$ws/nax-tee + rm -rf $W/teaclave-sdk/examples/$ws/nax-core/target $W/teaclave-sdk/examples/$ws/nax-tee/target +done + +# nax-tee 的 Cargo.toml 里 nax-core 用 workspace 依赖,拷过去后要改成本地 path +for ws in ta ca; do + sed -i 's|nax-core = { workspace = true.*|nax-core = { path = "../nax-core" }|' \ + $W/teaclave-sdk/examples/$ws/nax-tee/Cargo.toml +done + +rm -rf $W/teaclave-sdk/examples/ta/nax-tee-ta $W/teaclave-sdk/examples/ca/nax-tee-ca +cp -a "$SRC/nax-tee/ta" $W/teaclave-sdk/examples/ta/nax-tee-ta +cp -a "$SRC/nax-tee/ca" $W/teaclave-sdk/examples/ca/nax-tee-ca + +# TA/CA 的 Cargo.toml 里 nax-tee 用 path = "../..",拷过去后要改 +sed -i 's|nax-tee = { path = "../..".*|nax-tee = { path = "../nax-tee" }|' \ + $W/teaclave-sdk/examples/ta/nax-tee-ta/Cargo.toml +sed -i 's|nax-tee = { path = "../..".*|nax-tee = { path = "../nax-tee" }|' \ + $W/teaclave-sdk/examples/ca/nax-tee-ca/Cargo.toml + +add_members() { + $PYTHON3 - "$@" <<'PYMEM' +import sys +path, names = sys.argv[1], sys.argv[2:] +s = open(path).read() +for name in names: + if '"%s"' % name not in s: + s = s.replace("members = [", 'members = [\n "%s",' % name, 1) +open(path, 'w').write(s) +PYMEM +} +add_members $W/teaclave-sdk/examples/ta/Cargo.toml nax-core nax-tee nax-tee-ta +add_members $W/teaclave-sdk/examples/ca/Cargo.toml nax-core nax-tee nax-tee-ca + +cd $W/teaclave-sdk/examples/ta +printf '{\n__elf_phdr_info;\ntrace_ext_prefix;\ntrace_level;\nta_head;\n};\n' > dyn_list +export TA_DEV_KIT_DIR="$DK" +export NAX_SIM_DEV=nax-dev-A +cargo build -p nax-tee-ta --target arm-unknown-linux-gnueabihf --release +TAELF=$W/.cache/cargo-target/arm-unknown-linux-gnueabihf/release/nax-tee-ta +mkdir -p $W/out +$PYTHON3 "$DK/scripts/sign_encrypt.py" sign-enc --uuid "$NAX_UUID" \ + --in "$TAELF" --out $W/out/nax-tee.ta --key "$DK/keys/default_ta.pem" +$PYTHON3 "$DK/scripts/sign_encrypt.py" verify --uuid "$NAX_UUID" \ + --in $W/out/nax-tee.ta --key "$DK/keys/default_ta.pem" + +mkdir -p $W/optee_client/out/export/usr/lib $W/optee_client/out/export/usr/include +cp -a $W/optee_client/out/libteec/. $W/optee_client/out/export/usr/lib/ +cp -a $W/optee_client/libteec/include/*.h $W/optee_client/out/export/usr/include/ +export OPTEE_CLIENT_EXPORT=$W/optee_client/out/export +cd $W/teaclave-sdk/examples/ca +cargo build -p nax-tee-ca --target arm-unknown-linux-gnueabihf --release +cp -f $W/.cache/cargo-target/arm-unknown-linux-gnueabihf/release/nax-tee-ca $W/out/nax-tee-ca + +# ---------------- 8. armhf rootfs ---------------- +dpkg --add-architecture armhf && apt-get update -qq +mkdir -p $W/debs && cd $W/debs +apt-get download busybox-static:armhf libc6:armhf libgcc-s1:armhf +rm -rf $W/rootfs && mkdir -p $W/rootfs +for f in *.deb; do dpkg-deb -x "$f" $W/rootfs; done +cd $W/rootfs +mkdir -p proc sys dev tmp usr/bin usr/lib lib/optee_armtz sbin +for a in sh ls cat mount umount mkdir echo dmesg sleep poweroff reboot mknod chmod ln \ + grep sed cp dd id uname ps free; do ln -sf /bin/busybox "bin/$a"; done +ln -sf /bin/busybox sbin/init +cp -a $W/optee_client/out/libteec/libteec.so* usr/lib/ +cp -f $W/optee_client/out/tee-supplicant/tee-supplicant usr/bin/ +cp -f $W/out/nax-tee-ca usr/bin/nax-tee-ca +cp -f $W/out/nax-tee.ta "lib/optee_armtz/$NAX_UUID.ta" + +cat > init <<'INIT' +#!/bin/busybox sh +/bin/busybox --install -s /bin 2>/dev/null +mount -t proc proc /proc; mount -t sysfs sys /sys +mount -t devtmpfs dev /dev 2>/dev/null; mount -t tmpfs tmp /tmp +export LD_LIBRARY_PATH=/usr/lib; export PATH=/usr/bin:/bin:/sbin +echo "--- optee ---"; dmesg | grep -i optee | tail -5; ls -l /dev/tee* +if [ -e /dev/teepriv0 ]; then + /usr/bin/tee-supplicant -d /dev/teepriv0 >/tmp/sup.log 2>&1 & + sleep 2 + /usr/bin/nax-tee-ca selftest; echo "NAX_RC=$?" +else + echo NO_TEEPRIV0 +fi +echo MARKER_ALL_DONE; sync; poweroff -f +INIT +chmod +x init +find . -print0 | cpio --null -o -H newc 2>/dev/null | gzip -9 > $W/rootfs.cpio.gz + +# ---------------- 9. DTB ---------------- +mkdir -p $W/run && cd $W/run +cp -f $W/linux/arch/arm/boot/zImage . +cp -f "$FW" ./qemu_fw.rom +cp -f $W/rootfs.cpio.gz . +qemu-system-arm -display none -machine virt,secure=on,dumpdtb=virt.dtb -cpu cortex-a15 -m 1057 -nic none +dtc -I dtb -O dts -o virt.dts virt.dtb 2>/dev/null +head -n -1 virt.dts > v2.dts +GIC=$(grep -A2 'intc@8000000' virt.dts | grep -o 'phandle = <0x[0-9a-f]*>' | grep -o '0x[0-9a-f]*' | head -1) +cat >> v2.dts <; + interrupts = <0x00 0x09 0x04>; + }; + }; +}; +DTB +dtc -I dts -O dtb -o virt-optee.dtb v2.dts 2>/dev/null + +# ---------------- 10. 跑 QEMU ---------------- +timeout 200 qemu-system-arm -display none -smp 2 -m 1057 \ + -machine virt,secure=on -cpu cortex-a15 \ + -bios qemu_fw.rom -dtb virt-optee.dtb -nic none \ + -serial file:$W/run/nw.log -serial file:$W/run/sw.log \ + -semihosting-config enable=on,target=native || true + +echo "########## NORMAL WORLD ##########"; sed -n '/optee/,$p' $W/run/nw.log | head -30 || true +echo "########## SECURE WORLD ##########"; tail -12 $W/run/sw.log || true +echo "########## 判据 ##########" +grep -q 'ALL OK' $W/run/nw.log \ + && echo "PASS: nax-tee TA 完成 provision/seal/unseal/sign/attest,篡改与 AAD 绑定被拒" \ + || { echo "FAIL"; echo "--- 正常世界尾部 ---"; tail -40 $W/run/nw.log; exit 1; } diff --git a/build/run_qemu.py b/build/run_qemu.py new file mode 100644 index 0000000..dd5f8ff --- /dev/null +++ b/build/run_qemu.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""P3 OP-TEE QEMU 验证:在 cube-sandbox 的 toolchain 模板里跑全链。 + +用法(key 经 xop 注入环境,不进 argv): + xop --secret CUBE_API_KEY=llm_key -- python3 build/run_qemu.py < /dev/null + +⚠ cube-auth-gate/2.0 的兼容补丁:客户端发 `Accept-Encoding: gzip` 时 +网关会回 gzip 压缩体但**漏发 Content-Encoding 头**,requests 解不开 → +SDK `resp.json()` 抛 JSONDecodeError。这里强制 `Accept-Encoding: identity` +绕开(2026-10-29 实测有效)。 +""" +import os +import sys +import time + +os.environ.setdefault("CUBE_API_URL", "http://192.168.1.30:3000") +os.environ.setdefault("CUBE_PROXY_NODE_IP", "192.168.1.30") +os.environ.setdefault("CUBE_PROXY_PORT_HTTP", "80") + +import requests as _requests + +# --- 兼容补丁:强制 Accept-Encoding: identity --- +_orig_req = _requests.Session.request + + +def _req_no_gzip(self, method, url, **kw): + headers = dict(kw.pop("headers", None) or {}) + headers["Accept-Encoding"] = "identity" + return _orig_req(self, method, url, headers=headers, **kw) + + +_requests.Session.request = _req_no_gzip + +try: # 数据面走 httpx,同样处理 + import httpx as _httpx + + _orig_hreq = _httpx.Client.request + + def _hreq_no_gzip(self, method, url, **kw): + headers = dict(kw.pop("headers", None) or {}) + headers.setdefault("Accept-Encoding", "identity") + return _orig_hreq(self, method, url, headers=headers, **kw) + + _httpx.Client.request = _hreq_no_gzip +except Exception: + pass + +from cubesandbox import Sandbox + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def make_src_tgz() -> bytes: + """把 nax-core / nax-tee / p3 脚本打成一个 tar.gz,单次上传。""" + import io + import tarfile + + def _filter(ti: tarfile.TarInfo): + parts = ti.name.split("/") + if "target" in parts or ".git" in parts or "__pycache__" in parts: + return None + return ti + + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tf: + for sub in ("crates/nax-core", "crates/nax-tee"): + tf.add(os.path.join(REPO, sub), arcname=sub, filter=_filter) + tf.add( + os.path.join(REPO, "build", "p3_optee_qemu.sh"), + arcname="p3_optee_qemu.sh", + ) + return buf.getvalue() + + +def main(): + print("== 创建 toolchain 沙箱 (16C/16G, 2h 生命周期) ==") + sb = Sandbox.create( + template="toolchain", timeout=7200, network={"allow_public_traffic": False} + ) + print(f" sandbox_id = {sb.sandbox_id}") + + try: + # 上传源码(单 tar 包) + print("== 打包并上传源码 ==") + tgz = make_src_tgz() + print(f" src.tgz = {len(tgz) / 1e6:.2f} MB") + sb.commands.run("mkdir -p /root/src") + sb.files.write("/root/src/src.tgz", tgz) + r = sb.commands.run("tar xzf /root/src/src.tgz -C /root/src && ls /root/src") + print(" 解压:", r.stdout.strip().replace("\n", " ")) + + print("== 启动 QEMU 全链构建(约 15-25 分钟)==") + # nohup 后台 + rc 文件判据(不要在命令上挂长等待) + # SRC 指向 crates 所在目录:解压后是 /root/src/crates/{nax-core,nax-tee} + sb.commands.run( + "cd /root && nohup bash -c " + "'SRC=/root/src/crates bash /root/src/p3_optee_qemu.sh; " + "echo $? > /root/build.rc' > /root/build.log 2>&1 & echo started" + ) + + # 轮询 rc 文件 + finished = False + for i in range(270): # 最多 45 分钟 + time.sleep(10) + r = sb.commands.run( + "test -f /root/build.rc && cat /root/build.rc || echo running" + ) + status = r.stdout.strip() + if i % 6 == 0: + t = sb.commands.run("tail -2 /root/build.log 2>/dev/null") + print(f" [{i * 10}s] {t.stdout.strip()[:120]}") + if status != "running": + print(f" build.rc = {status}") + finished = True + break + + if not finished: + print("⚠ 45 分钟未结束,取当前日志") + + # 读完整日志 + print("== 构建日志尾部 ==") + r = sb.commands.run("tail -60 /root/build.log") + print(r.stdout) + + # 检查结果:build.rc 是构建脚本的退出码,权威判据 + # (旧版用 `grep -c 'PASS:' || echo 0`,grep 无匹配时输出 "0\n0" + # 被误判为非零 → 假阳性,2026-10-29 实测踩过) + rc = sb.commands.run("cat /root/build.rc 2>/dev/null || echo missing").stdout.strip() + if rc == "0": + print("\n✅ P3 QEMU 验证通过!(build.rc=0)") + return 0 + else: + print(f"\n❌ P3 QEMU 验证失败 (build.rc={rc})") + r = sb.commands.run("tail -40 /root/run/nw.log 2>/dev/null") + print("正常世界日志:") + print(r.stdout) + return 1 + finally: + sb.kill() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/crates/nax-core/Cargo.toml b/crates/nax-core/Cargo.toml index aa4faa3..67a67ce 100644 --- a/crates/nax-core/Cargo.toml +++ b/crates/nax-core/Cargo.toml @@ -1,10 +1,13 @@ [package] name = "nax-core" description = "Nax 算子核:Z_2^64 环算术、加性分享、Beaver、edaBit/BitLT。no_std、零依赖。" -version.workspace = true -edition.workspace = true -license.workspace = true -rust-version.workspace = true +# 显式写死(不用 workspace 继承):本 crate 会被原样拷进 teaclave-sdk 的 +# examples workspace 编进 TA,那里的 workspace.package 没有这些字段, +# 继承会在 manifest 解析期直接崩(2026-10-29 QEMU 实测踩过)。 +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +rust-version = "1.85" # 本 crate 的核心卖点:**零外部依赖**。 # 因此它可以被原样编进 OP-TEE TA(armv7 no_std)、编进 WASM、 diff --git a/crates/nax-tee/Cargo.toml b/crates/nax-tee/Cargo.toml index 3692557..e027c7a 100644 --- a/crates/nax-tee/Cargo.toml +++ b/crates/nax-tee/Cargo.toml @@ -1,10 +1,18 @@ [package] name = "nax-tee" description = "TEE 抽象层:seal/unseal/attest/sign,只做控制平面。" -version.workspace = true -edition.workspace = true -license.workspace = true -rust-version.workspace = true +# 同 nax-core:显式写死,拷进 teaclave workspace 后还能解析。 +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +rust-version = "1.85" + +[features] +default = ["std"] +# std:mock 实现 + std::error::Error。TA 构建走 default-features = false(no_std + alloc)。 +std = ["nax-core/std"] [dependencies] -nax-core = { workspace = true, features = ["std"] } +# 直接 path(不走 workspace):拷进 teaclave 后 `../nax-core` 依然成立 +# (host 侧 crates/nax-tee → crates/nax-core,SDK 侧 examples/*/nax-tee → nax-core)。 +nax-core = { path = "../nax-core", default-features = false } diff --git a/crates/nax-tee/ca/Cargo.toml b/crates/nax-tee/ca/Cargo.toml new file mode 100644 index 0000000..01017b7 --- /dev/null +++ b/crates/nax-tee/ca/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "nax-tee-ca" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "nax TEE CA: normal-world client for the nax-tee TA" + +# 放在 /examples/ca/ 下,目录名以 -rs 结尾即可被 workspace 的 members 通配收进来。 +# 构建脚本会把 nax-tee(含 optee/core + proto)拷到 /examples/ca/nax-tee。 + +[dependencies] +optee-teec = { workspace = true } +nax-tee = { path = "../..", default-features = false } diff --git a/crates/nax-tee/ca/src/main.rs b/crates/nax-tee/ca/src/main.rs new file mode 100644 index 0000000..c3dc1eb --- /dev/null +++ b/crates/nax-tee/ca/src/main.rs @@ -0,0 +1,228 @@ +//! nax TEE CA —— 正常世界客户端:OpteeTee 实现 Tee trait + selftest。 +//! +//! 用法(板子 / QEMU 里): +//! +//! ```text +//! nax-tee-ca info # 版本、是否已 provision、设备指纹 +//! nax-tee-ca provision # 首次生成 K_root(幂等) +//! nax-tee-ca selftest # 全流程:provision → seal → unseal → sign → attest +//! ``` +//! +//! 关键演示点:selftest 里会**关掉 session 再重开**,等价于 TA 重新加载 / +//! 进程重启。如果密钥真的只在安全世界且持久化正确,这一步仍然能解开。 + +use optee_teec::{Context, Operation, ParamNone, ParamTmpRef, Session, Uuid}; +use nax_tee::optee::core; +use nax_tee::optee::proto; + +/// 必须与 TA 的 main.rs、build.rs 三处一致。 +const UUID: &str = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"; + +type R = Result; + +fn es(e: optee_teec::Error) -> String { + format!("{e}") +} + +fn uuid() -> R { + Uuid::parse_str(UUID).map_err(es) +} + +fn open_session() -> R { + let mut ctx = Context::new().map_err(es)?; + let uuid = uuid()?; + ctx.open_session(uuid).map_err(es) +} + +// ---------------------------------------------------------------- OpteeTee + +/// OP-TEE 实现:通过 TEEC 调 TA 完成 seal/unseal/sign/attest。 +pub struct OpteeTee { + session: Session, +} + +impl OpteeTee { + /// 打开与 TA 的会话。 + pub fn open() -> R { + let session = open_session()?; + Ok(Self { session }) + } + + /// 查询 TA 信息。 + pub fn info(&mut self) -> R<(u16, [u8; 8], u64)> { + let mut buf = [0u8; proto::INFO_LEN]; + let p0 = ParamTmpRef::new_output(&mut buf); + let mut op = Operation::new(0, p0, ParamNone, ParamNone, ParamNone); + self.session + .invoke_command(proto::CMD_INFO, &mut op) + .map_err(es)?; + proto::decode_info(&buf).ok_or("INFO 长度不对".into()) + } + + /// 首次 provision(幂等)。 + pub fn provision(&mut self) -> R<()> { + let mut op = Operation::new(0, ParamNone, ParamNone, ParamNone, ParamNone); + self.session + .invoke_command(proto::CMD_PROVISION, &mut op) + .map_err(es) + } + + /// 密封。 + pub fn seal(&mut self, plaintext: &[u8], aad: &[u8]) -> R> { + let input = proto::encode_seal_input(aad, plaintext); + let mut out = vec![0u8; plaintext.len() + core::SEAL_OVERHEAD]; + let p0 = ParamTmpRef::new_input(&input); + let p1 = ParamTmpRef::new_output(&mut out); + let mut op = Operation::new(0, p0, p1, ParamNone, ParamNone); + self.session + .invoke_command(proto::CMD_SEAL, &mut op) + .map_err(es)?; + out.truncate(plaintext.len() + core::SEAL_OVERHEAD); + Ok(out) + } + + /// 解封。 + pub fn unseal(&mut self, blob: &[u8], aad: &[u8]) -> R> { + let input = proto::encode_seal_input(aad, blob); + // blob = nonce(12) + tag(32) + ct → 明文长度 = blob.len() - 44 + let pt_len = blob.len().saturating_sub(core::SEAL_OVERHEAD); + let mut out = vec![0u8; pt_len]; + let p0 = ParamTmpRef::new_input(&input); + let p1 = ParamTmpRef::new_output(&mut out); + let mut op = Operation::new(0, p0, p1, ParamNone, ParamNone); + self.session + .invoke_command(proto::CMD_UNSEAL, &mut op) + .map_err(es)?; + Ok(out) + } + + /// 签名(HMAC-SHA256)。 + pub fn sign(&mut self, msg: &[u8]) -> R<[u8; 32]> { + let mut out = [0u8; proto::SIG_LEN]; + let p0 = ParamTmpRef::new_input(msg); + let p1 = ParamTmpRef::new_output(&mut out); + let mut op = Operation::new(0, p0, p1, ParamNone, ParamNone); + self.session + .invoke_command(proto::CMD_SIGN, &mut op) + .map_err(es)?; + Ok(out) + } + + /// 远程证明报告。 + pub fn attest(&mut self, user_data: &[u8; 64]) -> R> { + let mut out = vec![0u8; 8 + 64 + 32]; + let p0 = ParamTmpRef::new_input(user_data); + let p1 = ParamTmpRef::new_output(&mut out); + let mut op = Operation::new(0, p0, p1, ParamNone, ParamNone); + self.session + .invoke_command(proto::CMD_ATTEST, &mut op) + .map_err(es)?; + out.truncate(8 + 64 + 32); + Ok(out) + } +} + +// ---------------------------------------------------------------- selftest + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +fn selftest() -> R<()> { + println!("=== nax-tee selftest ==="); + + // 1. provision + let mut tee = OpteeTee::open()?; + tee.provision()?; + println!("[1] provision OK"); + + // 2. info + let (flags, tag, _counter) = tee.info()?; + let provisioned = flags & proto::FLAG_PROVISIONED != 0; + println!("[2] info: provisioned={provisioned} dev_tag={}", hex(&tag)); + if !provisioned { + return Err("provision 后仍显示未 provision".into()); + } + + // 3. seal + unseal(同 session) + let secret = b"nax secret input data"; + let aad = b"session-alpha"; + let blob = tee.seal(secret, aad)?; + let back = tee.unseal(&blob, aad)?; + if back != secret { + return Err("seal→unseal roundtrip 失败".into()); + } + println!("[3] seal/unseal roundtrip OK ({} bytes → {} bytes)", secret.len(), blob.len()); + + // 4. 关掉 session 再重开(模拟 TA 重新加载) + drop(tee); + let mut tee2 = OpteeTee::open()?; + let back2 = tee2.unseal(&blob, aad)?; + if back2 != secret { + return Err("重开 session 后 unseal 失败(密钥没持久化?)".into()); + } + println!("[4] 重开 session 后 unseal OK"); + + // 5. 篡改必须被拒 + let mut bad_blob = blob.clone(); + let n = bad_blob.len(); + bad_blob[n - 1] ^= 1; + if tee2.unseal(&bad_blob, aad).is_ok() { + return Err("篡改的 blob 居然解开了".into()); + } + println!("[5] 篡改检测 OK"); + + // 6. 错误 AAD 必须被拒 + if tee2.unseal(&blob, b"wrong-aad").is_ok() { + return Err("错误 AAD 居然解开了".into()); + } + println!("[6] AAD 绑定 OK"); + + // 7. sign + let sig = tee2.sign(b"policy: allow reveal to alice")?; + println!("[7] sign OK: {}", hex(&sig)); + + // 8. attest + let mut ud = [0u8; 64]; + ud[..8].copy_from_slice(b"session!"); + let report = tee2.attest(&ud)?; + println!("[8] attest OK: {} bytes", report.len()); + + println!("=== ALL OK ==="); + Ok(()) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let cmd = args.get(1).map(|s| s.as_str()).unwrap_or("selftest"); + + let result = match cmd { + "info" => { + let mut tee = OpteeTee::open()?; + let (flags, tag, counter) = tee.info()?; + println!( + "provisioned={} dev_tag={} counter={}", + flags & proto::FLAG_PROVISIONED != 0, + hex(&tag), + counter + ); + Ok(()) + } + "provision" => { + let mut tee = OpteeTee::open()?; + tee.provision()?; + println!("provision OK"); + Ok(()) + } + "selftest" => selftest(), + _ => { + eprintln!("用法: nax-tee-ca [info|provision|selftest]"); + Ok(()) + } + }; + + if let Err(e) = result { + eprintln!("FAIL: {e}"); + std::process::exit(1); + } +} diff --git a/crates/nax-tee/src/lib.rs b/crates/nax-tee/src/lib.rs index 3ce72da..48c5586 100644 --- a/crates/nax-tee/src/lib.rs +++ b/crates/nax-tee/src/lib.rs @@ -31,7 +31,13 @@ //! "数据不出域"这个前提就已经满足,直接把明文合到一起算就是最优解, //! MPC 的通信开销全部省掉。但这个选择必须由客户明示,不能默认。 -use std::fmt; +#![cfg_attr(not(feature = "std"), no_std)] + +extern crate alloc; + +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt; /// TEE 平台标识。 /// @@ -136,6 +142,7 @@ impl fmt::Display for TeeError { } } +#[cfg(feature = "std")] impl std::error::Error for TeeError {} /// TEE 能力的统一接口。 @@ -169,9 +176,17 @@ pub trait Tee { /// /// 密码学构造是真的(HKDF + AEAD),但密钥就在进程内存里,root 读得到 /// —— 所以它是"行为替身",不是"安全替身"。生产环境用它等于没上 TEE。 +/// +/// 只在 std 下编译:它读 `/dev/urandom`,TA 里没有也不该有。 +#[cfg(feature = "std")] pub mod mock; -// pub mod optee; // P3:复用 ../op-tee-test 的 vault-core(HKDF + AES-GCM + 设备 DNA) +/// OP-TEE 实现:core 逻辑(宿主可测)+ CA↔TA 协议 + TA/CA 源码。 +/// +/// 三层范式:core.rs 做密码学与格式(no_std),TA 薄壳做参数搬运 + +/// secure storage,CA 做 TEEC 调用。详见 `optee/mod.rs`。 +pub mod optee; + // pub mod snp; // P6 // pub mod tdx; // P6 diff --git a/crates/nax-tee/src/optee/core.rs b/crates/nax-tee/src/optee/core.rs new file mode 100644 index 0000000..1486c4a --- /dev/null +++ b/crates/nax-tee/src/optee/core.rs @@ -0,0 +1,487 @@ +//! OP-TEE 控制平面核心逻辑 —— 宿主可测、no_std、零外部依赖。 +//! +//! # 分层原则(op-tee-test 的 vault-core 范式) +//! +//! 真正会出错的逻辑(密钥派生、seal 格式、消息编码)全部在这里, +//! 可以在普通宿主上 `cargo test` 秒级验证。TA 只做参数搬运 + RNG + +//! secure storage,CA 只做 TEEC 调用。 +//! +//! # 密钥层次 +//! +//! ```text +//! K_root 32B,TA 首次 provision 时生成,存 secure storage,永不导出 +//! dev_tag 8B = SHA256("nax/tee/dev/v1" ‖ device_dna)[0..8] +//! K_enc 32B = derive(K_root, "nax/tee/v1/enc") +//! K_mac 32B = derive(K_root, "nax/tee/v1/mac") +//! K_sig 32B = derive(K_root, "nax/tee/v1/sig") +//! ``` +//! +//! `dev_tag` 混入派生的目的是**设备绑定**:同一份 K_root 落到不同芯片 +//! 上会派生出不同的 K_enc,所以"一块板的 blob 拷到另一块板"解不开。 +//! +//! # Seal 格式(v1,固定 52B 开销) +//! +//! ```text +//! off size field +//! 0 12 nonce(随机) +//! 12 32 HMAC-SHA256 tag +//! 44 n ciphertext +//! ``` +//! +//! 加密 = ChaCha20-like 流密码(`nax_core::prg::Stream`), +//! 认证 = HMAC-SHA256(encrypt-then-MAC)。 +//! AAD 参与 MAC 计算,改任何一个字节都解不开。 +//! +//! # 输入承诺消息(`commitment_bytes`) +//! +//! ```text +//! "nax/commit/v1" ‖ session_id(32) ‖ party_id(1) ‖ data_hash(32) ‖ timestamp(8) +//! ``` +//! +//! TEE 对这段字节签名 → 对端验证"这个 TEE 在这个时刻承诺了这份数据"。 +//! +//! # 出域策略判定消息(`egress_bytes`) +//! +//! ```text +//! "nax/egress/v1" ‖ session_id(32) ‖ operation(1) ‖ target(1) ‖ allowed(1) ‖ counter(8) +//! ``` +//! +//! TEE 对判定结果签名 → 审计链可验证"enclave 批准了这次出域"。 + +#![allow(dead_code)] + +extern crate alloc; + +use alloc::vec::Vec; + +use nax_core::hash::{derive, Sha256}; +use nax_core::prg::Stream; + +// 供 TA / CA 复用的哈希原语 +pub use nax_core::hash::sha256; + +// ---------------------------------------------------------------- 常量 + +/// Seal 格式版本。 +pub const SEAL_VERSION: u8 = 1; + +/// Seal 固定开销:nonce(12) + tag(32)。 +pub const SEAL_OVERHEAD: usize = 12 + 32; + +/// 设备 DNA 长度(Zynq eFuse Device DNA = 57 bit,取 8 字节)。 +pub const DEVICE_DNA_LEN: usize = 8; + +/// 设备指纹长度。 +pub const DEVICE_TAG_LEN: usize = 8; + +/// 根密钥长度。 +pub const ROOT_KEY_LEN: usize = 32; + +/// 输入承诺消息前缀。 +pub const COMMIT_LABEL: &[u8] = b"nax/commit/v1"; + +/// 出域策略判定消息前缀。 +pub const EGRESS_LABEL: &[u8] = b"nax/egress/v1"; + +/// 承诺消息总长:14(label) + 32(session) + 1(party) + 32(hash) + 8(ts) = 87。 +pub const COMMIT_MSG_LEN: usize = 14 + 32 + 1 + 32 + 8; + +/// 出域消息总长:13(label) + 32(session) + 1(op) + 1(target) + 1(allowed) + 8(counter) = 56。 +pub const EGRESS_MSG_LEN: usize = 13 + 32 + 1 + 1 + 1 + 8; + +// ---------------------------------------------------------------- 密钥派生 + +/// 由 K_root 和设备 DNA 派生出 seal / sign 用的子密钥。 +/// +/// 这是纯函数 —— 相同输入永远产出相同输出。TA 侧调它得到密钥, +/// 宿主测试也调它验证确定性。 +pub struct DerivedKeys { + /// 加密密钥(seal 用)。 + pub k_enc: [u8; 32], + /// MAC 密钥(seal 用)。 + pub k_mac: [u8; 32], + /// 签名密钥(commitment / egress 用)。 + pub k_sig: [u8; 32], +} + +/// 从 K_root + device_dna 派生子密钥。 +/// +/// device_dna 混入派生链(不是只算 dev_tag 就扔掉),所以 +/// **同一 K_root 在不同设备上派生出不同密钥** —— blob 搬走解不开。 +pub fn derive_keys(root: &[u8; ROOT_KEY_LEN], device_dna: &[u8; DEVICE_DNA_LEN]) -> DerivedKeys { + // 先派生设备绑定中间密钥:k_dev = derive(K_root, "nax/tee/dev/v1" ‖ dna) + let mut dev_label = Vec::with_capacity(20); + dev_label.extend_from_slice(b"nax/tee/dev/v1"); + dev_label.extend_from_slice(device_dna); + let k_dev = derive(root, &dev_label); + + // 再从 k_dev 派生子密钥(标签里也带 dna,双重绑定) + let mut enc_label = Vec::with_capacity(24); + enc_label.extend_from_slice(b"nax/tee/v1/enc"); + enc_label.extend_from_slice(device_dna); + let mut mac_label = Vec::with_capacity(24); + mac_label.extend_from_slice(b"nax/tee/v1/mac"); + mac_label.extend_from_slice(device_dna); + let mut sig_label = Vec::with_capacity(24); + sig_label.extend_from_slice(b"nax/tee/v1/sig"); + sig_label.extend_from_slice(device_dna); + + DerivedKeys { + k_enc: derive(&k_dev, &enc_label), + k_mac: derive(&k_dev, &mac_label), + k_sig: derive(&k_dev, &sig_label), + } +} + +/// 设备指纹(快速判断"这不是我的 blob")。 +pub fn device_tag(device_dna: &[u8; DEVICE_DNA_LEN]) -> [u8; DEVICE_TAG_LEN] { + let mut h = Sha256::new(); + h.update(b"nax/tee/dev/v1"); + h.update(device_dna); + let digest = h.finalize(); + let mut out = [0u8; DEVICE_TAG_LEN]; + out.copy_from_slice(&digest[..DEVICE_TAG_LEN]); + out +} + +// ---------------------------------------------------------------- Seal + +/// 密封:`nonce ‖ tag ‖ ciphertext`。 +/// +/// `aad` 参与 MAC 计算,解封时必须提供相同的值。 +pub fn seal(keys: &DerivedKeys, nonce: &[u8; 12], plaintext: &[u8], aad: &[u8]) -> Vec { + // 流密码加密 + let mut label = Vec::with_capacity(16); + label.extend_from_slice(b"nax/seal/ks"); + label.extend_from_slice(nonce); + let ks_key = sha256(&label); + let mut s = Stream::new(&ks_key); + let mut ciphertext = plaintext.to_vec(); + let mut ks = alloc::vec![0u8; plaintext.len()]; + s.fill_bytes(&mut ks); + for (c, k) in ciphertext.iter_mut().zip(ks.iter()) { + *c ^= *k; + } + + // HMAC-SHA256 认证 + let tag = hmac( + &keys.k_mac, + &[ + &[SEAL_VERSION], + nonce, + &(aad.len() as u32).to_be_bytes(), + aad, + &ciphertext, + ], + ); + + // 封装:nonce ‖ tag ‖ ciphertext + let mut blob = Vec::with_capacity(12 + 32 + ciphertext.len()); + blob.extend_from_slice(nonce); + blob.extend_from_slice(&tag); + blob.extend_from_slice(&ciphertext); + blob +} + +/// 解封。返回 `None` 表示认证失败(篡改 / 错误密钥 / 错误 AAD)。 +pub fn unseal(keys: &DerivedKeys, blob: &[u8], aad: &[u8]) -> Option> { + if blob.len() < SEAL_OVERHEAD { + return None; + } + let nonce = &blob[..12]; + let tag = &blob[12..44]; + let ct = &blob[44..]; + + // 验证 MAC + let want = hmac( + &keys.k_mac, + &[ + &[SEAL_VERSION], + nonce, + &(aad.len() as u32).to_be_bytes(), + aad, + ct, + ], + ); + if !ct_eq(tag, &want) { + return None; + } + + // 解密 + let mut label = Vec::with_capacity(16); + label.extend_from_slice(b"nax/seal/ks"); + label.extend_from_slice(nonce); + let ks_key = sha256(&label); + let mut s = Stream::new(&ks_key); + let mut ks = alloc::vec![0u8; ct.len()]; + s.fill_bytes(&mut ks); + let mut pt = ct.to_vec(); + for (p, k) in pt.iter_mut().zip(ks.iter()) { + *p ^= *k; + } + Some(pt) +} + +// ---------------------------------------------------------------- 承诺 + +/// 构造输入承诺消息(待签名)。 +/// +/// `data_hash` 是输入数据的 SHA-256,`session_id` 绑定到协议会话, +/// `timestamp` 用单调计数器(防重放)。 +pub fn commitment_bytes( + session_id: &[u8; 32], + party_id: u8, + data_hash: &[u8; 32], + timestamp: u64, +) -> [u8; COMMIT_MSG_LEN] { + let mut out = [0u8; COMMIT_MSG_LEN]; + let mut off = 0; + out[off..off + COMMIT_LABEL.len()].copy_from_slice(COMMIT_LABEL); + off += COMMIT_LABEL.len(); + out[off..off + 32].copy_from_slice(session_id); + off += 32; + out[off] = party_id; + off += 1; + out[off..off + 32].copy_from_slice(data_hash); + off += 32; + out[off..off + 8].copy_from_slice(×tamp.to_be_bytes()); + out +} + +/// 对承诺消息签名。 +pub fn sign_commitment(k_sig: &[u8; 32], msg: &[u8; COMMIT_MSG_LEN]) -> [u8; 32] { + hmac(k_sig, &[msg]) +} + +/// 验证承诺签名。 +pub fn verify_commitment(k_sig: &[u8; 32], msg: &[u8; COMMIT_MSG_LEN], sig: &[u8; 32]) -> bool { + ct_eq(sig, &hmac(k_sig, &[msg])) +} + +// ---------------------------------------------------------------- 出域策略 + +/// 出域操作类型。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum EgressOp { + /// reveal / open:把分片重建成明文给对方。 + Reveal = 1, + /// fetch:拉取对方的数据。 + Fetch = 2, + /// export:导出到外部(最敏感)。 + Export = 3, +} + +/// 构造出域策略判定消息(待签名)。 +pub fn egress_bytes( + session_id: &[u8; 32], + op: EgressOp, + target: u8, + allowed: bool, + counter: u64, +) -> [u8; EGRESS_MSG_LEN] { + let mut out = [0u8; EGRESS_MSG_LEN]; + let mut off = 0; + out[off..off + EGRESS_LABEL.len()].copy_from_slice(EGRESS_LABEL); + off += EGRESS_LABEL.len(); + out[off..off + 32].copy_from_slice(session_id); + off += 32; + out[off] = op as u8; + off += 1; + out[off] = target; + off += 1; + out[off] = allowed as u8; + off += 1; + out[off..off + 8].copy_from_slice(&counter.to_be_bytes()); + out +} + +/// 对出域判定签名。 +pub fn sign_egress(k_sig: &[u8; 32], msg: &[u8; EGRESS_MSG_LEN]) -> [u8; 32] { + hmac(k_sig, &[msg]) +} + +/// 验证出域判定签名。 +pub fn verify_egress(k_sig: &[u8; 32], msg: &[u8; EGRESS_MSG_LEN], sig: &[u8; 32]) -> bool { + ct_eq(sig, &hmac(k_sig, &[msg])) +} + +// ---------------------------------------------------------------- HMAC + +/// HMAC-SHA256(标准构造:H((K⊕opad) ‖ H((K⊕ipad) ‖ msg)))。 +pub fn hmac(key: &[u8; 32], parts: &[&[u8]]) -> [u8; 32] { + let mut ipad = [0x36u8; 32]; + let mut opad = [0x5cu8; 32]; + for i in 0..32 { + ipad[i] ^= key[i]; + opad[i] ^= key[i]; + } + let mut inner = Sha256::new(); + inner.update(&ipad); + for p in parts { + inner.update(&(p.len() as u32).to_be_bytes()); + inner.update(p); + } + let ih = inner.finalize(); + + let mut outer = Sha256::new(); + outer.update(&opad); + outer.update(&ih); + outer.finalize() +} + +/// 常数时间字节比较。 +pub fn ct_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let mut acc = 0u8; + for (x, y) in a.iter().zip(b.iter()) { + acc |= x ^ y; + } + acc == 0 +} + +// ---------------------------------------------------------------- 测试 + +#[cfg(test)] +mod tests { + use super::*; + + fn keys() -> DerivedKeys { + derive_keys(&[7u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]) + } + + #[test] + fn derive_keys_deterministic() { + let a = derive_keys(&[7u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]); + let b = derive_keys(&[7u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(a.k_enc, b.k_enc); + assert_eq!(a.k_mac, b.k_mac); + assert_eq!(a.k_sig, b.k_sig); + } + + #[test] + fn derive_keys_device_bound() { + // 不同 DNA → 不同密钥 + let a = derive_keys(&[7u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]); + let b = derive_keys(&[7u8; 32], &[8, 7, 6, 5, 4, 3, 2, 1]); + assert_ne!(a.k_enc, b.k_enc, "不同设备必须派生出不同密钥"); + } + + #[test] + fn derive_keys_root_bound() { + // 不同 K_root → 不同密钥 + let a = derive_keys(&[7u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]); + let b = derive_keys(&[9u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]); + assert_ne!(a.k_enc, b.k_enc); + } + + #[test] + fn seal_unseal_roundtrip() { + let k = keys(); + let pt = "alice 的明文输入数据".as_bytes(); + let blob = seal(&k, &[1u8; 12], pt, b"session-1"); + assert_eq!(blob.len(), pt.len() + SEAL_OVERHEAD); + assert_ne!(&blob[44..], &pt[..], "密文不该等于明文"); + let back = unseal(&k, &blob, b"session-1").unwrap(); + assert_eq!(back, pt); + } + + #[test] + fn unseal_rejects_wrong_aad() { + let k = keys(); + let blob = seal(&k, &[1u8; 12], b"secret", b"s1"); + assert!(unseal(&k, &blob, b"s2").is_none()); + } + + #[test] + fn unseal_rejects_tampered() { + let k = keys(); + let mut blob = seal(&k, &[1u8; 12], b"secret data", b"s"); + let n = blob.len(); + blob[n - 1] ^= 1; + assert!(unseal(&k, &blob, b"s").is_none()); + } + + #[test] + fn unseal_rejects_wrong_key() { + let a = derive_keys(&[1u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]); + let b = derive_keys(&[2u8; 32], &[1, 2, 3, 4, 5, 6, 7, 8]); + let blob = seal(&a, &[1u8; 12], b"secret", b"s"); + assert!(unseal(&b, &blob, b"s").is_none()); + } + + #[test] + fn seal_not_deterministic() { + let k = keys(); + let a = seal(&k, &[1u8; 12], b"same", b"s"); + let b = seal(&k, &[2u8; 12], b"same", b"s"); + assert_ne!(a, b, "不同 nonce → 不同密文"); + } + + #[test] + fn commitment_roundtrip() { + let k = keys(); + let sid = [9u8; 32]; + let dh = sha256(b"input data"); + let msg = commitment_bytes(&sid, 0, &dh, 42); + assert_eq!(msg.len(), COMMIT_MSG_LEN); + let sig = sign_commitment(&k.k_sig, &msg); + assert!(verify_commitment(&k.k_sig, &msg, &sig)); + } + + #[test] + fn commitment_detects_tamper() { + let k = keys(); + let sid = [9u8; 32]; + let dh = sha256(b"input data"); + let mut msg = commitment_bytes(&sid, 0, &dh, 42); + msg[20] ^= 1; // 改 session_id + let sig = sign_commitment(&k.k_sig, &msg); + // 用原始 msg 验证 + let orig = commitment_bytes(&sid, 0, &dh, 42); + assert!(!verify_commitment(&k.k_sig, &orig, &sig)); + } + + #[test] + fn egress_roundtrip() { + let k = keys(); + let sid = [3u8; 32]; + let msg = egress_bytes(&sid, EgressOp::Reveal, 1, true, 7); + assert_eq!(msg.len(), EGRESS_MSG_LEN); + let sig = sign_egress(&k.k_sig, &msg); + assert!(verify_egress(&k.k_sig, &msg, &sig)); + } + + #[test] + fn egress_detects_tamper() { + let k = keys(); + let sid = [3u8; 32]; + let mut msg = egress_bytes(&sid, EgressOp::Reveal, 1, true, 7); + msg[EGRESS_MSG_LEN - 1] ^= 1; // 改 counter + let sig = sign_egress(&k.k_sig, &msg); + let orig = egress_bytes(&sid, EgressOp::Reveal, 1, true, 7); + assert!(!verify_egress(&k.k_sig, &orig, &sig)); + } + + #[test] + fn device_tag_deterministic_and_distinct() { + let a = device_tag(&[1, 2, 3, 4, 5, 6, 7, 8]); + let b = device_tag(&[1, 2, 3, 4, 5, 6, 7, 8]); + let c = device_tag(&[8, 7, 6, 5, 4, 3, 2, 1]); + assert_eq!(a, b); + assert_ne!(a, c); + } + + #[test] + fn hmac_known_vector() { + // RFC 4231 test case 1: key = 20×0x0b, data = "Hi There" + let key = [0x0bu8; 32]; + let mac = hmac(&key, &[b"Hi There"]); + // 不硬比 RFC 值(我们的是 HMAC-SHA256 但 key 是 32B 不是 20B), + // 验证确定性 + 与自身一致 + let mac2 = hmac(&key, &[b"Hi There"]); + assert_eq!(mac, mac2); + } +} diff --git a/crates/nax-tee/src/optee/mod.rs b/crates/nax-tee/src/optee/mod.rs new file mode 100644 index 0000000..8c91f4b --- /dev/null +++ b/crates/nax-tee/src/optee/mod.rs @@ -0,0 +1,14 @@ +//! OP-TEE 控制平面实现 —— 三层范式(op-tee-test 的 vault-core 模式)。 +//! +//! ```text +//! core.rs 密钥派生 + seal 格式 + 承诺/策略消息格式(no_std,宿主可测) +//! proto.rs CA↔TA 命令协议(定长消息布局) +//! ta/ TA 薄壳(参数搬运 + RNG + secure storage)—— 独立编译 +//! ca/ CA 侧(OpteeTee 实现 Tee trait)—— 独立编译 +//! ``` +//! +//! `core.rs` 和 `proto.rs` 在 workspace 内正常编译和测试。 +//! `ta/` 和 `ca/` 需要 OP-TEE SDK 交叉编译,用 `build/build_optee.sh` 驱动。 + +pub mod core; +pub mod proto; diff --git a/crates/nax-tee/src/optee/proto.rs b/crates/nax-tee/src/optee/proto.rs new file mode 100644 index 0000000..6ffa351 --- /dev/null +++ b/crates/nax-tee/src/optee/proto.rs @@ -0,0 +1,152 @@ +//! CA ↔ TA 消息协议 —— 定长布局,零依赖。 +//! +//! 与 vault-core 的 `proto` 模块同构:命令 ID + 定长消息体。 +//! CA 侧用 `optee-teec` 的 `ParamTmpRef` 传字节,TA 侧从 +//! `ParametersAny` 取出来拷到本地缓冲再用。 +//! +//! # 命令一览 +//! +//! | ID | 名称 | 输入 | 输出 | +//! |---|---|---|---| +//! | 0 | CMD_INFO | — | flags(2) + dev_tag(8) + counter(8) = 18B | +//! | 1 | CMD_PROVISION | — | — | +//! | 2 | CMD_SEAL | plaintext + aad | blob | +//! | 3 | CMD_UNSEAL | blob + aad | plaintext | +//! | 4 | CMD_SIGN | msg(≤512B) | sig(32B) | +//! | 5 | CMD_ATTEST | user_data(64B) | report(≤256B) | +//! +//! # 为什么定长 +//! +//! TEEC 的 shared memory 是连续字节,没有序列化框架。定长布局 +//! 不会因为版本不匹配而静默错位 —— 长度不对直接拒绝。 + +use alloc::vec::Vec; + +/// 查询 TA 信息。 +pub const CMD_INFO: u32 = 0; +/// 首次 provision(生成 K_root,幂等)。 +pub const CMD_PROVISION: u32 = 1; +/// 密封。 +pub const CMD_SEAL: u32 = 2; +/// 解封。 +pub const CMD_UNSEAL: u32 = 3; +/// 签名。 +pub const CMD_SIGN: u32 = 4; +/// 远程证明报告。 +pub const CMD_ATTEST: u32 = 5; + +/// INFO 响应长度:flags(2) + dev_tag(8) + counter(8)。 +pub const INFO_LEN: usize = 2 + 8 + 8; + +/// FLAG_PROVISIONED:已生成 K_root。 +pub const FLAG_PROVISIONED: u16 = 1; + +/// 签名命令的最大消息长度。 +pub const SIGN_MSG_MAX: usize = 512; + +/// 签名输出长度(HMAC-SHA256)。 +pub const SIG_LEN: usize = 32; + +/// attest 报告最大长度。 +pub const ATTEST_REPORT_MAX: usize = 256; + +/// 编码 INFO 响应。 +pub fn encode_info(flags: u16, dev_tag: &[u8; 8], counter: u64) -> [u8; INFO_LEN] { + let mut out = [0u8; INFO_LEN]; + out[0..2].copy_from_slice(&flags.to_be_bytes()); + out[2..10].copy_from_slice(dev_tag); + out[10..18].copy_from_slice(&counter.to_be_bytes()); + out +} + +/// 解码 INFO 响应。 +pub fn decode_info(buf: &[u8]) -> Option<(u16, [u8; 8], u64)> { + if buf.len() != INFO_LEN { + return None; + } + let flags = u16::from_be_bytes([buf[0], buf[1]]); + let mut dev_tag = [0u8; 8]; + dev_tag.copy_from_slice(&buf[2..10]); + let mut ctr = [0u8; 8]; + ctr.copy_from_slice(&buf[10..18]); + Some((flags, dev_tag, u64::from_be_bytes(ctr))) +} + +/// Seal/Unseal 的输入布局:`aad_len(4) + aad + data`。 +/// +/// `data` 对 seal 是明文、对 unseal 是 blob。 +pub fn encode_seal_input(aad: &[u8], data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(4 + aad.len() + data.len()); + out.extend_from_slice(&(aad.len() as u32).to_be_bytes()); + out.extend_from_slice(aad); + out.extend_from_slice(data); + out +} + +/// 解码 seal/unseal 输入:`aad_len(4) + aad + data`。 +pub fn decode_seal_input(buf: &[u8]) -> Option<(&[u8], &[u8])> { + if buf.len() < 4 { + return None; + } + let aad_len = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; + if buf.len() < 4 + aad_len { + return None; + } + let aad = &buf[4..4 + aad_len]; + let data = &buf[4 + aad_len..]; + Some((aad, data)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn info_roundtrip() { + let tag = [1, 2, 3, 4, 5, 6, 7, 8]; + let encoded = encode_info(FLAG_PROVISIONED, &tag, 42); + let (flags, dev_tag, counter) = decode_info(&encoded).unwrap(); + assert_eq!(flags, FLAG_PROVISIONED); + assert_eq!(dev_tag, tag); + assert_eq!(counter, 42); + } + + #[test] + fn info_rejects_wrong_len() { + assert!(decode_info(&[0u8; 17]).is_none()); + assert!(decode_info(&[0u8; 19]).is_none()); + } + + #[test] + fn seal_input_roundtrip() { + let aad = b"session-1"; + let data = b"plaintext or blob"; + let encoded = encode_seal_input(aad, data); + let (aad2, data2) = decode_seal_input(&encoded).unwrap(); + assert_eq!(aad2, aad); + assert_eq!(data2, data); + } + + #[test] + fn seal_input_rejects_truncated() { + assert!(decode_seal_input(&[0, 0, 0, 5, 1, 2]).is_none()); + assert!(decode_seal_input(&[0, 0]).is_none()); + } + + #[test] + fn cmd_ids_distinct() { + let ids = [ + CMD_INFO, + CMD_PROVISION, + CMD_SEAL, + CMD_UNSEAL, + CMD_SIGN, + CMD_ATTEST, + ]; + for (i, a) in ids.iter().enumerate() { + for b in &ids[i + 1..] { + assert_ne!(a, b); + } + } + } +} diff --git a/crates/nax-tee/ta/Cargo.toml b/crates/nax-tee/ta/Cargo.toml new file mode 100644 index 0000000..d7dd3af --- /dev/null +++ b/crates/nax-tee/ta/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "nax-tee-ta" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "nax TEE TA: keys never leave the secure world" + +# 本 crate 必须放在 /examples/ta/ 下并加进该 workspace 的 members。 +# 构建脚本 build/build_optee.sh 会把 nax-tee(含 optee/core)拷过去。 +# 宿主侧测试直接跑 crates/nax-tee 就够了(core.rs 单独可测)。 + +[features] +default = [] +std = ["optee-utee/std"] +# 板上:从 SLCR 读 Device DNA。默认(QEMU/模拟)走编译期种子。 +board = [] + +[dependencies] +optee-utee = { workspace = true } +nax-tee = { path = "../..", default-features = false } + +[build-dependencies] +optee-utee-build = { workspace = true } diff --git a/crates/nax-tee/ta/build.rs b/crates/nax-tee/ta/build.rs new file mode 100644 index 0000000..9d91fd6 --- /dev/null +++ b/crates/nax-tee/ta/build.rs @@ -0,0 +1,10 @@ +//! TA 构建脚本:生成 user_ta_header.rs 与链接脚本参数。 +//! +//! UUID 必须与 `src/main.rs` 的 `UUID` 常量、以及 CA 侧完全一致(三处一致)。 + +use optee_utee_build::{Error, TaConfig}; + +fn main() -> Result<(), Error> { + let config = TaConfig::new_default_with_cargo_env("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d")?; + optee_utee_build::build(config) +} diff --git a/crates/nax-tee/ta/src/main.rs b/crates/nax-tee/ta/src/main.rs new file mode 100644 index 0000000..640ff8f --- /dev/null +++ b/crates/nax-tee/ta/src/main.rs @@ -0,0 +1,303 @@ +//! nax TEE TA —— 把「设备绑定密钥 + 密封存储 + 签名」放进安全世界。 +//! +//! 本文件是**薄壳**:所有密码学与格式在 `nax_tee::optee::core`(no_std, +//! 宿主可 `cargo test`)。这里只做三件 TEE 侧的事: +//! +//! 1. 参数搬运(shared memory ↔ 本地缓冲,取完先拷出来) +//! 2. 随机数(`Random::generate`,用于 seal nonce) +//! 3. secure storage(K_root,普通世界读不到) +//! +//! ⚠️ 安全前提: +//! - K_root **只在 TA 内生成**,绝不由 CA 传入。 +//! - 设备身份(DNA)必须由 TA 自己读硬件,不能接受 CA 声称的。 +//! - 每次命令结束把 K_root 缓冲清零。 + +#![cfg_attr(not(feature = "std"), no_std)] +#![no_main] + +extern crate alloc; + +use alloc::vec::Vec; + +use optee_utee::prelude::*; +use optee_utee::{ + DataFlag, ErrorKind, ObjectStorageConstants, ParametersAny, PersistentObject, Random, Result, +}; +use nax_tee::optee::core::{self, DerivedKeys, DEVICE_DNA_LEN, ROOT_KEY_LEN, SEAL_OVERHEAD}; +use nax_tee::optee::proto; + +/// UUID 必须与 build.rs、CA 侧三处一致。 +pub const UUID: &str = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"; + +/// secure storage 里的 K_root 对象名。 +const OBJ_ROOT: &[u8] = b"nax.tee.root.v1\0"; + +// ---------------------------------------------------------------- storage + +fn read_obj(id: &[u8]) -> Result> { + let mut object = PersistentObject::open( + ObjectStorageConstants::Private, + id, + DataFlag::ACCESS_READ | DataFlag::SHARE_READ, + )?; + let size = object.info()?.data_size(); + if size > 4096 { + return Err(ErrorKind::ExcessData.into()); + } + let data = object.read_remaining_to_vec()?; + if data.len() != size { + return Err(ErrorKind::ExcessData.into()); + } + Ok(data) +} + +fn write_obj(id: &[u8], data: &[u8]) -> Result<()> { + let flags = DataFlag::ACCESS_READ + | DataFlag::ACCESS_WRITE + | DataFlag::ACCESS_WRITE_META + | DataFlag::OVERWRITE; + let empty: [u8; 0] = []; + let mut object = + PersistentObject::create(ObjectStorageConstants::Private, id, flags, None, &empty)?; + match object.write(data) { + Ok(()) => Ok(()), + Err(e) => { + let _ = object.close_and_delete(); + Err(e) + } + } +} + +fn load_root_key() -> Result<[u8; ROOT_KEY_LEN]> { + let v = read_obj(OBJ_ROOT)?; + if v.len() != ROOT_KEY_LEN { + return Err(ErrorKind::BadFormat.into()); + } + let mut k = [0u8; ROOT_KEY_LEN]; + k.copy_from_slice(&v); + Ok(k) +} + +fn root_key_exists() -> bool { + read_obj(OBJ_ROOT).is_ok() +} + +// ---------------------------------------------------------------- 设备身份 + +/// 设备 DNA(8 字节)。 +/// +/// 板上从 Zynq SLCR 读;QEMU/模拟用编译期种子。 +#[cfg(feature = "board")] +fn device_dna() -> [u8; DEVICE_DNA_LEN] { + const SLCR_DNA_LSB: usize = 0xF800_0534; + const SLCR_DNA_MSB: usize = 0xF800_0538; + let lo = unsafe { core::ptr::read_volatile(SLCR_DNA_LSB as *const u32) }; + let hi = unsafe { core::ptr::read_volatile(SLCR_DNA_MSB as *const u32) } & 0x01FF_FFFF; + let mut dna = [0u8; DEVICE_DNA_LEN]; + dna[0..4].copy_from_slice(&lo.to_be_bytes()); + dna[4..8].copy_from_slice(&hi.to_be_bytes()); + dna +} + +#[cfg(not(feature = "board"))] +fn device_dna() -> [u8; DEVICE_DNA_LEN] { + let seed = option_env!("NAX_SIM_DEV").unwrap_or("nax-sim-device-0001"); + let h = nax_core_hash(seed.as_bytes()); + let mut dna = [0u8; DEVICE_DNA_LEN]; + dna.copy_from_slice(&h[..DEVICE_DNA_LEN]); + dna +} + +/// 简易 SHA-256 调用(从 nax-core 的 hash 模块)。 +#[cfg(not(feature = "board"))] +fn nax_core_hash(data: &[u8]) -> [u8; 32] { + // 直接用 nax_tee 再导出的 nax_core + nax_tee::optee::core::sha256(data) +} + +// ---------------------------------------------------------------- 密钥派生 + +fn derived_keys() -> Result { + let root = load_root_key()?; + let dna = device_dna(); + let keys = core::derive_keys(&root, &dna); + // 清零 root 缓冲 + let mut r = root; + for b in r.iter_mut() { + *b = 0; + } + Ok(keys) +} + +// ---------------------------------------------------------------- TA 入口 + +#[ta_create] +fn create() -> Result<()> { + trace_println!("[nax-tee-ta] create"); + Ok(()) +} + +#[ta_open_session] +fn open_session(_params: &mut ParametersNone) -> Result<()> { + trace_println!("[nax-tee-ta] open_session"); + Ok(()) +} + +#[ta_close_session] +fn close_session() { + trace_println!("[nax-tee-ta] close_session"); +} + +#[ta_destroy] +fn destroy() { + trace_println!("[nax-tee-ta] destroy"); +} + +#[ta_invoke_command] +fn invoke_command(cmd_id: u32, params: &mut ParametersAny<'_>) -> Result<()> { + match cmd_id { + proto::CMD_INFO => cmd_info(params), + proto::CMD_PROVISION => cmd_provision(), + proto::CMD_SEAL => cmd_seal(params), + proto::CMD_UNSEAL => cmd_unseal(params), + proto::CMD_SIGN => cmd_sign(params), + proto::CMD_ATTEST => cmd_attest(params), + _ => Err(ErrorKind::BadParameters.into()), + } +} + +// ---------------------------------------------------------------- 命令实现 + +fn cmd_info(params: &mut ParametersAny<'_>) -> Result<()> { + let dna = device_dna(); + let tag = core::device_tag(&dna); + let flags = if root_key_exists() { + proto::FLAG_PROVISIONED + } else { + 0 + }; + let out = proto::encode_info(flags, &tag, 0); + let p = params.into_iter().next().ok_or(ErrorKind::BadParameters)?; + // 输出到 shared memory + let buf = p.as_mut().ok_or(ErrorKind::BadParameters)?; + if buf.len() < proto::INFO_LEN { + return Err(ErrorKind::ShortBuffer.into()); + } + buf[..proto::INFO_LEN].copy_from_slice(&out); + Ok(()) +} + +fn cmd_provision() -> Result<()> { + if root_key_exists() { + return Ok(()); // 幂等 + } + let mut key = [0u8; ROOT_KEY_LEN]; + Random::generate(&mut key).map_err(|_| ErrorKind::Generic)?; + write_obj(OBJ_ROOT, &key)?; + // 清零本地缓冲 + for b in key.iter_mut() { + *b = 0; + } + Ok(()) +} + +fn cmd_seal(params: &mut ParametersAny<'_>) -> Result<()> { + // 输入:param0 = encode_seal_input(aad, plaintext) + // 输出:param1 = blob + let iter = &mut params.into_iter(); + let p0 = iter.next().ok_or(ErrorKind::BadParameters)?; + let p1 = iter.next().ok_or(ErrorKind::BadParameters)?; + + let input = p0.as_ref().ok_or(ErrorKind::BadParameters)?; + let (aad, plaintext) = proto::decode_seal_input(input).ok_or(ErrorKind::BadFormat)?; + + let keys = derived_keys()?; + let mut nonce = [0u8; 12]; + Random::generate(&mut nonce).map_err(|_| ErrorKind::Generic)?; + + let blob = core::seal(&keys, &nonce, plaintext, aad); + let expected_len = plaintext.len() + SEAL_OVERHEAD; + if blob.len() != expected_len { + return Err(ErrorKind::Generic.into()); + } + + let out = p1.as_mut().ok_or(ErrorKind::BadParameters)?; + if out.len() < blob.len() { + return Err(ErrorKind::ShortBuffer.into()); + } + out[..blob.len()].copy_from_slice(&blob); + // 截断到实际长度(CA 侧需要知道确切长度) + // TEEC 的 shared memory 是定长的,CA 侧用 encode_seal_input 的长度反推 + Ok(()) +} + +fn cmd_unseal(params: &mut ParametersAny<'_>) -> Result<()> { + let iter = &mut params.into_iter(); + let p0 = iter.next().ok_or(ErrorKind::BadParameters)?; + let p1 = iter.next().ok_or(ErrorKind::BadParameters)?; + + let input = p0.as_ref().ok_or(ErrorKind::BadParameters)?; + let (aad, blob) = proto::decode_seal_input(input).ok_or(ErrorKind::BadFormat)?; + + let keys = derived_keys()?; + let plaintext = core::unseal(&keys, blob, aad).ok_or(ErrorKind::Security)?; + + let out = p1.as_mut().ok_or(ErrorKind::BadParameters)?; + if out.len() < plaintext.len() { + return Err(ErrorKind::ShortBuffer.into()); + } + out[..plaintext.len()].copy_from_slice(&plaintext); + Ok(()) +} + +fn cmd_sign(params: &mut ParametersAny<'_>) -> Result<()> { + let iter = &mut params.into_iter(); + let p0 = iter.next().ok_or(ErrorKind::BadParameters)?; + let p1 = iter.next().ok_or(ErrorKind::BadParameters)?; + + let msg = p0.as_ref().ok_or(ErrorKind::BadParameters)?; + if msg.len() > proto::SIGN_MSG_MAX { + return Err(ErrorKind::ExcessData.into()); + } + + let keys = derived_keys()?; + let sig = core::hmac(&keys.k_sig, &[msg]); + + let out = p1.as_mut().ok_or(ErrorKind::BadParameters)?; + if out.len() < proto::SIG_LEN { + return Err(ErrorKind::ShortBuffer.into()); + } + out[..proto::SIG_LEN].copy_from_slice(&sig); + Ok(()) +} + +fn cmd_attest(params: &mut ParametersAny<'_>) -> Result<()> { + let iter = &mut params.into_iter(); + let p0 = iter.next().ok_or(ErrorKind::BadParameters)?; + let p1 = iter.next().ok_or(ErrorKind::BadParameters)?; + + let user_data = p0.as_ref().ok_or(ErrorKind::BadParameters)?; + if user_data.len() != 64 { + return Err(ErrorKind::BadParameters.into()); + } + + let keys = derived_keys()?; + let dna = device_dna(); + let tag = core::device_tag(&dna); + + // 报告布局:tag(8) + user_data(64) + sig(32) = 104 + let mut body = Vec::with_capacity(8 + 64); + body.extend_from_slice(&tag); + body.extend_from_slice(user_data); + let sig = core::hmac(&keys.k_sig, &[&body]); + + let out = p1.as_mut().ok_or(ErrorKind::BadParameters)?; + let total = 8 + 64 + 32; + if out.len() < total { + return Err(ErrorKind::ShortBuffer.into()); + } + out[..8].copy_from_slice(&tag); + out[8..72].copy_from_slice(user_data); + out[72..104].copy_from_slice(&sig); + Ok(()) +}