Files
admin bcad01d697 feat(sa): SA 扩展模式真机端到端跑通 + 修掉主门禁被误删的 5 条
SA 扩展模式(安全锚点供能力、算力挂外部 VM):
- 板端 SA 服务端 ↔ OrbStack 外挂 VM 端到端跑通,判据 26/26
- seal/unseal/attest/sign + 会话物料全部可用;VM 侧拿不到 K_root
  (site 名骗不出、协议无导出端点、VM 侧无根密钥文件)
- 阶段一边界写死为 platform=none,不假装有硬件根

零种子守卫(fail-closed):
- CLI 入口(连网之前)+ Vault::new 双层拒绝全零主种子
- mpc node 的种子校验原本在连网 + Ray 注册之后,失败会伪装成「网络问题」,已前移
- 判据 18 条,两处破坏实验证明非恒绿

主门禁回归修复(本次最重要):
- 27cbdc7 删掉了 ci.sh 的第 18-22 条共 5 个 step,判据脚本都还在、
  只是不再被调用 ⇒ 门禁静默削弱(文件在、判据在、门禁不跑)
- 已从 237e646 原样恢复,SA 与零种子守卫顺延为第 23/24 条,总数回到 24
- 头部注释编号与 step 号重新一一对齐

新发现的真缺陷与盲区:
- help 文本与实现漂移:attest-upload 的 --upload-path-file 漏写(实现里必填),
  SA 客户端五个必填参数全没写进帮助 ⇒ 静默失败,代码照编译门禁照全绿
- 加两条守卫测试,并修掉判据的自指型假绿(查裸字符串恒为真,要查解析调用)
- shell lint 不扫 deploy/arm,而那里是板端真跑的脚本 ⇒ 抓到 4 处 var-ascii 命中,
  已修并把 deploy/arm 纳入扫描范围(35 → 38 个脚本)
- hostd 客户端补 .no_proxy():代理会把这一跳端点换掉,症状是 502 伪装成控制面没起来

门禁:tools/ci.sh 全量 EXIT=0,24 条全绿(第 22 条真链批缺环境显式 SKIPPED)。
2026-11-09 16:32:36 +08:00

701 lines
29 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""SA 扩展模式(安全锚点供能力、算力挂外部 VM)的本地回归。
# 这条判据守的是什么
SA 形态的信任基础是**一条边界**:VM(算力侧)能调用安全世界的能力,
但**永远拿不到 `K_root`**。这条边界一旦破了,后果是:
* Beaver 三元组全部可预测 ⇒ 密态乘法隐私性归零;
* 而症状是「不报错、不崩溃、结果数值也对」—— 最难发现的一类失败。
所以判据必须证明三件事,而且每条都要**双向配对**:
| 判据 | 正向 | 否定 |
|---|---|---|
| 能力可用 | seal→unseal 往返、attest、sign | 错误 AAD、错误 token 必须拒 |
| 边界成立 | 协议里**没有**导出 `K_root` 的操作 | 请求导出必须被拒 |
| 物料合法 | master-seed 非全零、party-seed 按 site 分化 | 全零根密钥必须拒启动 |
# ★ 为什么每条否定判据都带「期望特征」
只判「退出码非 0」会把**错误的原因**当成通过。例如 `Connection refused`
也是非 0 —— 那是「服务没起来」,会让「必须拒绝」这条用例**因为服务挂了
而通过**(假绿)。
所以这里每条否定判据都要求输出里出现**特定的错误特征**
(`凭据不匹配` / `解封失败` / `全零` …),并额外做一次**正向对照**:
同样的命令在**正确参数**下必须成功 —— 证明「拒绝」不是因为环境坏了。
# 用法
python3 tools/selftest-sa.py [--mpc PATH]
环境变量:
MPC_BIN 指定 mpc 二进制路径(默认自动找 target/{debug,release}/mpc)
# 负向实验(判据非恒绿的证明)
以下破坏都是**真的注入到实现里、改完重编译、跑本脚本**跑出来的,
不是「理论上应该会红」:
| 破坏 | 期望变红的判据 | 实测 |
|---|---|---|
| 鉴权恒真(`ct_eq` 换成 `true`) | 错凭据被拒 | ✅ 52→51 |
| `unseal` 不校验 AAD | unseal 成功 / 还原原文 | ✅ 52→50 |
| 协议里加 `root-key` 导出端点 | 没有 root-key 端点 / 未知操作 | ✅ 52→50 |
| CLI + 服务端**同时**去全零守卫 | 全零根密钥拒绝启动 | ✅ 52→51 |
| 回环模式接受任意 token | 回环模式带凭据被拒 | ✅ 52→51 |
★ **一个必须写清楚的分层事实**:
「服务端层拒绝全零根密钥」这条守卫,**端到端脚本抓不到** ——
因为 CLI 层也有一道同样的检查,CLI 先拒了,服务端层的守卫**根本没被执行到**。
所以:
* 端到端脚本覆盖**整体**行为(全零 ⇒ 起不来);
* 分层责任(服务端层自己拒不拒)由 `mpc-tee` 的 Rust 单测
`zero_root_key_is_rejected` 覆盖 —— 实测:注入破坏后该单测 FAILED。
这不是「判据漏了」,而是**分层守卫的固有性质**:端到端脚本无法区分
「是哪一层拒的」。把它写清楚,比假装端到端能覆盖要诚实。
"""
from __future__ import annotations
import argparse
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
# 一份**确定不是全零**的根密钥(64 位十六进制 = 32 字节)。
ROOT_KEY_HEX = "a3f1c2d4e5b60718293a4b5c6d7e8f90112233445566778899aabbccddeeff00"
# 一份**就是全零**的根密钥 —— 用于验证「全零必须被拒」。
ZERO_KEY_HEX = "00" * 32
# 共享密钥(>= 32 字节)。服务端与客户端读同一个文件。
SECRET = "0123456789abcdef0123456789abcdef"
WRONG_SECRET = "ffffffffffffffffffffffffffffffff"
# 会话标识与 AAD
SESSION_ID = "11" * 32
AAD = "73657373696f6e2d31" # "session-1"
PLAINTEXT = "68656c6c6f2d7361" # "hello sa"
class Checks:
"""判据收集器。
★ 每条判据必须能区分「真的过了」与「因为环境坏了而看起来过了」。
所以 `check` 的第二个参数永远是**显式的布尔表达式**,
不用「退出码非 0」这种宽松判据。
"""
def __init__(self) -> None:
self.passed = 0
self.failed = 0
self.names: list[str] = []
def check(self, name: str, ok: bool, detail: object = "") -> bool:
if ok:
self.passed += 1
print(f" [ok] {name}")
else:
self.failed += 1
self.names.append(name)
print(f" [FAIL] {name}")
if detail:
print(f" detail: {str(detail)[:500]}")
return ok
def finish(self) -> int:
total = self.passed + self.failed
print(f"\n判据 {total} 条:通过 {self.passed},失败 {self.failed}")
if self.failed:
print("SA_SELFTEST_FAILED: " + "; ".join(self.names), file=sys.stderr)
return 1
print("SA_SELFTEST_OK")
return 0
def find_mpc(explicit: str | None = None) -> str | None:
if explicit and os.path.isfile(explicit):
return explicit
env = os.environ.get("MPC_BIN", "")
if env and os.path.isfile(env):
return env
here = os.path.dirname(os.path.abspath(__file__))
root = os.path.abspath(os.path.join(here, ".."))
for cand in (
os.path.join(root, "target", "debug", "mpc"),
os.path.join(root, "target", "release", "mpc"),
os.path.join(root, "target", "x86_64-unknown-linux-musl", "release", "mpc"),
os.path.join(root, "target", "armv7-unknown-linux-musleabihf", "release", "mpc"),
):
if os.path.isfile(cand):
return cand
return None
def free_port() -> int:
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
class Sa:
"""起一个 SA 服务端进程。"""
def __init__(self, mpc: str, tmp: str, listen: str, root_file: str,
secret_file: str | None, platform: str = "none"):
args = [mpc, "tee", "sa-serve", "--listen", listen,
"--root-key-file", root_file, "--platform", platform]
if secret_file:
args += ["--shared-secret-file", secret_file]
self.args = args
self.listen = listen
# ★ 服务端**不会自己退出**(它是个常驻服务),
# 所以绝不能用 `proc.stdout.read()` —— 那会一直阻塞到进程结束,
# 症状是「脚本卡死」,而根因在几行之外。
# 这里改成:把 stdout 落到临时文件,按需读文件。
self._log = tempfile.NamedTemporaryFile(
mode="w+", prefix="mpc-sa-log.", suffix=".txt", delete=False
)
self._log_path = self._log.name
self.proc = subprocess.Popen(
args, stdout=self._log, stderr=subprocess.STDOUT
)
def wait_ready(self, timeout: float = 15.0) -> bool:
"""等服务端真的在监听。
★ 不能只看「进程还活着」—— 进程活着但绑定失败(端口被占)
也会一直活着,那样后面所有请求都是 Connection refused,
而「Connection refused」会让否定判据**因为错误的原因通过**。
"""
host, port = self.listen.rsplit(":", 1)
deadline = time.time() + timeout
while time.time() < deadline:
if self.proc.poll() is not None:
return False
try:
with socket.create_connection((host, int(port)), timeout=0.5):
return True
except OSError:
time.sleep(0.1)
return False
def stop(self) -> None:
try:
self.proc.terminate()
self.proc.wait(timeout=10)
except Exception:
try:
self.proc.kill()
except Exception:
pass
try:
self._log.close()
os.unlink(self._log_path)
except Exception:
pass
def output(self) -> str:
"""读服务端到目前为止的输出(**非阻塞**)。"""
try:
with open(self._log_path, "r", errors="replace") as f:
return f.read()
except OSError:
return ""
def run(mpc: str, args: list[str], timeout: int = 40) -> tuple[int, str]:
"""跑一次 mpc 命令,返回 (退出码, 合并输出)。"""
try:
r = subprocess.run(
[mpc, *args], capture_output=True, text=True, timeout=timeout
)
return r.returncode, (r.stdout + r.stderr)
except subprocess.TimeoutExpired:
return 124, "timeout"
def parse_kv(out: str) -> dict[str, str]:
"""从 `note!` 风格的 `key=value` 行里取值。"""
kv: dict[str, str] = {}
for line in out.splitlines():
line = line.strip()
if "=" in line and not line.startswith("|"):
k, _, v = line.partition("=")
k = k.strip()
v = v.strip()
if k and " " not in k:
kv.setdefault(k, v)
return kv
def main() -> int:
ap = argparse.ArgumentParser(description="SA 扩展模式本地回归")
ap.add_argument("--mpc", default=None, help="mpc 二进制路径")
args = ap.parse_args()
mpc = find_mpc(args.mpc)
if not mpc:
print("SA_SELFTEST_FAILED: 找不到 mpc 二进制(先 cargo build -p mpc-cli)",
file=sys.stderr)
return 1
print(f"被测二进制: {mpc}")
c = Checks()
tmp = tempfile.mkdtemp(prefix="mpc-sa-selftest.")
root_file = os.path.join(tmp, "root.hex")
zero_file = os.path.join(tmp, "zero.hex")
secret_file = os.path.join(tmp, "secret.txt")
wrong_file = os.path.join(tmp, "wrong.txt")
short_file = os.path.join(tmp, "short.txt")
with open(root_file, "w") as f:
f.write(ROOT_KEY_HEX)
with open(zero_file, "w") as f:
f.write(ZERO_KEY_HEX)
with open(secret_file, "w") as f:
f.write(SECRET + "\n")
with open(wrong_file, "w") as f:
f.write(WRONG_SECRET + "\n")
with open(short_file, "w") as f:
f.write("tooshort\n")
port = free_port()
listen = f"127.0.0.1:{port}"
endpoint = listen
sa = Sa(mpc, tmp, listen, root_file, secret_file)
try:
# ---------------------------------------------------------
# 0. 服务端必须真的起来
# ---------------------------------------------------------
if not c.check("SA 服务端能启动并监听", sa.wait_ready(), sa.output()[:300]):
return c.finish()
# ★ 正向对照:服务端的启动输出里必须带 ready 标记。
# 没有它的话,「后面的请求为什么失败」会无从判断是协议问题还是进程没起。
c.check(
"服务端输出含 sa_serve_ready 标记",
"sa_serve_ready=true" in sa.output(),
sa.output()[:300],
)
base = ["tee", "sa-client", "--endpoint", endpoint,
"--shared-secret-file", secret_file]
# ---------------------------------------------------------
# 1. seal → unseal 往返
# ---------------------------------------------------------
rc, out = run(mpc, base + ["seal", "--plaintext-hex", PLAINTEXT,
"--aad-hex", AAD])
kv = parse_kv(out)
c.check("★ seal 成功", rc == 0 and "sa_seal_ok=true" in out, out[:300])
blob = kv.get("sealed_hex", "")
c.check("seal 输出给出密文", len(blob) > 0, out[:300])
# ★ 密文长度 = 12(nonce) + 明文(8) + 16(tag) = 36 字节 = 72 位 hex。
# 这条挡住「服务端返回的是明文」这类灾难性错误。
c.check(
"密文长度符合 nonce+明文+tag",
len(blob) == 72,
f"len={len(blob)}",
)
c.check(
"密文里不出现明文",
PLAINTEXT not in blob.lower(),
"明文直接出现在密文里 ⇒ seal 根本没加密",
)
rc, out = run(mpc, base + ["unseal", "--blob-hex", blob, "--aad-hex", AAD])
kv = parse_kv(out)
c.check("★ unseal 成功", rc == 0 and "sa_unseal_ok=true" in out, out[:300])
c.check(
"unseal 还原出原文",
kv.get("plaintext_hex", "").lower() == PLAINTEXT,
f"got={kv.get('plaintext_hex')}",
)
# ★ 错误 AAD 必须被拒 —— 且**错误原因**要是解封失败,
# 不是「服务没起来」。
rc, out = run(mpc, base + ["unseal", "--blob-hex", blob,
"--aad-hex", "6f74686572"])
c.check(
"★ 错误 AAD 被拒(且原因是解封失败)",
rc != 0 and "解封失败" in out,
f"rc={rc} out={out[:200]}",
)
# ★ 篡改密文必须被拒(AEAD tag 校验)
tampered = blob[:-2] + ("00" if blob[-2:] != "00" else "11")
rc, out = run(mpc, base + ["unseal", "--blob-hex", tampered,
"--aad-hex", AAD])
c.check(
"★ 篡改密文被拒",
rc != 0 and "解封失败" in out,
f"rc={rc} out={out[:200]}",
)
# ---------------------------------------------------------
# 2. 鉴权:缺凭据 / 错凭据都必须被拒
# ---------------------------------------------------------
rc, out = run(mpc, ["tee", "sa-client", "--endpoint", endpoint,
"seal", "--plaintext-hex", PLAINTEXT, "--aad-hex", AAD])
c.check(
"★ 缺凭据被拒(且原因是缺少 Authorization 凭据)",
rc != 0 and "缺少 Authorization 凭据" in out,
f"rc={rc} out={out[:200]}",
)
rc, out = run(mpc, ["tee", "sa-client", "--endpoint", endpoint,
"--shared-secret-file", wrong_file,
"seal", "--plaintext-hex", PLAINTEXT, "--aad-hex", AAD])
c.check(
"★ 错凭据被拒(且原因是凭据不匹配)",
rc != 0 and "凭据不匹配" in out,
f"rc={rc} out={out[:200]}",
)
# ★ 回环信任模式**不接受任意 token**:没配密钥的服务端,
# 带了凭据的请求必须被拒(而不是「有 token 就放行」)。
lp = free_port()
lsa = Sa(mpc, tmp, f"127.0.0.1:{lp}", root_file, None)
try:
if c.check("回环模式服务端能启动", lsa.wait_ready(), lsa.output()[:300]):
rc, out = run(mpc, ["tee", "sa-client", "--endpoint",
f"127.0.0.1:{lp}",
"--shared-secret-file", secret_file,
"seal", "--plaintext-hex", PLAINTEXT,
"--aad-hex", AAD])
c.check(
"★ 回环模式带凭据被拒(不接受任意 token)",
rc != 0 and "凭据" in out,
f"rc={rc} out={out[:200]}",
)
# 正向对照:不带凭据必须成功 —— 证明上面那条不是「服务根本不通」
rc, out = run(mpc, ["tee", "sa-client", "--endpoint",
f"127.0.0.1:{lp}",
"seal", "--plaintext-hex", PLAINTEXT,
"--aad-hex", AAD])
c.check(
"回环模式不带凭据成功(正向对照)",
rc == 0 and "sa_seal_ok=true" in out,
f"rc={rc} out={out[:200]}",
)
finally:
lsa.stop()
# ---------------------------------------------------------
# 3. attest / sign
# ---------------------------------------------------------
ud = "aa" * 64
rc, out = run(mpc, base + ["attest", "--user-data-hex", ud])
kv = parse_kv(out)
c.check("★ attest 成功", rc == 0 and "sa_attest_ok=true" in out, out[:300])
report = kv.get("report_hex", "")
# 报告布局:user_data(64) ‖ tcb(4) ‖ sig(32) = 100 字节 = 200 位 hex
c.check("attest 报告长度 = 100 字节", len(report) == 200, f"len={len(report)}")
c.check(
"attest 报告里 user_data 原样透传",
report[:128].lower() == ud,
report[:128],
)
c.check(
"★ attest 诚实自曝:无证书链(阶段一没有硬件身份)",
kv.get("cert_chain_len") == "0",
f"cert_chain_len={kv.get('cert_chain_len')}",
)
c.check(
"★ attest 平台报 none(不谎称有硬件保护)",
kv.get("platform") == "none",
f"platform={kv.get('platform')}",
)
rc, out = run(mpc, base + ["sign", "--message-hex", "706f6c696379"])
kv = parse_kv(out)
c.check("★ sign 成功", rc == 0 and "sa_sign_ok=true" in out, out[:300])
sig1 = kv.get("sig_hex", "")
c.check("签名是 32 字节(HMAC-SHA256)", len(sig1) == 64, f"len={len(sig1)}")
# ★ 同样的消息签名必须稳定(否则它不能当审计锚点)
rc, out = run(mpc, base + ["sign", "--message-hex", "706f6c696379"])
sig2 = parse_kv(out).get("sig_hex", "")
c.check("同消息签名稳定(确定性)", sig1 == sig2 and sig1 != "", f"{sig1} vs {sig2}")
# ★ 不同的消息签名必须不同
rc, out = run(mpc, base + ["sign", "--message-hex", "6f74686572"])
sig3 = parse_kv(out).get("sig_hex", "")
c.check("不同消息签名不同", sig1 != sig3 and sig3 != "", f"{sig1} vs {sig3}")
# ---------------------------------------------------------
# 4. 物料:master-seed / party-seed
# ---------------------------------------------------------
rc, out = run(mpc, base + ["master-seed", "--session-id", SESSION_ID])
kv = parse_kv(out)
master = kv.get("master_seed_hex", "")
c.check("★ master-seed 成功", rc == 0 and "sa_master_seed_ok=true" in out,
out[:300])
c.check("master-seed 是 32 字节", len(master) == 64, f"len={len(master)}")
c.check(
"★ master-seed 不是全零",
master != "00" * 32,
"全零主种子 ⇒ Beaver 三元组全部可预测",
)
rc, out = run(mpc, base + ["master-seed", "--session-id", SESSION_ID])
master2 = parse_kv(out).get("master_seed_hex", "")
c.check("master-seed 确定性(同会话同种子)", master == master2,
f"{master} vs {master2}")
rc, out = run(mpc, base + ["master-seed", "--session-id", "22" * 32])
master3 = parse_kv(out).get("master_seed_hex", "")
c.check("不同会话主种子不同", master != master3, f"{master} vs {master3}")
rc, out = run(mpc, base + ["party-seed", "--session-id", SESSION_ID,
"--site", "alice"])
alice = parse_kv(out).get("party_seed_hex", "")
rc, out = run(mpc, base + ["party-seed", "--session-id", SESSION_ID,
"--site", "bob"])
bob = parse_kv(out).get("party_seed_hex", "")
c.check("★ party-seed 成功", len(alice) == 64 and len(bob) == 64,
f"alice={alice} bob={bob}")
c.check("不同 site 的种子不同", alice != bob, f"{alice} vs {bob}")
# ---------------------------------------------------------
# 5. ★ 边界:VM 侧**没有任何**导出 K_root 的途径
# ---------------------------------------------------------
# 这条是整个形态的信任基础。判据有两半:
# ① 协议里**没有** root-key / export 这类操作名;
# ② 直接请求那些路径必须被拒(404),且**服务仍在运行**
# (否则「被拒」可能只是进程崩了)。
for forbidden in ("root-key", "export", "k-root", "master-key"):
rc, out = run(mpc, base + ["party-seed", "--session-id", SESSION_ID,
"--site", forbidden])
kv = parse_kv(out)
# ★ site 名字只是派生标签,**不会**换来任何导出能力。
# 这条防的是「有人给协议加个按 site 分支的导出路径」。
# 注意用的是 `party-seed` —— `master-seed` 根本不看 site。
c.check(
f"site 名 {forbidden!r} 不会换来导出能力(只影响派生)",
rc == 0 and "sa_party_seed_ok=true" in out,
f"rc={rc} out={out[:200]}",
)
# ★ 派生的种子里**不得**出现根密钥本身。
c.check(
f"site {forbidden!r} 的派生种子不等于根密钥",
kv.get("party_seed_hex", "").lower() != ROOT_KEY_HEX.lower(),
kv.get("party_seed_hex", ""),
)
# 用原始 socket 直接打协议,验证「导出 K_root」的路径不存在。
rc, out = raw_post(endpoint, "/sa/v1/root-key", b"", SECRET)
c.check(
"★ 协议里没有 root-key 端点(404)",
rc == 404,
f"rc={rc} out={out[:200]}",
)
rc, out = raw_post(endpoint, "/sa/v1/export", b"", SECRET)
c.check(
"★ 协议里没有 export 端点(404)",
rc == 404,
f"rc={rc} out={out[:200]}",
)
# ★ 服务必须还活着 —— 证明上面两次请求只是「路由不存在」,
# 不是把服务打挂了。
rc, out = run(mpc, base + ["seal", "--plaintext-hex", PLAINTEXT,
"--aad-hex", AAD])
c.check(
"★ 请求不存在的端点后服务仍存活(正向对照)",
rc == 0 and "sa_seal_ok=true" in out,
f"rc={rc} out={out[:200]}",
)
# ★ 导出尝试的拒绝必须带**期望特征**:404 + 明确的「未知操作」。
# 注意措辞:路径前缀 `/sa/v1/` 是**能**匹配的,所以 404 落在
# 「操作不认识」这一层(而不是「路径不认识」)。这比笼统的 404 更精确 ——
# 前缀不匹配时报的才是「未知路径」。
rc, out = raw_post(endpoint, "/sa/v1/root-key", b"", SECRET)
c.check(
"★ 导出尝试的拒绝带期望特征(未知操作)",
rc == 404 and "未知操作" in out,
f"rc={rc} out={out[:200]}",
)
# ★ 路径前缀都不对 ⇒ 报「未知路径」(与「未知操作」区分开)。
rc, out = raw_post(endpoint, "/not-sa/v1/seal", b"", SECRET)
c.check(
"★ 路径前缀不对时拒绝(未知路径)",
rc == 404 and "未知路径" in out,
f"rc={rc} out={out[:200]}",
)
# ★ 未鉴权的导出尝试也必须被拒(401 先于 404):
# 否则「没鉴权也能试探协议」是个洞。
rc, out = raw_post(endpoint, "/sa/v1/root-key", b"", None)
c.check(
"★ 未鉴权访问被拒(401 先于 404)",
rc == 401,
f"rc={rc} out={out[:200]}",
)
# ---------------------------------------------------------
# 6. 启动前负向:配置不合法必须**拒绝启动**
# ---------------------------------------------------------
# ① 非回环监听且没配共享密钥
rc, out = run(mpc, ["tee", "sa-serve", "--listen", "192.168.1.233:19999",
"--root-key-file", root_file])
c.check(
"★ 非回环且无共享密钥 ⇒ 拒绝启动",
rc != 0 and "shared-secret" in out and "回环" in out,
f"rc={rc} out={out[:200]}",
)
# ② 全零根密钥
rc, out = run(mpc, ["tee", "sa-serve", "--listen", "127.0.0.1:19998",
"--root-key-file", zero_file])
c.check(
"★ 全零根密钥 ⇒ 拒绝启动",
rc != 0 and "全零" in out,
f"rc={rc} out={out[:200]}",
)
# ③ 共享密钥太短
rc, out = run(mpc, ["tee", "sa-serve", "--listen", "127.0.0.1:19997",
"--root-key-file", root_file,
"--shared-secret-file", short_file])
c.check(
"★ 共享密钥太短 ⇒ 拒绝启动",
rc != 0 and ("短" in out or "长度" in out),
f"rc={rc} out={out[:200]}",
)
# ④ 根密钥文件不是合法 hex
bad_hex = os.path.join(tmp, "bad.hex")
with open(bad_hex, "w") as f:
f.write("not-hex")
rc, out = run(mpc, ["tee", "sa-serve", "--listen", "127.0.0.1:19996",
"--root-key-file", bad_hex])
c.check(
"★ 根密钥文件非 hex ⇒ 拒绝启动",
rc != 0 and "十六进制" in out,
f"rc={rc} out={out[:200]}",
)
# ---------------------------------------------------------
# 7. 协议层细节
# ---------------------------------------------------------
# ① 非 POST 必须被拒(405)
rc, out = raw_request(endpoint, "GET", "/sa/v1/seal", b"", SECRET)
c.check("★ 非 POST 方法被拒(405)", rc == 405, f"rc={rc} out={out[:200]}")
# ② body 不是合法 hex 必须被拒(400)
rc, out = raw_post_raw_body(endpoint, "/sa/v1/seal", b"zzzz", SECRET)
c.check(
"★ body 非 hex 被拒(400)",
rc == 400 and ("十六进制" in out or "奇数" in out),
f"rc={rc} out={out[:200]}",
)
# ③ 认证模式下,非 POST 也必须先过鉴权?
# —— 不要求(405 先判),但必须**不是 200**。
rc, out = raw_request(endpoint, "GET", "/sa/v1/seal", b"", WRONG_SECRET)
c.check("错凭据 + 非 POST 不得返回 200", rc != 200, f"rc={rc}")
finally:
sa.stop()
shutil.rmtree(tmp, ignore_errors=True)
return c.finish()
def raw_request(endpoint: str, method: str, path: str, body: bytes,
secret: str | None, timeout: float = 15.0) -> tuple[int, str]:
"""手写一个 HTTP 请求,绕开 urllib 的代理与自动重定向。
★ 必须自己绕开本机代理:明文 HTTP 走代理会被改写,
症状是 502 / 连接失败 —— 看起来像 SA 没起来,实际是代理拦了。
"""
host, port = endpoint.rsplit(":", 1)
body_hex = body.hex()
head = (
f"{method} {path} HTTP/1.1\r\n"
f"Host: {endpoint}\r\n"
"Connection: close\r\n"
"Content-Type: text/plain\r\n"
f"Content-Length: {len(body_hex)}\r\n"
)
if secret is not None:
head += f"Authorization: Bearer {secret}\r\n"
head += "\r\n"
payload = head.encode() + body_hex.encode()
try:
with socket.create_connection((host, int(port)), timeout=timeout) as s:
s.sendall(payload)
chunks = []
while True:
b = s.recv(4096)
if not b:
break
chunks.append(b)
raw = b"".join(chunks)
except OSError as e:
return 0, f"socket error: {e}"
head_text, _, body_text = raw.partition(b"\r\n\r\n")
first = head_text.split(b"\r\n", 1)[0].decode("latin-1", "replace")
parts = first.split()
code = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else 0
# 响应体是 hex 编码的 UTF-8 文本
try:
decoded = bytes.fromhex(body_text.decode("latin-1").strip()).decode(
"utf-8", "replace")
except ValueError:
decoded = body_text.decode("latin-1", "replace")
return code, decoded
def raw_post(endpoint: str, path: str, body: bytes,
secret: str | None) -> tuple[int, str]:
return raw_request(endpoint, "POST", path, body, secret)
def raw_post_raw_body(endpoint: str, path: str, raw_body: bytes,
secret: str | None) -> tuple[int, str]:
"""POST 一个**非 hex** 的 body(服务端应当拒绝)。"""
host, port = endpoint.rsplit(":", 1)
head = (
f"POST {path} HTTP/1.1\r\n"
f"Host: {endpoint}\r\n"
"Connection: close\r\n"
"Content-Type: text/plain\r\n"
f"Content-Length: {len(raw_body)}\r\n"
)
if secret is not None:
head += f"Authorization: Bearer {secret}\r\n"
head += "\r\n"
payload = head.encode() + raw_body
try:
with socket.create_connection((host, int(port)), timeout=15) as s:
s.sendall(payload)
chunks = []
while True:
b = s.recv(4096)
if not b:
break
chunks.append(b)
raw = b"".join(chunks)
except OSError as e:
return 0, f"socket error: {e}"
head_text, _, body_text = raw.partition(b"\r\n\r\n")
first = head_text.split(b"\r\n", 1)[0].decode("latin-1", "replace")
parts = first.split()
code = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else 0
try:
decoded = bytes.fromhex(body_text.decode("latin-1").strip()).decode(
"utf-8", "replace")
except ValueError:
decoded = body_text.decode("latin-1", "replace")
return code, decoded
if __name__ == "__main__":
sys.exit(main())