From e983a1a4ab0ace558f191f5828fd3815be8f5034 Mon Sep 17 00:00:00 2001 From: rong Date: Fri, 30 Oct 2026 01:08:49 +0800 Subject: [PATCH] =?UTF-8?q?fix(p3-qemu):=20P3=20QEMU=20=E5=85=A8=E9=93=BE?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E9=80=9A=E8=BF=87=EF=BC=88ALL=20OK=EF=BC=89?= =?UTF-8?q?=E2=80=94=E2=80=94=20TA=20user=5Fta=5Fheader=20include=20+=20CA?= =?UTF-8?q?=20=E7=BC=96=E8=AF=91=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TA main.rs 删手写 #[no_mangle] 弱符号,改 include! $OUT_DIR/user_ta_header.rs (ta_head/ta_heap/ta_props/trace_* 全套由 optee-utee-build 生成,官方示例 aes-rs 同款;手写与生成定义冲突,漏写则链接器逐个 undefined) - ta/ca Cargo.toml 的 package 字段显式写死 version/edition/license,不再 workspace 继承(teaclave examples/ca 的 workspace.package 无 edition) - ca main.rs 命令分发挪进 fn run() -> R<()>,main 只收尾(? 不能用在 返回 () 的 main,E0277 x4) - p3_optee_qemu.sh / run_qemu.py:USTC apt/cargo/rustup 镜像、显式 commands.run 超时、traffic token 落盘、ghfast.top clone 回退等 判据:QEMU 正常世界 nax-tee-ca selftest 全 8 步通过(provision -> seal/unseal -> 重开 session -> 篡改拒 -> AAD 绑定 -> sign -> attest), sw.log 两条 ffff000f Security 拒绝为预期篡改/AAD 检测,NAX_RC=0。 宿主侧 cargo test --workspace 129 全绿。 --- build/p3_optee_qemu.sh | 59 ++++++++++-- build/run_qemu.py | 137 +++++++++++++++----------- crates/nax-tee/ca/Cargo.toml | 8 +- crates/nax-tee/ca/src/main.rs | 12 ++- crates/nax-tee/ta/Cargo.toml | 8 +- crates/nax-tee/ta/src/main.rs | 177 ++++++++++++++++++++++------------ 6 files changed, 268 insertions(+), 133 deletions(-) diff --git a/build/p3_optee_qemu.sh b/build/p3_optee_qemu.sh index 4c2c202..7319a5a 100755 --- a/build/p3_optee_qemu.sh +++ b/build/p3_optee_qemu.sh @@ -10,8 +10,8 @@ # ============================================================================ set -euo pipefail export DEBIAN_FRONTEND=noninteractive -export PATH=/opt/cargo/bin:/usr/bin:/bin:/usr/sbin:/sbin -export PYTHON3=/usr/bin/python3 +export PATH=/opt/cargo/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +export PYTHON3=$(which python3 2>/dev/null || echo /usr/local/bin/python3) export CROSS_COMPILE=arm-linux-gnueabihf- export AARCH32_CROSS_COMPILE=arm-linux-gnueabihf- export RUSTUP_HOME=/opt/rustup @@ -22,6 +22,19 @@ 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 +# crates.io 走 USTC sparse 镜像(沙箱直连 crates.io 超时,2026-10-29 实测) +mkdir -p /opt/cargo +cat > /opt/cargo/config.toml <<'CARGOCFG' +[source.crates-io] +replace-with = 'ustc' + +[source.ustc] +registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/" + +[net] +retry = 5 +CARGOCFG + NAX_UUID="a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" W=/root SRC=${SRC:-$W/src} @@ -29,17 +42,33 @@ JOBS=$(nproc) cd $W # ---------------- 1. 依赖 ---------------- -apt-get update -qq -apt-get install -y -qq --no-install-recommends \ +echo "STEP1: apt-get" +# Debian 12: apt 源在 debian.sources(不是 sources.list),换 USTC 镜像 +sed -i 's|http://deb.debian.org|https://mirrors.ustc.edu.cn|g; s|http://security.debian.org|https://mirrors.ustc.edu.cn/debian-security|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null +timeout 120 apt-get update -qq 2>&1 | tail -3 || echo "apt update skipped" +timeout 300 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 + swig python3-dev libncurses-dev 2>&1 | tail -5 +echo "CHECK: gcc=$(which gcc 2>/dev/null||echo MISSING) arm-gcc=$(which arm-linux-gnueabihf-gcc 2>/dev/null||echo MISSING) python3=$(which python3 2>/dev/null||echo MISSING) dtc=$(which dtc 2>/dev/null||echo MISSING)" +# python3 模块安装到 $PYTHON3(apt 装的是系统 Python,build 用的是 /usr/local/bin/python3) +$PYTHON3 -m pip install --quiet --break-system-packages cryptography pyelftools 2>&1 | tail -3 || true +$PYTHON3 -c "import cryptography, elftools; print('python deps OK')" 2>/dev/null \ + || { echo "pip failed, trying ensurepip"; $PYTHON3 -m ensurepip --default-pip 2>/dev/null; $PYTHON3 -m pip install --quiet cryptography pyelftools 2>/dev/null; } +$PYTHON3 -c "import cryptography, elftools; print('python deps OK')" 2>/dev/null || echo "WARN: python deps incomplete" +echo "STEP1_DONE" # ---------------- 2. 源码 ---------------- +echo "STEP2: clone sources" +# 清理残留(上次 kill 可能留半截目录) +for d in optee_os optee_client optee-build u-boot trusted-firmware-a teaclave-sdk linux; do + [ -d "$d" ] && { [ ! -f "$d/Makefile" ] && [ ! -f "$d/Cargo.toml" ] && [ ! -f "$d/Makefile.am" ] && rm -rf "$d" || true; } +done 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" + # ghfast.top 优先(GitHub 直连超时 133s,2026-10-29 实测),失败再直连 + git -c http.version=HTTP/1.1 clone -q --depth 1 ${3:+--branch $3} "https://ghfast.top/$1" "$2" \ + || git -c http.version=HTTP/1.1 clone -q --depth 1 ${3:+--branch $3} "$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 @@ -59,6 +88,7 @@ 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 工具链 ---------------- +echo "STEP3: rust toolchain" 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 @@ -70,6 +100,7 @@ fi export RUSTUP_TOOLCHAIN=nightly-2026-08-05 # ---------------- 4. optee_os + u-boot + ATF ---------------- +echo "STEP4: 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) @@ -77,6 +108,7 @@ 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. 内核 ---------------- +echo "STEP5: linux kernel" cd $W/linux make ARCH=arm vexpress_defconfig >/dev/null cat > /tmp/optee.frag <<'FRAG' @@ -95,12 +127,14 @@ grep -q '^CONFIG_OPTEE=y' .config || { echo "OPTEE 配置没生效"; exit 1; } make ARCH=arm -j"$JOBS" zImage # ---------------- 6. optee_client ---------------- +echo "STEP6: 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 ---------------- +echo "STEP7: nax-tee TA + CA" [ -d "$SRC/nax-core" ] || { echo "找不到 $SRC/nax-core"; exit 1; } [ -d "$SRC/nax-tee" ] || { echo "找不到 $SRC/nax-tee"; exit 1; } @@ -118,6 +152,15 @@ for ws in ta ca; do $W/teaclave-sdk/examples/$ws/nax-tee/Cargo.toml done +# 关键:nax-core / nax-tee 的 default = ["std"] 在 teaclave workspace 里会被 +# workspace 成员编译激活 → std 的 panic_impl 与 optee_utee 的冲突(E0152)。 +# 拷过去后把 default 改成 [],让 TA 侧始终走 no_std 路径。 +for ws in ta ca; do + sed -i 's|^default = \["std"\]|default = []|' \ + $W/teaclave-sdk/examples/$ws/nax-core/Cargo.toml \ + $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 @@ -163,6 +206,7 @@ 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 ---------------- +echo "STEP8: 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 @@ -220,6 +264,7 @@ DTB dtc -I dts -O dtb -o virt-optee.dtb v2.dts 2>/dev/null # ---------------- 10. 跑 QEMU ---------------- +echo "STEP10: run 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 \ diff --git a/build/run_qemu.py b/build/run_qemu.py index dd5f8ff..4f670f3 100644 --- a/build/run_qemu.py +++ b/build/run_qemu.py @@ -4,10 +4,9 @@ 用法(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 实测有效)。 +⚠ cube-auth-gate/2.0 的兼容补丁:强制 Accept-Encoding: identity。 +⚠ SDK commands.run() 默认 read=None,必须显式设 timeout。 +⚠ traffic token 只在 create 返回一次,立即落盘备用。 """ import os import sys @@ -19,7 +18,6 @@ os.environ.setdefault("CUBE_PROXY_PORT_HTTP", "80") import requests as _requests -# --- 兼容补丁:强制 Accept-Encoding: identity --- _orig_req = _requests.Session.request @@ -31,7 +29,7 @@ def _req_no_gzip(self, method, url, **kw): _requests.Session.request = _req_no_gzip -try: # 数据面走 httpx,同样处理 +try: import httpx as _httpx _orig_hreq = _httpx.Client.request @@ -48,10 +46,10 @@ except Exception: from cubesandbox import Sandbox REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BUILD_TIMEOUT = 3600 # 前台跑构建,最多 60 分钟 def make_src_tgz() -> bytes: - """把 nax-core / nax-tee / p3 脚本打成一个 tar.gz,单次上传。""" import io import tarfile @@ -72,71 +70,96 @@ def make_src_tgz() -> bytes: return buf.getvalue() +def run_cmd(sb, cmd, timeout=30): + """带超时的命令执行,打印 stderr 便于调试。""" + r = sb.commands.run(cmd, timeout=timeout) + if r.stdout.strip(): + print(r.stdout.rstrip(), flush=True) + if r.stderr.strip(): + print(f" [stderr] {r.stderr.rstrip()[:200]}", flush=True) + return r + + def main(): - print("== 创建 toolchain 沙箱 (16C/16G, 2h 生命周期) ==") + print("== 创建 toolchain 沙箱 (16C/16G, 2h) ==", flush=True) sb = Sandbox.create( template="toolchain", timeout=7200, network={"allow_public_traffic": False} ) - print(f" sandbox_id = {sb.sandbox_id}") + print(f" sandbox_id = {sb.sandbox_id}", flush=True) + + token = sb._data.get("trafficAccessToken", "") + token_file = f"/tmp/sb_token_{sb.sandbox_id}.txt" + with open(token_file, "w") as f: + f.write(token) + print(f" token → {token_file}", flush=True) try: - # 上传源码(单 tar 包) - print("== 打包并上传源码 ==") + # 上传 + print("== 上传源码 ==", flush=True) tgz = make_src_tgz() - print(f" src.tgz = {len(tgz) / 1e6:.2f} MB") - sb.commands.run("mkdir -p /root/src") + print(f" src.tgz = {len(tgz) / 1e6:.2f} MB", flush=True) + run_cmd(sb, "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", " ")) + run_cmd(sb, "tar xzf /root/src/src.tgz -C /root/src && ls /root/src") - 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) + # 前台跑构建(不 nohup),输出直接打出来 + print("== 构建开始(前台,最多 60 分钟)==", flush=True) + t0 = time.time() + try: r = sb.commands.run( - "test -f /root/build.rc && cat /root/build.rc || echo running" + "cd /root && SRC=/root/src/crates bash /root/src/p3_optee_qemu.sh; echo EXIT_CODE=$?", + timeout=BUILD_TIMEOUT, ) - 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 + print(r.stdout[-3000:] if len(r.stdout) > 3000 else r.stdout, flush=True) + if r.stderr.strip(): + print(f"[stderr] {r.stderr[-1000:]}", flush=True) + except Exception as e: + elapsed = int(time.time() - t0) + print(f"\n⚠ 构建异常 ({elapsed}s): {e}", flush=True) + # 尝试取日志 + try: + r2 = sb.commands.run("tail -30 /root/build.log 2>/dev/null", timeout=15) + print("build.log 尾部:", flush=True) + print(r2.stdout, flush=True) + except Exception: + pass - if not finished: - print("⚠ 45 分钟未结束,取当前日志") + elapsed = int(time.time() - t0) + print(f"\n== 构建耗时 {elapsed}s ==", flush=True) - # 读完整日志 - print("== 构建日志尾部 ==") - r = sb.commands.run("tail -60 /root/build.log") - print(r.stdout) + # 检查判据 + try: + r = sb.commands.run("tail -40 /root/run/nw.log 2>/dev/null", timeout=15) + if r.stdout.strip(): + print("正常世界日志:", flush=True) + print(r.stdout, flush=True) + except Exception: + pass - # 检查结果: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 + # 判据:ALL OK 在 nw.log + try: + r = sb.commands.run("grep -c 'ALL OK' /root/run/nw.log 2>/dev/null", timeout=10) + count = r.stdout.strip() + if count and int(count) > 0: + print("\n✅ P3 QEMU 验证通过!(ALL OK)", flush=True) + try: + sb.kill() + except Exception: + pass + try: + os.unlink(token_file) + except Exception: + pass + return 0 + except Exception: + pass + + print("\n❌ P3 QEMU 验证失败", flush=True) + print(f" 沙箱保留: {sb.sandbox_id}", flush=True) + print(f" token: {token_file}", flush=True) + return 1 finally: - sb.kill() + pass # 失败时保留沙箱供调试,成功时已在上方销毁 if __name__ == "__main__": diff --git a/crates/nax-tee/ca/Cargo.toml b/crates/nax-tee/ca/Cargo.toml index 01017b7..46558ce 100644 --- a/crates/nax-tee/ca/Cargo.toml +++ b/crates/nax-tee/ca/Cargo.toml @@ -1,8 +1,10 @@ [package] name = "nax-tee-ca" -version.workspace = true -edition.workspace = true -license.workspace = true +# 显式写死(不用 workspace 继承):拷进 teaclave-sdk 的 examples/ca 后 +# 那里的 workspace.package 没有 edition 等字段,继承会崩(2026-10-29 实测)。 +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" description = "nax TEE CA: normal-world client for the nax-tee TA" # 放在 /examples/ca/ 下,目录名以 -rs 结尾即可被 workspace 的 members 通配收进来。 diff --git a/crates/nax-tee/ca/src/main.rs b/crates/nax-tee/ca/src/main.rs index c3dc1eb..a3135d8 100644 --- a/crates/nax-tee/ca/src/main.rs +++ b/crates/nax-tee/ca/src/main.rs @@ -192,11 +192,11 @@ fn selftest() -> R<()> { Ok(()) } -fn main() { +fn run() -> R<()> { let args: Vec = std::env::args().collect(); let cmd = args.get(1).map(|s| s.as_str()).unwrap_or("selftest"); - let result = match cmd { + match cmd { "info" => { let mut tee = OpteeTee::open()?; let (flags, tag, counter) = tee.info()?; @@ -219,9 +219,13 @@ fn main() { eprintln!("用法: nax-tee-ca [info|provision|selftest]"); Ok(()) } - }; + } +} - if let Err(e) = result { +fn main() { + // 命令分发必须在返回 R<()> 的函数里做:`?` 不能用在返回 () 的 main 中 + //(E0277,2026-10-29 QEMU 实测)。 + if let Err(e) = run() { eprintln!("FAIL: {e}"); std::process::exit(1); } diff --git a/crates/nax-tee/ta/Cargo.toml b/crates/nax-tee/ta/Cargo.toml index d7dd3af..f174431 100644 --- a/crates/nax-tee/ta/Cargo.toml +++ b/crates/nax-tee/ta/Cargo.toml @@ -1,8 +1,10 @@ [package] name = "nax-tee-ta" -version.workspace = true -edition.workspace = true -license.workspace = true +# 显式写死(不用 workspace 继承):拷进 teaclave-sdk 后独立于其 +# workspace.package 解析(examples/ca 没有这些字段会崩,2026-10-29 实测)。 +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" description = "nax TEE TA: keys never leave the secure world" # 本 crate 必须放在 /examples/ta/ 下并加进该 workspace 的 members。 diff --git a/crates/nax-tee/ta/src/main.rs b/crates/nax-tee/ta/src/main.rs index 640ff8f..20b4793 100644 --- a/crates/nax-tee/ta/src/main.rs +++ b/crates/nax-tee/ta/src/main.rs @@ -12,7 +12,7 @@ //! - 设备身份(DNA)必须由 TA 自己读硬件,不能接受 CA 声称的。 //! - 每次命令结束把 K_root 缓冲清零。 -#![cfg_attr(not(feature = "std"), no_std)] +#![no_std] #![no_main] extern crate alloc; @@ -21,14 +21,27 @@ use alloc::vec::Vec; use optee_utee::prelude::*; use optee_utee::{ - DataFlag, ErrorKind, ObjectStorageConstants, ParametersAny, PersistentObject, Random, Result, + DataFlag, ErrorKind, ObjectStorageConstants, ParameterAny, ParameterMemref, + ParameterMemrefRead, ParameterMemrefWrite, ParametersAny, PersistentObject, + Random, Result, +}; +// ⚠️ 不能 `use nax_tee::optee::core::{self,..}` —— 会把 `core` 遮蔽成 +// `nax_tee::optee::core`,optee-utee 宏展开里的 `::core::ffi` 就找不到了 +//(E0432 + E0433,2026-10-29 QEMU 实测踩过)。只导具体符号。 +use nax_tee::optee::core::{ + derive_keys, device_tag, hmac, seal, sha256, unseal, DerivedKeys, DEVICE_DNA_LEN, ROOT_KEY_LEN, + SEAL_OVERHEAD, }; -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"; +// OP-TEE libutee/libutils 引用的符号(ta_head、ta_heap、ta_heap_size、ta_props、 +// ta_num_props、trace_level、trace_ext_prefix、tahead_get_trace_level)由 +// optee-utee-build 生成到 $OUT_DIR/user_ta_header.rs,文件末尾 include!。 +// 不要在这里手写 #[no_mangle] 弱符号——会与生成的定义冲突(重复定义)。 + /// secure storage 里的 K_root 对象名。 const OBJ_ROOT: &[u8] = b"nax.tee.root.v1\0"; @@ -40,12 +53,8 @@ fn read_obj(id: &[u8]) -> Result> { 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 { + if data.len() > 4096 { return Err(ErrorKind::ExcessData.into()); } Ok(data) @@ -102,25 +111,18 @@ fn device_dna() -> [u8; DEVICE_DNA_LEN] { #[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 h = sha256(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); + let keys = derive_keys(&root, &dna); // 清零 root 缓冲 let mut r = root; for b in r.iter_mut() { @@ -166,20 +168,83 @@ fn invoke_command(cmd_id: u32, params: &mut ParametersAny<'_>) -> Result<()> { } } +// ---------------------------------------------------------------- 参数辅助 + +/// 从 `ParametersAny` 里取第 `n` 个参数的可变缓冲。 +/// +/// `ParameterAny` 变体是 `MemrefInput`/`MemrefInout`/`MemrefOutput`, +/// 通过 `buffer_ptr()` + `buffer_len()` 构造切片。 +fn param_mut<'a>(params: &'a mut ParametersAny<'_>, n: usize) -> Result<&'a mut [u8]> { + let p: &mut ParameterAny = match n { + 0 => &mut params.0, + 1 => &mut params.1, + 2 => &mut params.2, + 3 => &mut params.3, + _ => return Err(ErrorKind::BadParameters.into()), + }; + match p { + ParameterAny::MemrefOutput(m) => { + let len = m.buffer_len(); + let ptr = m.buffer_ptr(); + if ptr.is_null() && len > 0 { + return Err(ErrorKind::BadParameters.into()); + } + Ok(unsafe { core::slice::from_raw_parts_mut(ptr, len) }) + } + ParameterAny::MemrefInout(m) => { + let len = m.buffer_len(); + let ptr = m.buffer_ptr(); + if ptr.is_null() && len > 0 { + return Err(ErrorKind::BadParameters.into()); + } + Ok(unsafe { core::slice::from_raw_parts_mut(ptr, len) }) + } + _ => Err(ErrorKind::BadParameters.into()), + } +} + +/// 从 `ParametersAny` 里取第 `n` 个参数的只读缓冲。 +fn param_ref<'a>(params: &'a ParametersAny<'_>, n: usize) -> Result<&'a [u8]> { + let p: &ParameterAny = match n { + 0 => ¶ms.0, + 1 => ¶ms.1, + 2 => ¶ms.2, + 3 => ¶ms.3, + _ => return Err(ErrorKind::BadParameters.into()), + }; + match p { + ParameterAny::MemrefInput(m) => { + let len = m.buffer_len(); + let ptr = m.buffer_ptr(); + if ptr.is_null() && len > 0 { + return Err(ErrorKind::BadParameters.into()); + } + Ok(unsafe { core::slice::from_raw_parts(ptr, len) }) + } + ParameterAny::MemrefInout(m) => { + let len = m.buffer_len(); + let ptr = m.buffer_ptr(); + if ptr.is_null() && len > 0 { + return Err(ErrorKind::BadParameters.into()); + } + Ok(unsafe { core::slice::from_raw_parts(ptr, len) }) + } + _ => Err(ErrorKind::BadParameters.into()), + } +} + // ---------------------------------------------------------------- 命令实现 fn cmd_info(params: &mut ParametersAny<'_>) -> Result<()> { let dna = device_dna(); - let tag = core::device_tag(&dna); + let tag = 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)?; + let buf = param_mut(params, 0)?; if buf.len() < proto::INFO_LEN { return Err(ErrorKind::ShortBuffer.into()); } @@ -192,9 +257,9 @@ fn cmd_provision() -> Result<()> { return Ok(()); // 幂等 } let mut key = [0u8; ROOT_KEY_LEN]; - Random::generate(&mut key).map_err(|_| ErrorKind::Generic)?; + // Random::generate 返回 () 不是 Result(E0599,2026-10-29 实测) + Random::generate(&mut key); write_obj(OBJ_ROOT, &key)?; - // 清零本地缓冲 for b in key.iter_mut() { *b = 0; } @@ -204,45 +269,35 @@ fn cmd_provision() -> Result<()> { 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 input = param_ref(params, 0)?; 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)?; + Random::generate(&mut nonce); - let blob = core::seal(&keys, &nonce, plaintext, aad); + let blob = 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)?; + let out = param_mut(params, 1)?; 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 input = param_ref(params, 0)?; 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 plaintext = unseal(&keys, blob, aad).ok_or(ErrorKind::Security)?; - let out = p1.as_mut().ok_or(ErrorKind::BadParameters)?; + let out = param_mut(params, 1)?; if out.len() < plaintext.len() { return Err(ErrorKind::ShortBuffer.into()); } @@ -251,19 +306,15 @@ fn cmd_unseal(params: &mut ParametersAny<'_>) -> Result<()> { } 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)?; + let msg = param_ref(params, 0)?; 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 sig = hmac(&keys.k_sig, &[msg]); - let out = p1.as_mut().ok_or(ErrorKind::BadParameters)?; + let out = param_mut(params, 1)?; if out.len() < proto::SIG_LEN { return Err(ErrorKind::ShortBuffer.into()); } @@ -272,32 +323,40 @@ fn cmd_sign(params: &mut ParametersAny<'_>) -> Result<()> { } 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()); + // 先拷贝 user_data,解除对 params 的不可变借用,避免与 param_mut 冲突 + let mut user_data = [0u8; 64]; + { + let src = param_ref(params, 0)?; + if src.len() != 64 { + return Err(ErrorKind::BadParameters.into()); + } + user_data.copy_from_slice(src); } let keys = derived_keys()?; let dna = device_dna(); - let tag = core::device_tag(&dna); + let tag = 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]); + body.extend_from_slice(&user_data); + let sig = hmac(&keys.k_sig, &[&body]); - let out = p1.as_mut().ok_or(ErrorKind::BadParameters)?; + let out = param_mut(params, 1)?; 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[8..72].copy_from_slice(&user_data); out[72..104].copy_from_slice(&sig); Ok(()) } + +// ---------------------------------------------------------------- TA 头 +// optee-utee-build 生成的 user_ta_header.rs:ta_head(.ta_head 段)、 +// ta_heap / ta_heap_size、ta_props / ta_num_props、trace_level / +// trace_ext_prefix / tahead_get_trace_level。必须 include 在 crate 根, +// 官方示例(aes-rs 等)同款写法。 +include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));